Stopping a Do While Loop

B

Beamer

I have programming setup to run inside a Do While loop where it looks for
certain text and then deletes the row. The problem I am having is getting
the loop to stop when it has found all of text in the document. My current
coding is:

Do While XAB < 40
.Forward = True
.Wrap = wdFindContinue
.MatchWholeWord = True
.MatchAllWordForms = False
.Execute FindText:="%<>%"
Selection.Rows.Delete
XAB = XAB + 1
Loop

Any suggestions would be appreciated.
 
A

Anand.V.V.N

Instead of
XAB = XAB + 1
use this
if xab=40
exit do
else
XAB=XAB+1
endif

Exit do whould exit the do loop.

Hope this was useful.

Anand
 
B

Beamer

The thing is I would actually like to find a conditional statement that would
tell the loop to exit when there were no more of the strings that it is
looking for in the document. The current use of a count to 40 is only
because that is the maximum number of times the loop would need to run,
however I would like for the programming to be more efficient and only loop
as many times as necessary.
 
T

Tony Jollans

Most of the code inside your loop can be outside it - the settings only need
doing once, so you could have

..Forward = True
..Wrap = wdFindContinue
..MatchWholeWord = True
MatchAllWordForms = False

Do While XAB < 40
.Execute FindText:="%<>%"
Selection.Rows.Delete
XAB = XAB + 1
Loop

That makes it easier to see what's going on. Now, what you want is to check
if the execute has been successful. As it returns a True/False value, you
can do this

Do While XAB < 40
If .Execute FindText:="%<>%" Then
Selection.Rows.Delete
Else
Exit Do
End If
XAB = XAB + 1
Loop

Now you can see that the XAB variable is unnecessary ...

Do
If .Execute FindText:="%<>%" Then
Selection.Rows.Delete
Else
Exit Do
End If
Loop

which can be shortened to:

Do While .Execute FindText:="%<>%"
Selection.Rows.Delete
Loop

Giving complete code of:

..Forward = True
..Wrap = wdFindContinue
..MatchWholeWord = True
MatchAllWordForms = False
Do While .Execute FindText:="%<>%"
Selection.Rows.Delete
Loop


Enjoy,
Tony
 
B

Beamer

The first tip that you gave will reduce the lines run, however I ran into a
problem where the If statement ( If .Execute FindText:="%<>%" Then) throws an
error because of an error in the conditional statement. I believe that the
error directly relates to the space between .Execute and FindText. Is there
a way to correct this error using brackets, or do I need to use an entirely
different conditional statement?

-Beamer
 
T

Tony Jollans

My apologies - I should test instead of just typing :)

The correct syntax is:

If .Execute(FindText:="%<>%") Then

and, in the While:

Do While .Execute(FindText:="%<>%")

Enjoy,
Tony
 

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