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

标签 vba ms-word word-automation

我正在寻找一种方法,以编程方式将当前部分的标题添加到 Word 文档中每个页面的页眉中。我找到了this page这解释了如何访问和修改 header 。阅读此链接后,我的理解是,要在每个页面上都有不同的内容,您需要添加正确的字段。现在我一直在寻找这个领域,但没有成功。 This other page给出了一个字段列表,wdFieldSection看起来很有希望,但它在我的文档中不起作用(它在每页上添加“1”)。

最佳答案

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

另一个为您提供更大灵活性的选项是添加对相应内容的交叉引用。下面的示例在章节标题周围添加一个(隐藏)书签,然后在页眉中添加对该书签的交叉引用(如果您需要第一页/偶数页/奇数页的任何特定页眉,则需要进行相应调整):

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

关于vba - 以编程方式在 MS Word 文档的标题中添加节标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37784467/

相关文章:

c# - 从保存对话框中捕捉取消状态,以获取即将关闭且未保存更改的 MS Word 文档

c# - OpenXML 将段落样式(Heading1、Heading2、Head 3 等)添加到文字处理文档

vba - excel:带有 protected 工作表的高级过滤器

excel - 使用VBA excel在ppt中创建文本框

python - Python 中 Excel 单元格中不需要的字符

vb.net - 使用 .NET 实现 Word 自动化 - 单一横向页面

c# - 使用互操作将多个单词表添加到单词中

excel - 在vba中使用AND条件

vba - 将范围从单元格内传递到自定义函数

vba - 识读文档中的每个单词并将其替换为该单词的第一个字母