我正在寻找一种方法,以编程方式将当前部分的标题添加到 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/