Consulting

Results 1 to 7 of 7

Thread: Code to create table of contents

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    VBAX Contributor
    Joined
    Jun 2004
    Location
    Texas
    Posts
    139
    Location

    Code to create table of contents

    Hi, all,

    Let me see if I can explain this clearly. I want my code to create a Table of Contents including all items in a style I've defined, SectionTitle, but I do NOT want the TOC to include any of the standard header styles. It works correctly when I do it manually, but I can't seem to make this work correctly from code.

    In my Word document, I manually created a TOC including Header 1 and my SectionTitle style. Then I manually created a TOC excluding Header 1 and including only my SectionTitle style. I used the Macro Recorder to trap and compare the code:

     ' TOC includes Header1 AND SectionTitle styles
    With ActiveDocument
        .TablesOfContents.Add Range:=Selection.Range, RightAlignPageNumbers:= _
        True, UseHeadingStyles:=True, UpperHeadingLevel:=1, _
        LowerHeadingLevel:=1, IncludePageNumbers:=True, AddedStyles:= _
        "SectionTitle,1", UseHyperlinks:=True, HidePageNumbersInWeb:=True, _
        UseOutlineLevels:=False
        .TablesOfContents(1).TabLeader = wdTabLeaderDots
        .TablesOfContents.Format = wdIndexIndent
    End With
    
    ' TOC includes ONLY SectionTitle styles
    With ActiveDocument
        .TablesOfContents.Add Range:=Selection.Range, RightAlignPageNumbers:= _
        True, UseHeadingStyles:=False, IncludePageNumbers:=True, AddedStyles _
        :="SectionTitle,1", UseHyperlinks:=True, HidePageNumbersInWeb:=True, _
        UseOutlineLevels:=False
        .TablesOfContents(1).TabLeader = wdTabLeaderDots
        .TablesOfContents.Format = wdIndexIndent
    End With
    I tried using the second piece of code (I'm working from Access VBA), but the resulting TOC still includes text formatted with the Header1 style as well as the SectionText style. I can't determine what Word is interpreting during manual creation that I'm not managing to tell it during automated creation.

    I'd appreciate any insights. Please let me know if I haven't explained my problem clearly enough.

    Thanks!!!
    ~eed
    Last edited by Aussiebear; 03-03-2025 at 02:47 AM.
    With program specs this fickle, you've just got to believe in Discord.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •