Flush bad karma from Word's find facility after an unsuccessful wildcard search

Article contributed by Bill Coan

There is a bug in Word that means any Find or Find or Replace operation in VBA that follows an unsuccessful wildcard search may sometimes fail. The following code fixes this problem.

Sub WildcardSearch()

 

  Dim myWorkingRange As Range

  Set myWorkingRange = ActiveDocument.Range

 

  'call a routine that removes any previous settings from the find dialog

  Call ClearFindAndReplaceParameters

 

  myWorkingRange.Find.Execute FindText:= "[!^013]" , _

      MatchWildcards:= True , Forward:= True

 

  'exit sub if search is successful

  If myWorkingRange.Find.Found Then

    MsgBox "tell the user something"

    Call ClearFindAndReplaceParameters

    Exit Sub

  End If

 

  'this is a dummy search because otherwise

  'subsequent searches will break down

  'somehow this search flushes the bad karma

  'and lets subsequent searches function

 

  myWorkingRange.Find.Execute FindText:= "^p" , _

      MatchWildcards:= False

 

  'call a routine that removes all settings from the find dialog

  'so future users of the dialog won't get strange results

 

  Call ClearFindAndReplaceParameters

 

End Sub


 

Sub ClearFindAndReplaceParameters()

 

  With Selection.Find

    .ClearFormatting

    .Replacement.ClearFormatting

    .Text = ""

    .Replacement.Text = ""

    .Forward = True

    .Wrap = wdFindStop

    .Format = False

    .MatchCase = False

    .MatchWholeWord = False

    .MatchWildcards = False

    .MatchSoundsLike = False

    .MatchAllWordForms = False

  End With

 

End Sub


 

Note: There is no simple way to reproduce this bug. In a macro that makes dozens of wildcard searches, the bug will eventually manifest itself, but I don't know of a way to force the bug to appear. The good news is that if you use the above workaround, the bug will never appear.

See also:
How to prevent the built-in BrowseNext and RepeatFind commands from creating bad karma for wildcard searches