- Back to Home »
- VBA »
- [VBA] On Error
Thursday, December 5, 2019
VBA Runtime Errors:
・Referencing a non-existent workbook, worksheet, or other object
・Invalid data ex. referencing an Excel cell containing an error
・Attempting to divide by zero
VBA On Error Statement:
・On Error GoTo 0
IF error, program is stop, display default error dialog
・On Error Resume Next
IF error, do not display error dialog, continue run next line code
・On Error GoTo Label
IF error, goto user defined label
Option Explicit
Sub ErrorResumenext()
'IF error, do not display error dialog, continue run next line code
'It mean that [Some code] will be run continue although error occur
On Error Resume Next
ActiveSheet.Shapes("Start_Button").Delete
If Err.Number <> 0 Then
Debug.Print "Error"
Else
Debug.Print "No error"
End If
'Some code
Debug.Print "do something"
End Sub
Sub ErrorGoTo0()
On Error Resume Next
ActiveSheet.Shapes("Start_Button").Delete
'From here IF error, program is stop, display default error dialog
'It mean that [Some code] do not run if error occur
On Error GoTo 0
ActiveSheet.Shapes("Start_Button").Delete
'Some code
Debug.Print "do something"
End Sub
Sub ErrGoToEnd()
'IF error, goto label nextProc
On Error GoTo nextProc
ActiveSheet.Shapes("Start_Button").Delete
'Some Code 1
nextProc:
'Some Code 2
End Sub