How to script in Microsoft Word
||Was this page created by accident or as a test? Please improve the educational quality of this page, and clarify what the intentions are on the discussion page so other people may contribute. The page might be able to remain at Wikibooks after 7 days when further development is likely.|
||A Wikibookian suggests that this book or chapter be merged with Word VBA.
Please discuss whether or not this merger should happen on the discussion page.
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
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
AutoClose() 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
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