Understanding Syntax

Writing code is the art of programming the computer to perform a specific procedure by defining each step in the procedure as a single VBA statement. For the code to work, every VBA statement must conform to rules of syntax, which define exactly how the code is written. The syntax of a VBA statement is the set of rules that define the exact order of words and where spaces, commas, parentheses, and other punctuation marks are required.

Like a spoken language, the VBA language consists of words (keywords), punctuation marks (for example, commas), and blank spaces. Keywords are plentiful, and each has its own specific rules of syntax. The syntax rules are so rigid that you'd never be able to figure them out by guessing. You have to know how to get the information you need, when you need it.

The VBA editor provides several tools to help with syntax. For example, you use the MsgBox() keyword in VBA to display a custom message onscreen. Imagine that you already know about the MsgBox() function and were about to use it in a program, and you type the following into a procedure:

As soon as the VBA editor sees the MsgBox( part, it shows a Quick Info screen tip for the MsgBox keyword, as in the example shown at the top of Figure 3-3. The Quick Info tip is actually a small syntax chart showing you the rules for using MsgBox correctly. Within the Quick Info tip, the bold-italic word Prompt means that you're expected to type a prompt next.

For the sake of example, suppose you type "Hello World" (with the quotation marks) and a comma into the line:

x = MsgBox("Hello World",

The comma lets the VBA editor see that you've typed a valid first argument and are now ready to type the second argument. The second argument in the syntax chart ([Buttons /s vbMsgBoxStyle = vbOKOnly]) is then boldfaced to indicate that you now should type the second argument. Also, a list of meaningless-looking names appears, called constants, as in the bottom half of Figure 3-3.

Quick Info

Constants

Figure 3-3:

Quick Info (top) and list of Constants (bottom).

Quick Info

Constants

Figure 3-3:

Quick Info (top) and list of Constants (bottom).

Okay, you gotta trust me on this one: The Quick Info and list of constants are actually there to help. Unfortunately, they are only of help to those people who've used the MsgBox() a zillion times in the past and need only brief reminders on syntax and available constants. For someone who's just learning, more in-depth information is needed. Fortunately, it's always easy to get.

0 0

Post a comment