I'm currently at the beginning of the learning curve for VBA.
I have taken a VB Basic course - the neat thing about it, was the
"Try/Catch" error catching commands.
I haven't found much in VBA for error catching. Are there any similar tools
in VBA as VB.Basic? Does anyone know of any good web pages on error catching?
Thanks for any thoughts . . .
VBA is based on Visual Basic 6.0, which has only the flimsiest relationship to
the VB.Net you studied. I expect Karl Peterson to come along any minute and give
you an earful on that subject.
In particular, VBA doesn't have anything like Try/Catch. It has the On Error
statement, which offers three variations:
On Error GoTo <line> -- If a trappable error occurs, execution jumps to the
line specified by the line number or label. Typically, you put an Exit Sub
statement at the end of the "normal" code, then a label that marks the start of
an error handler, and then the error-handling code. It's also possible to put
the label earlier in your code than the point where an error might happen, so it
loops back and executes the code again.
On Error GoTo 0 -- Disables any error handler that was activated by an On Error
GoTo statement.
On Error Resume Next -- If a trappable error occurs, execution jumps to the
line immediately after the point where the error occurred. That next line is
usually something like
If Err.Number <> 0 Then
' do something to log or fix the error
Err.Clear
End If
The Err object has at least two "interesting" properties: .Number is 0 if there
hasn't been an error, or a positive value if there has been an error. The
..Description property is a string suitable for displaying in a message box. If
you're dealing with objects, also have a look at the .Source property.
The VBA help has a topic named "Trappable Errors" that lists all the errors that
can be caught by an On Error statement. There are also a lot of non-trappable
errors.
If you have several procedures that call each other, the topic of which error
handler catches the error can become quite complex.