VBA选择性错误处理

时间:2015-04-22 19:20:17

标签: vba excel-vba excel

如何只捕获VBA中的特定错误?

到目前为止,我一直在错误处理程序中引发另一个错误,错误处理程序(我不想用于此特定错误)将错误传递给另一个处理程序,但这会使我的代码膨胀。

我想知道是否有更好的方法?

到目前为止我一直这样做的例子:

sub correct()
    On Error GoTo CorrectHandler
    wrong
CorrectHandler:
    'some code to handle out of range error (aka Err.Number 9)
End Sub

Sub wrong()
    Dim BadArray(1 To 1) as Variant
    On Error GoTo WrongHandler
    BadArray(100) = 1
WrongHandler:
    Select Case Err.Number
        Case 9
            Err.Raise 9
        'Code to handle other errors
    End Select
End Sub

1 个答案:

答案 0 :(得分:1)

除非您想拥有包含all possible errors you can run into的精选案例,否则通常会以相反的方式执行此操作。执行此类操作的典型用法是错误是否可以恢复。如果你想在错误处理程序的上下文中执行它(如果不是可以恢复,因为你丢失了原始错误中的信息,则更难调试),我会做这样的事情:< / p>

Sub correct()
    On Error GoTo CorrectHandler
    wrong
    Exit Sub
CorrectHandler:
    Debug.Print Err.Number
End Sub

Sub wrong()
    Dim BadArray(1 To 1) As Variant

    On Error GoTo WrongHandler

    Dim i As Integer
    i = 1 / 0
    BadArray(100) = 1

    Exit Sub
WrongHandler:
    If Err.Number = 11 Then
        Debug.Print "I can divide by 0, no problem."
        Resume Next
    Else
        Err.Raise Err.Number
    End If
End Sub

但一般来说,处理这些内联更好。关闭错误处理程序,然后测试错误号:

Sub wrong()
    Dim BadArray(1 To 1) As Variant
    Dim i As Integer

    'I think the next line might fail for some reason...
    On Error Resume Next
    i = 1 / 0
    If Err.Number = 11 Then
        Debug.Print "I can divide by 0, no problem."
    ElseIf Err.Number <> 0 Then
        Debug.Print "What the hell? Didn't expect that."
        Err.Raise Err.Number
    End If
    'Turn error handling back on.
    On Error GoTo 0

    BadArray(100) = 1
End Sub

在这种情况下,out of bounds赋值抛出但它被调用函数的处理程序捕获。