在word模板的第二页插入header,而第二页还不存在

Insert header on second page of a word template, while the second page doesn't exist yet

我需要创建一个 Word-Template,它将徽标动态添加到字母的 header 中。为了简化用户体验,生成的原始模板只有一页。 过程是这样的:

  1. 用户在Word中通过“文档>新建”打开模板
  2. 用户可以通过用户表单在不同的公司和徽标之间进行选择
  3. 根据company/logo的选择,在字母中添加不同的内容

我确实有一个限制,第一页的页脚与第二页以后的页脚不同。

这意味着,当我通过 VBA 代码将图片添加到第一页的 header 并添加文本(或只是空白 space)时,徽标不会'重复。

所以基本上我的问题是,如果我可以从第二页开始向 header 添加图片,而该页面尚不存在?

我目前的代码如下所示,尽管我删除了图像格式化部分,因为我认为它不相关:

With ActiveDocument
 .Sections(1).Footers(wdHeaderFooterFirstPage) _ 
 .Range.InlineShapes.AddPicture(path)
End With

我也试过抢先把header加到后面的页面,但是好像不行

With ActiveDocument
 .Sections(1).Footers(wdHeaderFooterFirstPage) _ 
 .Range.InlineShapes.AddPicture(path)
End With

With ActiveDocument
 .Sections(1).Footers(wdHeaderFooterPrimary) _ 
 .Range.InlineShapes.AddPicture(path)
End With

我已经包含了两个语句来放置图片。两者都有效:

Sub AddGraphicPage2()
  Application.ScreenUpdating = False
  Dim aSection As Section
  For Each aSection In ActiveDocument.Sections
    With aSection
      .Headers(wdHeaderFooterPrimary).Shapes.AddPicture FileName:="C:\picture.png"
      .Headers(wdHeaderFooterPrimary).Range.InlineShapes.AddPicture FileName:="C:\picture.png"
    End With
  Next aSection
  Application.ScreenUpdating = True
End Sub

检查所有部分使它成为一个通用宏,它还可以处理比单个页面更复杂的文档。

我想通了,为什么当我添加第二页(和第三页等等)时图像“移动”到第 2 页。这与我添加图像的方式有关。

最初我将附加图像的锚点定义为 Anchor:=Selection.Range。我只是在使用我知道可以处理图像格式的代码。

所以我刚刚删除了锚点,现在图像在每个 header 中都正确附加了,无论是在第 1 页、第 2 页还是第 13 页。

见下文,代码对我有用。

当然,我确实在一个函数中正确地实现了它,当我需要它时我会调用它;-)

ActiveDocument.Sections(1).PageSetup.DifferentFirstPageHeaderFooter = True

' Insert image in header for page 1

    With ActiveDocument.Sections(1).Headers(wdHeaderFooterFirstPage)
        With .Shapes.AddPicture(FileName:=filename, LinkToFile:=False, SaveWithDocument:=True)
            .name = "Logo_Page1"
            .Width = CentimetersToPoints(21)
            .Height = CentimetersToPoints(3)
            .RelativeHorizontalPosition = wdRelativeHorizontalPositionPage
            .Left = CentimetersToPoints(0)
            .RelativeVerticalPosition = wdRelativeVerticalPositionPage
            .Top = CentimetersToPoints(0)
            .WrapFormat.Type = wdWrapBehind
        End With
    End With
    
' Insert image in header from page 2 onwards
    
    With ActiveDocument.Sections(1).Headers(wdHeaderFooterPrimary)
        With .Shapes.AddPicture(FileName:=filename, LinkToFile:=False, SaveWithDocument:=True,Anchor:=Selection.Range)
            .name = "Logo_Page2"
            .Width = CentimetersToPoints(21)
            .Height = CentimetersToPoints(3)
            .RelativeHorizontalPosition = wdRelativeHorizontalPositionPage
            .Left = CentimetersToPoints(0)
            .RelativeVerticalPosition = wdRelativeVerticalPositionPage
            .Top = CentimetersToPoints(0)
            .WrapFormat.Type = wdWrapBehind
        End With
    End With