Microsoft Word 2024 Comprehensive Course — Beginner to Intermediate
W
Word 2024 Microsoft 365
📘 25 Modules Foundations Interface Formatting Graphics Tables & Charts References Collaboration Templates Macros & VBA

💻 Module 25: Visual Basic for Applications (VBA) in Word

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.

25.1 The VBA Editor — Full Tour

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.

Editor Panels — All Four

PanelPurposeShow/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

Adding a New Module

  1. In the Project Explorer, right-click the project (document or template) where you want to add code
  2. Insert → Module — a new empty module (e.g., "Module1") appears
  3. Double-click the module to open it in the Code Window
  4. Rename it in the Properties Window: click the Name field → type a descriptive name (e.g., DocUtilities, FormatMacros)

The Editor Toolbar — Essential Buttons

Button / KeyAction
F5Run the current Sub (must place cursor inside it first)
F8Step Into — execute one line at a time; yellow arrow shows current line
Shift+F8Step Over — execute a called procedure without stepping into it
Ctrl+BreakPause execution mid-run (useful to interrupt a loop running too long)
F9Toggle a breakpoint on the current line — execution pauses here when the macro runs
Ctrl+SSave the VBA project (saves to the host document/template)
Alt+F4Close the VBA Editor and return to Word

25.2 VBA Fundamentals — Syntax & Structure

Variables — Storing Data

A variable is a named container that holds a value. Declare variables with Dim (short for Dimension):

Dim strName As String        ' Holds text
Dim intCount As Integer      ' Holds whole numbers (-32768 to 32767)
Dim lngTotal As Long        ' Holds large whole numbers
Dim dblPrice As Double      ' Holds decimal numbers (e.g., 1234.56)
Dim boolDone As Boolean     ' Holds True or False only
Dim dtDate As Date          ' Holds a date value
Dim objDoc As Document     ' Holds a reference to a Word Document object

Variable Naming Conventions

  • Start with a lowercase type prefix for clarity: str = String, int = Integer, lng = Long, dbl = Double, bool = Boolean, obj = Object, dt = Date
  • Use camelCase: strFirstName, intPageCount, objCurrentDoc
  • Names cannot contain spaces or special characters; cannot start with a number
  • Always declare variables at the top of the Sub with Dim — add Option Explicit at the top of every module to force this and catch typos

Constants

Const COMPANY_NAME As String = "Skailit (Pty) Ltd"
Const MAX_PAGES As Integer = 50

Constants store values that never change during execution. Use UPPER_CASE with underscores by convention.

If / Then / Else — Conditional Logic

If intPageCount > 10 Then
    MsgBox "Document is long — consider splitting into sections."
ElseIf intPageCount > 5 Then
    MsgBox "Document is medium length."
Else
    MsgBox "Document is short."
End If

For / Next Loop — Repeating a Block

Dim i As Integer
For i = 1 To 5
    MsgBox "Iteration: " & i
Next i

For Each / Next Loop — Iterating a Collection

Dim oPara As Paragraph
For Each oPara In ActiveDocument.Paragraphs
    ' Do something with each paragraph
Next oPara

Do While / Loop — Repeat While a Condition Is True

Do While boolRunning = True
    ' Code runs as long as boolRunning is True
    boolRunning = False ' Eventually set to False to stop the loop
Loop

String Operators

  • & — 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 string
  • Len(str) — returns the length of a string
  • Left(str, n) — returns the first n characters
  • Right(str, n) — returns the last n characters
  • Mid(str, start, n) — returns n characters starting at position start
  • Trim(str) — removes leading and trailing spaces
  • UCase(str) / LCase(str) — convert to upper/lower case
  • InStr(str, search) — returns the position of search within str (0 if not found)

25.3 The Word Object Model

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.

Application               ← Word itself
 └── Documents             ← Collection of all open documents
     └── Document          ← One specific document
         ├── Paragraphs     ← All paragraphs
         │    └── Paragraph  ← One paragraph → .Range, .Style, .Text
         ├── Sections       ← Document sections
         │    └── Section → .Headers, .Footers, .PageSetup
         ├── Tables         ← All tables
         │    └── Table → .Rows, .Columns, .Cell(r,c)
         ├── ContentControls ← Content control fields
         ├── Bookmarks      ← Named bookmarks
         ├── Fields         ← Field codes (page numbers, dates)
         └── Range          ← Any span of text in the document

The Most Important Objects — Quick Reference

ObjectWhat It RepresentsCommon 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

Selection vs Range — When to Use Each

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

25.4 MsgBox & InputBox — User Interaction

Two built-in functions let you show messages and collect input from the user mid-macro — without building a full UserForm.

MsgBox — Displaying Information

' Simple message
MsgBox "Document saved successfully!"

' Message with title and icon
MsgBox "Processing complete.", vbInformation, "Skailit Macro"

' Yes/No question — capture the answer
Dim intAnswer As Integer
intAnswer = MsgBox("Do you want to save a copy?", vbYesNo + vbQuestion, "Confirm")
If intAnswer = vbYes Then
    ' User clicked Yes
End If

MsgBox Button Constants

ConstantButtons ShownReturn Values
vbOKOnlyOKvbOK (1)
vbYesNoYes / NovbYes (6) / vbNo (7)
vbYesNoCancelYes / No / CancelvbYes / vbNo / vbCancel (2)
vbOKCancelOK / CancelvbOK / vbCancel
vbInformationℹ️ icon
vbExclamation⚠️ icon
vbCritical❌ icon
vbQuestion❓ icon

InputBox — Collecting a Text Value

Dim strClientName As String
strClientName = InputBox("Enter the client's full name:", "Client Name", "Default Name")

If strClientName = "" Then
    MsgBox "No name entered. Macro cancelled.", vbExclamation
    Exit Sub ' Stop the macro immediately
End If

' Use the value
Selection.TypeText "Dear " & strClientName & ","

InputBox parameters: InputBox(prompt, title, defaultValue). Returns an empty string ("") if the user clicks Cancel — always check for this before using the value.

25.5 Working with Paragraphs & Ranges

Looping Through All Paragraphs

Sub ListHeadings()
    Dim oPara As Paragraph
    Dim strList As String
    For Each oPara In ActiveDocument.Paragraphs
        If oPara.Style = "Heading 1" Then
            strList = strList & oPara.Range.Text & vbNewLine
        End If
    Next oPara
    MsgBox "Heading 1 List:" & vbNewLine & strList
End Sub

Working with a Specific Paragraph by Index

' Get the text of the third paragraph
Dim strText As String
strText = ActiveDocument.Paragraphs(3).Range.Text

' Change the style of the first paragraph to Heading 1
ActiveDocument.Paragraphs(1).Style = "Heading 1"

Using Range for Targeted Text Manipulation

' Insert text at the very start of the document
Dim rng As Range
Set rng = ActiveDocument.Range(0, 0)
rng.InsertBefore "CONFIDENTIAL" & vbCr

' Insert text at the very end of the document
Set rng = ActiveDocument.Range
rng.Collapse wdCollapseEnd
rng.InsertAfter vbCr & "[End of Document]"

25.6 Find & Replace via VBA

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.

Basic Find & Replace

Sub ReplaceCompanyName()
    With ActiveDocument.Content.Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Text = "Acme Corporation"
        .Replacement.Text = "Pinnacle Industries"
        .MatchCase = False
        .MatchWholeWord = True
        .Execute Replace:=wdReplaceAll
    End With
    MsgBox "Company name updated throughout document.", vbInformation
End Sub

Multiple Replacements with a Helper Procedure

Sub BatchReplace()
    FindReplace "colour", "color"
    FindReplace "organisation", "organization"
    FindReplace "analyse", "analyze"
    MsgBox "Batch replacement complete."
End Sub

' Helper procedure called by BatchReplace
Sub FindReplace(strFind As String, strReplace As String)
    With ActiveDocument.Content.Find
        .Text = strFind
        .Replacement.Text = strReplace
        .Execute Replace:=wdReplaceAll
    End With
End Sub

25.7 Working with Content Controls via VBA

Content controls can be read and written programmatically — enabling auto-populated forms, validation, and data extraction.

Reading and Writing Content Controls by Tag

Sub PopulateFormFields()
' Reads a value from InputBox and writes it to a content control by Tag
    Dim oCC As ContentControl
    Dim strName As String
    strName = InputBox("Enter employee full name:", "Employee Name")
    If strName = "" Then Exit Sub
    For Each oCC In ActiveDocument.ContentControls
        If oCC.Tag = "emp_name" Then
            oCC.Range.Text = strName
        End If
    Next oCC
End Sub

Reading All Content Control Values (Data Extraction)

Sub ExtractFormData()
' Lists all content control Tags and their values
    Dim oCC As ContentControl
    Dim strReport As String
    For Each oCC In ActiveDocument.ContentControls
        strReport = strReport & oCC.Tag & " = " & oCC.Range.Text & vbNewLine
    Next oCC
    MsgBox strReport, vbInformation, "Form Data"
End Sub

Checking a Checkbox Control State

For Each oCC In ActiveDocument.ContentControls
    If oCC.Tag = "handover_confirm" Then
        If oCC.Checked = False Then
            MsgBox "Please confirm handover before submitting.", vbExclamation
            Exit Sub
        End If
    End If
Next oCC

25.8 Document Automation — Creating, Saving & Exporting

Creating a New Document from a Template

Sub CreateFromTemplate()
    Dim strTemplatePath As String
    Dim objNewDoc As Document
    strTemplatePath = Environ("APPDATA") & "\Microsoft\Templates\Corp_Letter_v1.dotx"
    Set objNewDoc = Documents.Add(Template:=strTemplatePath)
    objNewDoc.Activate
End Sub

Saving a Document

' Save the active document (same as Ctrl+S)
ActiveDocument.Save

' Save As a specific name and location
ActiveDocument.SaveAs2 Filename:="C:\Reports\Annual_Report_2025.docx", _
    FileFormat:=wdFormatXMLDocument

' Save As PDF
ActiveDocument.ExportAsFixedFormat OutputFileName:="C:\Reports\Report.pdf", _
    ExportFormat:=wdExportFormatPDF, _
    CreateBookmarks:=wdExportCreateHeadingBookmarks

Closing a Document

ActiveDocument.Close SaveChanges:=wdSaveChanges              ' Save and close
ActiveDocument.Close SaveChanges:=wdDoNotSaveChanges       ' Close without saving
ActiveDocument.Close SaveChanges:=wdPromptToSaveChanges   ' Ask user

25.9 Error Handling — Writing Robust Macros

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 — The Standard Pattern

Sub SafeMacro()
    On Error GoTo ErrorHandler ' Jump to ErrorHandler label if any error occurs

    ' ... your main code here ...
    ActiveDocument.Save

    Exit Sub ' Exit before reaching ErrorHandler (normal path)

ErrorHandler:
    MsgBox "An error occurred: " & Err.Description & vbNewLine & _
           "Error number: " & Err.Number, vbCritical, "Macro Error"
End Sub

On Error Resume Next — Skip Errors (Use Sparingly)

On Error Resume Next ' Ignore errors and continue to the next line
' ... risky code ...
On Error GoTo 0     ' Re-enable normal error handling after the risky section
Use On Error Resume Next carefully: It silently ignores errors, which can hide real problems. Use it only for short sections where you expect a specific, harmless error (e.g., checking if a bookmark exists). Always restore normal error handling immediately after with On Error GoTo 0.

25.10 Practical VBA Macro Library

Macro 1 — Count Words in Each Heading Section

Sub SectionWordCounts()
    Dim oPara As Paragraph, strOut As String
    Dim strHead As String, intWords As Integer
    For Each oPara In ActiveDocument.Paragraphs
        If oPara.Style = "Heading 1" Then
            strHead = oPara.Range.Text
            intWords = oPara.Range.Words.Count
            strOut = strOut & strHead & " — " & intWords & " words" & vbNewLine
        End If
    Next
    MsgBox strOut, vbInformation, "Section Word Counts"
End Sub

Macro 2 — Auto-Generate and Save a Letter from a Template

Sub GenerateLetter()
    Dim strClient As String, strRef As String
    Dim oCC As ContentControl
    strClient = InputBox("Client name:", "Letter Generator")
    If strClient = "" Then Exit Sub
    strRef = InputBox("Reference number:", "Letter Generator")
    ' Fill content controls by Tag
    For Each oCC In ActiveDocument.ContentControls
        Select Case oCC.Tag
            Case "client_name": oCC.Range.Text = strClient
            Case "ref_no": oCC.Range.Text = strRef
        End Select
    Next
    ' Save as PDF
    ActiveDocument.ExportAsFixedFormat _
        OutputFileName:="C:\Letters\" & strRef & "_" & strClient & ".pdf", _
        ExportFormat:=wdExportFormatPDF
    MsgBox "Letter saved as PDF.", vbInformation
End Sub

Macro 3 — Bold All Rand Amounts in the Document

Sub BoldRandAmounts()
' Finds all "R " followed by digits and makes them bold
    With ActiveDocument.Content.Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Replacement.Font.Bold = True
        .Text = "R [0-9]"
        .Replacement.Text = ""
        .MatchWildcards = True
        .Execute Replace:=wdReplaceAll
    End With
    MsgBox "All Rand amounts bolded.", vbInformation
End Sub

25.11 Quick Self-Check

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.

✓ Module 25 Complete — You Have Learned:

  • VBA Editor full tour — all four panels (Project Explorer, Properties Window, Code Window, Immediate Window) with keyboard shortcuts; adding modules; essential editor toolbar shortcuts (F5 run, F8 step, Ctrl+Break, F9 breakpoint, Alt+F4)
  • VBA fundamentals — variables and data types (String, Integer, Long, Double, Boolean, Date, Document); naming conventions and prefixes; Const for constants; Option Explicit
  • Control flow — If/Then/ElseIf/Else/End If; For/Next loop; For Each/Next loop; Do While/Loop
  • String functions — & concatenation, vbNewLine, vbTab, Len, Left, Right, Mid, Trim, UCase/LCase, InStr
  • The Word Object Model — full hierarchy diagram (Application → Documents → Document → Paragraphs/Sections/Tables/ContentControls/Bookmarks/Fields/Range)
  • The 7 most important objects with key properties and methods (Application, ActiveDocument, Selection, Range, Paragraph, Table, ContentControl)
  • Selection vs Range — when to use each
  • MsgBox — simple messages, vbInformation/Exclamation/Critical/Question icons, Yes/No questions, all button constants and return values
  • InputBox — collecting user text; empty string check; Exit Sub on cancel
  • Looping through paragraphs — For Each with style check; accessing paragraphs by index
  • Range manipulation — Range(0,0) for document start; Collapse wdCollapseEnd for end; InsertBefore/InsertAfter
  • Find & Replace via VBA — ActiveDocument.Content.Find with all properties; batch replace with helper Sub; multiple sequential replacements
  • Content controls via VBA — loop and match by Tag; read and write .Range.Text; check .Checked for checkboxes; data extraction
  • Document automation — Documents.Add from template; ActiveDocument.Save; SaveAs2 with FileFormat; ExportAsFixedFormat for PDF with bookmarks; Close with SaveChanges options
  • Error handling — On Error GoTo ErrorHandler pattern; Exit Sub before handler; Err.Description/Number; On Error Resume Next with On Error GoTo 0 restoration; caution warning
  • 3 practical VBA macros — SectionWordCounts, GenerateLetter (InputBox → ContentControls → PDF export), BoldRandAmounts (wildcard Find & Replace with formatting)

🎓 Course Complete!

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.


← Back to All Modules