Help with "On Error"

G

Gary Hillerson

I thought I understood "On Error" but I'm thinking that I got it
wrong.

Can someone point me to a clear description of "On Error" and
"Resume?"

I may be confused:

--------------
If I'm calling a single function and want to simply go to the next
statement in case of an error, I can write:

Private Sub MySub.
On Error Resume Next
'some call like Open a file
'other code that will be executed regardless of errors
End Sub
----------------

If i'm calling a bunch of potentially error-causing functions, I
thought I could install an error handler and then simply drop out of
my routine, like this:

Private Sub MySub2
On Error Goto ErrHandler
'some system call
'some code
'another system call
'more code
Exit Sub
ErrHandler:
MsgBox "Got an Error"
Exit Sub


But in reading Word 2003's help, it sounded like you have to have a
Resume statement or the error handler will stay alive, which I don't
want. Does exiting the subroutine terminate the error handler? If not,
how do I terminate without resuming immediately after the offending
call?
 
J

Jezebel

There are two ways to handle errors:

1. Ignore them using 'on error resume next'. This has its uses, but be very
careful with it. For example if you have code like

on error resume next
If MyObject.Property = XXX then
... DO this

and you get an error on the If statement, the 'DO this' will be executed ---
as if the If statement returned TRUE. You can switch off the resume next
with 'On error goto 0'. So this sort of construction is fine:

On error resume next
ActiveDocument.CustomDocumentProperties(Name).Delete
On error goto 0

This deletes the property if it exists and does nothing if not.


2. Use 'On error Goto ...' Once you've gone to the error handler, your code
is in an 'error state' and it stays that way until either you execute a
resume, or you fall out the bottom of your process. The danger with not
resuming is if your code meets another error: your code will then pass the
error up the line. Here's one structure that a lot of people use, in one
form or another:


Sub MySub()

on error goto MySub_Error

.... main code

MySub_Exit:
on error resume next
... clean-up code goes here
exit sub

MySub_Error:
.... handle the error here
If retry then
Resume
elseif ignore then
Resume Next
end if
Resume MySub_Exit

end Sub
 
M

Malcolm Smith

There's a great and full description in the excellent book "Visual Basic
In Your Face", if it's still in print. It's a collection of excellent
articles about the workings of VB, which of course applies to VBA, and the
error handling is the subject of one chapter.

- Malc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top