Latest posts by techwriter (see all)
- Get an ‘A’ on Your Next Research Paper With These 6 Simple Steps - November 28, 2016
- An Amazing and FREE Source of Magazines and Periodicals — ISSUU - November 25, 2016
- Three Free Photo Sites for Technical and Business Writers - November 23, 2016
© Ugur Akinci
Very simply put, you can use MS Word VBA to write macros, which are nothing but automated action steps running one after the other at the click of your mouse or when you select the macro from the menu bar. Macros save us time. Instead of selecting three or four items in a row each time, we can write a macro in VBE (Visual Basic Editor) screen, save the macro, go back to Word, and run the macro.
To get a little more technical about it, macros are also called “procedures” in MS WORD VBA terminology.
There are two types of procedures in Word VBA:
- Subroutines — just like a macro, a subroutine does something (opens a window, triggers a menu item, etc.) when it is “called,” that is, triggered; activated.
- Functions — a function is just like a subroutine but with a major difference: a function returns a value; it makes an “output”. For example a function can take the value of an integer that we provide in Word, take its square and then print the squared value in a message box.
In VBE, we start writing a subroutine with the word “Sub.” We start writing a function with the word “Function.” Then we give the procedure a name which consists of letters, numbers, and the underscore character ONLY.
When we hit return after the name, VBE automatically prints the closing statements “End Sub” (for subroutines” and “End Function” (for functions). Every VBA statement must go in between those opening and closing statements.
For example, for a subroutine named HelloWorld():
And, for a function named HelloWorld():
How to Write a VBA Macro
Let’s write a simple subroutine (macro) that will print “Hello TCC Readers!!!” in a message pop-up box when selected in MS Word.
Make sure a module is selected in the VBE Project pane:
Type the following in the VBE Code Pane:
Press Alt + F11 to switch back to MS Word screen.
On the ribbon and in the Developer tab, click the Macros icon to display the Macros list:
Select HelloWorld and click Run and your message box will pop-up with your message:
Congratulations! You’ve just written and successfully ran your first Word VBA macro!