Fixed: Word VBA crashes on “Find.Execute Replace:=wdReplaceAll”

This morning I hit a test case in which, for the first time in over a year running the same Word VBA macro, a Range.Find.Execute Replace:=wdReplaceAll hung, then crashed Word 2013 (32-bit, running on Win8.1 x64).  The Execute was running inside a custom Undo record, and was the first action taken inside that record.

Searching led me to this forum post by vbRichard suggesting that the empty Undo record was the problem.  I edited my code to change the document after opening the record, before running Execute, and Execute now runs fine!  Thanks to vbRichard, whomever you are 🙂 .  I also added code to clean up the change just before closing the Undo record.

Since my use case is English, I added a zero-width joiner (“ZWJ”, ChrW(&H200D)) before the text I was processing, then deleted it at the end.  I could have used any character I was confident wouldn’t appear in the input, or wouldn’t affect the function’s main task.  The result is below (licensed CC-BY 4.0).

' Top of module:
Private Const U_ZWJ = &H200D

' Inside a function:
Dim r as Range
' ... code here to set r ...
Dim undos As UndoRecord
Set undos = Application.UndoRecord
undos.StartCustomRecord "90125"     ' or whatever record title you like
r.InsertBefore ChrW(U_ZWJ)
    ' now r includes the ZWJ.  
r.MoveStart wdCharacter, 1          ' remove the ZWJ from r
' ... code here to process r ...
r.MoveStart wdCharacter, -1         ' re-select the ZWJ
If AscW(r.Characters.first) = U_ZWJ Then   'sanity check
    r.Collapse wdCollapseStart
    r.MoveEnd wdCharacter, 1        ' select only the ZWJ
    r.Delete
End If
undos.EndCustomRecord

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s