Page 32 - Excel for Scientists and Engineers: Numerical Methods
P. 32
CHAPTER 1 INTRODUCING VISUAL BASIC FOR APPLICATIONS 9
Entering VBA Code
Of course, most of the VBA code you create will not be recorded, but
instead entered at the keyboard. As you type your VBA code, the Visual Basic
Editor checks each line for syntax errors. A line that contains one or more errors
will be displayed in red, the default color for errors. Variables usually appear in
black. Other colors are also used; comments (see later) are usually green and
some VBA keywords (Function, Range, etc.) usually appear in blue. (These
default colors can be changed if you wish.)
If you type a long line of code, it will not automatically wrap to the next line
but will simply disappear off the screen. You need to insert a line-continuation
character (the underscore character, but you must type a space followed by the
underscore character followed by ENTER) to cause a line break in a line of VBA
code, as in the following example:
Worksheets("Sheet1 ").Range("A2:67").Copy -
(Worksheets("Sheet2").Range("C2"))
The line-continuation character can't be used within a string, i.e., within
quotes.
I recommend that you type the module-level declaration Option Explicit at the
top of each module sheet, before any procedures. Option Explicit forces you to
declare all variables using Dim statements; undeclared variables produce an error
at compile time.
When you type VBA code in a module, it's good programming practice to
use TAB to indent related lines for easier reading, as shown in the following
procedure.
Sub Initialize0
ForJ=l TON
P(J) = 0
Next J
End Sub
Figure 1-10. A simple VBA Sub procedure.
In order to produce a more compact display of a procedure, several lines of
code can be combined in one line by separating them with colons. For example,
the procedure in Figure 1-10 can be replaced by the more compact one in Figure
1 - 1 1 or even by the one in Figure 1 - 12.
Sub Initialize0
For J = 1 To N: P(J) = 0: Next J
End Sub
Figure 1-11. A Sub procedure with several statements combined.