A family of Microsoft word processing software products for creating web, email, and print documents.
Use the return value of Selection.Find.Execute (or the Found property) to decide whether to run the rest of the logic, and exit the loop when nothing is found. The Execute method returns True if something is found and False if not.
A minimal pattern based on the documented behavior is:
Sub Moving_Numerals()
Application.ScreenUpdating = False
Do
With Selection.Find
.ClearFormatting
.Text = "|"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchWildcards = False
End With
' Execute returns True if found, False if not
If Not Selection.Find.Execute Then
Exit Do ' nothing found: leave the loop
End If
' at this point, "|" has been found – run the rest of the code
' ... your existing processing here ...
Loop
Application.ScreenUpdating = True
End Sub
Key points:
-
Find.Executereturns a Boolean (Trueif the find operation is successful). - Test that Boolean immediately and
Exit Do(orExit Sub) when it isFalse. - This avoids relying on
Selection.Find.Foundat the bottom of the loop and ensures the macro stops cleanly when the search text is not found.
If additional Find operations inside the loop may also fail, guard each of them similarly:
If Not Selection.Find.Execute Then
' not found – either skip this block or exit
GoTo NextIteration ' or Exit Do / Exit Sub
End If
' code that assumes a successful find
Then place a NextIteration: label just before Loop if using GoTo.
References: