出错时VBA Excel停止转到

时间:2015-05-20 01:14:25

标签: vba excel-vba onerror excel

我在子程序中的某处写过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")

2 个答案:

答案 0 :(得分:6)

看看下面的示例,它显示了两者 - 手动进行错误处理并允许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")

答案 1 :(得分:0)

试试这个

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