VBA在代码执行期间更改错误处理方法

Fil*_*ipB 0 excel vba

我有一个宏,部分代码涉及:1)检测列是否包含空单元格 - 如果是这样填充它们有一些值2)检测列是否包含包含错误的单元格(如N/A)以及是否所以填补它们的价值

现在,如果列中没有错误/空单元格,则找到它们的行会显示"运行时错误1004,找不到单元格".

我使用错误处理来跳过GoTo.

下面是代码 - 第一个错误处理转到完美的作品,而第二个给出了预期的错误,虽然有错误处理转到集,这似乎并没有工作.带注释的代码:

On Error GoTo EErrorOne


'depending on file I get, below line will generate error and code successfully skips to ErrorOne label

Workbooks(nazwawb).Sheets(szitnr).Columns(ktorepole).SpecialCells (xlCellTypeBlanks)

' code to be skipped

    Workbooks(nazwawb).Sheets(szitnr).Columns(ktorepole).Select
    Selection.SpecialCells(xlCellTypeBlanks).Select
    Selection.Value = "Some Value"

' end of code to be skipped

EErrorOne:

' successfully skipped error line by now. Below line should set a new Error handling procedure.

On Error GoTo EErrorTwo



Workbooks(nazwawb).Sheets(szitnr).Columns(ktorepole).Select

' Below line generates an error but does not skip to EErrorTwo label as detailed in the current Error handling procedure

Selection.SpecialCells(xlCellTypeFormulas, 16).Select   

' code to be skipped


Selection.SpecialCells(xlCellTypeFormulas, 16).Select
    Selection.Value = "Some Value"

' end of code to be skipped


EErrorTwo:



' Below line should reset error handling procedure to normal for subsequent handling of other errors:
On Error GoTo 0
Run Code Online (Sandbox Code Playgroud)

似乎忽略了错误处理过程(GoTo特定标签),而是显示错误消息,好像错误处理被重置为GoTo 0.如何跳过第二个错误?

Dar*_*ook 6

你不会在它们发生时清除你的错误,只是试图跳过它们并且代码想知道错误发生了什么.

正如Chip Pearson在他的网站上所说:

当引发第一个错误时,执行转移到Err1:之后的行.发生第二个错误时,错误处理程序仍处于活动状态,因此On Error语句不会捕获第二个错误

并继续

Resume语句指示VBA在代码中的指定点继续执行.您只能在错误处理块中使用Resume; 任何其他用途都会导致错误.此外,除了退出过程之外,Resume是唯一的方法,以摆脱错误处理块.不要使用Goto语句将代码执行从错误处理块中引出.这样做会导致错误处理程序出现奇怪问题. http://www.cpearson.com/excel/errorhandling.htm

理想的方法是首先避免错误 - 在打开它之前检查工作簿是否存在,在尝试引用它之前检查工作簿中是否存在工作表,如果发生错误则跳出例程的主体,处理错误然后再次跳回来.

举个例子:

Sub Test()

    On Error GoTo ERR_HANDLE

    '.... code ....

FAST_EXIT:
    'Code to tidy up, clear references etc before finishing.

Exit Sub

ERR_HANDLE:
    Select Case Err.Number
        Case 1004
            'Code to resolve error
            '.
            '.
            'Resume - clear error, jump back to line that caused it.
            'Resume Next - clear error, jump to line after the one that caused error.
            'Resume FAST_EXIT - clear error and go to line label.

        Case 92 'Do something else to resolve error.

        Case Else
    End Select

End Sub
Run Code Online (Sandbox Code Playgroud)

  • 为了进一步澄清Darren的答案,错误处理程序处于活动状态,直到明确告知代码.标准错误处理使用"On Error GoTo SomeLineLabel:错误处理标签后的代码:恢复或继续下一步".最后的陈述实质上就是清除错误. (2认同)