Hi. I am using the Range.Find.Execute method to find an occurrence of a
string in my range. But how do I find the next occurrence, and the next
occurence? I.e. how do I iterate through all the occurences?
Thanks!
The usual setup goes something like this:
Dim myRg As Range
Set myRg = ActiveDocument.Range
With myRg.Find
.Text = "find this"
.Format = False
.Forward = True
.Wrap = wdFindStop
While .Execute
' do something with myRg here
' this may be needed:
myRg.Collapse wdCollapseEnd
Wend
End With
The .Execute method does two things when it finds an occurrence: It moves the
range myRg to cover only the found text, and it returns the value True. The
return value acts as the condition of the While loop, so the True causes
execution to go into the body of the loop.
Inside the loop, you can do things like changing the formatting of myRg,
changing the value of myRg.Text, copying myRg.FormattedText to another document,
etc.
If the value of myRg.Text hasn't changed, then you need to collapse the range to
its end so that the next .Execute doesn't find the same occurrence again.
After the last occurrence has been worked on, the next .Execute will return
False and the loop will exit.