【问题标题】:Microsoft Word VBA to insert footer from excelMicrosoft Word VBA 从 excel 插入页脚
【发布时间】:2017-06-12 10:56:45
【问题描述】:

我正在尝试通过 Excel (VBA) 在 Word 文档中插入页脚。我希望页脚是这样的:

Footer Left Right Footer: CustomText Page 1 of 5

下面是用excel写的vba代码:

Sub FooterTextwithpageNum()
    Dim wb As Workbook
    Dim objWord As Object
    Dim FooterTemp As Object
    
    Set objWord = GetObject(, "Word.Application")
    objWord.Visible = True
    Set FooterTemp = objWord.ActiveDocument 
  
    FooterTemp.Sections(1).Footers(1).Range.Text = "This is Custom Text"

    FooterTemp.Sections(1).Footers(1).PageNumbers.Add FirstPage:=True
End Sub

代码执行后得到如下结果:

Footer Left Right Footer: This is Custom Text 1

而不是将页码作为 Y 的第 X 页,它只是数字 1,2 等。有人可以帮我将页码作为 Y 的 X 页吗?如下图:

【问题讨论】:

  • 为什么要投反对票?

标签: vba ms-word footer


【解决方案1】:

请查看此链接:How Can I Add a Page X of Y Footer to a Microsoft Word Document?

我没有仔细研究它以弄清楚如何添加您的自定义文本,但下面的代码已从链接适应您的子,并插入 Y 页 X。

Sub FooterTextwithpageNum()

    Dim wb As Workbook
    Dim objWord As Object
    Dim objDoc As Object
    Dim FooterTemp As Object
    Dim objTemplate As Object
    Dim objRange As Object

    Set objWord = GetObject("", "Word.Application")
    objWord.Visible = True
    Set objDoc = objWord.Documents.Add()
    Set FooterTemp = objWord.ActiveDocument

    Set objTemplate = objDoc.AttachedTemplate
    Set objRange = FooterTemp.Sections(1).Footers(1).Range

    objTemplate.AutoTextEntries("Page X of Y").Insert objRange

End Sub

【讨论】:

  • 您好,Garth,感谢您的及时回复。我尝试了您发布的代码并收到run-time error 5941。在将这个问题发布到堆栈溢出之前,我尝试在互联网上搜索选项,但找不到任何更接近我正在寻找的解决方案。它要么插入自定义文本或页码,但不能同时插入两者。我想知道如何在已经打开的 word 文档的页脚左侧添加一些文本,在页脚右侧添加 Y 页 X。
  • 添加了页脚在主帖上的外观截图
【解决方案2】:

这是我如何使用 Word 的内置制表位让它工作的:.InsertAfter vbTab

放置两次以获得左右页脚。

整个 Excel VBA 页脚代码:

    ' FOOTER
    With wrdDoc.sections(1).Footers(wdHeaderFooterPrimary).Range
        .InsertAfter Text:="Printed: "
        .Fields.Add .Characters.Last, wdFieldEmpty, "DATE \@ ""MM/DD//YYYY""", False
        .InsertAfter vbTab
        .InsertAfter vbTab
        .InsertAfter Text:="Page "
        .Fields.Add Range:=.Characters.Last, Type:=wdFieldEmpty, Text:="PAGE", PreserveFormatting:=False
        .InsertAfter Text:=" of "
        .Fields.Add Range:=.Characters.Last, Type:=wdFieldEmpty, Text:="NUMPAGES", PreserveFormatting:=False
    End With

结果:

使用 Office 2016 (Office 365)。

【讨论】:

    猜你喜欢
    • 2017-03-17
    • 1970-01-01
    • 2020-12-24
    • 2014-01-12
    • 2017-11-09
    • 1970-01-01
    • 1970-01-01
    • 2021-05-11
    • 2019-06-04
    相关资源
    最近更新 更多