A Find loop inside a Find--possible?

L

Larry

Here's the pattern I use for macros in which some action is performed
after each item is found. But the steps done inside the loop don't work
if they involve Selection.Find. In other words, it doesn't seem possible
to do a Find inside a Find. Is there any way around this?

Thanks,
Larry


Application.ScreenUpdating = False
With Selection.Find
.ClearFormatting
.Text = "text"
.Forward = True
.Wrap = wdFindContinue

Do While .Execute
' do steps

Loop
End With
 
D

Doug Robbins

Better if you tell us exactly what you are trying to do. That is what you
are starting with and what you want to end up with.

--
Hope this helps.

Please reply to the newsgroup unless you wish to avail yourself of my
services on a paid consulting basis.

Doug Robbins - Word MVP
 
H

Helmut Weber

Hi Larry,

no problem, once you have understood how ranges work.
And the selection is a range, too, the selection.range.

If you search in a range, and the search is successfull,
then the range changes to what you have found.
So you have to remember what the starting definition was:
Range.start, Range.end. (In case you do something to it.)
And restore it afterwards. Not always quite simple.

Let's say:
range.start = 400
range.end = 500
replace "brown" by "yellow", in that range,
then to perform another replace,
you would have to move the range's end for as many characters
as .found was true. Too complicated.

Enclose your range in a bookmark.

The bookmark's range shrinks and expands, whatever you do in it.

Go through this in single step mode [F8] and look.

Sub test7885()
Dim r As Range
Set r = ActiveDocument.Range(100, 200)
ActiveDocument.Bookmarks.Add "mark1", r
With ActiveDocument.Bookmarks("mark1").Range.Find
.Text = "yellow"
.Replacement.Text = "brown"
If .Execute(Replace:=wdReplaceAll) Then
.Text = "brown"
.Replacement.Text = "yellow"
.Execute Replace:=wdReplaceAll
End If
.Text = "yellow"
.Replacement.Text = "brown"
.Execute Replace:=wdReplaceAll
End With
End Sub

Sample text: "The quick brown fox jumps over the lazy dog." repeated.


Greetings from Bavaria, Germany

Helmut Weber, MVP, WordVBA

Win XP, Office 2003
"red.sys" & Chr$(64) & "t-online.de"
 

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