识别空单元格或显示#REF!给定范围内的错误

时间:2016-05-07 05:48:10

标签: excel-vba vba excel

我的代码无法正常运行。它仅显示第一个空单元格T10,但是从T10到T15的单元格都是空的。我还想识别显示#REF的单元格!在他们中。我不需要空单元格的地址(因为在更大的范围内可能有很多)但是想知道#REF的单元格地址!谢谢!

Sub Identiycells()
Dim Cancel As Boolean
Dim cell As Range
Dim sh As Worksheet
For Each sh In ThisWorkbook.Worksheets(Array("a", "b"))
For Each cell In sh.Range("T6:T18")
     If IsEmpty(cell) 'Or showing #REF! Then
         MsgBox "Data Missing or Formula error" & cell.Address
    Application.Goto cell, True
    Cancel = True
    Exit For
    End If
Next cell
Next sh
End Sub

1 个答案:

答案 0 :(得分:1)

您可以收集字符串中的错误,并且最后只报告一次。要检查#REF或其他错误,您可以使用IsError(cell.value)进行测试。

当您浏览不同的工作表时,最好指定单元格所在的工作表。您可以使用Split(cell.address(External:=True), "]")(1)获取包含其工作表的单元格引用。

建议代码:

Sub Identiycells()
    Dim Cancel As Boolean
    Dim cell As Range
    Dim sh As Worksheet
    Dim report as String ' collect all errors
    Dim errorMsg as String ' error for current cell
    Dim errorCell as Range ' cell to focus at the end

    For Each sh In ThisWorkbook.Worksheets(Array("a", "b"))
        For Each cell In sh.Range("T6:T18")
            errorMsg = ""
            If IsEmpty(cell) Then
                 errorMsg = "Data Missing"
                 If errorCell Is Nothing Then Set errorCell = cell
            ElseIf IsError(cell.value) Then
                 errorMsg = "Invalid Reference"
                 Set errorCell = cell
            End If
            If errorMsg <> "" Then 
                report = report & errorMsg & " in " & _
                    Split(cell.address(External:=True), "]")(1) & vbCrLf
            End If
        Next cell
    Next sh
    If Not errorCell Is Nothing Then
        MsgBox report
        Application.Goto errorCell, True
        Cancel = True
    End If
End Sub