Working with Bookmarks in VBA
Article contributed by Ibby
Types of Bookmarks
The most important thing you need to know when working with bookmarks in Word is that there are two “types” of bookmarks – “placeholder” bookmarks and “enclosing” bookmarks.
Before we proceed, and whenever you work with bookmarks, you should turn on display of bookmarks by going to Tools | Options | View and selecting “Bookmarks”. This makes it easier to see what's actually happening.
(1) Placeholder Bookmarks
If you click somewhere in the document and insert a bookmark it will look
like a beam
I
– this is a “placeholder”
bookmark.
(2) Enclosing Bookmarks
Now, if you select some text and insert a bookmark it will look like the
selected text is enclosed in square brackets ie: [selected text] –
this is an
“enclosing”
bookmark.
Inserting and retrieving text from a Bookmark
There are several methods of inserting text at/into a bookmark. The method you use depends on whether you need to retrieve the text from the bookmark at a later time.
Lets look at the more obvious ways of inserting text at a bookmark.
ActiveDocument.Bookmarks("myBookmark").Range.Text = "Inserted Text"
If the bookmark is a placeholder bookmark, the inserted text will look like this:
I Inserted Text
If the bookmark is an enclosing bookmark, it will be deleted, and the inserted text will appear in it's place.
ActiveDocument.Bookmarks("myBookmark").Range.InsertBefore _
"Inserted Text"
ActiveDocument.Bookmarks("myBookmark").Range.InsertAfter _
"Inserted Text"
With both these methods, if the bookmark is a placeholder bookmark, the text will be inserted after the bookmark:
I Inserted Text
With enclosing bookmarks (even if the bookmark only encloses a space), the following occurs:
InsertAfter – [
Original Text
]
Inserted Text
InsertBefore – [
Inserted Text
Original Text
]
In order to retrieve the text in a bookmark, the bookmark needs to be
an enclosing bookmark. Then you can use the following to retrieve the text
from the bookmark:
strBookmark = ActiveDocument.Bookmarks("myBookmark").Range.Text
You have already seen how to add text to an enclosing bookmark using the InsertBefore method above. But what if you want to insert text into a placeholder bookmark (making it an enclosing bookmark) so that you can retrieve the text from it at a later time ? And what if the bookmark is already an enclosing bookmark but you want to replace the text inside it ? There is no single command in VBA to achieve this. What you need to do is replace the bookmark with the inserted text (the bookmark is deleted), then re-create the bookmark around the inserted text. The following code is an example of how this is done:
Dim bmRange As Range
Set bmRange =
ActiveDocument.Bookmarks("myBookmark").Range
bmRange.Text = "Inserted Text"
ActiveDocument.Bookmarks.Add _
Name:="myBookmark", _
Range:=bmRange
See also Inserting text at a bookmark without deleting the bookmark