VBA Excel 出错时停止转到

VBA Excel Stop On Error Goto

我在子程序的某处写了On Error GoTo ErrorMessage。我想在 End if 命令后停止此命令,如下所示。

    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")

试试这个

    On Error Resume Next '".. GoTo ErrorMessage" replaced by "...resume next"
    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

    If Err.Number > 0 Then GoTo ErrorMessage ' Stop here

    ' I have some codes here

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

查看下面的示例,其中显示了手动错误处理和允许 VBA 捕获运行时错误:

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

基于此,您可以稍微修改您的代码以允许VBA在运行时处理错误。

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")