PDA

View Full Version : Updating Tables of Contents only



Roderick
03-16-2019, 07:07 AM
This is a link from a Microsoft forum which is now closed and therefore I'm bringing it into here to continue the conversation:
https://answers.microsoft.com/en-us/msoffice/forum/all/how-to-automatically-update-tables-of-contents/626dabcd-cdc4-4780-a979-82d1a6faefda

I have a template with two TOCs: one does Headings 1-6 whilst the other looks at Headings 7-8; each TOC working in its own purpose.

This is TOC 1:

{ TOC \o "1-6" \z }

...and this is TOC 2:

{ TOC \o "7-8" \n \p "." \z }

What I want to do is to update just the TOCs and not all the rest of the fields in the document.

The link above provides a procedure written by Doug Robbins (thanks Doug) a couple of years back:

Dim toc As TableOfContents
Dim tof As TableOfFigures
With ActiveDocument
.Range.Fields.Update
For Each toc In .TablesOfContents
toc.Update
Next toc
For Each tof In .TablesOfFigures
tof.Update
Next tof
End With

If I insert a Heading 1 title in my document and then run this procedure it updates the TOC - but once only. If I add further Headings, say 2 and 3, and run the procedure again then nothing happens.

It goes to this line and then stops without doing anything:

toc.Update

Is there something I have to adjust to make the TOCs update themselves every time?

Thanks

Roderick

gmaxey
03-16-2019, 03:54 PM
This seems to work here:


Sub ScratchMacro()
'A basic Word macro coded by Greg Maxey
Dim oToc As TableOfContents
For Each oToc In ActiveDocument.TablesOfContents
oToc.Update
Next oToc
lbl_Exit:
Exit Sub
End Sub

Roderick
03-19-2019, 04:38 AM
Thanks, Greg, for the idea. Unfortunately, this does not work either: it always breaks off at toc.Update command line.

There must be something wrong but I cannot spot what is, in essence, a very simple command.

I've got around the problem by re-writing the field each time and that does the trick. Admittedly, there could be a better way but I cannot waste time in trying to resolve the problem if this solution does the trick.

This is the code that I use now:

40 If ActiveDocument.Bookmarks.Exists("ContentsTop") Then
50 ActiveDocument.Bookmarks("ContentsTop").Range.Select
60 With ActiveDocument
70 .TablesOfContents.Add Range:=Selection.Range, RightAlignPageNumbers:= _
True, UseHeadingStyles:=True, LowerHeadingLevel:=6, UpperHeadingLevel:=1, IncludePageNumbers:=True, _
UseHyperlinks:=False, HidePageNumbersInWeb:=True, UseOutlineLevels:=False
80 .TablesOfContents(1).TabLeader = wdTabLeaderDots
90 .TablesOfContents.Format = wdIndexIndent
100 End With
110 End If


Every time I add a Heading 1-6 it calls this procedure and updates the TOC.

Thanks

Roderick