Search code examples
vbaexcelonerror

VBA Excel Stop On Error Goto


I have written On Error GoTo ErrorMessage somewhere in a subroutine. I want to stop this command after End if command as shown below.

    On Error GoTo ErrorMessage
    Sheet2.Range("A1").Font.Bold = True
    Sheet2.Range("B1").Font.Bold = True     
    If LastRow_Sh2 >= First_Row_Sheet2 Then
        Sheet2.Range(FromCol & First_Row_Sheet2 & ":" & ToCol & LastRow_Sh2).ClearContents
        Exit Sub
    End If
    ' Stop here

    ' I have some codes here

ErrorMessage:
    MsgBox ("Error message: The input values are invalid")

Solution

  • Take a look at the example below that shows both - error handling manually and allow VBA to catch a runtime error:

    Sub Test()
    
        On Error GoTo ErrorHandler
        Dim Divisor As Integer
        Dim Num As Integer
        Dim Answer As Double
    
        Num = 100
        Divisor = 0
    
        ' ================================
        ' throw an error here forcefully
        ' and allow ErrorHandler to handle
        ' the error
        ' ================================
        Answer = Num / Divisor
        MsgBox "Answer is " & Answer, vbOKOnly + vbInformation, "Answer"
    
        ' stop error handling
        On Error GoTo 0
    
        ' ================================
        ' throw an error here forcefully
        ' and allow VBA to handle the error
        ' ================================
        Answer = Num / Divisor
        MsgBox "Answer is " & Answer, vbOKOnly + vbInformation, "Answer"
    
        Exit Sub
    
    ErrorHandler:
        MsgBox "Handling the error here", vbOKOnly + vbInformation, "ErrorHandler"
        Resume Next
    
    End Sub
    

    Based on this, you can modify your code slightly to allow VBA to handle the error on runtime.

    On Error GoTo ErrorMessage
    Sheet2.Range("A1").Font.Bold = True
    Sheet2.Range("B1").Font.Bold = True     
    If LastRow_Sh2 >= First_Row_Sheet2 Then
        Sheet2.Range(FromCol & First_Row_Sheet2 & ":" & ToCol & LastRow_Sh2).ClearContents
        Exit Sub
    End If
    
    ' Stop here
    ' The statement below will disable error handling that was
    ' done by ErrorMessage
    On Error GoTo 0
    
    ' I have some codes here
    ' If this block of code has errors, VBA will handle it and
    ' allow debugging
    
    ErrorMessage:
        MsgBox ("Error message: The input values are invalid")