VBA Code


Types of Views

Application.ActiveWindow.View.Type = wdViewType.wdNormalView 

Displays all non printing characters (hidden text, tab marks, space marks, paragraph marks)

objView.ShowAll 

Toggles the display of just headings or Headings and text

objView.ShowAllHeadings = True / False 

Toggles the display of square brackets around each bookmarks

objView.ShowBookmarks = True / False 

objView.ShowDrawings 
objView.ShowFieldCodes
objView.ShowHeading
objView.ShowHiddenText
objView.ShowParagraphs
objView.ShowSpaces
objView.ShowText
objView.ShowTextBoundaries
objView.TableGridlines


Displaying the Ruler

This is equivalent to (View > Ruler).
Returns or sets whether the ruler(s) is displayed in the active window (Print Layout).
ActiveWindow.DisplayRulers = True
If the view is Print Layout and the Display Rulers is true then the DisplayVerticalRulers determiens whether a vertical ruler will be displayed.

If Application.DisplayRulers = False Then 

End If

You cannot display a vertical ruler unless the horizontal ruler is displayed.


Move to a particular page

Selection.GoTo What:=wdGoToPage 
               Which:=wdGoToNext
               Name:="2"


Document Map

This is the vertical area across the left edge of the window that displays an Outline of the document using heading styles
Determines if the document map is visible or not

Application.DocumentMap = True / False 

Returns or sets the width of the document map as a percentage of the width of the window.

Application.DocumentMapPercentWidth = 20 


Get the Column Number of the selection

This only works for selections, not for ranges.

With Dialogs(wdWordDialog.wdDialogFormatColumns) 
   Debug.Print . ColumnNo
End With


Selecting Pages

To select the page the cursor is in

Selection.GoTo What:=wdGoToBookmark, Name:="\page" 


Deleting Pages


'To set a range object to the page the range is currently in:
'Having previously set the MyRange variable to a range somewhere ...
'you can then operate on the page without selecting it, e.g.

Set MyRange = MyRange.GoTo(What:=wdGoToBookmark, Name:="\page") 
MyRange.Delete

'To set a range object to a particular page number:
'you can then operate on the page without selecting it, e.g.

Dim MyRange As Range 
Set MyRange = ActiveDocument.Range(0, 0)
Set MyRange = MyRange.GoTo(What:=wdGoToPage, Name:="4")
Set MyRange = MyRange.GoTo(What:=wdGoToBookmark, Name:="\page")
MyRange.Delete


Inserting Pages


HeaderFooter object

A HeaderFooter object represents either a single header or footer.
The headerfooter object can represent either a header or footer. This object is available from the Selection obect
A HeaderFooters collection contain HeaderFooter objects of one type (header or footer).
The HeadersFooters collection includes all headers and footers in the specified document section.


A HeaderFooter collection, whether it be a collection of headers or a collection of footers is indexed by one of the constants in the following enumeration.


wdInformation.wdInHeaderFooter 
wdInformation.wdHeaderFooterType

There are three different types of headers and three types of footers
Primary
First Page
Even Pages


Primary

To obtain the HeaderFooter object that represents the primary header in the first section of the active document

Dim objHeaderFooter As HeaderFooter 
objHeaderFooter = ActiveDocument.Sections(1).Headers wdHeaderFooterIndex.wdHeaderFooterPrimary

objHeaderFooter = ActiveDocument.Sections(1).Footers wdHeaderFooterIndex.wdHeaderFooterPrimary 

The following code changes the text in both the primary header and the primary footer

With ActiveDocument.Sections(1) 
   .Headers(wdHeaderFooterIndex.wdHeaderFooterPrimary).Range.Text = "some text"
   .Footers(wdHeaderFooterIndex.wdHeaderFooterPrimary).Range.Text = "some text"
End With


Current Selection

Note that if the current selection is within a header or footer then the HeaderFooter property of the Selection object will return the active HeaderFooter object.

objHeaderFooter = Selection.HeaderFooter 


Activating

ActiveWindow.ActivePane.View.SeekView = wdSeekView.wdSeekCurrentPageHeader 
ActiveWindow.ActivePane.View.SeekView = wdSeekView.wdSeekCurrentPageFooter


Deactivating

ActiveWindow.ActivePane.View.SeekView = wdSeekView.wdSeekMainDocument 


Modifying

With ActiveDocument.Sections(1).Footers(wdHeaderFooterIndex.wdHeaderFooterPrimary) 
   .Delete
   .Fields.Add range := Selection, type := wdfieldname, text := "\p"
   .InsertAfter text := vbTab
   .InsertAfter text := vbTab
   .Collapse direction := wdCollapseDirection.wdCollapseStart
   .Fields.Add range := Selection, type := fieldauthor
End With

Does a Header or Footer Exists

In any document the three types of headerfooter objects always exist although the property will be set to False when they are not visible or not being used within a document.


The Exists property can be used to determine whether a first page or odd page header / footer exists

Dim bExists As Boolean 
bExists = ActiveDocument.Sections(1).Headers(wdHeaderFooterIndex.wdHeaderFooterFirstPage).Exists


bExists = ActiveDocument.Sections(1).Headers(wdHeaderFooterIndex.wdHeaderFooterEvenPages).IsHeader 
bExists = ActiveDocument.Sections(1).Footers(wdHeaderFooterIndex.wdHeaderFooterEvenPages).IsFooter

Different First Page

Use the DifferentFirstPageHeaderFooter property with the PageSetup object to specify a different first page.
The following example inserts text into the first page footer in the active document.

With ActiveDocument 
    .PageSetup.DifferentFirstPageHeaderFooter = True
    .Sections(1).Footers(wdHeaderFooterFirstPage) _
        .Range.InsertBefore _
        "Written by Joe Smith"
End With


objPageSetup.DifferentFirstPagePagesHeaderFooter = True / False 


Different Odd Even

Use the OddAndEvenPagesHeaderFooter property with the PageSetup object to specify different odd and even page headers and footers.
If the OddAndEvenPagesHeaderFooter property is True, you can return an odd header or footer by using wdHeaderFooterPrimary, and you can return an even header or footer by using wdHeaderFooterEvenPages.


Use the Add method with the PageNumbers object to add a page number to a header or footer.
The following example adds page numbers to the primary footer in the first section of the active document.

With ActiveDocument.Sections(1) 
    .Footers(wdHeaderFooterPrimary).PageNumbers.Add
End With


objPageSetup.OddAndEevenPagePagesHeaderFooter = True / False 

The OddAndEvenPagesHeaderFooter property of the PageSetup object can be used to specify different odd and even page headers and footers.
When this property is True, the index wdHeaderFooterPrimary refers to the odd header or footer.
The primary header (or footer) is defined based on the values of two properties:
The primary header is:
1) The only header when DifferentFirstPageHeaderFooter = False and OddAndEvenPagesHeaderFooter = False
2) The non first page header when DifferentFirstPageHeaderFooter = True and OddAndEvenPagesHeaderFooter = False
3) The odd page header when DifferentFirstPageHeaderFooter = False and OddAndEvenPagesHeaderFooter = True
4) The non first page odd header when DifferentFirstPageHeaderFooter = True and OddAndEvenPagesHeaderFooter = True



Insert an image into a header


Sub AddImageToHeader() 
Dim SrcePath As String

SrcePath = "C:\Users\Chris\Desktop\Testing\Test.png"

ThisDocument.Sections.Item(1).Headers(wdHeaderFooterPrimary) _
  .Range.InlineShapes.AddPicture (SrcePath)

ThisDocument.Sections(1).Headers(wdHeaderFooterPrimary) _
  .Range.Paragraphs(1).Alignment = wdAlignParagraphCenter
End Sub

Insert a table into a header


Sub UpdateHeader() 
    Dim oDoc As Word.Document, oSec As Word.Section, rng As Word.Range
    Set oDoc = ActiveDocument

    For Each oSec In oDoc.Sections
        Set rng = oSec.Headers(Word.WdHeaderFooterIndex.wdHeaderFooterFirstPage).Range
        AddHeaderToRange rng

        Set rng = oSec.Headers(Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range
        AddHeaderToRange rng
    Next oSec
End Sub

Private Sub AddHeaderToRange(rng As Word.Range)
    With rng
        .Tables.Add Range:=rng, NumRows:=1, NumColumns:=2
        With .Tables(1)
            .Borders.InsideLineStyle = wdLineStyleNone
            .Borders.OutsideLineStyle = wdLineStyleNone
            .Rows.SetLeftIndent LeftIndent:=-37, RulerStyle:=wdAdjustNone
            .Columns(2).SetWidth ColumnWidth:=300, RulerStyle:=wdAdjustNone
            .Cell(1, 1).Range.InlineShapes.AddPicture FileName:="Your Pic Solution", LinkToFile:=False, SaveWithDocument:=True
            .Cell(1, 2).Range.Font.Name = "Arial"
            .Cell(1, 2).Range.Font.Size = 9
            .Cell(1, 2).Range.ParagraphFormat.Alignment = wdAlignParagraphRight
            .Cell(1, 2).Range.Text = "Test header" & vbNewLine & "Second Line"
        End With
    End With
End Sub

Sub UpdateHeaders() 
Dim Tbl As Table, Sctn As Section
With ActiveDocument
  Set Tbl = .Tables.Add(Range:=.Range(0, 0), NumRows:=1, NumColumns:=2)
  With Tbl
    .Borders.InsideLineStyle = wdLineStyleNone
    .Borders.OutsideLineStyle = wdLineStyleNone
    .Rows.SetLeftIndent LeftIndent:=-37, RulerStyle:=wdAdjustNone
    .Columns(2).SetWidth ColumnWidth:=300, RulerStyle:=wdAdjustNone
    .Cell(1, 1).Range.InlineShapes.AddPicture FileName:="Your Pic Solution", LinkToFile:=False, SaveWithDocument:=True
    .Cell(1, 2).Range.Font.Name = "Arial"
    .Cell(1, 2).Range.Font.Size = 9
    .Cell(1, 2).Range.ParagraphFormat.Alignment = wdAlignParagraphRight
    .Cell(1, 2).Range.Text = "Test header" & vbCr & "Second Line"
  End With
  For Each Sctn In .Sections
    With Sctn
      With .Headers(wdHeaderFooterPrimary)
        If .LinkToPrevious = False Then .Range.FormattedText = Tbl.Range.FormattedText
      End With
      With .Headers(wdHeaderFooterFirstPage)
        If .LinkToPrevious = False Then .Range.FormattedText = Tbl.Range.FormattedText
      End With
    End With
  Next
  Tbl.Delete
End With
End Sub


Insert page numbers into a footer


Sub testing() 

Selection.TypeText "Page "
Selection.Fields.Add Range:=Selection.Range, _
                     Type:=WdFieldType.wdFieldPage

Selection.TypeText " out of "
Selection.Fields.Add Range:=Selection.Range, _
                     Type:=WdFieldType.wdFieldNumPages


Selection.TypeText "first"
Selection.TypeText vbTab
Selection.TypeText "second"

Dim oRange As Word.Range

    Set oRange = ActiveDocument.Bookmarks("BM_FooterSection2").Range
    oRange.Text = "monday"
    ActiveDocument.Bookmarks.Add "BM_FooterSection2", oRange

    Set oRange = ActiveDocument.Bookmarks("BM_FooterSectionPgNo").Range
    oRange.Text = "tuesday"
    ActiveDocument.Bookmarks.Add "BM_FooterSectionPgNo", oRange
    
End Sub


How can I prevent users from editing the header of a document

Private WithEvents wdApp As Word.Application 

Private Sub Document_New()
'assign Word to the application variable
    If wdApp Is Nothing Then
        Set wdApp = ThisDocument.Application
    End If
End Sub

Private Sub Document_Open()
'assign Word to the application variable
If wdApp Is Nothing Then
    Set wdApp = ThisDocument.Application
End If
End Sub

Private Sub wdApp_WindowSelectionChange(ByVal Sel As Selection)
'quit if active doc isn't attached to this template
    If ActiveDocument.AttachedTemplate <> ThisDocument Then Exit Sub
'get out of the header/footer if we're in it
    Select Case Sel.StoryType
    Case wdEvenPagesFooterStory, wdEvenPagesHeaderStory, _
               wdFirstPageFooterStory, wdFirstPageHeaderStory, _
               wdPrimaryFooterStory, wdPrimaryHeaderStory
        ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument
        Exit Sub
    Case Else
    End Select
End Sub

Alignment Tabs

For normal tabs refer to Paragraphs > VBA Code > Tabs


objRange.InsertAlignmentTab WdAlignmentTabAlignment.wdCenter, _ 
                            WdAlignmentTabRelative.wdMargin


Page Numbers

The PageNumbers property of the HeaderFooter object returns a PageNumbers collection, which holds all of the PageNumber objects for that particular header or footer.
In most cases a header (or footer) will contain a single pagenumber object (if any) denoted by PageNumbers(1).
To add a page number to a header or footer
The Add method inserts a text frame containing the page number field into the specified header or footer
The text frame is positioned according to the PageNumberAlignment parameter.
If FirstPage is set to False a page number is not added to the first page

objPageNumbers.Add PageNumberAlignment:=wdPageNumberAlignment.wdAlignPageNumberLeft, 
                   FirstPage:= True | False

If you want to insert a page number within some other text then you can use the Fields.Add method using the type wdFieldPage

Dim objRange As Range 
   Set objRange = ActiveDocument.Sections(1).Headers(wdHeaderFooterIndex.wdHeaderFooterPrimary).Range
   objRange.ParagraphFormat.Alignment = wdParagraphAlignment.wdAlignParagraphCenter
   objRange.Text = "some text"
   objRange.Collapse wdCollapseDirection.wdCollapseEnd
   objRange.Fields.Add objRange, wdFieldPage
   objRange.Move wdStory
   objRange.InsertAfter "some more text"


Inserting Page Numbers


activedocument.footnotes.add range:=myrange, text:="my text" 
With Selection.Sections(1).Headers(wdHeaderFooterPrimary).Pagenumbers
   .NumberStyle = wdPageNumberStyle.wdPageNumberStyleArabic
   .HeadingLevelForChapter = 0
   .IncludeChapterNumber = False
   .ChapterPageSeperator = wdSeparatorType.wdSeperatorHyphen
   .RestartNumberingAtSection = True
   .StartNumbering = 5
End With


ipageno = Application.Selection.Information(WdInformation.wdActiveEndPageNumber) 

oFooter.PageNumbers.Add PageNumberAlignment:=wdAlignPageNumberCenter, _ 
                        FirstPage:=True


Return the Page Number at the current cursor position

Selection.Information(wdActiveEndPageNumber) 
ActiveDocument.Content.Information(wdInformation.wdActiveEndPageNumber)

Return the number of pages in the active document

Selection.Information(wdInformation.wdNumberOfPagesInDocument) 

ActiveDocument.BuiltInDocumentProperties("Number of Pages") 

The last method is the most reliable, but also the slowest

ActiveDocument.Content.ComputeStatistics(wdStatistic.wdStatisticsPages) 

Page Setup


Dim oSection As Word.Section 
Dim oSection As Word.Section = ActiveDocument.PageSetup

Protected Document

Set oSection = Application.Selection.Sections(1) 
Debug.Print oSection.PageSetup.PageWidth

This will generate an error if the document has protection


You cannot change the following if the document is protected

ActiveDocument.PageSetup.FirstPageTray = wdPrinterPaperCassette 
ActiveDocument.PageSetup.OtherPagesTray =


ActiveDocument.PageSetup.PaperSize = wdPaperSize.wdPaperCustom 


ActiveDocument.PageSetup.PageWidth = 

Settings the pagewidth property automatically changes the Papersize property to wdPaperCustom


With ActiveDocument.PageSetup 
   .LeftMargin = InchesToPoints(0.5)
   .RightMargin = InchesToPoints(0.5)
   .TopMargin = InchesToPoints(0.5)
   .BottomMargin = InchesToPoints(0.5)
   .SetAsTemplateDefault
End With


ActiveDocument.Sections(1).PageSetup.Orientation = wdOrientation.wdOrientLandscape 

From Edge

oSection.PageSetup.HeaderDistance = 
oSection.PageSetup.FooterDistance =

Printing


List of Installed Printers

There does not seem to be a way to access the list of installed printers from VBA
This currently requires API calls.


Changing the Selected Printer

Returns or sets the name of the active printer

Application.ActivePrinter 


Sending the Document to the Printer


Call ActiveDocument.PrintOut(Background:=True, _ 
                             Range:= wdPrintOutRange.wdPrintAllDocument
                             Append:=False, _
                             OutputFileName:="", _
                             From:="1", _
                             To:="3", _
                             Item:=wdPrintOutItem.wdPrintDocumentContent
                             Copies:=1, _
                             Pages:="1,3,5-6"
                             PageType:=wdPrintOutPages.wdPrintOddPagesOnly
                             PrintToFile:=False, _
                             Collate:=True, _
                             FileName:="", _
                             PrintZoomColumn:=0, _
                             PrintZoomRow:=0, _
                             PrintZoomPaperWidth:=0, _
                             PrintZoomPaperHeight:=0)

Background - Variant. Set to True to have the macro continue while Microsoft Word prints the document.
Range - Variant. The page range. Can be any WdPrintOutRange constant.
Append - Variant. Set to True to append the specified document to the file name specified by the OutputFileName argument. False to overwrite the contents of OutputFileName.
OutputFileName - Variant. If PrintToFile is True, this argument specifies the path and file name of the output file.
From - Variant. The starting page number when Range is set to wdPrintFromTo.
To - Variant. The ending page number when Range is set to wdPrintFromTo.
Item - Variant. The item to be printed. Can be any WdPrintOutItem constant.
Copies - Variant. The number of copies to be printed.
Pages - Variant. The page numbers and page ranges to be printed, separated by commas. For example, "2, 6-10" prints page 2 and pages 6 through 10.
PageType - Variant. The type of pages to be printed. Can be any WdPrintOutPages constant.
PrintToFile - Variant. True to send printer instructions to a file. Make sure to specify a file name with OutputFileName.
Collate - Variant. When printing multiple copies of a document, True to print all pages of the document before printing the next copy.
FileName - Variant. The path and file name of the document to be printed. If this argument is omitted, Word prints the active document. (Available only with the Application object.)
ActivePrinterMacGX - Variant. This argument is available only in Microsoft Office Macintosh Edition. For additional information about this argument, consult the language reference Help included with Microsoft Office Macintosh Edition.
ManualDuplexPrint - Variant. True to print a two-sided document on a printer without a duplex printing kit. If this argument is True, the PrintBackground and PrintReverse properties are ignored. Use the PrintOddPagesInAscendingOrder and PrintEvenPagesInAscendingOrder properties to control the output during manual duplex printing. This argument may not be available to you, depending on the language support (U.S. English, for example) that you've selected or installed.
PrintZoomColumn - Variant. (Added in 2000). The number of pages you want Word to fit horizontally on one page. Can be 1, 2, 3, or 4. Use with the PrintZoomRow argument to print multiple pages on a single sheet.
PrintZoomRow - Variant. (Added in 2000). The number of pages you want Word to fit vertically on one page. Can be 1, 2, or 4. Use with the PrintZoomColumn argument to print multiple pages on a single sheet.
PrintZoomPaperWidth - Variant. (Added in 2000) .The width to which you want Word to scale printed pages, in twips (20 twips = 1 point; 72 points = 1 inch).
PrintZoomPaperHeight - Variant. (Added in 2000). The height to which you want Word to scale printed pages, in twips (20 twips = 1 point; 72 points = 1 inch).



Returns or sets the default tray your printer uses to print documents.

Application.Options.DefaultTrayID = wdPaperTray.wdPrinterUpperBin 

This changes the view of the active document to print preview

Application.PrintPreview = True 

If Application.PrintPreview = True Then 
End If

ActiveDocument.Repaginate 



© 2026 Better Solutions Limited. All Rights Reserved. © 2026 Better Solutions Limited TopPrev