VBA is the programming language built into every Microsoft Office application. In Word, it gives you the ability to automate any task — from filling in content controls based on user input, to generating a complete formatted report from a data source, to building your own interactive dialogs. This module is designed for Word users who have completed Module 24 and want to move beyond the recorder into purposeful code. No prior programming experience is assumed.
The VBA Editor (also called the IDE — Integrated Development Environment) is where you write, edit, run, and debug VBA code. Open it with Alt+F11 from any Word document.
| Panel | Purpose | Show/Hide |
|---|---|---|
| Project Explorer (top-left) |
Tree view of all open documents and templates. Each project has folders: Microsoft Word Objects (ThisDocument), Modules (where Subs live), Forms (UserForms), Class Modules. Double-click any item to open it. | View → Project Explorer or Ctrl+R |
| Properties Window (bottom-left) |
Shows the properties of the currently selected object (a form, a module, or a UserForm control). Used mainly when designing UserForms. | View → Properties Window or F4 |
| Code Window (main area, right) |
Where you write and edit VBA code. Open a module (double-click in Project Explorer) to activate it. IntelliSense auto-suggests properties and methods as you type — press Tab or Enter to accept a suggestion. | Double-click any module in Project Explorer |
| Immediate Window (bottom) |
A command-line area where you can type and execute single VBA statements instantly — without running a full macro. Invaluable for testing: type ? ActiveDocument.Name and press Enter to print the document name. |
View → Immediate Window or Ctrl+G |
| Button / Key | Action |
|---|---|
| F5 | Run the current Sub (must place cursor inside it first) |
| F8 | Step Into — execute one line at a time; yellow arrow shows current line |
| Shift+F8 | Step Over — execute a called procedure without stepping into it |
| Ctrl+Break | Pause execution mid-run (useful to interrupt a loop running too long) |
| F9 | Toggle a breakpoint on the current line — execution pauses here when the macro runs |
| Ctrl+S | Save the VBA project (saves to the host document/template) |
| Alt+F4 | Close the VBA Editor and return to Word |
A variable is a named container that holds a value. Declare variables with Dim (short for Dimension):
str = String, int = Integer, lng = Long, dbl = Double, bool = Boolean, obj = Object, dt = DatestrFirstName, intPageCount, objCurrentDocOption Explicit at the top of every module to force this and catch typosConstants store values that never change during execution. Use UPPER_CASE with underscores by convention.
& — concatenates (joins) two strings: "Hello" & " " & "World" → "Hello World"vbNewLine — inserts a new line in a string (for MsgBox messages)vbTab — inserts a tab character in a stringLen(str) — returns the length of a stringLeft(str, n) — returns the first n charactersRight(str, n) — returns the last n charactersMid(str, start, n) — returns n characters starting at position startTrim(str) — removes leading and trailing spacesUCase(str) / LCase(str) — convert to upper/lower caseInStr(str, search) — returns the position of search within str (0 if not found)VBA interacts with Word through the Object Model — a hierarchy of objects representing every part of Word and every document. Understanding this hierarchy is the key to writing purposeful code.
| Object | What It Represents | Common Properties & Methods |
|---|---|---|
Application |
The Word application itself | .ActiveDocument, .Documents.Add, .Documents.Open, .Quit, .DisplayAlerts |
ActiveDocument |
Shortcut to the currently active document | .Name, .Path, .FullName, .Save, .SaveAs2, .Close, .Paragraphs, .Tables, .Sections, .ContentControls, .Words.Count |
Selection |
Currently selected text — or cursor position if nothing is selected | .Text, .TypeText, .TypeParagraph, .Style, .Font.Bold, .Font.Size, .Font.Color, .ParagraphFormat.Alignment, .Find, .HomeKey, .EndKey, .MoveDown |
Range |
A defined span of text (defined by start and end character positions) — more precise than Selection; does not move the cursor | .Text, .Style, .Font, .InsertBefore, .InsertAfter, .Delete, .Select, .Find, .SetRange(start, end) |
Paragraph |
One paragraph in the document | .Range.Text, .Style, .Format.SpaceAfter, .Format.Alignment, .LeftIndent |
Table |
A table in the document | .Rows.Count, .Columns.Count, .Cell(r, c).Range.Text, .Rows.Add, .Style, .Select |
ContentControl |
A content control field in the document | .Title, .Tag, .Range.Text, .Type, .Checked (checkbox), .DropdownListEntries |
| Use Selection when… | Use Range when… |
|---|---|
| The user has selected text and the macro should act on that selection; working interactively; inserting text at the cursor | Manipulating specific parts of the document programmatically without moving the cursor; looping through paragraphs or tables; background processing where the cursor position must not change |
Two built-in functions let you show messages and collect input from the user mid-macro — without building a full UserForm.
| Constant | Buttons Shown | Return Values |
|---|---|---|
vbOKOnly | OK | vbOK (1) |
vbYesNo | Yes / No | vbYes (6) / vbNo (7) |
vbYesNoCancel | Yes / No / Cancel | vbYes / vbNo / vbCancel (2) |
vbOKCancel | OK / Cancel | vbOK / vbCancel |
vbInformation | ℹ️ icon | — |
vbExclamation | ⚠️ icon | — |
vbCritical | ❌ icon | — |
vbQuestion | ❓ icon | — |
InputBox parameters: InputBox(prompt, title, defaultValue). Returns an empty string ("") if the user clicks Cancel — always check for this before using the value.
VBA Find & Replace is far more powerful than the manual dialog — you can run multiple replacements sequentially, use variables as search/replace strings, and combine replacements with conditional logic.
Content controls can be read and written programmatically — enabling auto-populated forms, validation, and data extraction.
Without error handling, any unexpected situation (a missing bookmark, an empty content control, a file that doesn't exist) causes your macro to crash with an ugly error dialog. Error handling makes macros professional and reliable.
On Error GoTo 0.
Q1: What is the difference between Selection and Range in the Word Object Model, and when would you choose one over the other?
✓ Selection represents the currently selected text (or cursor position) — it moves the visible cursor and is appropriate when the macro should act on what the user has highlighted, or when inserting text at the cursor position. Range is a defined span of text identified by character positions — it does not move the cursor and is better for background processing, looping through document content, or making changes to specific parts of the document without disrupting the user's view. Use Selection for interactive macros; use Range for automated processing and loops.
Q2: You want a macro that asks the user to type a reference number, then automatically inserts that number into a content control with the Tag "ref_no". Write the key lines of VBA code.
✓
Dim strRef As String
Dim oCC As ContentControl
strRef = InputBox("Enter reference number:", "Reference")
If strRef = "" Then Exit Sub
For Each oCC In ActiveDocument.ContentControls
If oCC.Tag = "ref_no" Then oCC.Range.Text = strRef
Next oCC
The InputBox collects the reference number. The empty string check exits gracefully if the user cancels. The For Each loop finds the content control by its Tag property and sets its text to the entered value.
Q3: Explain what the following code does, line by line: On Error GoTo ErrorHandler at the start of a Sub, then Exit Sub before ErrorHandler:, then MsgBox Err.Description.
✓ Line 1 (On Error GoTo ErrorHandler): instructs VBA that if any runtime error occurs in this Sub, execution should immediately jump to the label called ErrorHandler — rather than crashing with an ugly system error. Line 2 (Exit Sub): placed at the end of the normal code path, this exits the Sub cleanly when no error occurred — so the code doesn't accidentally "fall through" into the error handler section on a successful run. Line 3 (MsgBox Err.Description): inside the ErrorHandler section, this displays a user-friendly message box showing the description of whatever error occurred (Err is the VBA global error object; .Description gives the human-readable error text). Together these three elements form the standard VBA error handling pattern.
Q4: You want to loop through every paragraph in a document and apply the "Normal" style to any paragraph that currently uses the "Default Paragraph Font" style. Write the core loop.
✓
Dim oPara As Paragraph
For Each oPara In ActiveDocument.Paragraphs
If oPara.Style = "Default Paragraph Font" Then
oPara.Style = "Normal"
End If
Next oPara
This iterates through every paragraph in the active document. For each paragraph, it checks whether the style name matches "Default Paragraph Font" — and if so, changes it to "Normal". This is a common cleanup task for documents pasted from web pages where text often arrives with this inappropriate style.
Q5: What file format must a Word document be saved as in order to store VBA macros inside it — and what happens if you try to save a macro-containing document as a standard .docx file?
✓ Macros must be stored in a .docm file (Word Macro-Enabled Document) or a .dotm file (macro-enabled template). The standard .docx format does not support macros by design — it is a "macro-free" format for security. If you try to save a document containing macros as .docx, Word shows a warning: "The following features cannot be saved in Macro-Free Workbook". If you click Yes (save as .docx anyway), the macros are permanently stripped from the file. Click No and choose to save as .docm instead to preserve them.
Q6: Write a short VBA Sub that exports the active document to PDF at the path "C:\Reports\Output.pdf" with heading bookmarks enabled.
✓
Sub ExportToPDF()
ActiveDocument.ExportAsFixedFormat _
OutputFileName:="C:\Reports\Output.pdf", _
ExportFormat:=wdExportFormatPDF, _
CreateBookmarks:=wdExportCreateHeadingBookmarks
MsgBox "Exported to PDF successfully.", vbInformation
End Sub
ExportAsFixedFormat is the VBA method for PDF export. OutputFileName sets the save path and filename. ExportFormat:=wdExportFormatPDF specifies PDF (not XPS). CreateBookmarks:=wdExportCreateHeadingBookmarks generates clickable navigation bookmarks from Heading-styled paragraphs — equivalent to ticking "Create bookmarks using Headings" in the manual export dialog.
Congratulations — you have completed all 25 modules of the MS Word 2024 Beginner to Intermediate Course. You now have a comprehensive, professional command of Word — from basic formatting to multi-level numbering, mail merge, collaboration, forms, templates, macros, and VBA automation.
Continue practising by applying these skills to real documents in your workplace. The best way to consolidate this knowledge is to use it — build a template for your organisation, automate a repetitive task with a macro, or collaborate on a document using Track Changes.