End of document reached

S

Steve Wylie

Is there a command I can use as part of a loop that will stop the loop once
the end of the document has been reached? Sort of "REPEAT ... UNTIL
End_Of_Document" arrangement?

Steve
 
L

Lars-Eric Gisslén

Steve,

Perhaps this can be a starting point:

Sub EODocTest()
Dim nMovement As Long

While Selection.Range.End <
ActiveDocument.Bookmarks("\EndOfDoc").Range.Start
Selection.MoveRight
nMovement = nMovement + 1
Wend

MsgBox "Reached the EndOfDoc after" & Str(nMovement) & " movements"
End Sub

Regards,
Lars-Eric
 
J

Jay Freedman

Hi, Steve,

It depends on what you're doing inside the loop. If you're doing a Find or
Replace, then "am I at the end of the document?" is the wrong question --
the right one is "are there any more occurrences to find/replace?" To
implement that, you should know that the .Find.Execute method returns True
when it finds the next occurrence, and False when it fails to find another
occurrence. This means your loop can look like this:

With MyRange.Find
' set up parameters like .Text, .Replacement, .Direction
Do While .Execute
' MyRange now points to the found text
' do something with the found stuff
MyRange.Collapse Direction:=wdCollapseEnd
Loop
End With

For an example of this technique, see the code in
http://www.mvps.org/word/FAQs/MacrosVBA/FindReplaceSymbols.htm.

If you have the ability to use ReplaceAll (possibly by using a wildcard
search), that will be even faster than building a Do While loop. For an
example of this, see
http://www.mvps.org/word/FAQs/MacrosVBA/ReplaceQuotes.htm.

If for some reason you can't use Find/Replace, there are a variety of kludgy
things you can do, such as comparing MyRange.End to
ActiveDocument.Range.End, or checking the result of MyRange.Move to see
whether it equals the number of characters (or other units) that was
requested. I try to avoid these methods if possible, because there are lots
of gotchas involved.
 
S

Steve Wylie

ActiveDocument.Bookmarks("\EndOfDoc")

Do you mean that there are "system" bookmarks in Word to represent things
like the end of the document, start of document etc? If so, where can I
find a list of these?

Steve
 

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