【问题标题】:How does On Error Resume Next handle errors in If statements and loopsOn Error Resume Next 如何处理 If 语句和循环中的错误
【发布时间】:2017-03-25 22:29:09
【问题描述】:

在 VBA 代码中处理错误时,there are a few methods commonly utilized。其中一种方法是使用On Error Resume Next 的内联错误处理。但是,在阅读了现有问题“VBA: How long does On Error Resume Next work?”后,我发现不清楚程序是否会在下一行继续执行,或者程序是否会在下一个逻辑点继续执行。

MSDN has the following description 用于On Error Resume Next 的功能:

指定当发生运行时错误时,控制权转到 紧跟在发生错误的语句之后的语句 执行继续的地方。使用此表单而不是 On Error GoTo 访问对象时。

此外,Resume 关键字上有(现已停用)StackOverflow 文档,其中声明了与 On Error Resume Next 类似的内容:

Resume Next 继续执行紧随其后的语句 导致错误的语句。如果错误实际上不是 在此之前处理,然后允许继续执行 具有潜在的无效数据,这可能会导致逻辑错误和 意外行为。

这并没有明确说明错误处理行如何处理控制流语句的初始行中的错误。具体来说,如果错误发生在If .. Then .. Else .. End If 语句的第一行,程序是从If 语句的第一行开始运行,还是从End If 语句之后的第一行开始运行?

【问题讨论】:

    标签: vba error-handling


    【解决方案1】:

    On Error Resume Next 将导致程序在限定语句导致错误时进入If .. Then 语句或[While/Do/For/For Each] 循环。

    为了解决这个问题,我在一个空的 Excel (2007) 工作簿中创建了一对测试函数。然后我使用 Excel 的电子表格来评估已知错误案例和已知成功案例的功能。


    Test1 - If 语句

    Public Function Test1(intN As Integer) As String
    On Error Resume Next
        Test1 = ""
        If 1 / intN > 0 Then
            Test1 = Test1 + "A"
        Else
            Test1 = Test1 + "B"
        End If
        Test1 = Test1 + "C"
    End Function
    

    当输入数字为0 时,此函数将在If 1 / intN > 0 Then 行抛出错误,并将评估其他数字,例如1-1

    结果:

    Test1(-1) -> BC
    Test1(0)  -> AC
    Test1(1)  -> AC
    

    从结果中可以看出,Test1(0) 中的错误导致程序跳过了If 1 / intN > 0 Then 行。 A 被添加到字符串中,然后程序从 Else End If 跳过。字符C被添加到字符串中,函数结束。


    Test2 - [Do] 循环

    Public Function Test2(intN As Integer) As String
    On Error Resume Next
        Test2 = ""
        Do While 1 / intN > 0
            Test2 = Test2 + "A"
            intN = intN - 1
        Loop
        Test2 = Test2 + "C"
    End Function
    

    当输入数字为0时,此函数将在Do While 1 / intN > 0行抛出错误,对于正整数将返回一个AA..AC字符串,对于负整数返回C

    结果:

    Test1(-1) -> C
    Test1(0)  -> AC
    Test1(1)  -> AAC
    

    当进入循环时,On Error Resume Next 将导致程序从Do While 1 / intN > 0 直接跳到Test2 = Test2 + "A",不管它在循环的哪个迭代中。

    每当intN = 0时,程序运行循环中包含的代码并命中intN = intN - 1,导致intN = -1不再遍历循环代码。

    由此,可以解释为在ForWhile 循环的情况下,循环将以类似的方式运行,取字面值下一行并在到达循环底部时返回。

    【讨论】:

      猜你喜欢
      • 2017-05-09
      • 2011-01-13
      • 2021-05-10
      • 2017-10-01
      • 1970-01-01
      • 2012-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多