A VBA Language Primer
In this section, we’ll take a look at the syntax and structure of the VBA language. Entire books have been devoted to VBA, but we’ll just hit the high points here. When you’re through with this section, you’ll understand the basic building blocks of VBA and how to use them to create a program.
in VBA code is a command for your computer
to perform. The statement in Example 18-1 displays a
message box with the text “Hello, world!”:
Example 18-1. Hello World
MsgBox "Hello, world!"
Very long statements may be broken into several lines by using the
line continuation character "
_" (Example 18-2)
. You can also use
indentation to make your code more readable. Indentation does not
affect the way the code is executed.
Example 18-2. Using the Line Continuation Character
.ParagraphFormat.TabStops.Add Position:=InchesToPoints(1.15), _ Alignment:=wdAlignTabLeft, Leader:=wdTabLeaderSpaces
Comments are documentation in your code. The more you comment, the better you — and anybody else — will understand your code later. Add a comment by prefacing a line of text with a single quote, or by typing a single quote and additional text after a statement, but on the same line. Anything following the quote is considered a comment and will not be executed (Example 18-3).
Example 18-3. Commenting Your Code
' This is a comment that takes up an entire line. i = 3 ' This is a comment after a statement
is a name that you define to hold a value. ...