以编程方式在 MS Word 文档的 header 中添加章节标题

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

我正在寻找一种方法,以编程方式将当前部分的标题添加到 word 文档中每个页面的 header 中。我发现 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 给出了一个字段列表,wdFieldSection 看起来很有前途,但它在我的文档中不起作用(它在每个页面上添加了“1”)。

实现此目的的直接(推荐)方法是在 header 中使用 STYLEREF 字段,指向用于格式化章节标题的样式。

另一个为您提供更大灵活性的选项是添加对相应内容的交叉引用。下面的示例在部分标题周围添加了一个(隐藏的)书签,然后在 header 中添加对该书签的交叉引用(如果您需要 first/even/odd 页面的任何特定 headers相应调整):

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