Call InsertTableOfContents to insert a TOC (table of contents) field into the document at the current position.
A table of contents in a Word document can be built in a number of ways and formatted using a variety of options. The field switches that you pass to the method control the way the table is built and displayed by Microsoft Word.
How should the necessary switches be obtained? The easiest way to specify the switches is to insert and configure a table of contents into a Word document first.
- In the Insert menu, click Reference - Index and Tables.
- Switch to the Table of Contents tab of the Index and Tables dialog and insert the table of contents.
- Switch display of field codes on to see the switches. You can press Alt+F9 in Microsoft Word to toggle display of field codes on or off.
For example, after creating a table of contents, the following field is inserted into the document: { TOC \o "1-3" \h \z \u }. You can copy \o "1-3" \h \z \u and use it as the method parameter.
Note that InsertTableOfContents will only insert a TOC field, but will not actually build the table of contents. Microsoft Word builds the table of contents when the field is updated. If you insert a table of contents using this method and then open the file in Microsoft Word, you will not see the table of contents because the TOC field has not yet been updated. In Microsoft Word, fields are not automatically updated when a document is opened, but you can update fields in a document at any time by pressing F9.
To make Microsoft Word automatically update the TOC on open, you can add the following macro to your document using Microsoft Word's Visual Basic editor:
[VBA]
Private Sub Document_Open()
Selection.WholeStory
Selection.Fields.Update
End Sub
Example DocumentBuilderInsertTOC
Shows how to insert a Table of Contents field into a document.
[C#]
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.InsertTableOfContents("\\o \"1-3\" \\h \\z \\u");
[Visual Basic]
Dim doc As Document = New Document()
Dim builder As DocumentBuilder = New DocumentBuilder(doc)
builder.InsertTableOfContents("\o ""1-3"" \h \z \u")
[Java]
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.insertTableOfContents("\\o \"1-3\" \\h \\z \\u");