Page Number with header/footer Word Document VBA example

Page Number with header/footer Word Document VBA example

PageNumber

A page number in a header or footer. The PageNumber object is a member of the PageNumbers collection. The PageNumbers collection includes all the page numbers in a single header or footer.

In this article we will insert page number in the footer section of a page and play with. Consider following document has no header footer yet:

Code example

Public Sub InsertPageNumber()
    'Declare variable to bind selection
    Dim oSelection As Selection
    'Bind Selection
    Set oSelection = Selection
    
    'Declare document object
    Dim oDocument As Document
    'Bind reference
    Set oDocument = ActiveDocument
    'Activate the view
    oDocument.ActiveWindow.View.Type = wdPrintView
    'enable footer
    oDocument.ActiveWindow.View.SeekView = wdSeekCurrentPageFooter
    
    'Get page number object
    Dim oPageNumber As PageNumber
    
    'Add Page Number and bind object
    Set oPageNumber = oSelection.HeaderFooter.PageNumbers.Add(PageNumberAlignment:=wdAlignPageNumberCenter)
    
    'Now play with Page Number
    oPageNumber.Alignment = wdAlignPageNumberRight
End Sub

Output

Please leave your comments or queries under comment section also please do subscribe to out blogs to keep your self upto date.

Leave a Reply

Your email address will not be published. Required fields are marked *