An implementation of Visual Basic that is built into Microsoft products.
Use the range-based Find consistently and avoid Selection.Find, which can continue past the intended range. Also ensure the range is moved forward after each match so the loop progresses and naturally stops at the end of the document when .Wrap = wdFindStop.
A simplified pattern that stops at the end of the document:
Sub Word_to_Excel_Part_One()
Dim rng As Range
Set rng = ActiveDocument.Content
With rng.Find
.ClearFormatting
.Text = "F90"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop ' stop at end of document
.Format = False
.MatchCase = True
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Do While rng.Find.Execute
' rng is now at the found "F90"
' Do work relative to rng here, without using Selection.Find
' Example: move rng to the end of this match so the next Execute
' starts after the current one
rng.Collapse Direction:=wdCollapseEnd
Loop
End Sub
Key points:
-
.Wrap = wdFindStoponrng.Findensures the loop stops when the end ofActiveDocument.Contentis reached. - Avoid
Selection.Findwith its own.Wrapinside the loop; it operates independently ofrngand can search beyond the intended area. - After each successful
rng.Find.Execute, collapserngto its end (wdCollapseEnd) so the next search starts after the current match.
If additional searches (for "kg" or the wildcard pattern) are needed, perform them on a Range derived from rng (e.g., Set rng2 = rng.Duplicate) and keep .Wrap = wdFindStop on those range finds as well, instead of using Selection.Find.
References: