bobmain said:
What is the VBA code for detecting the end of document?
I want to work through a document to the end - how do I know when I
have reached the end (programmatically).
Hi, Bob,
The literal answer to this question depends on exactly how you "work through
a document" -- whether you're using the Selection or a Range object, whether
you're advancing one character at a time or one word, sentence, or
paragraph, whether you're inserting, changing or deleting...
You might be able to use something like
If MyRange.End = ActiveDocument.Range.End Then
The better answer is to design your macro so it doesn't have to detect the
end of the document. How you do this depends on what you're doing. In some
cases you can use a For Each loop to do something to each member of a
collection (such as the Paragraphs collection or the Tables collection).
More often, you can use a Find -- either Selection.Find or, better, define a
Range object and use that object's .Find -- to locate each place where you
want to make a change. Word's Find is very powerful and gives you lots of
ways to look for things. In addition to looking for a specific word or
phrase, you can look for formatting, styles, patterns (see
http://word.mvps.org/FAQs/General/UsingWildcards.htm), and more. After
setting up the parameters that determine what you're looking for, you may be
able to do a ReplaceAll, or you may need to do something at each found
location. The "skeleton" of such a macro looks like this:
Sub DoSomething()
Dim MyRange As Range
Set MyRange = ActiveDocument.Range
With MyRange.Find
.ClearFormatting
.Format = False
.Forward = True
.MatchWildcards = False
.Wrap = wdFindStop
.Text = "look for this"
Do While .Execute = True
' MyRange now contains the found text;
' do something with it, such as
MyRange.Words(1).Bold = True
' prepare for next search
MyRange.Collapse Direction:=wdCollapseEnd
Loop
End With
End Sub