Search code examples
vbams-word

How to update a Table of Tables with macro vba-Word?


I'm a beginner in word-vba macros (but I quite good for excel-vba) and I'm looking to update a "Table of Tables". I've found out how to do so for "Table of Content" and "Table of Figures" (with ActiveDocument.TablesOfContents(1).Update) but the Collection TableOfTables doesn't exist. Does someone know what I have to do?

Thanks in advance,


Solution

  • There isn't a "Table of Tables" object or a TableOfTables collection. A "Table of Tables" is really just a kind of "Table of Contents". Indeed, so too is a "Table of Figures". If you look at the field codes underlying these, you'll see all three use a TOC field - a "Table of Tables" and a "Table of Figures" would have field codes like { TOC \h \z \c "Table" } and { TOC \h \z \c "Figure" }, respectively. So, if you want to update any of these (or any custom types you create), but not necessarily all, you can simply loop through the TableOfContents collection and check what follows the \c switch, if present. Likewise, you can loop through the TableOfContents collection and update all items in it. Hence:

    Sub Demo()
    Application.ScreenUpdating = False
    Dim TOC As TableOfContents
    For Each TOC In ActiveDocument.TablesOfContents
      TOC.Update
      'Or depending on what you want to update:
      'TOC.UpdatePageNumbers
    Next
    Application.ScreenUpdating = True
    End Sub
    

    A simpler way - for all fields - would be:

    Sub Demo()
    Application.ScreenUpdating = False
    With ActiveDocument
      .Fields.Update
      .PrintPreview
      .ClosePrintPreview
    End With
    Application.ScreenUpdating = True
    End Sub