You might also be interested in our Interactive VBA Tutorial for Excel. While some of the examples / exercises are specific to Excel VBA, much of the content is generic to all VBA and you may find it useful to learn concepts like If Statements, Loops, MessageBoxes, and more.
VBA PDF (Free Downloads)
Download our free Microsoft Word VBA Tutorial! Or VBA Tutorials for other Office Programs!
Download
Word VBA Examples “CheatSheet”
Below you will find simple VBA code examples for working with Microsoft Word.
Select / Go To
Description
VBA Code
Backspace
Selection.TypeBackspace
Select Entire Document
Selection.HomeKey Unit:=wdStory
Selection.Extend
Copy
Selection.Copy
Delete
Selection.Delete Unit:=wdCharacter, Count:=1
Insert After
Selection.InsertAfter “text”
Beginning of Line
Selection.HomeKey Unit:=wdLine
End of Line
Selection.EndKey Unit:=wdLine
Paste
Selection.Paste
Select All
Selection.WholeStory
Select Entire Line
Selection.EndKey Unit:=wdLine, Extend:=wdExtend
Move Up Paragraph
Selection.MoveUp Unit:=wdParagraph, Count:=1
Move Right One Character
Selection.MoveRight Unit:=wdCharacter, Count:=1
Move Right One Cell in Table
Selection.MoveRight Unit:=wdCell
Go To Start of Doc
Selection.HomeKey Unit:=wdStory
Go To End of Doc
Selection.EndKey Unit:=wdStory
Go To Page 1
Selection.GoTo What:=wdGoToPage, Which:=wdGoToNext, Name:=”1″
Go To Top of Page
Selection.GoTo What:=wdGoToBookmark, Name:=”\Page”
Selection.MoveLeft Unit:=wdCharacter, Count:=1
Return to Top
Bookmarks
Description
VBA Code
Add
With ActiveDocument.Bookmarks
.Add Range:=Selection.Range, Name:=”Name”
.DefaultSorting = wdSortByName
.ShowHidden = False
End With
Count
Dim n as Integer
n = ActiveDocument.Bookmarks.Count
Delete
ActiveDocument.Bookmarks(“BookmarkName”).Delete
Exists?
If ActiveDocument.Bookmarks.Exists(“BookmarkName”) = True then
‘Do something
End If
Go To
Selection.GoTo What:=wdGoToBookmark, Name:=”BookmarkName”
Select
ActiveDocument.Bookmarks(“BookmarkName”).Select
Replace Text
Selection.GoTo What:=wdGoToBookmark, Name:=”BookmarkName”
Selection.Delete Unit:=wdCharacter, Count:=1
Selection.InsertAfter “New Text”
ActiveDocument.Bookmarks.Add Range:=Selection.Range, _
Name:=”BookmarkName”
Return to Top
Document
Description
VBA Code
Activate
Documents(“Example.doc”).Activate
Add to Variable
Dim doc As Document
Set doc = Documents.Add
Add
Documents.Add
Add (From Another Doc)
Documents.Add Template:=”C:\Forms\FormDoc.doc”, _
NewTemplate:=False
Close
Documents(“Example.doc”).Close
Close – Save Changes
Documents(“Example.doc”).Close SaveChanges:=wdSaveChanges
Close – Do Not Save
Documents(“Example.doc”).Close SaveChanges:=wdDoNotSaveChanges
Close – Prompt to Save
Documents(“Example.doc”).Close SaveChanges:=wdPromptToSaveChanges
Return to Top
Columns
Description
VBA Code
Save As
Documents(“Example.doc”).SaveAs (“C:\Example\Example.doc”)
Save
Documents(“Example.doc”).Save
Protect
Documents(“Example.doc”).Protect Password:=”password”
Unprotect
Documents(“Example.doc”).UnProtect Password:=”password”
Number of Pages
Dim varNumberPages as Variant
varNumberPages = _
ActiveDocument.Content.Information(wdActiveEndAdjustedPageNumber)
Documents(“Example.doc”).Print
Return to Top
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro - A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!Learn More!!
Font
Description
VBA Code
Size
Selection.Font.Size = 12
Bold
Selection.Font.Bold = True
Italics
Selection.Font.Italic = True
Underline
Selection.Font.Underline = wdUnderlineSingle
All Caps
Selection.Font.AllCaps = True
Color
Selection.Font.TextColor = vbRed
Name
Selection.Font.Name = “Abadi”
Subscript
Selection.Font.Subscript = True
SuperScript
Selection.Font.Superscript = True
Highlight Color
Selection.Range.HighlightColorIndex = wdYellow
Style
Selection.Style = ActiveDocument.Styles(“Normal”)
Return to Top
Insert
Description
VBA Code
Insert AutoText
Selection.TypeText Text:=”a3″
Selection.Range.InsertAutoText
Insert Date Code
Insert File
Selection.InsertFile (“C:\Docs\Something.doc”)
Insert Page Break
Selection.InsertBreak Type:=wdPageBreak
Insert Paragraph Symbol
Selection.TypeText Text:=Chr$(182)
Insert Tab
Selection.TypeText Text:=vbTab
Insert Text
Selection.TypeText Text:=”Any Text”
Insert Type Paragraph
Selection.TypeParagraph
Insert Paragraph
Selection.InsertParagraph
Return to Top
Loops
Description
VBA Code
Do Until End of Doc
Do Until ActiveDocument.Bookmarks(“\Sel”) = ActiveDocument.Bookmarks(“\EndOfDoc”)
‘Do Something
Sub
For Each Doc in Docs
Dim doc As Document
ForEach doc In Documents
‘Do Something
Next doc
Loop Through Paragraphs
Sub through Paragraphs
Dim i As Long, iParCount As Long
iParCount = ActiveDocument.Paragraphs.CountFori = 1 To iParCount
ActiveDocument.Paragraphs(i).Alignment = wdAlignParagraphLeft
Next i
Return to Top
VBA Programming | Code Generator does work for you!
Paragraph
Description
VBA Code
KeepLinesTogether
Selection.ParagraphFormat.KeepTogether = True
KeepWithNext
Selection.ParagraphFormat.KeepWithNext = True
Space After
Selection.ParagraphFormat.SpaceAfter = 12
Space Before
Selection.ParagraphFormat.SpaceBefore = 0
Align Center
Selection.ParagraphFormat.Alignment = wdAlignParagraphCenter
Align Right
Selection.ParagraphFormat.Alignment = wdAlignParagraphRight
Align Left
Selection.ParagraphFormat.Alignment = wdAlignParagraphLeft
Left Indent
Selection.ParagraphFormat.LeftIndent = InchesToPoints(3.75)
Right Indent
Selection.ParagraphFormat.RightIndent = InchesToPoints(1)
Line Spacing
With Selection.ParagraphFormat
.LineSpacingRule = wdLineSpaceExactly
.LineSpacing = 12
End With
Loop Through All Paragraphs
Sub through Paragraphs
Dim i As Long, iParCount As Long
iParCount = ActiveDocument.Paragraphs.CountFori = 1 To iParCount
ActiveDocument.Paragraphs(i).Alignment = wdAlignParagraphLeft
Next i
Return to Top
Word VBA Macro Tutorial
This is a tutorial for using VBA with Microsoft Word. This tutorial will teach you how to write a simple Macro and interact with Documents, Ranges, Selections, and Paragraphs.
Note: If you’re brand new to Macros / VBA you might also find this article useful: How to write VBA Macros from Scratch.
VBA is the programming language used to automate Microsoft Office programs including Word, Excel, Outlook, PowerPoint, and Access.
Macros are blocks of VBA code that perform specific tasks.
When you Record a Macro, Word will write VBA code into a Macro, allowing you to repeat your actions. You can see a list of all available Macros from View > Macros.
After recording a Macro, you will be able to edit the Macro from the Macro List:
When you click Edit, you open the VBA Editor. Using the VBA Editor you can edit recorded Macros or write a Word Macro from scratch. To access the VBA Editor use the shortcut ALT + F11 or click Visual Basic from the Developer Ribbon.
Simple Word Macro Example
This is a simple example of a Word VBA Macro. It performs the following tasks:
- Opens a Word Document
- Writes to Document
- Closes and Saves the Word Document.
Word Macro Basics
All VBA code must be stored within procedures like this. To create a procedure in VBA type “Sub WordMacroExample” (Where “WordMacroExample” is your desired Macro name) and press ENTER. VBA will automatically add the parenthesis and End Sub.
Word Document Object
When interacting with Microsoft Word in VBA, you will frequently reference Word “Objects”. The most common objects are:
Application Object – Microsoft Word itself
Document Object – A Word document
Range Object – A part of a Word document
Selection Object – A selected range or cursor location.
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Application
Application is the “top-level” object. All other objects in Word can be reached through it.
In addition to accessing other Word objects, there are “application-level” settings that can be applied:
Application.Options.AllowDragAndDrop = TrueThis is an example of accessing the “Selection” of “Windows(1)” with in the Application:
Application.Windows(1).Selection.Characters.CountHowever, the most common Word objects can be accessed directly, without typing the full hierarchy. So instead, you can (and should) just type:
Selection.Characters.CountDocuments
ActiveDocument
Often, you will have two or more documents opened in Word and you will need specify which specific Word Document to interact with. One way to specify which document is to use ActiveDocument. For example:
ActiveDocument.PrintOut…would print the ActiveDocument. The ActiveDocument is the document in Word which “has focus”
To switch the ActiveDocument, use the Activate command:
Documents("Example.docx").ActivateThisDocument
Instead of using ActiveDocument to reference the active document, you can use ThisDocument to reference the document where the macro is stored. ThisDocument will never change.
ThisDocument.PrintOutDocument Variables
However, for more complicated macros, it can be hard to keep track of the Active Document. It can also be frustrating to switch back and forth between documents.
Instead, you can use Document variables.
This macro will assign the ActiveDocument to a variable and then print the document using the variable:
Sub VarExample() Dim oDoc As Document Set oDoc = ActiveDocument oDoc.PrintOut End SubDocument Methods
Open Document
To Open a Word Document:
Documents.Open "c:\Users\SomeOne\Desktop\Test PM.docx"We recommend always assigning a Document to a variable upon opening it:
Dim oDoc as Document Set oDoc = Documents.Open("c:\Users\SomeOne\Desktop\Test PM.docx")Create New Document
To create a new Word Document:
Application.Options.AllowDragAndDrop = True0We can instruct Word to create a new doc based on some template:
Application.Options.AllowDragAndDrop = True1As always, it is useful and huge problem saver to assign document to variable upon creating or opening:
Application.Options.AllowDragAndDrop = True2Save Document
To save a document:
Application.Options.AllowDragAndDrop = True3or SaveAs:
Application.Options.AllowDragAndDrop = True4Close Document
To close a Document and save changes:
Application.Options.AllowDragAndDrop = True5or without saving changes:
Application.Options.AllowDragAndDrop = True6Print Document
This will print the active Document:
ActiveDocument.PrintOutRange, Selection, Paragraphs
Range and Selection are probably the most important objects in Word VBA, certainly the most used.
Range refers to some portion of document, usually, but not necessarily, text.
Selection refers to selected text (or other object like pictures) or, if nothing is selected, an insertion point.
Paragraphs represent paragraphs in document. Its less important than it sounds, because you can’t directly access paragraph text (you need to access particular paragraph range to make modifications).
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Range
Range can be any part of document, including entire document:
Application.Options.AllowDragAndDrop = True8or it can be small as one character.
Another example, this range would refer to first word in document:
Application.Options.AllowDragAndDrop = True9Usually, you would want to get range which refers to specific part of document and then modify it.
In the following example we will make the first word of second paragraph bold:
Application.Windows(1).Selection.Characters.Count0Set Range Text
To set the text value of a Range:
Application.Windows(1).Selection.Characters.Count1(Tip: Note the space after “Hello”. Because word object includes space after word, with just “hello” we would get “Hellonext word”)
There are hundreds of things which you can do with ranges. Just a few examples (these assume you are already made object variable oRange referring to range of interest):
Change font
Application.Windows(1).Selection.Characters.Count2Display in message box number of characters in particular range
Application.Windows(1).Selection.Characters.Count3Insert some text before it
Application.Windows(1).Selection.Characters.Count4Add a footnote to range
Application.Windows(1).Selection.Characters.Count5Copy it to clipboard
Application.Windows(1).Selection.Characters.Count6After above code, oRange would refer to text starting with fifth and ending with 50th character in document.
Selection
Selection is even more widely used than Range, because it is easier to work with Selections than Ranges, IF your macro ONLY interacts with the ActiveDocument.
First select the desired part of your document. For example select the second paragraph in active document:
Application.Windows(1).Selection.Characters.Count7Then you can use the Selection Object to type some text:
Application.Windows(1).Selection.Characters.Count8We can type some paragraphs bellow “Some text”:
Application.Windows(1).Selection.Characters.Count9Often, it’s necessary to know if some text is selected or we have just a insertion point:
Selection.Characters.Count0When working with Selection object we want to place insertion point to particular place, and issue commands starting from this point.
Beginning of document:
Selection.Characters.Count1Beginning of current line:
Selection.Characters.Count2The Extend parameter wdMove moves the insertion point. Instead, you could use wdExtend which will select all text between the current insertion point.
Selection.Characters.Count3Move Selection
The most useful method for changing position of insertion point is Move. To move Selection two characters forward:
Selection.Characters.Count4to move it backwards, use negative number for Count parameter:
Selection.Characters.Count5Unit parameter can be wdCharacter, wdWord, wdLine, or more (use Word VBA help to see others).
To move words instead:
Selection.Characters.Count6
Selection is easier to work with (compared to ranges) because it is like a robot using Word, mimicking human user. Where Insertion point is – some action would take place. But, this means that you must take care where insertion point is! This is not easy after many steps in code. Otherwise, Word would change text in not desired place.
In the case you need some property or method not available in Selection object you can always easily obtain range associated with selection:
Selection.Characters.Count7TIP: Using Selection is often easier than using ranges, but also it’s way slower (important when you deal with big documents)
Paragraphs
You can’t directly use Paragraphs object to change text:
Selection.Characters.Count8Above wouldn’t work (actually it will throw an error). You need to first obtain range associated with particular paragraph:
Selection.Characters.Count9But you can directly change its style:
ActiveDocument.PrintOut0or change its paragraph level formatting:
ActiveDocument.PrintOut1or maybe you want to keep this paragraph on the same line with next paragraph:
ActiveDocument.PrintOut2Make paragraph centered:
ActiveDocument.PrintOut3It is VERY useful to assign a particular paragraph to object variable. If we assign particular paragraph to variable we don’t have to worry if the first paragraph becomes the second because we inserted one paragraph before it:
ActiveDocument.PrintOut4Here is an example where we insert a paragraph above the first paragraph, but we can still reference the old first paragraph because it was assigned to a variable:
ActiveDocument.PrintOut5Paragraph object is very frequently used in loops:
ActiveDocument.PrintOut6Word VBA Tutorial Conclusion
This tutorial covered the basics of Word VBA. If you’re new to VBA, you should also review our general VBA Tutorial to learn more about Variables, Loops, MessageBoxes, Settings, Conditional Logic and much more.
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Word Macro Examples
Word Macro ExamplesTemplatesAdd New DocumentsCount Words in SelectionTextBoxesSaveAs PDFBookmarksTablesFind and Find and ReplaceOpen DocumentsWord VBA FAQs
What is a Word Macro?
A Macro is a general term that refers to a set of programming instructions that automates tasks. Word Macros automate tasks in Word using the VBA programming language.
Does word have VBA?
Yes, Microsoft Word has the VBA Editor. It can be accessed with by pressing ALT + F11 or by navigating to Developer > Visual Basic.