Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 37 ยท Working with Word and Outlook

Word Automation with VBA

Automate Microsoft Word with VBA: create documents, work with Range and Selection, styles, tables, find and replace, bookmarks and template filling.

Word has its own object model, separate from Excel's. The top object is Word.Application, which holds Documents; each Document holds paragraphs, tables, sections, bookmarks and a Range for any stretch of text. You can write macros inside Word itself, or drive Word from Excel or another Office program.

The central idea is the same as in Excel: avoid Selection (which acts like the user's cursor) and work with Range objects instead. This lesson covers documents, text, styles, tables, find and replace, and filling a template with bookmarks.

VBA is read-only here. The runnable examples are JavaScript stand-ins for the text-processing ideas, such as placeholder replacement and building a table from data.

Documents and the Application

VB
Sub NewLetter()
    Dim doc As Document
    Set doc = Documents.Add            ' inside Word; Application is implicit
    doc.Content.Text = "Dear customer," & vbCr & "Thank you for your order."
    doc.SaveAs2 FileName:="C:\Out\Letter.docx", FileFormat:=wdFormatXMLDocument
    doc.Close SaveChanges:=False
End Sub

From another application (for example Excel) you start Word yourself. Early binding needs a reference to the Word library (Tools > References); the late-bound version needs none:

VB
Dim wdApp As Object, doc As Object
Set wdApp = CreateObject("Word.Application")
wdApp.Visible = False
Set doc = wdApp.Documents.Open("C:\Templates\Letter.docx")
' ... work ...
doc.Close False
wdApp.Quit
Set wdApp = Nothing

Always Quit the instance you started, or a hidden WINWORD.EXE keeps running.

Range, paragraphs and styles

VB
Dim doc As Document: Set doc = ActiveDocument
Dim r As Range

Set r = doc.Content
r.InsertAfter "Report title" & vbCr
doc.Paragraphs(1).Style = doc.Styles(wdStyleHeading1)

Set r = doc.Paragraphs(doc.Paragraphs.Count).Range
r.InsertParagraphAfter
Set r = doc.Paragraphs(doc.Paragraphs.Count).Range
r.Text = "Body text."
r.Style = doc.Styles(wdStyleNormal)
r.Font.Size = 11

Facts to remember:

  • A paragraph ends with the carriage return vbCr (Chr 13), not vbCrLf.
  • Range(Start, End) uses character positions: doc.Range(0, 5) is the first five characters.
  • doc.Content is the whole main text; doc.Paragraphs(1).Range is one paragraph.
  • Use styles (Heading 1, Normal) rather than direct formatting. Styles are what make a table of contents and consistent design possible.

Find and replace

VB
With ActiveDocument.Content.Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Text = "{CustomerName}"
    .Replacement.Text = "Ada Lovelace"
    .Forward = True
    .Wrap = wdFindStop
    .Execute Replace:=wdReplaceAll
End With

This is the simplest way to fill a template: write placeholders like in the document, and replace each one. For long replacement text (over 255 characters) set the range text yourself instead.

Bookmarks

A bookmark marks a position or a text span that code can find by name.

VB
Sub FillBookmark(doc As Document, name As String, value As String)
    If doc.Bookmarks.Exists(name) Then
        Dim r As Range
        Set r = doc.Bookmarks(name).Range
        r.Text = value
        doc.Bookmarks.Add name, r          ' replacing text deletes the bookmark; re-add it
    End If
End Sub

Bookmarks survive reformatting better than placeholder text and are the standard way to build form letters, contracts and invoices.

Tables

VB
Dim t As Table
Set t = doc.Tables.Add(Range:=doc.Paragraphs(doc.Paragraphs.Count).Range, _
                       NumRows:=3, NumColumns:=2)
t.Style = "Table Grid"
t.Cell(1, 1).Range.Text = "Item"
t.Cell(1, 2).Range.Text = "Price"
t.Rows(1).Range.Font.Bold = True
t.Cell(2, 1).Range.Text = "Pen"
t.Cell(2, 2).Range.Text = "1.50"

Indexing is Cell(row, column), starting at 1. For many rows, build tab-delimited text and use Range.ConvertToTable, which is much faster than setting cells one by one.

Try it: placeholder filling and table text

JS Fill a template with placeholders

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

No output.

JS Build a table from data (ConvertToTable idea)

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

No output.

Common mistakes

  • Using Selection in code that must run unattended; Range is faster and does not depend on the cursor.
  • Writing vbCrLf instead of vbCr in Word text.
  • Forgetting wdApp.Quit, leaving invisible Word processes.
  • Hard-coding Paragraphs(5) when paragraphs can move; use bookmarks or styles.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why prefer Range over Selection in a macro?

    Range objects work independently of the user's cursor and are the standard approach for automation.
  2. 2. What character ends a paragraph in Word text?

    Word paragraphs end with a carriage return, Chr(13).
  3. 3. What is a good way to fill a form letter?

    Bookmarks and placeholders let code locate positions by name or token.
  4. 4. When controlling Word from Excel, what should you always do at the end?

    A started Word instance keeps running invisibly unless you quit it.

Summary

  • Word's hierarchy is Application > Documents > Document > Range/Paragraphs/Tables.
  • Work with Range and styles, not Selection and manual formatting.
  • Fill templates using placeholders with Find.Execute or named bookmarks.
  • Build tables with Tables.Add or ConvertToTable; use vbCr between paragraphs.
  • Quit any Word instance you start from another application.

Next: Outlook E-mail Automation with VBA