Microsoft Word Table Of Contents (ToC) VBA code example

TableOfContents

Refers to a summary of the document based on sections with page numbers. Table of contents can have links to the source topic or section by which user can directly navigate to the source page or section. A standard TOC (Table of contents) can be inserted in a word document by following below steps:

  1. Select the range where you want to put TOC ideally should be start of the document or first page of the document
  2. Navigate Reference tab
  3. Click on Table of Contents button as shown below figure 1.0
  4. Select appropriate template
figure 1.0
figure 1.1

Code example

Public Sub TOC()
    
    'Bind active document reference
    Dim oDocument As Document
    Set oDocument = ActiveDocument
    
    'Bind source range where TOC needs to be created
    Dim oSourceRange As Range
    Set oSourceRange = oDocument.Range(Start:=0, End:=0)
    
    'Create ToC
    Dim oToC As TableOfContents
    Set oToC = oDocument.TablesOfContents.Add(Range:=oSourceRange, UseFields:=True, UseHeadingStyles:=True, LowerHeadingLevel:=2, UpperHeadingLevel:=1)
    
    'Change tab leader
    oToC.TabLeader = wdTabLeaderDashes
    
    'Add hyperlinks
    oToC.UseHyperlinks = True
    'Memory CleanUp
    Set oDocument = Nothing
    Set oSourceRange = Nothing
    Set oToC = Nothing
End Sub

Next>> Understand Table Object a complete reference guide Word Add-in

Leave a Reply

Your email address will not be published. Required fields are marked *