Microsoft Office Tutorials and References
In Depth Information
GoTo Statement
The GoTo statement forces the procedure to change immediately to another section of the
procedure unconditionally. The section of code that is to be branched to needs to be marked
with either a line number or a line label, allowing the program to jump either forward or
backward within the procedure. Using the GoTo statement is discouraged because it can
cause procedures to become more difficult to understand and debug.
The syntax for the GoTo statement is shown here:
GoTo line
In the preceding code, line is a required line label that must be a line number or a line label
that is defined within the same procedure. Line numbers can be any series of digits and must
begin in the first column. Line labels can be any series of characters that starts with a letter
and ends with a colon (:). Line labels are not case sensitive and must begin in the first column.
Because GoTo statements can lead to unstructured code, using them is strongly discouraged.
If used sparingly, they can be very useful. The following section on error handling offers bet­
ter understanding of when and how to use the GoTo statement and line labels.
Error Handling
Every procedure should have some form of error-handling abilities, even if it does no more
than inform the user of what caused the error and then exits. Procedures that are meant to be
called from other procedures and not necessarily invoked by the user, for example, should
return to the calling procedure some type of indication that it was able to complete
successfully.
Consider the Select Case example covered earlier in the chapter that calculated the number of
days in a month. It specifically checked whether or not the variable intMonth matched any of
the expected clauses. If intMonth contained any value outside of the 1 to 12 range, the Select
Case statement returned a -1.
By returning a value that is outside the realm of expected values, it allows any statement that
depended upon the value of intMonth to confirm that it was a legal value.
Besides adding data validation code to check your own code, VBA also allows you to trap
errors that it detects. By trapping the errors that VBA detects, your procedure might be able
to correct them and continue executing.
To trap VBA errors, you use the On Error command. It takes the basic form
On Error Goto line label
Search JabSto ::




Custom Search