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

标签 vba error-handling

我坚持使用某种我可以解决的方法,但是它使我感到烦恼,我没有直接答案来解决如何使用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/

相关文章:

python - 检查 Python 中的无效路径

c++ - 用于错误检查的转换函数算不算好?

forms - 是否可以在 VBA 的列表框中添加组合框作为列?

sql - Access - 检查月份和年份是否在日期范围内

vba - Do Loop 类型不匹配中的“If”语句

excel - 优化问题。查询不适用于超过 5 个股票代码。每次我用 5 个股票运行它平均需要 5-6 分钟

python - 如何使用Nominatim处理错误?

reactjs - React Redux一页应用: handle an API 404 with full page render

vba - Excel VBA - 工作表名称通配符搜索

c# - 在解析 XDocument 时处理空 XElement