VBA and Microsoft Word

VBA can be used to complete a wide range of tasks in Microsoft Word. Some of the most useful are writing and reading to the document. This allows your code and scripts to interact with documents hopefully automating the boring stuff.

Microsoft Document Model

When starting to use VBA to control Microsoft word it is important to get a better understanding of how Word stores the data and how you can access it. There are two key ideas that help to get you started on automating the stuffing out of future word projects. 

    Paragraphs - Word allows you to read the document Paragraph by Paragraph
    Tables - Word allows you to read through the document Table by Table

These are the two concepts we are going to use for this introduction to VBA and word documents. In the examples below the understanding of how the new line character is important as this will be returned in most instances. 

Reading Text From Word


We have created a basic word document that we are going to use VBA to get the text from each paragraph. Here is the example document. 

Word Document:


Code:
Sub readParagraph()

PCount = ActiveDocument.Paragraphs.Count
For i = 1 To PCount
    Par = ActiveDocument.Paragraphs(i).Range.Text
    MsgBox Par
    '[Add processing comments to manipulate sMyPar]
    'ActiveDocument.Paragraphs(J).Range.Text = sMyPar
Next i


End Sub

In Word:


Output:



Writing Text To Word

Word Document:
The same document from the example above has been used.


Code:
Sub writeParagraph()

ActiveDocument.Paragraphs(1).Range.Text = "Updated text here" + Chr(13) + Chr(7)


End Sub

In Excel:


Output:

Writing Tables in Word

Document:
The word document above has had a table added below the paragraphs.

Code:
Sub writeTable()

ActiveDocument.Tables(1).Cell(1, 1).Range = "Title"

End Sub

In Word:

Output:


Reading Tables in Word

Code:
Sub readTable()

TCount = ActiveDocument.Tables.Count
For i = 1 To TCount
    Table = ActiveDocument.Tables(i).Cell(1, 1)
    MsgBox (Table)
Next i


End Sub

In Word:


Output:

Reading Tables in Word (and Removing New Line characters)

Code:
Sub readTable2()

TCount = ActiveDocument.Tables.Count
For i = 1 To TCount
    Table = ActiveDocument.Tables(i).Cell(1, 1)
    MsgBox Replace(Table, Chr(13) + Chr(7), "")
Next i


End Sub

In Word:


Output:



Related Sections

Python - Learn the python from the basics up. This fast track example code course will get you creating powerful python programs in no time.



Must Read Articles


VBA and Microsoft Excel - Getting the most out of excel with VBA programming
VBA and Microsoft Word - Getting the most out of word with VBA programming
Application Object - Using the applications features in your code.
Installing VBA and First Program - What do you need to start using visual basic application VBA.