Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 42 ยท Mail Merge, Macros and Automation

Macros and VBA in Word

Record and run Word macros, assign them to buttons and shortcuts, read and edit VBA code in the Visual Basic Editor, handle macro security and save macro-enabled files.

A macro is a saved sequence of actions that Word can repeat on demand. If you find yourself doing the same ten clicks every day (applying a set of formats, cleaning pasted text, inserting a standard block), a macro turns them into one click. Behind each macro is code in VBA (Visual Basic for Applications), a programming language built into Office.

Word cannot run on this site, so the VBA below is read-only. The runnable examples are small stand-ins in Python and JavaScript that show how a recorder and a macro work.

The Developer tab

Macro tools live on the Developer tab, which is hidden by default. Show it with File > Options > Customize Ribbon, then tick Developer in the right-hand list. It has Visual Basic, Macros, Record Macro, Macro Security and the content-control buttons.

Recording a macro

  1. Click View > Macros > Record Macro... (or Developer > Record Macro).
  2. Give it a Macro name (letters, numbers, underscores; no spaces), for example CleanPaste.
  3. Choose Store macro in: All Documents (Normal.dotm) makes it available everywhere; the current document keeps it local.
  4. Add a Description.
  5. Assign it: Button adds it to the Quick Access Toolbar, Keyboard assigns a shortcut such as Ctrl+Alt+K. Check that the key is not already used (the dialog warns you under Currently assigned to).
  6. Click OK. The pointer shows a recorder icon.
  7. Do the actions. Then Stop Recording.

Rules for good recording:

  • The recorder ignores mouse movement inside the text. Use the keyboard to select text (Shift+arrow, Ctrl+Shift+arrow, Home, End).
  • Do not click a place to position the cursor; use keys instead.
  • Use Find (Ctrl+F) in a recording to move to specific text.
  • Plan the steps first, and rehearse them once.

Run a macro with View > Macros > View Macros (Alt+F8), select it and click Run, or use the button or shortcut you assigned. Ctrl+Z can undo a macro in one step in most cases.

Looking at the code

Press Alt+F11 to open the Visual Basic Editor (VBE). The Project Explorer on the left shows Normal (global) and your document; macros are in Modules. A recorded macro to make selected text bold and red looks like this (read-only):

VB
Sub RedBold()
'
' RedBold Macro
'
    Selection.Font.Bold = True
    Selection.Font.Color = wdColorRed
End Sub

Reading the pieces:

  • Sub ... End Sub wraps a procedure with no return value (Function returns one).
  • Selection is the current selection or the cursor.
  • .Font.Bold is a property; = True sets it.
  • Lines that begin with ' are comments.

The Word object model is a tree: Application contains Documents, each Document contains Paragraphs, Tables, Sections, Fields and Range objects. Learn a few of them and you can edit documents without a selection, which is faster and safer:

VB
Sub FixDoubleSpaces()
    With ActiveDocument.Content.Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Text = "  "
        .Replacement.Text = " "
        .Forward = True
        .Wrap = wdFindContinue
        .Execute Replace:=wdReplaceAll
    End With
End Sub
VB
Sub CountHeadings()
    Dim p As Paragraph, n As Long
    For Each p In ActiveDocument.Paragraphs
        If p.OutlineLevel = wdOutlineLevel1 Then n = n + 1
    Next p
    MsgBox "Heading 1 count: " & n
End Sub

Use F5 inside the editor to run, F8 to step line by line, F9 to set a breakpoint. The Immediate window (Ctrl+G) tests expressions, for example ?ActiveDocument.Paragraphs.Count.

Why recorded macros are brittle

A recorder writes down what you did, not what you meant. It replays actions on whatever is selected at that time, and may contain unneeded lines like Selection.TypeText for every keystroke. Clean up the code: remove repeated lines, replace Selection with Range objects where possible and add checks (for example, "if nothing is selected, stop").

This runnable stand-in shows the recording idea in Python: a recorder stores actions, and a player replays them on any text. It is not VBA.

Python A tiny macro recorder (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The same idea in the browser: a button that runs a stored list of text operations. Edit the list to change the macro.

Run a macro on text

Running, editing and organizing

  • Macros dialog (Alt+F8): Run, Step Into, Edit, Create, Delete, Organizer. Organizer copies macros between documents and templates.
  • Add to the ribbon: File > Options > Customize Ribbon > Choose commands from: Macros, and drag a macro to a custom group.
  • Auto macros: names such as AutoOpen, AutoNew and AutoClose run on those events. They are a frequent malware hiding place; use them sparingly.
  • Digital signature for projects: in the VBE, Tools > Digital Signature signs your code so others can trust it.

Saving macro files

Macros cannot be stored in a plain .docx. Choose:

Format Contains macros? Use
.docx No Normal documents
.docm Yes Macro-enabled document
.dotx No Template
.dotm Yes Macro-enabled template
Normal.dotm Yes Your personal macros, loaded in every session

If you save a document with macros as .docx, Word warns that they will be removed.

Macro security

Macros can do anything you can, including deleting files, so malicious documents use them. Never enable macros in a file you did not expect. In Developer > Macro Security (Trust Center > Macro Settings) the options are:

  • Disable all macros without notification
  • Disable all macros with notification (the default; a yellow bar appears with Enable Content)
  • Disable all macros except digitally signed macros
  • Enable all macros (not recommended)

Files downloaded from the internet may be blocked by a red message bar ("Mark of the Web"). Microsoft's current default blocks macros in such files. Keep trusted macros in Trusted Locations or sign them. Cloud and Mac versions use different settings, and Word on the web does not run VBA. Office Scripts and Office Add-ins (see Add-ins, Copilot and Integration) are the modern alternatives for sharing automation.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which shortcut opens the Visual Basic Editor?

    Alt+F11 opens the VBE; Alt+F8 opens the macro list.
  2. 2. In which file type can a document with a macro be saved?

    .docm is the macro-enabled document format.
  3. 3. Why should you use the keyboard rather than the mouse to move the cursor while recording?

    The recorder records keyboard navigation but ignores mouse positioning in the document body.
  4. 4. What is the safest default macro setting?

    Macros stay off until you decide that a file is trustworthy.

Summary

  • Show the Developer tab to record, run and edit macros.
  • Plan recordings and use the keyboard to navigate.
  • Open Alt+F11 to read and edit VBA; learn Selection, Range and Find.
  • Save macro files as .docm or .dotm; personal macros live in Normal.dotm.
  • Keep macro security strict and never enable unknown macros.

Next: Quick Parts, Fields and Content Controls