View Single Post
  #3   Report Post  
Posted to microsoft.public.excel.programming
Bob Phillips[_4_] Bob Phillips[_4_] is offline
external usenet poster
 
Posts: 834
Default error handling in VBA

On Error Resume Next can be very useful if we want test a certain condition
that may or may not be met, and then test the results afterwards. That is
testing for predictable errors that we don't want to crash and burn on.

For instance, suppose we intend to add a worksheet, but it may already have
been added. We can use code like this

On Error Resume Next
Set ws = Worksheets("mySheet")
On Error Goto 0
If ws Is Nothing Then

Set ws = Worksheets.Add
ws.Name = "mySheet"
End If

'then do stuff with ws

So as you can see, it is a useful technique to help us test things. The
important thing is to make sure that the scope of an On Error Resume Next is
very limited, as I did above by restricting it to just one line of code, so
that real errors don't just get ignored.

The better way is proper error handling, like this

On Error GoTo errHandler

'do stuff like sending mail

Exit Sub 'so we don't drop into the error handler

errHandler:
MsgBox "Unexpected error" & vbNewline & _
"Error: " & Err.Number & ", " & Err.Description, _
vbOkOnly & vbCritical, "My App - Error"

--

HTH

Bob

"sam" wrote in message
...
Hi All,

Why do we use "On error resume next" shouldnt we be resolving those
errors.

For eg: if we are sending important email notifications through excel VBA
which affect management decisions, shouldnt we be avoiding to user "On
error
resume next"? IF for some reason there is an error and an email is not
sent
it might affect a lot of things.

My concern is: how do we handle error is this situations? is there a
better
way to handle errors, rather than using "On error resume next" statement?

Thanks in advance.