Am trying to insert footer in Word Document from Excel (VBA). I want the footer to be like this:
Footer Left Right Footer:
CustomText Page 1 of 5
Below is the vba code written in excel:
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
After the code executes am getting result as below:
Footer Left Right Footer:
This is Custom Text 1
Instead of getting page numbers as Page X of Y its just numerals 1,2 etc. Can anybody please help me in getting page numbers as Page X of Y? Like below image:
Please have a look at this link: How Can I Add a Page X of Y Footer to a Microsoft Word Document?
I didn't look at it enough to figure out how to add your custom text as well but the code below is adapted to your sub from the link and does insert Page X of 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
Here is how I got it to work using Word's built in tab stops: .InsertAfter vbTab
Put it twice to have a left & right footer.
Entire Excel VBA footer code:
' 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
Result:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.