This is a collection of recipes for scripting Microsoft Word using Visual Basic for Applications.
A great way of learning about Word VBA is using its macro recording function. With the function, you tell Word to start recording, then perform various tasks on the document in the normal way, and finally, tell Word to stop recording. What you did on the document will have been recorded by Word, and stored as a VBA code macro. While the code often cannot be meaningfully used without modification, it can make a useful starting point and at times is the only way to find the code for a particular task. At other times a macro can be useful in its own right.
The content of a macro can be viewed in detail and changed by selecting Edit while the macro is selected in the Macros dialog. It can be run also, and if possible, depending on the code, the action that was taken for the recording will then appear on the document. For example, if the recorded code started with a text selection already made, then a text selection on the document is needed before running the macro. If such a selection was needed but none was found, the macro would end without the intended action. Some of the most useful macros work on the assumption that a prior selection was made, though some do not.
Macro code lines can also be copied into a procedure with a Private Sub Document_Open() heading. When this is done and the procedure is placed in the ThisDocument module, the code within it will run whenever the Word document itself is opened. Such a facility can be used to automatically configure a page's formats. Code can be copied and pasted from one module to another and edited like other text. Access the code editor with Edit in the Macros dialog or by pressing Alt+F11 together from any location within Word. A study of the code editor, sometimes called the VDE, is well advised.
For those who are new to macro recording it is a good idea to restrict the scope of your macros to just the document that you have written them for. Then if there are mishaps, not so much damage is done. The scope of a macro's action is set in the Macros dialog. If you have not yet named your main document, it will be listed as Document1(document) or something similar. Remember to save your macro work. Saving the work in either the editor or the document will save both together, though recent versions of Word will require that a macro-enabled (.docm) file ending is chosen. At times it will be found that a document's macros are blocked by Word's trust settings (options) though these are easily changed.
Menu paths to the Macros dialog: To start, stop, view, or edit a macro:
- Word 2007, or 2010: View (tab) > Macros (group) > down-pointing triangle below Macros button > ...then choose from menu
- Word 2007: Developer (tab) > Code (group) > ...then choose from menu
Menu paths to the VDE, (the VBA editor): To open or close the editor:
- Press Alt+F11 together, or
- Select Edit from the Macros dialog. (See above).
Links: See Also
The Basic ProcedureEdit
A basic procedure can be written in a standard module (say, Module1) or in the ThisDocument module using the basic procedure shell format. It has a heading with a name and ends with a closing line. The following procedure is called ColorTheFont, though any number of such procedures can be written. It makes any existing text dark red and 60pt in size.
Sub ColorTheFont() ThisDocument.Select Selection.Font.ColorIndex = wdDarkRed Selection.Font.Size = 60 End Sub
A Document-open procedure is only written in the ThisDocument module, and will cause its contents to run when the Word document is opened. The following procedure will write Sausages for tea on the Word document when it is opened. It cannot be given any other name and only one of these should exist.
Private Sub Document_Open() Selection.TypeText Text:="Sausages for tea" End Sub
Procedures in ProceduresEdit
Assume that both the document-open and standard procedures above existed in a Word .docm document. The standard procedure could be listed in the open procedure so that it runs too. First the typing would be done then the standard procedure would make the type dark red and 60pt in size. Any number of procedures could be listed here.
Private Sub Document_Open() Selection.TypeText Text:="Sausages for tea" ColorTheFont End Sub
You can insert and delete text as follows:
Selection.TypeText Text:="Inserted as if by typing on keyboard" Selection.Delete 'Deleted the single char after cursor, or a non-empty selection
You can move cursor around as follows:
Selection.MoveDown Unit:=wdLine Selection.MoveRight Unit:=wdCell 'At the end of a row, moves to the next row
Selection means the part of the document that is currently selected by the mouse. Selections can also be made by code as if they had been made by the mouse. Even if the mouse has not made any selection of text and even if the cursor is just sitting at some empty document's start, there is a selection implied. In these cases the selection has both of its start and end points at the same position, and so has virtually zero width. In the absence of a mouse selection having been made, and if no other start point is implied, the use of the selection method will assume that you intend the current position of the cursor. This example will make a selection of the text, starting from the current cursor position, and extending it to the end of the current line. It then does work with the selection, making it bold in this case, then collapses the selection as if it had not existed, leaving the cursor where it was before:
Sub BoldLine() Selection.EndKey Unit:=wdLine, Extend:=wdExtend Selection.Font.Bold = True Selection.Collapse (wdCollapseStart) 'or wdCollapseEnd to leave cursor at selection end End Sub
Work can also be done on parts of the document without selecting them. For example, by specifying the range of interest. Ranges can be specified for any section from a single character to an entire document, though it can be tricky to get right. This simplest example sets a variable TheRange to represent the entire document's content-range then uses the variable to change the document's text to the color green.
Sub DocContentRange() Set TheRange=ThisDocument.Content TheRange.Font.ColorIndex=wdGreen End Sub
This example sets the third paragraph in italics.
Sub ThirdParaRange() Set TheRange = ThisDocument.Paragraphs(3).Range TheRange.Italic = True End Sub
Many properties can be applied to a range in the same way as for a selection, and such methods are useful for search and replace operations. Conditional code with ranges can expedite complex tasks. For example, Replace any text in Times Roman with Garamond, unless it is in italics. In the latter case use Arial. If the text were 500 pages long a range method would be preferred to one where the user had to make endless selections.
You can format text including text color, background color, and font properties as follows:
Selection.Font.Color = RGB(0, 0, 255) 'Foreground color AKA text color Selection.Range.HighlightColorIndex = wdYellow 'Background color as highlight Selection.Font.Name = "Verdana" 'Font face Selection.Font.Size = 8 'Font size Selection.Font.Bold = True 'Or False Selection.Font.Bold = wdToggle Selection.Font.Italic = True Selection.Font.Underline = True
Copying and PastingEdit
You copy and paste as follows:
Prerequisites: Accessing the clipboard from a Word document requires that a reference to MSForms (Microsoft Forms Object Library) is set in the document. You can set the reference by adding and subsequent removing of a user form, via Insert > UserForm in a pop-up menu. To check the presence of a reference, see Tools > References menu.
Placing text on the clipboard:
Set MyClipboard = New MSForms.DataObject MyClipboard.SetText "My string" MyClipboard.PutInClipboard
Getting text from the clipboard:
Set MyClipboard = New MSForms.DataObject MyClipboard.GetFromClipboard TextContent = MyClipboard.GetText
- DataObject Class at msdn.microsoft.com; contains a section on Visual Basic, whose applicability to Word VBA is unclear.
Sub PasteTabSeparatedPlainTextToTable() 'This paste prevents loss of formatting of the table cells Set MyClipboard = New MSForms.DataObject MyClipboard.GetFromClipboard TextContent = MyClipboard.GetText SplitArray = Split(TextContent, vbNewLine) For Each Element In SplitArray SplitArray2 = Split(Element, vbTab) TabSkipNeeded = False Set OldSelection = Selection.Range For Each CellContent In SplitArray2 If TabSkipNeeded Then Selection.MoveRight Unit:=wdCell Else TabSkipNeeded = True Selection.EndKey Unit:=wdLine, Extend:=wdExtend End If Selection.TypeText Text:=CellContent Next OldSelection.Select Selection.MoveDown Unit:=wdLine Next End Sub
- Record or run a macro (Word 2007) at microsoft.com
- Create a macro (Word 2003) at microsoft.com
- Recording a macro to generate code (Office 2000) at microsoft.com
- MS Word 2010 VBA Language Reference: This is perhaps the most useful source of code samples and instruction in the use of VBA for Word.
- Code Samples for Newbies and Others: An A to Z listing of interesting pieces.
- Word MVP: Contains what you were afraid to ask about Word VBA at the basic level and a bit beyond too, though the drop-menu and API material will have now become out of date.