none
How to insert a TOC info a Word doc via a macro RRS feed

  • Question

  • I want to write a macro to insert a TOC into a Word doc.  The Word doc contains some text "INSERT TOC HERE".  I want the macro to insert the TOC at that spot in the document (replacing the "INSERT TOC HERE" text).  I'm using Office 2010.

    I'm a newbie at VBA and can't figure out how to do this.  Maybe some smart person on here can show me code that does it?  Doesn't sound difficult, but Microsoft help is utterly useless. 

    Friday, September 6, 2013 10:14 PM

Answers

  • Hi Sean

    Try this to get going:

    1. Select the INSERT TOC HERE text

    2. Insert/Bookmarks, type in a meaningful name, click Add

    3. Start the macro recorder

    4. Insert/Bookmarks, select the Bookmark, GoTo

    5. Insert the TOC of your choice

    6. Stop the macro recorder

    Now UNDO inserting the TOC and run your macro. Does that basically do what you're looking for?


    Cindy Meister, VSTO/Word MVP, my blog

    Saturday, September 7, 2013 8:34 AM
    Moderator

All replies

  • Hi Sean

    Try this to get going:

    1. Select the INSERT TOC HERE text

    2. Insert/Bookmarks, type in a meaningful name, click Add

    3. Start the macro recorder

    4. Insert/Bookmarks, select the Bookmark, GoTo

    5. Insert the TOC of your choice

    6. Stop the macro recorder

    Now UNDO inserting the TOC and run your macro. Does that basically do what you're looking for?


    Cindy Meister, VSTO/Word MVP, my blog

    Saturday, September 7, 2013 8:34 AM
    Moderator
  • Rather than a macro why not use the Insert TOC feature?

    If using a macro, use that feature anyway and incorporate it in your macro. \

    In Word, a Table of Contents is normally a TOC field. You could put that field in where you want to put "Insert TOC Here" and Word will create it on the fly.

    How to create a table of contents in Microsoft Word

    Why use Microsoft Word’s built-in heading styles?

    Complex Documents


    Charles Kenyon Madison, WI

    Sunday, September 8, 2013 9:40 PM
  • Hi Cindy,

    The steps you listed work, however there are some other constraints I didn't mention.  The first constraint is that I want to run this macro on a generated document (generated from another tool).  That tool does not know how to insert bookmarks, fields, etc.  It just knows how to insert text.  So I need the macro to search for the "INSERT TOC HERE" text and select it.

    The second constraint I have is that the macro will be deployed to a team of people.  When I followed your steps the resulting macro I got was:

    Sub Macro1()
        Selection.GoTo What:=wdGoToBookmark, Name:="TOC"
        With ActiveDocument.Bookmarks
            .DefaultSorting = wdSortByName
            .ShowHidden = False
        End With
        Application.Templates( _
            "C:\Users\ststrou\AppData\Roaming\Microsoft\Document Building Blocks\1033\14\Built-In Building Blocks.dotx" _
            ).BuildingBlockEntries("Automatic Table 1").Insert Where:=Selection.Range _
            , RichText:=True
    End Sub

    I think it would be problematic to deploy this macro to others because it refers to "C:\Users\ststrou".

    

    Monday, September 9, 2013 2:38 PM
  • Hi Charles,

    Your suggestion is similar to Cindy's (she suggests inserting a bookmark, whereas you suggest using a field).  Unfortunately the document is generated by a tool that doesn't know how to insert bookmarks or fields - it only knows how to insert text.  That's why I need to search for the special "INSERT TOC HERE" text, select it, then replace it with the inserted TOC.

    Monday, September 9, 2013 2:42 PM
  • Hi Sean

    If you have to search for specific text, then, again, record a macro that searches the text to get the first step. Then please post it here so that we're all "on the same wavelength" :-)

    I tend to forget that people will often use the pre-formatted entries offered by the Ribbon, which is why you're getting the BuildingBlock saved in an outside source.

    If you use the "Insert Table of Contents" entry, further down the list that works via a dialog box and set options there (test first, then record a macro) do you 1) get an acceptable result and 2) get more "neutral" code? (Note: you should be able to see (and edit) the field code that maintains the TOC by using Alt+F9 to toggle the field code view.)


    Cindy Meister, VSTO/Word MVP, my blog

    Monday, September 9, 2013 3:02 PM
    Moderator
  • Hi Cindy,

    I tried recording the search part but the macro recorder doesn't record those steps.  Specifically, I turned in recording then did "Find", then entered the text to search for, then selected the text, then inserted the TOC, then stopped the recording.  In the resulting macro it only had the line for inserting the TOC (didn't record the other steps).

    As for your suggestion about using "Insert Table of Contents", that worked.  The resulting code is more "neutral", as you put it.  Here is that code, for reference:

    Sub Macro3()
        With ActiveDocument
            .TablesOfContents.Add Range:=Selection.Range, RightAlignPageNumbers:= _
                True, UseHeadingStyles:=True, UpperHeadingLevel:=1, _
                LowerHeadingLevel:=3, IncludePageNumbers:=True, AddedStyles:="", _
                UseHyperlinks:=True, HidePageNumbersInWeb:=True, UseOutlineLevels:= _
                True
            .TablesOfContents(1).TabLeader = wdTabLeaderDots
            .TablesOfContents.Format = wdIndexIndent
        End With
    End Sub

    Monday, September 9, 2013 3:57 PM
  • Hi Sean

    Recording Find actions: Use the "Advanced Find" option from the drop down list (small arrow next to the magnifying glass).


    Cindy Meister, VSTO/Word MVP, my blog

    Monday, September 9, 2013 5:51 PM
    Moderator
  • Hi Cindy,

    That worked!  Below is the complete macro:

    Sub InsertTOC()
        Selection.Find.ClearFormatting
        With Selection.Find
            .Text = "INSERT TOC HERE"
            .Replacement.Text = ""
            .Forward = True
            .Wrap = wdFindContinue
            .Format = False
            .MatchCase = False
            .MatchWholeWord = False
            .MatchWildcards = False
            .MatchSoundsLike = False
            .MatchAllWordForms = False
        End With
        Selection.Find.Execute
        With ActiveDocument
            .TablesOfContents.Add Range:=Selection.Range, RightAlignPageNumbers:= _
                True, UseHeadingStyles:=True, UpperHeadingLevel:=1, _
                LowerHeadingLevel:=3, IncludePageNumbers:=True, AddedStyles:="", _
                UseHyperlinks:=True, HidePageNumbersInWeb:=True, UseOutlineLevels:= _
                True
            .TablesOfContents(1).TabLeader = wdTabLeaderDots
            .TablesOfContents.Format = wdIndexIndent
        End With
    End Sub
    When I run this, it finds the "INSERT TOC HERE" text and replaces it with the TOC.  Thanks!
    Monday, September 9, 2013 6:25 PM
  • One follow-up question ... when I insert an automatic TOC it includes a label of "Contents" or "Table of Contents" above the table itself, which I like the look of.  It looks like the label is part of the TOC somehow.  But when I insert it via the "Insert Table of Contents" command I don't get any label above it, and don't see any way to specify a label on the TOC dialog.  Is there a way to specify the label for the TOC?  Or should I just insert some text above the TOC myself?

    Thanks.

    Monday, September 9, 2013 6:33 PM
  • You need to insert the text above the TOC yourself when you use the "neutral" approach.

    After Selection.Find.Execute try putting the following line in your code (which you can, of course, edit)...

    Selection.Text = "Table of Contents"


    Cindy Meister, VSTO/Word MVP, my blog

    Monday, September 9, 2013 6:47 PM
    Moderator
  • Hi all,

    Another question regarding this.  I've noticed that if I run the macro and the string I'm searching for is not found, it inserts the TOC at the end of document (presumably where the search ended).  Instead I'd like it to not insert the TOC at all if the string is not found.  I tried adding a check around the Selection.Find.Execute command, e.g:

    if ( Selection.Find.Found = True ) then

        Selection.Find.Execute ...

    But that didn't work.  With that check added the macro never inserts the TOC, even if the string is found.  Clearly I don't understand something basic here (no pun intended :-)  Can someone help me?

    Monday, September 23, 2013 10:50 PM