gpt4 book ai didi

excel - VBA:显示标准运行时错误处理程序

转载 作者:行者123 更新时间:2023-12-02 11:33:03 25 4
gpt4 key购买 nike

我对在 Excel 中处理 VBA 错误的正确方法有疑问。如果发生特定错误,例如 xxxxxxx,则应显示 MsgBox。如果发生另一个错误,应该弹出标准运行时错误处理程序。如何才能做到这一点?下面是示例代码:

On Error Resume Next

'Line of code that causes an error here.

If Err.Number = xxxxxxx Then

MsgBox "Specific error message."

ElseIf Err.Number = 0 Then

Do nothing

Else 'Some error other than xxxxxxx.

'This is the problem. Here I would like to display standard run-time error
'handler without causing the error again.

End If

On Error GoTo 0

最佳答案

通过将其放入“Else” block 中,您可以获得一个看起来非常类似于标准错误消息的消息框:

MsgBox "Run-time error '" & Err.Number & "':" & _
vbNewLine & vbNewLine & _
Error(Err.Number), vbExclamation + vbOKOnly, _
"YourProjectNameHere"

但这只是一个传真。它不是 VB6 提出的实际错误消息对话框;它只是被格式化为看起来像它。此时,“On Error Resume Next”语句仍禁用错误处理。

但是如果您真的真的想要调用标准错误处理代码,您可以将其放在“Else” block 中:

Dim SaveError As Long
SaveError = Err.Number
On Error Goto 0
Error (SaveError)

此代码保存错误号,重新启用错误处理,然后重新引发错误。您可以通过这种方式调用 VB 运行时的真正错误处理机制。但请注意:如果调用链中较高位置的事件错误处理程序未捕获此错误,则在用户单击“确定”按钮后,它将终止您的程序

请注意,您还将无法在该错误处理程序中使用“Erl”获取发生错误的实际行号,因为您正在使用“Error (SaveError)”语句重新生成运行时错误。但这可能并不重要,因为大多数 VB 代码实际上并不使用任何行号,因此 Erl 无论如何都只是返回 0。

关于excel - VBA:显示标准运行时错误处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4558300/

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