Add page number in Word using VBA

淺唱寂寞╮ 提交于 2019-12-13 09:00:02

问题


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.


回答1:


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



回答2:


This works for me. It will add "Page ## of ##" at the center of the footer:

Sub Insert_PageNumber()

If ActiveWindow.View.SplitSpecial <> wdPaneNone Then
    ActiveWindow.Panes(2).Close
End If

If ActiveWindow.ActivePane.View.Type = wdNormalView Or ActiveWindow. _
    ActivePane.View.Type = wdOutlineView Then
    ActiveWindow.ActivePane.View.Type = wdPrintView
End If

ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageFooter
Selection.ParagraphFormat.Alignment = wdAlignParagraphCenter

Selection.TypeText Text:="Page "

Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:= _
    "PAGE  \* Arabic ", PreserveFormatting:=True

Selection.TypeText Text:=" of "

Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:= _
    "NUMPAGES  ", PreserveFormatting:=True

ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument

End Sub


来源:https://stackoverflow.com/questions/24515203/add-page-number-in-word-using-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!