Monday, February 8, 2010

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.

Thanks!

No comments: