可以使用 Section 的 Headers 属性和 Footers 属性向文档中的页眉和页脚添加文本。 文档的每一部分都包含三个页眉和页脚:
对于文档级自定义项和应用程序级外接程序,这些过程有所不同。
**适用于:**本主题中的信息适用于 Word 2007 和 Word 2010 的文档级项目和应用程序级项目。有关更多信息,请参见按 Office 应用程序和项目类型提供的功能。
文档级自定义项
若要使用以下各代码示例,请从项目内的 ThisDocument 类运行这些示例。
向文档中的页脚添加文本
下面的代码示例设置要插入到文档各部分主页脚中的文本的字体,然后将文本插入到页脚中。
For Each section As Word.Section In Me.Sections Dim footerRange As Word.Range = section.Footers(Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range footerRange.Font.ColorIndex = Word.WdColorIndex.wdDarkRed footerRange.Font.Size = 20 footerRange.Text = "Confidential" Next
foreach (Word.Section wordSection in this.Sections) { Word.Range footerRange = wordSection.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range; footerRange.Font.ColorIndex = Word.WdColorIndex.wdDarkRed; footerRange.Font.Size = 20; footerRange.Text = "Confidential"; }
向文档中的页眉添加文本
下面的代码示例添加一个字段以在文档中的每个页眉中显示页码,然后设置段落对齐方式以使文本与页眉呈右对齐。
For Each section As Word.Section In Me.Sections Dim headerRange As Word.Range = section.Headers(Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range headerRange.Fields.Add(headerRange, Word.WdFieldType.wdFieldPage) headerRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight Next
foreach (Word.Section section in this.Sections) { Word.Range headerRange = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range; headerRange.Fields.Add(headerRange, Word.WdFieldType.wdFieldPage); headerRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight; }
应用程序级外接程序
若要使用以下各代码示例,请从项目内的 ThisAddIn 类运行这些示例。
向文档中的页脚添加文本
下面的代码示例设置要插入到文档各部分主页脚中的文本的字体,然后将文本插入到页脚中。 此代码示例使用活动文档。
For Each section As Word.Section In Me.Application.ActiveDocument.Sections Dim footerRange As Word.Range = section.Footers(Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range footerRange.Font.ColorIndex = Word.WdColorIndex.wdDarkRed footerRange.Font.Size = 20 footerRange.Text = "Confidential" Next
foreach (Word.Section wordSection in this.Application.ActiveDocument.Sections) { Word.Range footerRange = wordSection.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range; footerRange.Font.ColorIndex = Word.WdColorIndex.wdDarkRed; footerRange.Font.Size = 20; footerRange.Text = "Confidential"; }
向文档中的页眉添加文本
下面的代码示例添加一个字段以在文档中的每个页眉中显示页码,然后设置段落对齐方式以使文本与页眉呈右对齐。 此代码示例使用活动文档。
For Each section As Word.Section In Me.Application.ActiveDocument.Sections Dim headerRange As Word.Range = section.Headers(Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range headerRange.Fields.Add(headerRange, Word.WdFieldType.wdFieldPage) headerRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight Next
foreach (Word.Section section in this.Application.ActiveDocument.Sections) { Word.Range headerRange = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range; headerRange.Fields.Add(headerRange, Word.WdFieldType.wdFieldPage); headerRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight; }