VBA: On Error Resume Next 工作多久?

VBA: How long does On Error Resume Next work?

我正在阅读有关如何使用 On Error Resume Next 的信息,并且我正在尝试弄清楚该行将适用于该程序多长时间。在微软网站上,我发现了这样一句话:"An On Error Resume Next statement becomes inactive when another procedure is called." 这到底是什么意思?什么被认为是程序?

我问是因为我正在我的程序中使用该行,但我不希望它 Resume Next 发生的所有运行时错误,只是下一行中明显的错误。


代码:

Dim zRange As Range

Call FilterTableFor(fieldNameColumn, Array("baseunitprice", "burden", "MTLBURRATE", "PurPoint", "Vendornum"))

On Error Resume Next
Set zRange = commentsColumnRange.SpecialCells(xlCellTypeVisible)
zRange.Formula = "target"

Call FilterTableFor(fieldNameColumn)

我还发现(并且知道了一段时间)On ErrorGoTo 行被认为是糟糕的编码。是否有 Try-Catch 可以用于这样的一行?

我在想这样的事情:

Dim zRange As Range

Call FilterTableFor(fieldNameColumn, Array("baseunitprice", "burden", "MTLBURRATE", "PurPoint", "Vendornum"))

Try
Set zRange = commentsColumnRange.SpecialCells(xlCellTypeVisible)
zRange.Formula = "target"
Catch()

Call FilterTableFor(fieldNameColumn)

我什至没有用它做任何事情,因为我觉得没有必要。

感谢您的宝贵时间。

您只想在

时使用 "On Error Resume Next"
  1. 你知道为什么会出错了

  2. 你知道它不会影响代码的其他部分。

  3. 你在出现错误的代码后立即使用"On Error Goto 0"。

话虽如此,您几乎不应该使用它。您应该找出错误发生的原因以及处理错误的代码。

该网站的意思是,一旦您退出调用它的子程序或函数,下一个简历将不再受到影响,您的错误将如常出现。

更好的选择是以这种方式使用 goto。但有些人几乎同样对此皱眉。

sub SomeSub()
    On Error Goto TestFailed

    'Some code

    'Some code

    'Some code

Exit sub

TestFailed:
    'Some code here to alert you to and/or handle the fallout of the error.
End sub

您并不总是需要一堆代码来处理错误,但您确实应该做点什么。也许只是让您的代码将 cells.font.color 属性 更改为 vbRed。简单地做 On Error Resume Next (a line of code that might error) On Error Goto 0 是非常糟糕的形式。

正如其他人指出的那样,On Error Goto Label 本质上是 VBA 版本的 Try ... Catch,我使用它 frequently

回答你的问题"How long does On Error Resume Next work?"

答案是:直到下一个定义On error ...

因此,如果您定义 On error resume next,它将跳过所有错误,直到您定义 On error goto 0On error goto label

ON ERROR... 声明的范围

ON ERROR ...的效果一旦遇到以下情况之一即结束:

  1. 另一个ON ERROR ...。 (可能是 ON ERROR RESUME xON ERROR GOTO x 的形式)
  2. Exit Sub / Exit Function 在同一个 sub/function 定义的地方。
  3. End Sub / End Function of the sub/function where defined.

使用 ON ERROR RESUME NEXT 不好吗?

是也不是。

我会说不要在不知道这个声明的效果的情况下使用。尽可能避免。尽可能缩短范围。

要取消 ON ERROR RESUME NEXT 语句的效果,您可以调用 ON ERROR GOTO 0