如何检查 Excel 单元格是否包含 REF! VBA 中的错误

How to check that Excel cell contains REF! error in VBA

我在 Excel 中发现了很多关于如何做到这一点的讨论,但我的目标是捕获 REF! VBA 中的错误,而不是 Excel 本身的错误。可能吗?

If IsError(cell.Value) Then
    If cell.Value = CVErr(xlErrName) Then
        ...
    End If
End If

原代码错误,如果单元格不包含错误,将给出类型不匹配错误。

If cell.Value = CVErr(xlErrRef) Then
    ...
End If

Sub CheckRef()
Dim CheckRange As Range, CheckCell As Range

    Set CheckRange = [A1:D10]                ' as per app

    For Each CheckCell In CheckRange
    If IsError(CheckCell) And _
       CVErr(CheckCell) = CVErr(2023) Then ' 2023 --> xlErrRef
            MsgBox ("#REF! in  " & CheckCell.AddressLocal)
            Exit Sub                     ' exit after first #REF! found
        End If
    Next CheckCell
End Sub

例子

  • 在 B2 中输入“=1/0”以创建不同于“#REF!”的错误
  • 在B4、B5中输入1
  • 在B7中输入“=B4+B5”
  • 删除第 4 行
  • 运行 Sub CheckRef()