gpt4 book ai didi

VBA 选择性错误处理

转载 作者:行者123 更新时间:2023-12-04 20:42:41 24 4
gpt4 key购买 nike

如何仅捕获 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

最佳答案

通常,除非您想要一个包含 all possible errors you can run into 的 Select Case,否则您会以相反的方式执行此操作。 .执行此类操作的典型用途是错误可恢复。如果您想在错误处理程序的上下文中执行此操作(如果由于丢失原始错误中的信息而无法恢复,则更难调试),我会这样做:

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

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

关于VBA 选择性错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29806947/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com