Erika Ehrli - Adventures with Office Products & Technologies
MSDN & TechNet: Releasing Office, SharePoint, Exchange & Lync Centers and content for developers and IT professionals.

Getting the best out of bookmarks in Microsoft Word

Getting the best out of bookmarks in Microsoft Word

  • Comments 3

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();

    foreach 
(Word.Bookmark bookmark in Word.Application.ActiveDocument.Bookmarks)
    {
        sw.WriteLine(
"Name: {0}, Contents: {1}", bookmark.Name, bookmark.Range.Text);
    
}
    MessageBox.Show(sw.ToString(), 
"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!

Leave a Comment
  • Please add 5 and 1 and type the answer here:
  • Post
  • 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

  • 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.

  • Nice manners Scot.  Learn how to spell your name.

Page 1 of 1 (3 items)