Find the index of selected bookmark (Wd 2002 +)

I

Ian B

I have a bookmark spanning a selection.
I place the insertion point within the bookmark.
I need to use VBA to determine the name of the bookmark containing the
insertion point.
Sounds simple, but I can't get the index, which I need to get the name.
As a last resort I could note the range of insertion point, and search all
bookmarks for one spanning that range, but that's a bit "heavy".
Any help much appreciated

TIA

Ian B
 
S

Shauna Kelly

Hi Ian

ActiveDocument.bookmarks(1) refers to the first bookmark in the document. If
there are no bookmarks in the document it will return Nothing.

Selection.Bookmarks(1) refers to the first bookmark within the selection. If
there are no bookmarks in the Selection it will return Nothing.

So something like this will work:

Sub PlayWithBookmarks()

Dim BM As Word.Bookmark

'If there are any bookmarks at the selection, then ...
If Selection.Bookmarks.Count > 0 Then

'... get the first bookmark within the selection
Set BM = Selection.Bookmarks(1)

'Tell the user the name of the bookmark
MsgBox BM.Name

End If

'You can test to see if BM is a bookmark
If BM Is Nothing Then
'there was no bookmark at the selection
Else
'Do something with the bookmark,
'eg, make the range of the bookmark pink
BM.Range.Font.Color = wdColorRose
End If

End Sub


Have a look at Word's VBA help at the Bookmarks property for more examples
and explanation.

Hope this helps.

Shauna Kelly. Microsoft MVP.
http://www.shaunakelly.com/word
 
I

Ian B

Thanks Shauna

You're a "Champ".
Does the job very simply.
Also works with Comments collection.

Tks again

Ian B
 
F

fumei via OfficeKB.com

Just as ab added comment, the Bookmarks collection is dynamic and tied to the
PARENT object.

Say you have a document with three boomarks: One, Two Three

ActiveDocument.Bookmarks will have the order in the collection as:

One
Three
Two

As ActiveDocument.Bookmarks will be in alphabetical order. Even if you set
it for Location.

ActiveDocument.RANGE.Bookmarks will have the collection order as:

One
Two
Three

as the collection is set to the PARENT object.

ActiveDocument.Bookmarks are for the document, and so the order is
alphabetical. (One, Two, Three). If you moved Three to be the first bookmark,
ActiveDocument.Bookmarks would have the order as still One, Three, Two -
alphabetical.

ActiveDocument.Range.Bookmarks are for the range, and range is always
location. So, One, Two, Three. If you move Three to be the first bookmark,
Range.Bookmarks order would be Three, One, Two - the actual order in the
Range.
 

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