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

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
Before you start
Example file
Expert Word - Automation.docx
Download the practice document used in this tutorial and follow along in Word.
Word document (.docx) · 38 KB
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.
| Chore | How often | Minutes | Error risk | Good tool |
|---|---|---|---|---|
| Typing the club contact box | Daily | 1 | Low | Quick Part or AutoText (no code) |
| Fixing Tutering Club and other typos | Daily | Seconds | Low | AutoCorrect entry |
| Cleaning pasted text in handouts | 10 per week across sites | 10 | Medium | Recorded macro, then edited |
| Updating fields and saving a PDF of the monthly report | Monthly | 5 | High (forgotten updates) | Short VBA macro |
| 60 completion certificates | Twice a year | 90 | High (names) | Mail merge or a python-docx script |
| Checking 40 old handouts for headings and template version | Once a term | 120 | Medium | python-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
Compare your options
Each tool runs in a different place and needs different skills. Pick by where the people who will use it work.
| Tool | Code? | Runs in | Best for | Limits |
|---|---|---|---|---|
| Quick Parts / AutoText | No | Word desktop | Inserting the same content again and again | Inserts content; doesn't change existing text |
| AutoCorrect | No | Word on that computer | Fixing or expanding words as you type | Only as you type, only on your computer |
| Recorded macro | Generated for you | Word for Windows and Mac | Replaying a fixed series of commands | Follows the cursor; you can't select text with the mouse while recording |
| VBA macro | VBA | Word for Windows and Mac | Loops, decisions, many documents at once | Not in Word for the web; files need .docm or .dotm; blocked in files from the internet |
| Office add-in | JavaScript | Word for Windows, Mac and the web | A team tool in a side pane that works everywhere | Needs web development, hosting and deployment |
| python-docx | Python | Outside Word, on any computer with Python | Creating, reading or cleaning many .docx files | Can't update fields, rebuild a TOC, paginate or make PDFs |
| Power Automate | Low-code | The cloud | Workflows started by a form, an email or a schedule | Depends 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
- Prepare. Open a copy of the messy handout. Decide the exact steps before you start; every click is recorded.
- Name it. Click Record Macro and type a name with no spaces, such as
CleanHandout. - 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.
- 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.
- 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.
- Stop. Click View
then Macros then Stop Recording (or the same button on the Developer tab). - Run it. Press Alt+F8, pick
CleanHandoutand click Run.
Read and improve the code in the VBA editor
Press Alt+F11 (or Developer
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 SubWord 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 SubWhat 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.Contentis 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 SubSave, 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 in | File type | Who gets it |
|---|---|---|
| Normal.dotm | Your personal global template | Only 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.docx.
Macro security. Macros can do anything Word can, including deleting files, so Word is careful about them. The settings live in File
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
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
.docxfrom the kit template and use it as the base; it keeps all the styles. - Setting
para.textkeeps 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
| Mistake | What happens | Fix |
|---|---|---|
| Automating before trying Quick Parts or AutoCorrect | Hours spent on code for a one-click problem | Try the no-code tools first |
| Clicking in the document while recording | Word doesn't record the selection, so the macro does something else | Move and select with the keyboard while recording |
| Keeping the recorded code as it is | It depends on the cursor and is hard to read or change | Switch to a Range, remove extra settings, add comments and Option Explicit |
| Saving a document with macros as .docx | The macros are removed | Save as .docm, or keep the macros in a .dotm |
| Asking people to enable all macros | Every document they open can run harmful code | Share a .dotm from a trusted location or have the macros signed |
| Running a script or macro on the only copy | One bug changes every file | Test on copies in a separate folder |
| Expecting python-docx to update fields or make PDFs | The TOC and page numbers stay out of date | Finish 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.
- 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.
- 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. - Run: press Alt+F8 and run it. Turn on Ctrl+Shift+8 and notice that triple spaces became double spaces.
- Read: press Alt+F11, open NewMacros and find your recording. Point out the lines that use
Selection. - Rewrite: replace it with the
CleanHandoutandReplaceAllWildcode from this tutorial, withOption Explicitat the top. Run it on the copy and check that empty paragraphs are gone. - Decide per paragraph: create a paragraph style named Tip Box (any border and shading), add the
StyleTipsmacro, and run it. Check the message: how many tips did it find? - Save safely: save the handout as a normal
.docxand 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.
You are recording a macro and want to select the next sentence. What should you do?
Word doesn't let you select text with the mouse while recording. Keyboard selection is recorded.
Why change a recorded macro from the Selection to ActiveDocument.Content?
A Range such as ActiveDocument.Content doesn't depend on the cursor, so the macro behaves the same every time.
Volunteers get a macro-enabled file by email and see a red Security Risk bar. What is the right response?
Files from the internet carry the Mark of the Web and have macros blocked on purpose. Use a trusted location or signed macros instead of lowering security.
Which task is python-docx NOT able to do by itself?
python-docx edits the file's content without running Word, so it can't update fields, paginate or export PDFs.
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