VBA 中的错误处理 - 下一个错误恢复

Error handling in VBA - on error resume next

我有以下代码:

ErrNr = 0
For Rw = StRw To LsRw 'ToDo speed up with fromrow torow
    If Len(ThisWorkbook.Sheets(TsSh).Cells(Rw, TsCl)) = 0 Then
        ThisWorkbook.Sheets(TsSh).Cells(Rw, TsCl).Interior.ColorIndex = 46
        ErrNr = ErrNr + 1
    End If
Next

我的问题是如果页面上有错误,我的代码之后就不是运行了。我认为解决方案应该是:

On Error Resume Next
N = 1 / 0    ' cause an error
If Err.Number <> 0 Then 
    N = 1
End If

但是我不知道怎么用这个代码。

这取决于你想做什么。

  • On Error Resume Next 将忽略错误发生的事实。这是让您的代码执行完成的好方法,但 只会保证它 不会 做您想要的事
  • On Error Goto 0 是默认响应。会弹出VBA正在生成
  • 的错误信息
  • On Error Goto <label>会导致您的代码在发生错误时跳转到指定的标签,并允许您根据错误代码采取适当的措施。

最后一个选项 On Error Goto <label> 通常是最有用的,您需要深入了解如何最好地将它用于您的应用程序。

This site is where I got the details above from, and is usually the first results that comes from Googling for "excel vba on error"。我自己已经多次使用该参考资料。

我通常尽量避免 On Error Resume Next,因为无论发生什么错误,它都会尝试继续(尽管在某些情况下它很有用)。

下面的代码将所有错误传递到过程中,这些错误可以根据具体情况进行处理。

Sub test1()

    Dim n As Double

    On Error GoTo ERROR_HANDLER

        n = 1 / 0  ' cause an error

    On Error GoTo 0
    Exit Sub

ERROR_HANDLER:
    Select Case Err.Number
        Case 11 'Division by zero
            n = 1
            Err.Clear
            Resume Next
        Case 13 'Type mismatch

        Case Else
            'Unhandled errors.
            MsgBox "Error " & Err.Number & vbCr & _
                " (" & Err.Description & ") in procedure test1."
            Err.Clear

    End Select

End Sub

我已经解释了您关于在遍历一系列单元格并检查值时如何处理常见工作表错误的要求。如果您尝试查看包含错误的单元格(例如 #N/A、#DIV/0!、#VALUE! 等),您将得到如下信息:

Runtime error '13':
Type mismatch.

这些可以用 VBA 的 IsError function 捕获。

Dim rw As Long

With ThisWorkbook.Sheets(TsSh)
    For rw = StRw To LsRw
        If IsError(.Cells(rw, 1)) Then
            .Cells(rw, 1).Interior.ColorIndex = 10
        ElseIf Not CBool(Len(.Cells(rw, 1).Value2)) Then
            .Cells(rw, 1).Interior.ColorIndex = 46
        End If
    Next rw
End With

在上面,我捕获了有错误的单元格并将它们着色为绿色。请注意,我正在检查它们是否有错误 before 我检查零长度。