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. Show 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 ToDescription VBA Code Backspace Selection.TypeBackspace Select Entire Document Selection.HomeKey Unit:=wdStory 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” Return to Top BookmarksDescription VBA Code Add With ActiveDocument.Bookmarks Count Dim n as Integer Delete ActiveDocument.Bookmarks(“BookmarkName”).Delete Exists? If ActiveDocument.Bookmarks.Exists(“BookmarkName”) = True then Go To Selection.GoTo What:=wdGoToBookmark, Name:=”BookmarkName” Select ActiveDocument.Bookmarks(“BookmarkName”).Select Replace Text Selection.GoTo What:=wdGoToBookmark, Name:=”BookmarkName” Return to Top DocumentDescription VBA Code Activate Documents(“Example.doc”).Activate Add to Variable Dim doc As Document Add Documents.Add Add (From Another Doc) Documents.Add Template:=”C:\Forms\FormDoc.doc”, _ 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 ColumnsDescription 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 Documents(“Example.doc”).Print Return to Top VBA Coding Made EasyStop 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!! FontDescription 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 InsertDescription VBA Code Insert AutoText Selection.TypeText Text:=”a3″ 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 LoopsDescription VBA Code Do Until End of Doc Do Until ActiveDocument.Bookmarks(“\Sel”) = ActiveDocument.Bookmarks(“\EndOfDoc”) For Each Doc in Docs Dim doc As Document Loop Through Paragraphs Sub through Paragraphs Return to Top VBA Programming | Code Generator does work for you! ParagraphDescription 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 Loop Through All Paragraphs Sub through Paragraphs Return to Top
Word VBA Macro TutorialThis 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 ExampleThis is a simple example of a Word VBA Macro. It performs the following tasks:
Word Macro BasicsAll 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 ObjectWhen 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! ApplicationApplication 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:
This is an example of accessing the “Selection” of “Windows(1)” with in the Application:
However, the most common Word objects can be accessed directly, without typing the full hierarchy. So instead, you can (and should) just type:
DocumentsActiveDocumentOften, 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:
…would print the ActiveDocument. The ActiveDocument is the document in Word which “has focus” To switch the ActiveDocument, use the Activate command:
ThisDocumentInstead 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.
Document VariablesHowever, 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:
Document MethodsOpen DocumentTo Open a Word Document:
We recommend always assigning a Document to a variable upon opening it:
Create New DocumentTo create a new Word Document: 0We can instruct Word to create a new doc based on some template: 1As always, it is useful and huge problem saver to assign document to variable upon creating or opening: 2Save DocumentTo save a document: 3or SaveAs: 4Close DocumentTo close a Document and save changes: 5or without saving changes: 6Print DocumentThis will print the active Document:
Range, Selection, ParagraphsRange 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! RangeRange can be any part of document, including entire document: 8or it can be small as one character. Another example, this range would refer to first word in document: 9Usually, 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: 0Set Range TextTo set the text value of a Range: 1(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 2Display in message box number of characters in particular range 3Insert some text before it 4Add a footnote to range 5Copy it to clipboard 6After above code, oRange would refer to text starting with fifth and ending with 50th character in document. SelectionSelection 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: 7Then you can use the Selection Object to type some text: 8We can type some paragraphs bellow “Some text”: 9Often, it’s necessary to know if some text is selected or we have just a insertion point: 0When working with Selection object we want to place insertion point to particular place, and issue commands starting from this point. Beginning of document: 1Beginning of current line: 2The Extend parameter wdMove moves the insertion point. Instead, you could use wdExtend which will select all text between the current insertion point. 3Move SelectionThe most useful method for changing position of insertion point is Move. To move Selection two characters forward: 4to move it backwards, use negative number for Count parameter: 5Unit parameter can be wdCharacter, wdWord, wdLine, or more (use Word VBA help to see others). To move words instead: 6
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: 7TIP: Using Selection is often easier than using ranges, but also it’s way slower (important when you deal with big documents) ParagraphsYou can’t directly use Paragraphs object to change text: 8Above wouldn’t work (actually it will throw an error). You need to first obtain range associated with particular paragraph: 9But you can directly change its style: 0or change its paragraph level formatting: 1or maybe you want to keep this paragraph on the same line with next paragraph: 2Make paragraph centered: 3It 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: 4Here 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: 5Paragraph object is very frequently used in loops: 6Word VBA Tutorial ConclusionThis 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 ExamplesWord Macro ExamplesTemplatesAdd New DocumentsCount Words in SelectionTextBoxesSaveAs PDFBookmarksTablesFind and Find and ReplaceOpen DocumentsWord VBA FAQsWhat 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. |