I had thought that there were only going to be four screen-casts in this series on adding / updating tables-of-contents in OpenXML WordprocessingML documents. However, I can see that there are now going to be at least six.
In the screen-cast that I present in this post, I show how you can add a TOC using the Open XML SDK, and then modify the normal.dotx, adding a macro, so that whenever you open a document that contains a TOC, Word repaginates the document and updates the TOC. This is an approach that would be useful if, for instance, you have a department of sales engineers who prepare proposals that need a TOC inserted at the beginning of the proposal. You could write a small program that would install the AutoOpen macro, and distribute this program to all members of the department. Alternatively, you could post instructions on an internal web site showing how to add the macro. It is important to note that nothing will go wrong if one of the salespeople does not have the macro. If the macro is not there, then it simply means that the user needs to click on the table of contents and update it by clicking on the content control tab at the top of the TOC.
Here is the complete list of screen-casts in this series.
Explains the markup of tables-of-contents. TOCs use field markup.See Deep dive into OpenXML Fields for more info.
Presents some sample code that shows how to insert TOC markup into a document.
Shows how to use Word Automation to update the TOC.
Shows how to use Word Automation Services to update the TOC.
Shows how to use an AutoOpen macro to update the TOC whenever any document that contains a TOC is opened.
Following is the listing for the AutoOpen macro:
' AutoOpen Macro
' Update the entire first table of contents.
' The TOC must exist or this produces an error.
On Error GoTo DontUpdate
On Error GoTo 0
One key point about this approach: you don't want to set the <w:updateFields val='true'> element in the settings part. If this element is there, then even though there is a macro that will update the TOC, Word will still put up a modal dialog box indicating, "This document contains fields that may refer to other files. Do you want to update the fields in this document." In addition, you do not want to set the w:dirty attribute to true on the <w:fldChar w:fldCharType='begin'/> element.