On Error in VBA

On Error GoTo

The division by zero error will be printed.


Sub TestError()
    Dim gotError As Boolean
    On Error GoTo errorHandler
    gotError = True
    
    Dim x As Integer
    Dim y As Integer
    Dim z As Integer
    z = x / y   'divide by zero error
    gotError = False

errorHandler:
If gotError Then
         MsgBox "A division by zero error has occured"
End If

End Sub

                                                           




Print the Error


Sub TestError()
    Dim gotError As Boolean
    On Error GoTo errorHandler
    gotError = True
    
    Dim x As Integer
    Dim y As Integer
    Dim z As Integer
    z = x / y   'divide by zero error
    gotError = False

errorHandler:
If gotError Then
         MsgBox Err.Number & ":" & Err.Description
End If

End Sub
                                                           


On Error Resume Next

The division by zero error will not be printed.


Sub TestError()
    Dim gotError As Boolean
    On Error Resume Next
    gotError = True
    
    Dim x As Integer
    Dim y As Integer
    Dim z As Integer
    z = x / y   'divide by zero error
    gotError = False

errorHandler:
If gotError Then
         MsgBox "A division by zero error has occured"
End If

End Sub