Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
191 views
in Technique[技术] by (71.8m points)

Add page number in Word using VBA

I am looking for hours for one of the simplest things to do (but with MS things are never simple...): How can I programmatically add in my Word footer 'Page #', using VBA ?
There are zillions of different ways on the internet but none is working. Just a couple of examples

This code fails at Fields.Add:

Sub pageNumber()
    ActiveDocument.Sections(ActiveDocument.Sections.Count) _
        .Headers(wdHeaderFooterPrimary).Range.Select
    With Selection
        .Paragraphs(1).Alignment = wdAlignParagraphCenter
        .TypeText Text:="Page "
        .Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:= _
            "PAGE ", PreserveFormatting:=True
        .TypeText Text:=" of "
        .Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:= _
            "NUMPAGES ", PreserveFormatting:=True
    End With
End Sub

This code doesn't allow me to add a word like 'page' before:

With ActiveDocument.Sections(1) 
 .Footers(wdHeaderFooterPrimary).PageNumbers.Add _ 
 PageNumberAlignment:=wdAlignPageNumberLeft, _ 
 FirstPage:=True 
End With

Any additional hint ?
Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

OK, the following code finally works:

With objWord.ActiveDocument.Sections(Section)
    .Footers(wdHeaderFooterPrimary).Range.Text = vbTab & "Page "
    .Footers(wdHeaderFooterPrimary).PageNumbers.Add FirstPage:=True
End With

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...