VBA在特定列中查找错误值

时间:2013-04-25 14:23:23

标签: excel vba

Sub Macro9()
Dim LReturnValue As Boolean

LReturnValue = IsError(Sheets("Lookup Addition").Range("A:A").Value)

If LReturnValue = False Then
    i = MsgBox("there were no errors", vbOKOnly)
Else
    i = MsgBox("there were errors", vbOKOnly)
End If

End Sub

我对IsError(Customfunction())语法应该是什么感到困惑。我们如何告诉它检查范围内的每个细胞?

2 个答案:

答案 0 :(得分:3)

计算范围内的错误不需要循环(如果范围很大,则可能非常慢)或甚至任何VBA。

只需将此工作表函数添加到某个单元格即可。如果您不希望用户看到此单元格,则可以隐藏行/列/表。

=SUMPRODUCT(ISERROR(A:A)*(1=1))

如果您仍想为用户提供弹出框,您的VBA现在将是:

Sub CountErr()  
     MsgBox "There are " & ActiveSheet.Range("B1").Value & " Errors"  
End Sub

有意义吗?

答案 1 :(得分:0)

您可以简单地使用hte工作表函数来计算错误数:

LReturnValue = Application.Worksheetfunction.CountIf(Range("A:A"),IsError) > 0

我认为这样做会告诉你在你选择的范围内发现了多少错误。

<强> REVISED

Sub CheckRangeForErrors()

    Dim errCount As Long
    Dim rng As Range
    Dim cl As Range
    Dim col As String

    col = Application.InputBox("Enter the column letter you would like to check for errors", "Column Name?")

    If Not Len(col) = 1 Then
        MsgBox "You have entered an invalid selection", vbCritical
        Exit Sub
    End If

    Set rng = Sheets("Lookup Addition").Range(col & "1", Range(col & "1048576").End(xlUp))

    errCount = Application.Evaluate("COUNTIF("& rng.Address &",IsError)")

    If errCount = 0 Then
        MsgBox "there were no errors", vbOKOnly
    Else
        MsgBox "there were " & errCount & " errors", vbOKOnly
    End If


End Sub