Getting the best out of bookmarks in Microsoft Word

Suppose you have a .NET application that needs to open a Word document and insert data from a database or from an XML file. To provide this functionality, Microsoft Word documents contain bookmarks, a set of “placeholders” that allow you to insert text at design time and runtime. I want to share with you some guidelines that I use to work with bookmarks:

To go to a particular location and insert text, you can create your own bookmarks using the Boomark object. You can also take advantage of the set of prefedined bookmarks to go to a particular location in a document. For example, to insert text at the end of a document, you can do something like:

private object _endOfDoc “\\endofdoc”;
Word.Range _rng doc.Bookmarks.get_Item(ref _endOfDoc).Range;
_rng.Text “Bookmark demo”;

There are times when you have a huge document and you get lost with all the bookmarks that you might have, or like me, you create some bookmarks and forget or mispell the names you defined for the bookmarks (doh!) while coding. You can use the following snippet of code to get a list of all the bookmarks that you have in your document:

public void ListBookmarks()
    StringWriter sw 
= new StringWriter();

(Word.Bookmark bookmark in Word.Application.ActiveDocument.Bookmarks)
“Name: {0}, Contents: {1}”, bookmark.Name, bookmark.Range.Text);
“Bookmarks and Contents”);

You should also explore the “Bookmark View Controls” provided by Visual Studio Tools for Office v2.0. Take a look at this cool video created by Paul Stub and learn more about bookmarks.

Happy bookmark programming!

Comments (3)

  1. paul dewhurst says:

    your "create your own bookmarks" link does not go anywhere, the link has changed, it redirects you to another link that does not exist as well. This makes your page here a waste of time, please check your pages for bad links and stop clogging up the internet

  2. Scot says:

    Shut up, Paul. You’re looking at a page that’s nearly two years old and expecting links to be correct after all this time? That’s like a gajillion years old at the rate the internet changes. Links change and people don’t review their old work over and over and over again to update it constantly.

    Deal with it and stop being an inter-snob.

  3. Scott says:

    Nice manners Scot.  Learn how to spell your name.