My Technical Notes

Tuesday, 10 March 2015

Updating all fields in Word document

The following code works in Word 2010:

'' Update all the fields, indexes, etc. in the specified document.
Sub UpdateAllFieldsIn(doc As Document)
    '' Update tables. We do this first so that they contain all necessary
    '' entries and so extend to their final number of pages.
    Dim toc As TableOfContents
    For Each toc In doc.TablesOfContents
    Next toc
    Dim tof As TableOfFigures
    For Each tof In doc.TablesOfFigures
    Next tof
    '' Update fields everywhere. This includes updates of page numbers in
    '' tables (but would not add or remove entries). This also takes care of
    '' all index updates.
    Dim sr As range
    For Each sr In doc.StoryRanges
        While Not (sr.NextStoryRange Is Nothing)
            Set sr = sr.NextStoryRange
            '' FIXME: for footnotes, endnotes and comments, I get a pop-up
            '' "Word cannot undo this action. Do you want to continue?"
    Next sr
End Sub
'' Update all the fields, indexes, etc. in the active document.
'' This is a parameterless subroutine so that it can be used interactively.
Sub UpdateAllFields()
    UpdateAllFieldsIn ActiveDocument
    MsgBox "All fields updated"
End Sub

No comments: