to look for errors that prevent the program from running properly. You might
create an
If...Then
statement and not include the corresponding
End If
statement. The compiler runs constantly, so VBA
finds some mistakes almost
immediately after you make them.
VBA uses the compiler to find many of the syntax errors that you make and
displays an error message. You can try this feature. Open a new project,
create a
Sub
(the name isn’t important), and type
MsgBox()
. Then press
Enter. VBA displays a message box stating that
it was expecting an equals
sign (=). When you use parentheses after
MsgBox
, VBA expects that you want
to include a result variable to hold the result, such as
MyResult =
MsgBox(“My Prompt”)
. You should also notice
that the errant line of code
appears in a highlight color, which is normally red.
Missing elements are another syntax error that VBA finds with relative ease.
When you fail to include an
End If
statement for an
If...Then
statement,
VBA always finds it and displays an error message. However, VBA doesn’t
find this error in most cases until you try to run the program. In addition, it
doesn’t
show the errant
If...Then
statement — VBA normally highlights
the
End Sub
or
End Function
statement instead, thus making this error a
little harder to find.
The compiler also finds many of the punctuation errors that you can make in
your code. When a line of code becomes too long
and you try to move to the
next line without adding a continuation character, the compiler notices the
error and tells you about it. (See the “Writing Your First Sub” section of
Chapter 3 for a description of the continuation character.) The compiler also
notes missing periods between elements of a statement
or missing parenthe-
ses from function calls (when needed).
When you add
Option Explicit
to your code, the compiler checks vari-
ables for a number of problems. You could try to
assign a string value to an
integer. VBA allows you to make this error when you type the code. However,
when you try to run the code, the compiler sees the type mismatch and tells
you about it. The compiler can detect many variable errors that would go
unnoticed otherwise, thus making your code less likely to contain errors.
Understanding
run-time errors
A
run-time error
happens when something outside your program is incorrect.
A disk access request can fail, or you can type the wrong information. Your
VBA code is correct, but the program still fails because of this external error.
Run-time errors are the reason why many large companies, such as Microsoft,
run beta programs. (A
beta program
is a vendor-sponsored
method of getting
a program before its developers have finished it for the purpose of testing
136
Do'stlaringiz bilan baham: