On Error GoTo 0
It disables the current error handler.So it is used to resume execution normally (without any error handler).
Code:
Sub ErrorHandler()
Dim dblValue As Double
On Error Resume Next
ThisWorkbook.Worksheets("A").Range("A1") = "Transformer" ' Subscript out of range error will occur if there is no sheet named "A" in the Workbook
'On Error GoTo 0 'error handler disabled..next error will not be handled.Uncomment the line to check the effect.
dblValue = 1 / 0 ' Division by Zero error
MsgBox "Ingnored all the errors."
End Sub
In above example if one uncomments the line On Error GoTo 0 then it will not handle the error that comes after this statement.
On Error GoTo -1
When an error occurs within a procedure, an exception object is created. On Error GoTo -1 is used to set this exception object to nothing.
If it is not done then next error handler statement (e.g. On Error GoTo errHandler / On Error Resume Next ...) will not work.
To check the effect of not using it comment the line 'On error GoTo -1' in the snippet given below.
Code:
Sub ErrorTest()
Dim dblValue As Double
On Error GoTo ErrHandler1
dblValue = 1 / 0
ErrHandler1:
MsgBox "Exception Caught"
On Error GoTo -1 'Comment this line to check the effect
On Error GoTo ErrHandler2
dblValue = 1 / 0
ErrHandler2:
MsgBox "Again caught it."
End Sub
But if you use Resume Next as an error handler then an exception object is not created.
Code:
Sub ErrorTest()
Dim dblValue As Double
On Error Resume Next
dblValue = 1 / 0
MsgBox "Exception Caught"
On Error GoTo ErrHandler
dblValue = 1 / 0
'No need to set exception object to nothing as it has not been created
ErrHandler:
MsgBox "Again caught it."
End Sub
More examples to understand the same.
Code:
Sub ErrorTestUserHandler()
Dim dblValue As Double
For lngloop = 1 To 10
On Error GoTo ErrHandler
dblValue = 1 / 0
ErrHandler:
MsgBox "Caught it."
On Error GoTo -1 'Comment this line and run it again to see the effect
Next
End Sub
Code:
Sub ErrorTestResumeNext()
Dim dblValue As Double
For lngloop = 1 To 10
On Error Resume Next
dblValue = 1 / 0
MsgBox "Caught it."
'No need to set exception object to nothing as it has not been created
Next
End Sub
Bookmarks