Skip to content
ArumSoft Learning
KO

    Expert Word · Tutorial 2 of 9

    How to Automate Word with VBA Macros, Office Add-ins and Python

    Decide which Word chores are worth automating, then pick the right tool: a VBA macro, an Office JavaScript add-in or a python-docx script.

    Level
    Expert
    Time
    15 min read
    Updated:
    Applies to:
    Word for Microsoft 365, Word 2024, Word 2021, Word for the web
    A handout after running two small macros: double spaces and empty paragraphs are gone and every tip uses the Tip Box style.
    Example: A handout after running two small macros: double spaces and empty paragraphs are gone and every tip uses the Tip Box style.

    What you'll learn

    • Decide which Word chores are worth automating with frequency, time and error risk
    • Choose between Quick Parts, AutoCorrect, macros, add-ins, python-docx and Power Automate
    • Record a macro, then read and improve its VBA code in the Visual Basic Editor
    • Save and share macros safely in .docm or .dotm files without lowering security
    • Batch-create or check many .docx files with a short python-docx script

    Example file

    Expert Word - Automation.docx

    Download the practice document used in this tutorial and follow along in Word.

    Word document (.docx) · 38 KB

    Download example file

    The Tutoring Club's template kit from Tutorial 1 made documents consistent. But coordinators still repeat the same chores: cleaning text pasted from emails, styling every tip box, updating fields before a PDF goes out, making sixty certificates. Each chore is small. Together they eat hours, and people make mistakes when they are bored.

    In this tutorial you will decide which chores are worth automating, compare the tools Word gives you (from no-code AutoCorrect to VBA, Office add-ins and Python), record a macro and turn it into readable code, and learn how to share it without teaching anyone to switch off macro security.

    Decide what's worth automating

    Automation costs time up front: building, testing, explaining and fixing it later. It pays off when a task scores high on at least two of three things:

    • Frequency: how often someone does it (per week, per term).
    • Time: how many minutes it takes each time.
    • Error risk: how bad a mistake is (a typo in a child's name on a certificate is worse than an extra space).

    A quick estimate: times per term × minutes each gives the time you could save. Double it if mistakes are costly. If building the automation would take longer than that, wait or pick a simpler tool.

    ChoreHow oftenMinutesError riskGood tool
    Typing the club contact boxDaily1LowQuick Part or AutoText (no code)
    Fixing Tutering Club and other typosDailySecondsLowAutoCorrect entry
    Cleaning pasted text in handouts10 per week across sites10MediumRecorded macro, then edited
    Updating fields and saving a PDF of the monthly reportMonthly5High (forgotten updates)Short VBA macro
    60 completion certificatesTwice a year90High (names)Mail merge or a python-docx script
    Checking 40 old handouts for headings and template versionOnce a term120Mediumpython-docx script

    Notice that the first two rows need no code at all. Always try the simplest tool first: Quick Parts and AutoText for repeated content, AutoCorrect (File then Options then Proofing then AutoCorrect Options) for repeated typos, and mail merge for one document per row of a list.

    Compare your options

    Each tool runs in a different place and needs different skills. Pick by where the people who will use it work.

    ToolCode?Runs inBest forLimits
    Quick Parts / AutoTextNoWord desktopInserting the same content again and againInserts content; doesn't change existing text
    AutoCorrectNoWord on that computerFixing or expanding words as you typeOnly as you type, only on your computer
    Recorded macroGenerated for youWord for Windows and MacReplaying a fixed series of commandsFollows the cursor; you can't select text with the mouse while recording
    VBA macroVBAWord for Windows and MacLoops, decisions, many documents at onceNot in Word for the web; files need .docm or .dotm; blocked in files from the internet
    Office add-inJavaScriptWord for Windows, Mac and the webA team tool in a side pane that works everywhereNeeds web development, hosting and deployment
    python-docxPythonOutside Word, on any computer with PythonCreating, reading or cleaning many .docx filesCan't update fields, rebuild a TOC, paginate or make PDFs
    Power AutomateLow-codeThe cloudWorkflows started by a form, an email or a scheduleDepends on your Microsoft 365 plan; some Word actions need a premium license

    Record a macro

    A macro is a small program saved under a name. The quickest way to make one is to let Word watch you. You can record from View then Macros then Record Macro, or turn on the Developer tab (File then Options then Customize Ribbon, tick Developer) and use its Code group.

    Developer then Code then Record Macro. While recording, the button changes to Stop Recording.
    1. Prepare. Open a copy of the messy handout. Decide the exact steps before you start; every click is recorded.
    2. Name it. Click Record Macro and type a name with no spaces, such as CleanHandout.
    3. Choose where it lives. In Store macro in, All Documents (Normal.dotm) makes it available in every document on your computer. Choosing the open document keeps it inside that file.
    4. Optional shortcut. Click Button to add it to the Quick Access Toolbar, or Keyboard to give it a key combination that isn't already used.
    5. Do the steps. Click OK, press Ctrl+H, type two spaces in Find what and one in Replace with, click Replace All, close the dialog.
    6. Stop. Click View then Macros then Stop Recording (or the same button on the Developer tab).
    7. Run it. Press Alt+F8, pick CleanHandout and click Run.

    Read and improve the code in the VBA editor

    Press Alt+F11 (or Developer then Code then Visual Basic) to open the Visual Basic Editor. In the Project pane on the left, open Normal > Modules > NewMacros. Your recording looks something like this:

    Sub CleanHandout()
    '
    ' CleanHandout Macro
    '
        Selection.Find.ClearFormatting
        Selection.Find.Replacement.ClearFormatting
        With Selection.Find
            .Text = "  "
            .Replacement.Text = " "
            .Forward = True
            .Wrap = wdFindContinue
            .Format = False
            .MatchCase = False
            .MatchWholeWord = False
            .MatchWildcards = False
            .MatchSoundsLike = False
            .MatchAllWordForms = False
        End With
        Selection.Find.Execute Replace:=wdReplaceAll
    End Sub

    Word recorded every setting in the Replace dialog, used the Selection (the cursor), and replaced only pairs of spaces, so three spaces become two. Here is the same idea rewritten so a teammate can read it, plus empty-paragraph cleanup using the wildcards from the Advanced find and replace tutorial:

    Option Explicit
    
    ' Cleans pasted text in a handout. Run it on a copy first.
    Sub CleanHandout()
        ' Two or more spaces become one space
        ReplaceAllWild " {2,}", " "
        ' Repeated paragraph marks become one: no empty paragraphs
        ReplaceAllWild "^13{2,}", "^p"
    End Sub
    
    ' Wildcard Replace All in the main text of the active document
    Private Sub ReplaceAllWild(findText As String, _
                               replaceText As String)
        Dim rng As Range
        ' The whole main text, not the selection
        Set rng = ActiveDocument.Content
        With rng.Find
            .ClearFormatting
            .Replacement.ClearFormatting
            .Text = findText
            .Replacement.Text = replaceText
            .MatchWildcards = True
            .Execute Replace:=wdReplaceAll
        End With
    End Sub

    What changed and why:

    • Option Explicit at the top makes VBA refuse to run if you misspell a variable name, instead of quietly creating a new empty one. Turn it on for every new module with Tools then Options in the editor and tick Require Variable Declaration.
    • Comments start with an apostrophe. Write why as well as what.
    • A Range instead of the Selection. ActiveDocument.Content is the whole main text, so the macro does the same thing wherever the cursor is, and the screen doesn't jump around.
    • A small helper (ReplaceAllWild) is written once and called twice, so adding a third cleanup is one line.

    Now a macro you couldn't record at all, because it makes a decision for each paragraph. It needs a paragraph style named Tip Box in the document (from the kit template):

    Option Explicit
    
    ' Applies Tip Box to every paragraph that starts with "Tip:"
    Sub StyleTips()
        Dim para As Paragraph
        Dim count As Long
    
        For Each para In ActiveDocument.Paragraphs
            If LCase(Left(para.Range.Text, 4)) = "tip:" Then
                para.Range.Style = ActiveDocument.Styles("Tip Box")
                ' Remove hand formatting, keep the style
                para.Range.Font.Reset
                count = count + 1
            End If
        Next para
    
        MsgBox count & " tip paragraphs now use Tip Box."
    End Sub

    Before

    • Double and triple spaces
    • Empty paragraphs for spacing
    • Tips formatted by hand, each differently

    After

    • CleanHandout: single spaces, no empty paragraphs
    • StyleTips: every tip uses Tip Box
    The practice handout before and after running the two macros.

    Save, share and trust macros safely

    An ordinary .docx can't hold macros. If you save a document with a macro as .docx, Word warns that the VB project can't be saved in a macro-free document, and the macro is removed. Choose where the code should live:

    Store the macro inFile typeWho gets it
    Normal.dotmYour personal global templateOnly you, in every document on your computer. Good for your own tools
    A macro-enabled document.docm (Word Macro-Enabled Document)Anyone who opens that one file and is allowed to run its macros
    A macro-enabled template.dotm (Word Macro-Enabled Template)Everyone who creates documents from it, or loads it as a global template

    For a team, the tidy choice is a separate TC Tools.dotm that holds only the club's macros, while the kit templates stay macro-free .dotx files. Each coordinator loads it with Developer then Templates then Document Template: under Global templates and add-ins, click Add. The macros then appear in Alt+F8 in every document, but the documents themselves stay .docx.

    Macro security. Macros can do anything Word can, including deleting files, so Word is careful about them. The settings live in File then Options then Trust Center then Trust Center Settings then Macro Settings, and the safe default is to disable macros with a notification. Files that came from the internet, including email attachments, carry a Mark of the Web, and Microsoft 365 blocks macros in them by default with a red Security Risk bar.

    Office add-ins: automation that works everywhere

    An Office add-in is a small web app that runs inside Word, usually as a pane on the right. It is written in HTML and JavaScript using the Word JavaScript API, and the same add-in works in Word for Windows, Mac and the web. You find installed ones under Home then Add-ins or Developer then Add-ins then Word Add-ins, depending on your version.

    The code talks to the document through objects much like VBA's, but it works in batches: you queue up requests, then context.sync() sends them to Word. This is the tip-styling idea as an add-in would do it:

    // Word JavaScript API, inside an add-in:
    // style every paragraph that starts with "Tip:"
    await Word.run(async (context) => {
      const paras = context.document.body.paragraphs;
      paras.load("items/text");
      await context.sync();
      for (const p of paras.items) {
        if (p.text.toLowerCase().startsWith("tip:")) {
          p.style = "Tip Box";
        }
      }
      await context.sync();
    });

    Building one is a web development project: you need a manifest file, a place to host the web files, and a way to deploy it. Developers can sideload an add-in to test it; for a team, a Microsoft 365 admin usually deploys it from the admin center, and public add-ins are listed in Microsoft's add-in store. For the Tutoring Club, an add-in only makes sense if many volunteers use Word for the web and a volunteer with web skills will maintain it. Start from the Word add-ins documentation linked in Sources.

    Batch work outside Word: python-docx and Power Automate

    python-docx is a free Python library that reads and writes .docx files directly, without opening Word. It is ideal when you have many files to create or check. This script makes one certificate per student from a base document that has a [Name] line:

    # pip install python-docx
    from docx import Document
    
    names = ["Ana Lopez", "Min-jun Park", "Sam Lee"]
    
    for name in names:
        # A .docx saved from the kit template
        doc = Document("Certificate base.docx")
        for para in doc.paragraphs:
            if "[Name]" in para.text:
                para.text = para.text.replace("[Name]", name)
        doc.save(f"Certificate - {name}.docx")

    And this one lists how many headings each handout in a folder has, a quick way to find handouts that were formatted by hand instead of with styles:

    from pathlib import Path
    from docx import Document
    
    for path in sorted(Path("Handouts").glob("*.docx")):
        doc = Document(str(path))
        heads = [p.text for p in doc.paragraphs
                 if p.style.name.startswith("Heading")]
        print(path.name, "-", len(heads), "headings:", heads[:3])
    • Start from a .docx, not the .dotx. python-docx opens documents, so save a .docx from the kit template and use it as the base; it keeps all the styles.
    • Setting para.text keeps the paragraph style but replaces the bold or colored parts inside it with plain text. Format the placeholder line with a paragraph style, not by hand.
    • It isn't Word. It can't update fields or a table of contents, work out page numbers or save PDFs. Open the results in Word for those steps, or run a VBA macro over them.
    • Work on copies in their own folder, so a script mistake can't overwrite the originals.

    Power Automate is Microsoft's cloud workflow tool. If your organization has it, a flow can, for example, take a sign-up form response, fill a Word template's content controls with the answers, convert the result to PDF and save it to SharePoint. Some of the Word actions need a premium license, and what you can use depends on your Microsoft 365 plan, so check with whoever manages your account before you plan around it.

    Common mistakes

    MistakeWhat happensFix
    Automating before trying Quick Parts or AutoCorrectHours spent on code for a one-click problemTry the no-code tools first
    Clicking in the document while recordingWord doesn't record the selection, so the macro does something elseMove and select with the keyboard while recording
    Keeping the recorded code as it isIt depends on the cursor and is hard to read or changeSwitch to a Range, remove extra settings, add comments and Option Explicit
    Saving a document with macros as .docxThe macros are removedSave as .docm, or keep the macros in a .dotm
    Asking people to enable all macrosEvery document they open can run harmful codeShare a .dotm from a trusted location or have the macros signed
    Running a script or macro on the only copyOne bug changes every fileTest on copies in a separate folder
    Expecting python-docx to update fields or make PDFsThe TOC and page numbers stay out of dateFinish those steps in Word

    Practice

    Practice

    Record a macro, then make it readable

    Guided practice

    Download the example file above and open it in Word. Page 1 is a math handout pasted together from emails: double spaces, empty paragraphs and tips formatted by hand. Page 2 is your task list. Save a copy before you start, and work in the copy.

    1. Score: in the table on page 2, estimate how often each chore happens, how long it takes and how risky it is. Circle the two worth automating.
    2. Record: start View then Macros then Record Macro, name it CleanHandout, store it in All Documents (Normal.dotm), and record one Replace All of two spaces with one. Stop recording.
    3. Run: press Alt+F8 and run it. Turn on Ctrl+Shift+8 and notice that triple spaces became double spaces.
    4. Read: press Alt+F11, open NewMacros and find your recording. Point out the lines that use Selection.
    5. Rewrite: replace it with the CleanHandout and ReplaceAllWild code from this tutorial, with Option Explicit at the top. Run it on the copy and check that empty paragraphs are gone.
    6. Decide per paragraph: create a paragraph style named Tip Box (any border and shading), add the StyleTips macro, and run it. Check the message: how many tips did it find?
    7. Save safely: save the handout as a normal .docx and confirm that the macros are still in Normal.dotm, not in the document.

    Independent challenge: One click before every PDF

    Write a macro UpdateAndExportPdf that updates every field (ActiveDocument.Fields.Update), saves the document, and saves a PDF copy next to it with ActiveDocument.ExportAsFixedFormat. Look up the arguments in the Word VBA reference. Then extend StyleTips so it also catches tips that start with a space, using LTrim. Add both macros to the Quick Access Toolbar.

    Reflect: which chore in your own week scores highest on frequency, time and error risk, and what is the simplest tool that would handle it?

    Check your understanding0 of 4 correct

    Pick an answer to see whether it's right and why.

    1. You are recording a macro and want to select the next sentence. What should you do?

    2. Why change a recorded macro from the Selection to ActiveDocument.Content?

    3. Volunteers get a macro-enabled file by email and see a red Security Risk bar. What is the right response?

    4. Which task is python-docx NOT able to do by itself?

    You're ready to move on when

    Tick each one off as you go. Your ticks are saved in this browser only.

    Related

    Sources and further reading

    Was this guide helpful? Spot a mistake? Send feedback · admin@arumsoft.com