Find .execute still not clicking

G

Greg

Everytime I think that I am beginning to grasp the Find.Execute process
something comes up to cloud my understanding.

Take this small test as an example.

Document text:

Abc abc abc abc

The code:

Public Sub Test()
Dim myRange As Range

Set myRange = ActiveDocument.Range
With myRange.Find
.ClearFormatting
.Text = "abc"
.Format = False
.Forward = True
.Wrap = wdFindStop
.MatchCase = False
Do While .Execute
myRange.Font.Bold = False
'myRange.Collapse Direction:=wdCollapseEnd
Loop
End With
End Sub

I understand that I could use a replace:=wdReplaceAll operation here
but I am trying to get my head around stepping through each found term
and performing an action.

Most of the time when I try something like this I can spend 15 minutes
or more trying stop circular loops. After a while it dawns on me to
put in the wdFindStop line and the Collapse Direction line.

What I don't understand is why a loop is not occurring when I run the
code above with the .collapse line activated?
 
G

Greg

Sorry, I meant with the .collapse line deactivate. The macro performs
just as well with or without that line. It seems like it should hang
up and loop on the first term found.
 
K

Klaus Linke

Hi Greg,

To debug, generously sprinkle some "myRange.Select" lines into your code, then single-step through it and watch what happens in the document.

If the selected text matches the .Find.Text, Word will go to the next match. You can check that in the user interface.
Still there are lots of situations where you can end up with an endless loop by accident.

Greetings,
Klaus
 
H

Helmut Weber

Hi Greg,

unfortunately I can't produce an endless loop,
if I want to create one.
Besides that, how the range behaves,
depends on what you do to it.
Do While .Execute
myRange.Font.Bold = False ' !!!
'myRange.Collapse Direction:=wdCollapseEnd
Loop

needs no collapsing, as the content of the range,
the string, doesn't change.

Whereas
Do While .Execute
myRange.Font.Bold = False
myrange.text = "xxx" ' !!! Content of range changes.
'myRange.Collapse Direction:=wdCollapseEnd
Loop

would need the collapsing.

The first example processes all occurences of "abc".
The second example stops after the first occurence.


Greetings from Bavaria, Germany

Helmut Weber, MVP
"red.sys" & chr(64) & "t-online.de"
Word XP, Win 98
http://word.mvps.org/
 

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