尝试在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吗?如下图所示:
答案 0 :(得分:0)
请查看此链接:How Can I Add a Page X of Y Footer to a Microsoft Word Document?
我没有仔细研究如何添加您的自定义文本,但下面的代码适用于您的链接并插入Y的页面。
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
答案 1 :(得分:0)
这是我如何使用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
结果: