To add a header with Word VBA, set the header range’s text, for example ActiveDocument.Sections(1).Headers(wdHeaderFooterPrimary).Range.Text = "Quarterly Report". This replaces the contents of the primary header in the document’s first section; the example macro below also centers and bolds the text.
What a Word header is and how VBA reaches it
A header is content positioned in the top margin area of a page. Word stores headers and footers within sections, rather than as one universal text area for the entire document. In VBA, a document contains a collection of sections, and each section has a collection of headers. A header’s Range is the object you can edit, format, or use as the insertion point for fields and other content.
Word provides three header types for a section: the primary header, the first-page header, and the even-page header. The primary header is the usual choice when the same header should appear throughout a section. If the section uses a different first-page header or different odd and even headers, those alternatives are separate objects. Editing the primary header alone does not necessarily change what appears on those pages.
Sections matter when a document has different layouts, such as portrait pages followed by landscape pages, or chapters with distinct headers. A document can have just one section, but inserting a section break creates another section with its own header settings. Header behavior can also be affected by whether the section is linked to the one before it.
A basic macro to add and format a header
This example targets the primary header in the first section of the active document. It replaces any existing content in that header, then centers and bolds the new text. Change the sample wording to suit your document.
Sub AddHeaderToFirstSection()
' Add a centered, bold title to the first section's primary header.
Dim doc As Document
Dim headerRange As Range
Set doc = ActiveDocument
Set headerRange = doc.Sections(1).Headers(wdHeaderFooterPrimary).Range
headerRange.Text = "Quarterly Report"
headerRange.ParagraphFormat.Alignment = wdAlignParagraphCenter
headerRange.Font.Bold = True
End Sub
Before running any macro, save a copy of the document: Word macros cannot be undone with Ctrl+Z. This code replaces the selected header’s existing text and formatting may affect the replacement text, so preserve a version of the file if the current header matters. If you also need to keep the macro inside the document, save it as a Word Macro-Enabled Document (.docm); the standard .docx format does not store VBA code.
How to add and run the macro in Word
In Word for Microsoft 365 on Windows, open the Visual Basic Editor with Developer > Visual Basic. If the Developer tab is not visible, enable it through File > Options > Customize Ribbon, select Developer, and choose OK. You can also open the editor with Alt+F11 on Windows.
- In the Visual Basic Editor, choose Insert > Module in the project for the document or another appropriate VBA project.
- Paste the macro into the module. Make sure the document you want to edit is active in Word.
- Return to Word and choose Developer > Macros. Select
AddHeaderToFirstSectionand choose Run. Alt+F8 opens the macro list on Windows. - Check the first section’s header in Print Layout, then save the document. If the macro is part of the document, use the
.docmformat.
On Word for Mac, the Developer tab and Visual Basic Editor are available when enabled in Word’s ribbon settings. You can also access the VBA tools from Word’s Tools > Macro menu. Keyboard shortcuts can depend on the Mac keyboard and function-key settings, so use the menu if a Windows shortcut does not apply. Macro security settings may block code from running; only enable or run macros from sources you trust.
Choosing the right section and header type
The sample deliberately changes only section 1’s primary header. It does not automatically add a header to every section, nor does it fill a special first-page or even-page header. Before adapting it, decide which pages should display the new content.
- Same header throughout a simple document: The primary header in the first section is often enough when the document has one section and does not use special first-page or alternating-page headers.
- Different first page: If Different First Page is enabled in the Header & Footer tab, edit the first-page header separately with
wdHeaderFooterFirstPage. - Different odd and even pages: If the document uses different odd and even headers, the even-page header is addressed with
wdHeaderFooterEvenPages; the primary header serves the other applicable pages. - Different chapters or layouts: Inspect each section and its link setting. Later sections may inherit a preceding section’s header when
LinkToPreviousis on.
For a later section that needs its own independent header, set that header’s LinkToPrevious property to False before changing its content. Otherwise, editing a linked header can also change what appears in the preceding section. Be cautious when unlinking: Word may copy the prior header into the new section, so review the result rather than assuming the new header starts empty.
Adding more than plain text
Headers can contain more than a title. They can include page numbers, dates, logos, rules, and other formatted content. Plain text is suitable for a fixed label, but a page number should be a Word field rather than a typed number. A field updates according to the page where it appears; typed text such as “Page 1” will stay the same on every page unless you change it yourself.
For more complex layouts, use the header range as a starting point and insert or format the desired Word objects. For example, VBA can add a page-number field through the range’s Fields.Add method, or insert a table to position a title on one side and a page number on the other. The details depend on the layout and field type, so test the result in Print Layout and on pages where the header type changes.
Formatting through headerRange.Font and headerRange.ParagraphFormat applies to the range you have selected. A header range includes Word’s paragraph structure, so formatting may have effects beyond just the visible letters. If the document uses existing styles or carefully designed header elements, inspect the range and consider applying a named style or modifying only the relevant text rather than replacing the entire range.
Common problems and how to fix them
- The old header disappeared: The line
headerRange.Text = "Quarterly Report"replaces the range contents. Restore the saved copy or revise the macro to insert text without replacing existing content. - The header appears on some pages but not others: Check whether the section has a different first-page header, alternating odd/even headers, or a section break. The macro edits only the primary header in the first section.
- Changing one section changes another: The sections may be linked. Inspect
LinkToPreviousand unlink a section before giving it distinct content. - The macro cannot be found: Confirm that the code is in a standard module in a VBA project available to the active Word session, and that the macro name is spelled correctly in the macro list.
- The macro is disabled: Word’s security settings may prevent it from running. Do not lower macro security broadly or run code from an unknown file; use a trusted source and follow your organization’s policy.
- The header looks different in the saved file: Check the document in Print Layout, inspect all sections and page types, and verify that fonts, margins, and header distances suit the intended paper layout.
When to use VBA instead of Word’s ribbon
For a one-off change, the ribbon is usually simpler: choose Insert > Header, select a layout, and type the content. On the Header & Footer tab, Word also offers options such as Different First Page and Different Odd & Even Pages. This is a good choice when you want to see the design as you build it or avoid running code.
VBA is useful when you need to repeat the same header operation across many documents, create a document from a template, or automate a multi-step workflow. It also makes it easier to apply consistent text and formatting. Automation is not automatically safer, though: a macro that overwrites a header can remove a logo, field, or existing text just as quickly as it can add a new title. Test on a copy and make the target section and header type explicit.
Frequently Asked Questions
How do I add a header to every page in Word using VBA?
For a one-section document using the primary header, edit Sections(1).Headers(wdHeaderFooterPrimary).Range. If the document has multiple sections or special first-page or odd/even headers, edit each relevant section and header type; one assignment does not cover every variation.
Does assigning Range.Text append to the existing header?
No. Setting a range’s Text replaces the contents of that range. Use a method that inserts text at a chosen position if you need to preserve existing header content, and inspect the result before saving.
Why does my macro change the header in another section?
Those sections may be linked through LinkToPrevious. A linked header shares its content with the preceding section. Turn off the link for the section that needs a distinct header, then edit and review that section.
Can I add a page number with the same method?
Use a Word page-number field rather than typing a numeral into the header. A field can display the correct page number on each page and update as the document changes.
Can I save a Word macro in a DOCX file?
No. A DOCX file does not retain VBA macros. Save the macro in a .docm document or an appropriate macro-enabled template, such as a .dotm file.
Related
- Insert a Personal Signature in Word 365
- Insert a Line in Word or Google Docs: Quick Steps
- Insert a Functional Checkbox in Word: Clickable Options
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- Excel VBA Find Last Row: Reliable Methods and ExamplesIn Excel VBA, find the last row in one column with Cells(Rows.Count, "A").End(xlUp).Row, replacing A with the column…
- Excel VBA IsError: Check for Worksheet Errors in CodeIn Excel VBA, IsError(expression) returns True when an expression evaluates to an error value and False otherwise. Use…
- Vba loop through rows?Learn how to loop through Excel rows with VBA, find the last row, handle conditions and deletions, and…
- Excel VBA Not Working? Diagnose Common Macro ProblemsIf Excel VBA is not working, first check that you are using the desktop version of Excel, the…
- VBA Range Is Empty? How to Check Cells CorrectlyTo check whether a VBA range contains no entered values or formulas, use Application.CountA(target) = 0. First make…
- Excel VBA Collection: How It Works and When to Use ItAn Excel VBA Collection is an in-memory container that holds related items and lets you retrieve them by…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.