Dan
Dan

Reputation: 7724

Updating table of contents in word

I have a macro for my word document which is meant to update all the fields and all the table of contents.

Sub UpdateFields()
    Dim oStory As Range
    For Each oStory In ActiveDocument.StoryRanges
        oStory.Fields.Update
        If oStory.StoryType <> wdMainTextStory Then
            While Not (oStory.NextStoryRange Is Nothing)
                Set oStory = oStory.NextStoryRange
                oStory.Fields.Update
            Wend
        End If
    Next oStory
    Set oStory = Nothing

    Dim TOC As TableOfContents
    For Each TOC In ActiveDocument.TablesOfContents
        TOC.Update
    Next
End Sub

However, when it is run I get this error.

enter image description here
Error and then debug below
I would appreciate any help in fixing the problem.

Upvotes: 3

Views: 5668

Answers (2)

Variatus
Variatus

Reputation: 14373

The error thrown indicates that the TableOfContents specified for update doesn't exist. Word will produce errors of this type when using For ... Each loops to access some of its collections. The number of TOCs Word is aware of may have changed while editing the document. To avoid the error, avoid For ... Each enumerations. Use code like the following instead.

Dim i As Integer

With ActiveDocument
    For i = 1 To .TablesOfContents.Count
        .TableOfContents(i).Update
    Next i
End With

Upvotes: 0

joeschwa
joeschwa

Reputation: 3175

The issue is caused by naming the sub UpdateFields. For unknown reasons this name is reserved in Word VBA. Rename the sub to an allowed name (for example, FieldUpdates) and the code will work fine.

Upvotes: 6

Related Questions