Inserting text at a bookmark without deleting the bookmark
Article contributed by Dave Rado
The problem
The following line:
ActiveDocument.Bookmarks("BookmarkName").Range.Text = "Hello world"
deletes the bookmark.
Using the InsertAfter or InsertBefore method doesn't work satisfactorily either; if the bookmark is currently empty, then the line:
ActiveDocument.Bookmarks("Temp").Range.InsertAfter "Hello world"
will leave you with the bookmark at the start of the text you've just
inserted, rather than containing it. And if the bookmark already contains
some text, then “Hello world”
will be appended to the existing text, instead of replacing it.
The solution
The best way to insert text at a bookmark without losing the
bookmark – which works reliably whether or not the bookmark currently encloses
any text - is to set a range variable to the bookmark's range, as follows:
Dim BMRange As Range
'Identify current Bookmark range and insert text
Set BMRange = ActiveDocument.Bookmarks("MyBookmark").Range
BMRange.Text = "Hello world"
'Re-insert the bookmark
ActiveDocument.Bookmarks.Add "MyBookmark", BMRange
If you have a macro which updates many bookmarks (for example, a userform macro), then repeating the above code over and over again would be very laborious, so the best plan is to call a subroutine with arguments as in the following example:
Sub UpdateBookmark(BookmarkToUpdate As String,
TextToUse
As String)
Dim BMRange
As Range
Set BMRange =
ActiveDocument.Bookmarks(BookmarkToUpdate).Range
BMRange.Text = TextToUse
ActiveDocument.Bookmarks.Add BookmarkToUpdate, BMRange
End Sub
You could call it like this:
UpdateBookmark "NameOfBookMark", "String you want to insert"
See also Working with Bookmarks in VBA.