Find next occurence

M

McGeeky

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!
 
G

Greg Maxey

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!

Hard to quess what you are really trying to do. Something like this;

Sub ScratchMacro()
Dim findText As String
Dim i As Long
Dim myRange As Range
Set myRange = ActiveDocument.Range
findText = InputBox("Enter text to find")
With myRange.Find
.Text = findText
.MatchWholeWord = True
While .Execute
i = i + 1
Wend
End With
MsgBox findText & " found " & i & " times."
End Sub
 
J

Jay Freedman

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top