Do While Loop

N

Neal

Hi -

I was trying to incorporate in my code the Sub DoFindReplace(FindText As String, ReplaceText As String)
in Dave Rado's article "How to cut out repetition..." http://word.mvps.org/FAQs/MacrosVBA/ProcArguments.htm
but I seem to be caught in the loop.

My find and replace operations are:

Call DoFindReplace("^p", "@@^p")
Call DoFindReplace"@@^p@@^p", "^p")
Call DoFindReplace"@@^p", "^t")

Since the ^p isn't removed, it stays in the loop and just keeps adding more and more @@.

Question: How can I adapt the loop statement so that it only replaces ^p to @@^p one time for
each occurrence?

Here's the code:

Sub DoFindReplace(FindText As String, ReplaceText As String)

With Selection.Find
.ClearFormatting
.Replacement.ClearFormatting

.Text = FindText
.Replacement.Text = ReplaceText

.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
Do While .Execute
'Keep going until nothing found
.Execute Replace:=wdReplaceAll
Loop
'Free up some memory
ActiveDocument.UndoClear
End With

End Sub

Thanks in advance for your help.
Neal
 
J

Jay Freedman

Hi, Neal,

The thing to notice about Dave's code is that he's always replacing a
longer string with a shorter one, for example replacing "^p^p" with
"^p". The reason he uses the While loop is that the document might
contain even longer strings like "^p^p^p^p^p^p^p^p" and the code will
reduce that by one ^p in each pass around the loop until eventually
there's only one remaining.

You're trying to go the other way, adding @@ characters to the ^p, so
there is no time when the loop stops. In your case, you don't need --
don't want -- the While loop at all. You just want to do the
ReplaceAll once.

You could make the DoFindReplace routine detect whether the FindText
string is a substring of the ReplaceText string. The code is

If InStr(ReplaceText, FindText) > 0 Then
.Execute Replace:=wdReplaceAll
Else
Do While .Execute
'Keep going until nothing found
.Execute Replace:=wdReplaceAll
Loop
End If

If the condition is true, then you just run .Execute once; if it's
false, then you run the While loop.
 

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