This is a collection of recipes for scripting Microsoft Word using Visual Basic for Applications.
Overview[edit | edit source]
Scripting in Microsoft Word is pretty easy. There are some things to know. Like macros. We’ll start from small parts and work to the bigger ones. Let’s start. First, we’ll need to enable the Developer tab on Word. Go to File > Options > Customize Ribbon and then find Developer and check it. Create a file and save it as an
.docm file. Now, we’re ready to write out code! Note that word uses Visual Basic Script aka VBScript.
Part 1: Macros[edit | edit source]
Macros are actions made when a button is pressed. For this example, Word has two types of macros. Macros for when a button is pressed and macros for when an action happens inside of Word. We’ll be focusing on Word macros that are programmable. We’ll start on something called
AutoOpen() does is that when Microsoft Word is opened, any code that is put under
AutoOpen() will execute when you launch Microsoft Word. Let's write some code to demonstrate how this works.
Sub AutoOpen() 'Macro used when Word just started up. MsgBox "Hello World!", 0, "Title" 'Creates message box after Word is open. End Sub
This code executes when Microsoft Word is open. Since the macro name
AutoOpen() executes code when Word opens. Another macro we'll be looking at is
is a macro when closing Word. So if we put the same code that we put under
msgbox will show up when Word is closing.
Sub AutoClose() 'Macro used when Word is about to close MsgBox "Hello World!", 0, "Title" 'Creates message box when closing Word End Sub
Creating a file under directories[edit | edit source]
We can create files with VBScript using simple code. This code will create a text file (or whatever type of file you wanna create) containing text. Just be careful if you have any important files on your desktop (or where you've saved the document) because they will be overwritten.
Sub AutoOpen() 'Macro used when Word just started up. Open "test.txt" For Output As #1 'Creates text file in current directory Print #1, "Hello World!" 'Writes text in text file. Close #1 'EOF End Sub
We can also create files under a custom directory. Like
C:\Hello-World. It's the same way as writing a text file.
Sub AutoOpen() 'Macro used when Word just started up. FileSystem.MkDir "C:\Hello-World" 'Creates directory Open "test.txt" For Output As #1 'Creates text file in the C:\Hello-World directory Print #1, "Hello World!" 'Writes text in text file. Close #1 'EOF End Sub
Macro Recording[edit | edit source]
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 steps as if you were working without a macro recorder, and finally, tell Word to stop recording. VBA code corresponding to what you did using Word GUI has been recorded by Word. While the code often cannot be meaningfully used without a modification, by starting from it and modifying it you can save a lot of time that would otherwise be spent reading the VBA documentation.
- Word 2007: View (tab) > Macros (group) > down-pointing triangle below Macros button > Record Macro
- Word 2007: Developer (tab) > Code (group) > Record Macro
- 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
Text Editing[edit | edit source]
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
Moving Cursor[edit | edit source]
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
Selecting[edit | edit source]
You can select regions of text as follows:
Selection.EndKey Unit:=wdLine, Extend:=wdExtend
Formatting[edit | edit source]
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 Pasting[edit | edit source]
You copy and paste as follows:
Clipboard[edit | edit source]
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.
Various[edit | edit source]
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