vbams-wordword-automation

Programmatically adding section titles in the header of a MS Word document


I am looking for a way to programmatically add the title of the current section into the header of each page in a word document. I have found this page that explains how to access and modify the header. My understanding after reading this link is that to have something different on each page you need to add the right field. Now I have been looking for this field without success. This other page gives a list of fields, and wdFieldSection looked very promising but it didn't work in my document (it adds "1" on each page).


Solution

  • The direct (and recommended) way to achieve this is to use a STYLEREF field in the header pointing to the style used to format your section titles.

    Another option which gives you more flexibility is to add a cross reference to the respective content. The example below adds a (hidden) bookmark around the section title and then adds a cross reference to that bookmark in the header (if you need any particular headers for first/even/odd pages you need to adjust accordingly):

    Sub AddSectionTitlesToHeader()
    
        Dim oSection As Section
    
        For Each oSection In ActiveDocument.Sections
            Dim oRangeTitle As Range
            Dim oRangeHeader As Range
            Dim bmName As String
    
            ' make sure to use a different header for each section
            oSection.PageSetup.DifferentFirstPageHeaderFooter = False
            oSection.PageSetup.OddAndEvenPagesHeaderFooter = False
            oSection.Headers(wdHeaderFooterPrimary).LinkToPrevious = False
    
            ' add a bookmark around the section title
            ' (this assumes the title is in the section's
            ' first paragraph, adjust accordingly)
            Set oRangeTitle = oSection.Range.Paragraphs.First.Range
            bmName = "_bmSectionTitle" & oSection.Index
            oRangeTitle.Bookmarks.Add bmName, oRangeTitle
    
            ' add a cross reference in the header
            Set oRangeHeader = oSection.Headers(wdHeaderFooterPrimary).Range
            oRangeHeader.InsertCrossReference _
                ReferenceType:=WdReferenceType.wdRefTypeBookmark, _
                ReferenceKind:=WdReferenceKind.wdContentText, _
                ReferenceItem:=bmName
        Next
    
    End Sub