Search code examples
c#ms-wordoffice-interop

Interop: how to iterate over fields in endnotes and footnotes?


I'm iterating over fields in a Word document using

Document document = application.ActiveDocument;
foreach (Field f in document.Fields)
{ ... }

Works great except that it only iterates over field in the body of the document, excluding footnotes and endnotes. How do I include fields in the entire document?


Solution

  • A Word document consists of multiple StoryRanges. Besides footnotes and endnotes there are also headers, footers, Shapes, etc.

    Here's how to explicitly access fields in footnotes:

    foreach (Word.Footnote ftn in document.Footnotes)
    {
        foreach (Word.Field fld in ftn.Range.Fields)
        {
            System.Diagnostics.Debug.Print(fld.Code.Text + ", " + fld.Result.Text);
        }
    }
    

    If you want to access all Stories in the document see the StoryRanges information in the Langauge Reference. There's example code there that shows how you can "hit" all the stories.