Search code examples
ms-wordvstooffice-interopoffice-addinsword-interop

VSTO Word Office Interop: Find References to Bookmark


Given a selection in Word which contains a Bookmark - e.g. a heading such as this (this is inside the SelectionChange event):

var selectionWithBookmark = e.Selection.Bookmarks.Cast<dynamic>().Select(b => b.Range as Range).FirstOrDefault();

How do I find all cross-references (i.e. Type == WdFieldType.wdFieldRef) in the document that refer to this bookmark?

I would like to find not just the Fields themselves, but the paragraphs containing those fields as well.

Looking for answers in either C# or VB.

I can loop/iterate all references in the document, but there is no way to link them to the Bookmark (aside from the Code property - but the REF number doesn't actually exist on the bookmark either from what I can see). What it is missing is some form of Target property that I can compare to the bookmark itself.


Solution

  • The following statement in the question makes me wonder...

    the REF number doesn't actually exist on the bookmark either from what I can see.

    The bookmark name should contain the REF number, but it will be preceded by an underscore _ so the name won't show up in the UI by default.

    In the Bookmarks dialog box there's a little checkbox "Hidden bookmarks": click it two, three times and a list should show up, as illustrated in the following screen shot.

    Bookmarks dialog with REF number

    Debug.Print(bookmark.Name) should also show this.

    Once the bookmark name is known, it shouldn't be difficult to locate the corresponding REF fields.