如果数组中的任何值包含错误值,则返回 true

时间:2021-04-26 12:06:11

标签: excel vba

如果数组 (array = ActiveSheet.Range("A1").CurrentRegion.Value) 中的任何值包含 #NA 错误,只需将布尔值设置为 true。

我已经读到 wks.Cells.SpecialCells(xlCellTypeFormulas, xlErrors) 可以做到这一点,但我不确定如何将它应用到我的代码中。任何其他方法也可以。

2 个答案:

答案 0 :(得分:2)

请试试这个代码:

Sub checkNAError()
   Dim wks As Worksheet, rngErr As Range, celV As Range
   
    Set wks = ActiveSheet 'use here the sheet you need to check
    On Error Resume Next
      Set rngErr = wks.cells.SpecialCells(xlCellTypeFormulas, xlErrors)
   On Error GoTo 0
   If Not rngErr Is Nothing Then
        For Each celV In rngErr.cells
            If celV.value = CVErr(2042) Then MsgBox "#N\A error on cell " & celV.Address
        Next
    Else
        MsgBox "No any error in sheet " & wks.name
   End If
End Sub

答案 1 :(得分:2)

您可以使用以下代码:

它基本上是查看单元格中的所有值:

Sub check_for_errors()
    Dim ws As Worksheet
    Dim arr As Variant
    Dim i As Long, j As Long
    Dim errorFound As Boolean
    
    Set ws = ActiveSheet
    
    arr = ws.Range("a1").CurrentRegion.Value
    errorFound = False
    For i = LBound(arr, 1) To UBound(arr, 1)
        For j = LBound(arr, 2) To UBound(arr, 2)
            If IsError(arr(i, j)) Then
                errorFound = True
                Exit For
            End If
        Next j
        If errorFound Then Exit For
    Next i
    
    Debug.Print errorFound
End Sub
相关问题