Using Word Automation to Update Word's Table of Contents

Tuesday, January 23, 2007 11:11:23 PM (Central Standard Time, UTC-06:00)

This one took a while to figure out... so I thought I would post it for others.  So the problem was I am building a document using the Word Automation model within C#.  When I inserted text that had styles defined for the TOC (Header 1 for example) I couldn't get the new header text to appear in the TOC contents in my final document output.

My usual approach of recording a macro in Word and then reviewing the VBA code resulted in the followin:

Sub Macro2()
'
' Macro2 Macro
'
'

WordBasic.UpdateTableOfContents
End Sub

But there was no indication of how to "Update entire table", like the option shown in the UI.  No matter what I indicated it was always the same code as shown above.

I saw other approaches online that cycled through the Fields collection and called update, but again there was not option for "Update Entire Table".  When I tried it, it didn't update the TOC with the header 1 text I had just added to the document.

After digging a around a bit more I finally figured it out:

Word.Application _wordApp;

internal void UpdateTOC()
{
//cycle through all of the TOC's and Update them
foreach (Word.TableOfContents contents in _wordApp.Application.ActiveDocument.TablesOfContents)
{
contents.Update();
}
}