Befuddled by Bookmarks

T

TT

I am really becoming confused when it comes to navigating bookmarks. I have
no problem when I reference bookmarks by name, but I run into problems
whenever I try to vavigate based on wdGotoNext, wdGotoAbsolute, wdGotoFirst,
etc. I have a document with 3 bookmarks (the msgbox confirms this when I run
the macro below). However, the code below always returns "The bookmark does
not exist". when it hits the .Goto. What am I missing?

Public Sub macro2()
Dim rng As Range
MsgBox ActiveDocument.Range.Bookmarks.Count
Set rng = ActiveDocument.Range.GoTo(wdGoToBookmark, wdGoToAbsolute, 2)
End Sub
 
J

Jay Freedman

I am really becoming confused when it comes to navigating bookmarks. I have
no problem when I reference bookmarks by name, but I run into problems
whenever I try to vavigate based on wdGotoNext, wdGotoAbsolute, wdGotoFirst,
etc. I have a document with 3 bookmarks (the msgbox confirms this when I run
the macro below). However, the code below always returns "The bookmark does
not exist". when it hits the .Goto. What am I missing?

Public Sub macro2()
Dim rng As Range
MsgBox ActiveDocument.Range.Bookmarks.Count
Set rng = ActiveDocument.Range.GoTo(wdGoToBookmark, wdGoToAbsolute, 2)
End Sub

I think the GoTo method is semi-broken, but I never use it for this
kind of application anyway. This statement does the same thing and is
100% reliable:

Set rng = ActiveDocument.Range.Bookmarks(2).Range

Technically, if the GoTo method worked as documented, it would return
"that represents the start position of the specified item", so you'd
have to follow the Set statement with

rng.Collapse Direction:=wdCollapseStart

to get the same result, but if you really wanted the range of the
entire bookmark then you can omit it.

There is a small wrinkle to this, which you may want to take advantage
of someday... The expression ActiveDocument.Range.Bookmarks(2).Range
returns the range of the second bookmark *by physical location in the
document*, while ActiveDocument.Bookmarks(2).Range returns the range
of the second bookmark *alphabetically by name in the list of
bookmarks*. This difference corresponds to the two sorting orders you
can see in the Insert > Bookmark dialog when you click the "Name" and
"Location" radio buttons.
 

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