gpt4 book ai didi

vba - 处理子例程中的重复性VBA错误

转载 作者:行者123 更新时间:2023-12-03 07:48:26 24 4
gpt4 key购买 nike

我坚持使用某种我可以解决的方法,但是它使我感到烦恼,我没有直接答案来解决如何使用On Error Goto重复发生错误的问题。我的问题本质上是as this one,但是提供的答案是OP总体方法的替代方法,而不是如何处理特定问题。
我在下面简化了一个例子。我是,很好,是,可能有十几种方法可以重写此代码以避免出现任何错误-我只是用它来举例说明试图弄清楚为什么我= 0时此代码正常工作的问题,但是当i = 3,6,9时不是吗?

Sub vbaErrorConfusion()
Dim theArray(9) As Long, i As Long

For i = 0 To 9
On Error GoTo fixingErrors
'next line will intentionally create an error when
'when i = {0} this works as expected, but at i=3 next line throws an error.
theArray(i) = i + 1 / (i Mod 3)
On Error GoTo 0

next_i:
Next i

Exit Sub
'----Error Handling----
'this works as expected when i=0 but not when i = 3,6,9
fixingErrors:

Err.Clear
On Error GoTo 0
'at this point I would expect my error state to be the same as the start of procedure?
theArray(i) = -1
GoTo next_i
End Sub
我的 Err变量在第一个0实例后显示的内容。
enter image description here
运行 Err.Clear后,我希望 i=3的行为与 i=0相同,但是我的过程因以下VBA错误而停止,希望没有任何错误捕获。
enter image description here
我想有某种方法可以重置 Error变量或处理这种情况,而无需解决方法?任何质量回应都将得到认可。谢谢。

最佳答案

要告诉VBA您已处理了该错误,您需要一个Resume语句。因此,将GoTo next_i行替换为Resume next_i可为您带来预期的结果。
您不需要Err.Clear。另外,On Error GoTo 0将禁用错误处理程序。但是,这些行都不会告诉VBA您已处理了错误。
i=0的代码中,错误处理程序已激活,但未告知VBA错误已得到处理(即,没有Resume语句)。在i=3上,另一个错误发生了,而先前的错误没有得到处理。在这种情况下,当前过程/功能/属性无法处理第二个错误,因此是致命的。
您还应该将On Error GoTo fixingErrors行放在循环之外。

Sub vbaErrorConfusion()
On Error GoTo fixingErrors
Dim theArray(9) As Long, i As Long

For i = 0 To 9
'*On Error GoTo fixingErrors
'next line will intentionally create an error when
'when i = {0} this works as expected, but at i=3 next line throws an error.
theArray(i) = i + 1 / (i Mod 3)
'*On Error GoTo 0

next_i:
Next i

Exit Sub
'----Error Handling----
'this works as expected when i=0 but not when i = 3,6,9
fixingErrors:

'*Err.Clear
'*On Error GoTo 0
'at this point I would expect my error state to be the same as the start of procedure?
theArray(i) = -1
Resume next_i
End Sub

关于vba - 处理子例程中的重复性VBA错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65063380/

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