Replace bookmarks content without removing the bookmark

Viewed 2254

I want to replace the text content of bookmarks without loosing the bookmark.

foreach(Bookmark b in document.Bookmarks)
{
    b.Range.Text = "newtext";  // text is set in document but bookmark is gone
}

I tried to set the new Range of the bookmark before the Text setting but I still have the same problem.

I also tried to re-add the bookmark with document.Bookmarks.Add(name, range); but I can't create an instance of range.

3 Answers

With the above approach, you still lose the bookmark before it is added back in. If you really need to preserve the bookmark, I find that you can create an inner bookmark that wraps around the text (a bookmark within bookmark). After having the inner bookmark, you simply need to do:

innerBookmark.Range.Text = newText;

After the text replacing, the inner bookmark is gone and the outer bookmark is preserved. No need to set range.End.

You can create the inner bookmark manually or programmatically depending on your situation.

Related