Word AutoOpen Macro that will ignore Table of Contents RRS feed

  • Question

  • I have a document that has meta datastamped in it that I use an auto open macro to update the fields.  The issue that I'm running in to is there is a group of documents that are starting to show up that have a table of contents that is causing  to crash when the auto open macro reaches the TOC.  I'm wondering if there is an adjustment I can make to the macro that will ignore a Table of contents.

    Here is the current macro

    Sub AutoOpen()
    Dim aStory As Range
    Dim aField As Field
    For Each aStory In ActiveDocument.StoryRanges
    For Each aField In aStory.Fields
    Next aField
    Next aStory
    End Sub

    Thanks in advance.

    • Edited by MCCameronL Friday, December 9, 2016 10:19 PM
    Friday, December 9, 2016 9:54 PM

All replies

  • It seems to me your code could be reduced to:

    Sub AutoOpen()
    Application.ScreenUpdating = False
    Dim aStory As Range
    For Each aStory In ActiveDocument.StoryRanges
    Next aField
    Application.ScreenUpdating = True
    End Sub

    That said, if you want to avoid updating TOC fields, you might use code like:

    Sub AutoOpen()
    Application.ScreenUpdating = False
    Dim i As Long, aField As Field
    With ActiveDocument
      For Each aField In .Range.Fields
        If aField.Type <> wdFieldTOC Then aField.Update
      Next aField
      For i = 2 To 11
      Next i
    End With
    Application.ScreenUpdating = True
    End Sub

    Paul Edstein
    [MS MVP - Word]

    • Edited by macropodMVP Saturday, December 10, 2016 2:55 AM
    • Proposed as answer by Charles Kenyon Sunday, December 11, 2016 12:19 AM
    Saturday, December 10, 2016 2:53 AM
  • Thanks Paul for the solution.

    Hi MCCameronL,

    Just a gentle reminder, here we mainly focus on Office client related question and feedback. For macro related question, you might want to post in our dedicated "Word for Developer" forum, that's where most of the experts hang out:


    The reason why we recommend posting appropriately is you will get the most qualified pool of respondents, and other partners who read the forums regularly can either share their knowledge or learn from your interaction with us. Thank you for your understanding.


    Ethan Hua

    Please remember to mark the replies as answers if they helped.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.

    Monday, December 12, 2016 6:33 AM