VBA Word
Word is a Microsoft application used for word processing. VBA is embdedded within the Word application and can be used to programmatically work with Word. The Word Object Library contains classes that make working with Word in VBA possible. The classes in the Word Object Library are collectively referred to as the Word Object Model. When using VBA in Word, a reference is included to the Word Object Library.
Word Object Model
The Word Object Model contains classes that make it possible to work with Word in VBA. The Word Object Model contains many classes but the general overview of the model is Application → Document → Range.
Context
The place where VBA code is written determines the implied context when referring to classes. For example, when using VBA in Word and referring to the Application object, it is implied that Application and Word.Application are the same object. However, when using VBA in another application to work with Word, it is necessary to qualify references to avoid naming collisions with classes in the other application. Using qualified references requires that a reference is set to the library where the classes are defined. If a reference cannot be set, late-binding can be used instead.
Public Sub Example()
'''In Word
Debug.Print Application Is Word.Application 'Prints: True
End Sub
Public Sub Example()
'''In Excel
'Requires a reference to the Word Object Library
Debug.Print Application Is Word.Application 'Prints: False
Debug.Print Application Is Excel.Application 'Prints: True
End Sub
To retrieve the Word Application object from another application, attempt to retrieve the running application and if that fails start a new instance of the application.
Public Function GetWordApp() As Object
On Error Resume Next
Set GetWordApp = GetObject(, "Word.Application")
On Error GoTo 0
If GetWordApp Is Nothing Then
Set GetWordApp = CreateObject("Word.Application")
End If
End Sub
Application
The Application object represents the Word application itself. The Application object is the top-level object and provides access to the rest of the Word Object Model. The Application object can be used to access functionality and properties of the Word application.
Options
The Application.Options property contains a number of options that can be set for the Word application.
Public Sub Example()
Word.Application.Options.DisplayGridLines = True
End Sub
Validation Methods
The Application object has methods which facilitate validating and cleaning text:
Public Sub Example()
Debug.Print Word.Application.CheckGrammar("Hello my name is Peter.")
Debug.Print Word.Application.CheckGrammar("Hello, my name is Peter.")
Debug.Print Word.Application.CheckSpelling("Helllo, how are you?")
Debug.Print Word.Application.CheckSpelling("Hello, how are you?")
Dim S As String
S = "Hello," & Chr(0) & "World!"
S = Word.Application.CleanString(S)
Debug.Print Asc(Mid$(S, 7, 1)) 'Null character replaced with Space
End Sub
Documents
The Document class represents a Word document. The Documents collection object represents all open Word documents and can be accessed from the Application.Documents property.
Iterate Documents
To iterate over all open documents use a For Each loop with the Documents collection object.
Public Sub Example()
Dim D As Word.Document
For Each D In Word.Application.Documents
Debug.Print D.Name
Next D
End Sub
Add Document
To add a document use the Documents.Add method.
Public Sub Example()
Dim D As Word.Document
Set D = Word.Application.Documents.Add
End Sub
Save Document
To save a document use the SaveAs2 method and the Save method. To save a document in a specific file format supply the SaveAs2 method with a FileFormat argument from the WdSaveFormat enum.
Public Sub Example()
Dim D As Word.Document
Set D = Word.Application.Documents.Add
D.SaveAs2 Environ$("USERPROFILE") & "\Desktop\Example.docx", wdFormatDocumentDefault
D.Content.InsertAfter "Hello, World!"
D.Save
End Sub
Open and Close Document
To open a document use the Documents.Open method. To close a document use the Close method.
Public Sub Example()
Dim D As Word.Document
Set D = Word.Application.Documents.Open(Environ$("USERPROFILE") & "\Desktop\Example.docx")
D.Content.InsertAfter "Hello, World!"
D.Save
D.Close
End Sub
Check Spelling and Grammar
The CheckSpelling method can be used to check a Document for spelling mistakes. The CheckGrammar method can be used to check a Document for grammar issues.
Public Sub Example()
Dim D As Word.Document
Set D = Word.Application.Documents(1)
D.CheckSpelling
D.CheckGrammar
End Sub
Ranges
The Range object represents an area of a Word document. Working with Ranges is important for using VBA with Word. There are different ways to retrieve a Range object.
Range Method
The Range method can be used to get a Range object using a starting character and ending character number.
Public Sub Example()
Dim D As Word.Document
Set D = Word.Application.Documents(1)
Dim R As Word.Range
Set R = D.Range(0, 10)
End Sub
Range Property
Certain objects in Word have a Range property which can be used to return a Range object.
Public Sub Example()
Dim D As Word.Document
Set D = Word.Application.Documents(1)
Dim R As Word.Range
Set R = D.Paragraphs(1).Range
End Sub
Content Property
The Content property of a Document object returns a Range object that represents all the content in the document.
Public Sub Example()
Dim D As Word.Document
Set D = Word.Application.Documents(1)
Dim R As Word.Range
Set R = D.Content
End Sub
StoryRanges Property
The StoryRanges collection object contains Range objects that represent "stories". The types of stories are defined in the WdStoryType enum.
Public Sub Example()
Dim D As Word.Document
Set D = Word.Application.Documents(1)
Dim R As Word.Range
Set R = D.StoryRanges(wdMainTextStory) 'Same as Document.Content
End Sub
Sentences
The Document.Sentences property and the Range.Sentences property return a Sentences collection object containing a the sentences within a Document or Range. Each sentence is a Range object.
Public Sub Example()
Dim D As Word.Document
Set D = ThisDocument
Dim Ss As Word.Sentences
Set Ss = D.Range.Sentences
Dim S As Word.Range
For Each S In Ss
Debug.Print S.Text
Next S
End Sub
Paragraphs
The Paragraph object can be used to retrieve a Range object representing a paragraph. Paragraphs can be accessed from the Paragraphs collection object. Use the Document.Paragraphs property to retrieve the Paragraphs collection object for a Document.
Public Sub Example()
Dim D As Word.Document
Set D = Word.Application.Documents(1)
Dim R As Range
Set R = D.Paragraphs(1).Range
End Sub
Words
The Document.Words property and the Range.Words property return a Words collection object containing a collection of all the words within a Document or Range. Each word in the collection is a Range object.
Public Sub Example()
Dim D As Word.Document
Set D = Word.Application.Documents(1)
Dim R As Word.Range
For Each R In D.Words
Debug.Print R.Text
Next R
End Sub
Check Spelling, Grammar, and Synonyms
The Range.CheckGrammar method can be used to check a Range for Grammar issues.
The Range.CheckSpelling method can be used to check a Range for spelling mistakes.
The Range.CheckSynonyms method can be used to check for synonyms of a word.
Public Sub Example()
Dim D As Word.Document
Set D = Word.Application.Documents(1)
D.Content.CheckSpelling
D.Content.CheckGrammar
D.Content.Words(1).CheckSynonyms
End Sub
Basic Methods
Basic methods of the Range object include Copy, Cut, Delete, Move, Paste, InsertAfter, and InsertBefore.
Basic Properties
Basic properties of the Range object include Bold, Font, Italic, Style, Text, And Underline.
Paragraphs
The Paragraph object represents a paragraph. The Paragraphs collection object contains a collection of Paragraph objects. Use the Document.Paragraphs property or the Range.Paragraphs property to get a Paragraphs collection containing all paragraphs in a Document or Range. The Paragraph object and the Paragraphs collection object have many of the same properties and methods. It may not be necessary to loop over all Paragraph objects in the collection, but instead call a particular method on the entire collection.
Public Sub Example()
Dim D As Word.Document
Set D = Word.Application.Documents(1)
D.Paragraphs.IndentFirstLineCharWidth 4
End Sub
Bookmarks
The Bookmark class represents a Bookmark. The Bookmarks collection object contains a collection of Bookmark objects. Use the Document.Bookmarks property to get a Bookmarks collection containing all Bookmarks in a Document. Bookmarks can be used to locate part of a document.
Public Sub Example()
Dim D As Word.Document
Set D = Word.Application.Documents(1)
Dim B As Word.Bookmark
Set B = D.Bookmarks.Add("Test", D.Range(0, 0))
End Sub
Tables
The Table object represents a table with rows and columns. The Tables collection object contains a collection of Table objects. Use the Document.Tables property to get a Tables collection containing all Table objects in a Document.
Add Table
To add a Table use the Tables.Add method. The Add method takes a Range where the table will be added, the number of rows, the number of columns, the default table behavior as a member of the WdDefaultTableBehavior enum, and the auto fit behavior as a member of the WdAutoFitBehavior enum.
Public Sub Example()
Dim D As Word.Document
Set D = Word.Application.Documents(1)
Dim T As Word.Table
Set T = D.Tables.Add(D.Range(0, 0), 10, 3)
With T.Borders
.OutsideLineStyle = wdLineStyleSingle
.OutsideLineWidth = wdLineWidth025pt
.InsideLineStyle = wdLineStyleSingle
End With
T.Cell(1, 1).Range.Text = "Header1"
T.Cell(1, 2).Range.Text = "Header2"
T.Cell(1, 3).Range.Text = "Header3"
T.Rows(1).Range.Bold = True
T.Range.ParagraphFormat.Alignment = wdAlignParagraphCenter
T.Rows(1).Cells.VerticalAlignment = wdCellAlignVerticalCenter
End Sub
ContentControls
The ContentControl object represents a control. The ContentControls collection object contains ContentControl objects. Use the Document.ContentControls property to get a ContentControls collection containing all ContentControl objects in a Document.
Add ContentControl
To add a ContentControl use the ContentControls.Add method with a member of the WdContentControlType enum and provide a Range object for where the control will be added.
Public Sub Example()
Dim D As Word.Document
Set D = Word.Application.Documents(1)
Dim CC As Word.ContentControl
Set CC = D.ContentControls.Add(wdContentControlDropdownList, D.Range(0, 0))
CC.DropdownListEntries.Add "List Entry 1", "Value 1", 1
CC.DropdownListEntries.Add "List Entry 2", "Value 2", 2
CC.DropdownListEntries.Add "List Entry 3", "Value 3", 3
End Sub
Comments
The Comment object represents a comment. The Comments collection object contains a collection of Comment objects. Use the Document.Comments property to get a Comments collection containing all Comment objects in a Document.
Add Comment
To add a Comment use the Comments.Add method and provide a Range object and the comment text.
Public Sub Example()
Dim D As Word.Document
Set D = Word.Application.Documents(1)
Dim C As Word.Comment
Set C = D.Comments.Add(D.Range(0, 0), "Test Comment")
End Sub
MailMerge
The MailMerge object provides the ability to use the MailMerge feature in VBA.
Public Sub Example()
Dim D As Word.Document
Set D = Word.Application.Documents(1)
Dim SourcePath As String
SourcePath = "C:\ExampleMailingList.xlsx"
D.MailMerge.Fields.Add Range:=D.Range(0, 0), Name:="Name"
D.MailMerge.OpenDataSource _
Name:=SourcePath, _
ConfirmConversions:=False, _
ReadOnly:=False, _
LinkToSource:=True, _
AddToRecentFiles:=False, _
PasswordDocument:="", _
PasswordTemplate:="", _
WritePasswordDocument:="", _
WritePasswordTemplate:="", _
Revert:=False, _
Format:=wdOpenFormatAuto, _
Connection:= _
"Provider=Microsoft.ACE.OLEDB.12.0;" & _
"User ID=Admin;" & _
"Data Source=" & SourcePath & ";" & _
"Mode=Read;" & _
"Extended Properties=""HDR=YES;IMEX=1;"";" & _
"Jet OLEDB:System database="""";" & _
"Jet OLEDB:Registry Path="""";" & _
"Jet OLEDB:Engine Type=37;" & _
"Jet OLEDB:Database ", _
SQLStatement:="SELECT * FROM `Sheet1$`", _
SQLStatement1:="", _
SubType:=wdMergeSubTypeAccess
With D.MailMerge
.Destination = wdSendToNewDocument
.SuppressBlankLines = True
With .DataSource
.FirstRecord = wdDefaultFirstRecord
.LastRecord = wdDefaultLastRecord
End With
.Execute Pause:=False
End With
End Sub
Find
The Find object represents the find operation. The Find object contains properties and methods to conduct a specific find operation.
Find
To find text set the Text property and use the Execute method. The Execute method returns True if the text was found. The Found property will be set to True if the text was found after Execute is called.
Public Sub Example()
Dim D As Word.Document
Set D = Word.Application.Documents(1)
Dim F As Word.Find
Set F = D.Content.Find
With F
.Text = "Hello, World!"
Debug.Print .Execute
Debug.Print .Found
End With
End Sub
Find and Replace
To replace text set the Text property of the Find object and the Text property of the Find object's Replacement object property. Set the Replace parameter of the Execute method to a member of the WdReplace enum.
Public Sub Example()
Dim D As Word.Document
Set D = Word.Application.Documents(1)
Dim F As Word.Find
Set F = D.Content.Find
With F
.Text = "Hello, World!"
.Replacement.Text = "How's it goin'?"
Debug.Print .Execute(Replace:=wdReplaceAll)
End With
End Sub
Find and Highlight
To highlight found text use the HitHighlight method. To clear highlighted hits use the ClearHitHighlight method.
Public Sub Example()
Dim D As Word.Document
Set D = Word.Application.Documents(1)
Dim F As Word.Find
Set F = D.Content.Find
With F
.ClearHitHighlight
.HitHighlight "Hello, World!"
End With
End Sub
Match Options
Various matching options can be set by setting certain properties to True:
- MatchAlefHamza
- MatchAllWordForms*
- MatchByte
- MatchCase
- MatchControl
- MatchDiacritics
- MatchFuzzy
- MatchKashida
- MatchPhrase
- MatchPrefix
- MatchSoundsLike
- MatchSuffix
- MatchWholeWord
- MatchWildcards
Certain properties render other properties useless. For example, using MatchWildcards or MatchAllWordForms renders the MatchCase property meaningless.
Only one of the MatchPhrase, MatchWildcards, MatchSoundsLike, MatchAllWordForms, or MatchFuzzy options can be set to True at a given time.
When using the MatchAllWordForms property, the search text should be lowercase. Using uppercase causes the text not to match when it should.
Public Sub Example()
'''Match and highlight forms of "run"
Dim D As Word.Document
Set D = Word.Application.Documents(1)
Dim F As Word.Find
Set F = D.Content.Find
With F
.MatchAllWordForms = True
.MatchWholeWord = True
'Search text must be lowercase. Matches with uppercase and lowercase
.HitHighlight "run"
End With
End Sub
ComputeStatistics
The Document.ComputeStatistics method or the Range.ComputeStatistics method can be used to retrieve information about the content of a Document or Range. Pass a member of the WdStatistic enum to retrieve a specific value.
Public Sub Example()
Dim D As Word.Document
Set D = Word.Application.Documents(1)
Debug.Print "Characters: " & D.ComputeStatistics(wdStatisticCharacters)
Debug.Print "CharactersWithSpaces: " & D.ComputeStatistics(wdStatisticCharactersWithSpaces)
Debug.Print "FarEastCharacters: " & D.ComputeStatistics(wdStatisticFarEastCharacters)
Debug.Print "Lines: " & D.ComputeStatistics(wdStatisticLines)
Debug.Print "Pages: " & D.ComputeStatistics(wdStatisticPages)
Debug.Print "Paragraphs: " & D.ComputeStatistics(wdStatisticParagraphs)
Debug.Print "Words: " & D.ComputeStatistics(wdStatisticWords)
End Sub