VBA Word Snippets
All codes at your own riskCreate a TOC (table of content)
Creating a TOC in Word is quite easy but has its pitfalls when you update it. This is because Word always adds new bookmarks to the target addresses - in our case headings. This means that there can quickly be many bookmarks around a single heading.
Here is a small script to create a table of contents at the place of selection and to dispose of an existing table of contents beforehand and to mercilessly delete existing _TOC* bookmarks.
The script can be adapted to your own requirements, especially with regard to the properties.
See also at Microsoft: TablesOfContents.Add method (Word)
Sub CreateTableOfContents()
' Uses the active document
' Deletes an existing TOC, removes all _TOC Bookmarks and creates a new TOC at selection
Dim doc As Document
Dim toc As TableOfContents
Set doc = ActiveDocument
On Error Resume Next
doc.TablesOfContents(1).Delete
On Error GoTo 0
RemoveTocMarks doc
Dim tocRange As Range
Set tocRange = Selection.Range
Set toc = doc.TablesOfContents.Add(Range:=tocRange, _
UseHeadingStyles:=True, _
UpperHeadingLevel:=1, _
LowerHeadingLevel:=2, _
UseHyperlinks:=True, _
HidePageNumbersInWeb:=True, _
UseOutlineLevels:=False, _
IncludePageNumbers:=False, _
TableID:="Formal")
toc.Update
End Sub
Private Sub RemoveTocMarks(doc As Document)
' Removes all bookmarks starting with _Toc
' be sure you want this
Dim bm As Bookmark
Dim show As Boolean
show = doc.Bookmarks.ShowHidden
doc.Bookmarks.ShowHidden = True
For Each bm In doc.Bookmarks
If Left(bm.Name, 4) = "_Toc" Then
bm.Delete
End If
Next bm
doc.Bookmarks.ShowHidden = show
End Sub