繁体   English   中英

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

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

尝试这个

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM