您需要将页眉/页脚添加到wdHeaderFooterFirstPage
第一页的范围并进入wdHeaderFooterPrimary
对于所有其他页面,具体取决于文档的页眉/页脚设置。
下面的示例在所有页面中创建一个标题,其中包含一个带有两个单元格的表格。左侧为图像,右侧为文本。
Sub UpdateHeader()
Dim oDoc As Word.Document, oSec As Word.Section, rng As Word.Range
Set oDoc = ActiveDocument
For Each oSec In oDoc.Sections
Set rng = oSec.Headers(Word.WdHeaderFooterIndex.wdHeaderFooterFirstPage).Range
AddHeaderToRange rng
Set rng = oSec.Headers(Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range
AddHeaderToRange rng
Next oSec
End Sub
Private Sub AddHeaderToRange(rng As Word.Range)
With rng
.Tables.Add Range:=rng, NumRows:=1, NumColumns:=2, DefaultTableBehavior:=wdWord8TableBehavior, AutoFitBehavior:=wdAutoFitFixed
With .Tables(1)
.Borders.InsideLineStyle = wdLineStyleNone
.Borders.OutsideLineStyle = wdLineStyleNone
.Rows.SetLeftIndent LeftIndent:=-37, RulerStyle:=wdAdjustNone
.Columns(2).SetWidth ColumnWidth:=300, RulerStyle:=wdAdjustNone
.Cell(1, 1).Range.InlineShapes.AddPicture filename:="image path", LinkToFile:=False, SaveWithDocument:=True
.Cell(1, 2).Range.Font.Name = "Arial"
.Cell(1, 2).Range.Font.Size = 9
.Cell(1, 2).Range.ParagraphFormat.Alignment = wdAlignParagraphRight
.Cell(1, 2).Range.Text = "Test header"
End With
End With
End Sub
同样的原则也适用于页脚。
Sub UpdateFooter()
Dim oDoc As Word.Document, oSec As Word.Section, rng As Word.Range
Set oDoc = ActiveDocument
For Each oSec In oDoc.Sections
Set rng = oSec.Footers(Word.WdHeaderFooterIndex.wdHeaderFooterFirstPage).Range
AddFooterToRange rng
Set rng = oSec.Footers(Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range
AddFooterToRange rng
Set rng = oSec.Footers(Word.WdHeaderFooterIndex.wdHeaderFooterEvenPages).Range
AddFooterToRange rng
Next oSec
End Sub
Private Sub AddFooterToRange(rng As Word.Range)
With rng
.Font.Name = "Arial"
.Font.Size = 9
.Text = "Footer sample text"
With .ParagraphFormat
.Alignment = wdAlignParagraphJustify
.LineSpacingRule = wdLineSpaceExactly
.LineSpacing = Application.LinesToPoints(1)
.LeftIndent = Application.CentimetersToPoints(-1.6)
.RightIndent = Application.CentimetersToPoints(-1.6)
End With
End With
End Sub
最后,删除现有的标头:
Sub ClearExistingHeaders(oDoc As Word.Document)
Dim oSec As Word.Section, oHeader As HeaderFooter
For Each oSec In oDoc.Sections
For Each oHeader In oSec.Headers
oHeader.Range.Delete
Next
Next
End Sub