Basic Structure of VBA Macros
If you want to create a blank macro that you can then edit yourself, you can do so by summoning the Macros dialog box, typing a name for the macro you want to create, and clicking the Create button. Then Word switches you to the VBA editor and creates a skeleton of a macro for you, like this:
Sub BoldItalic() ' ' BoldItalic Macro ' ' End Sub
The lines that begin with apostrophes are comments. VBA ignores them completely, but you can use them to remind yourself what the macro does or how it works. Comments can appear on lines all by themselves, or they can appear at the end of a line, like this:
Sub BoldItalic() 'The BoldItalic macro
The Sub and the End Sub statements mark the beginning and end of the macro's main procedure. As you see later, a macro can call on other procedures or functions that you define elsewhere in your code. However, the simplest macros consist of these lines with some additional VBA statements between them.
For example, the following macro contains two VBA statements - one to make the selected text bold and the other to make it italic:
Sub BoldItalic() Selection.Font.Bold = wdToggle Selection.Font.Italic = wdToggle End Sub
The net effect of this command is to make the selected text both bold and italic.
Well, not quite. The effect of this macro is to change both the bold and italic attributes of the selected text. If the text isn't already bold or italic, the macro makes it bold and italic. But if the text is already formatted as bold but not italic, the macro turns off the bold attribute and turns on italic. And, if no text is selected, the macro sets the bold and italic attributes for text you subsequently type.
So here, just a page into this tutorial, you already have an example of the Undeniable Truth of VBA programming: Even simple macros sometimes don't work the way you expect them to. The outcome of a macro often depends a great deal on whether text is selected, how the selected text (if any) is formatted, the view (Normal, Page Layout, or Outline), and many other factors. The moral of the story: Test everything.
In this tutorial:
- Programming with VBA
- Basic Structure of VBA Macros
- Understanding the Basic Elements of VBA
- Working with Variables and Data
- Using static variables
- Using Strings
- Of Objects, Properties, and Methods
- Getting to know the object model
- Using the With statement
- Controlling Your Programs
- The ElseIf structure
- For/Next Loops
- User Input and Output
- User-Defined Procedures and Functions