找不到对象时如何进行?

时间:2019-05-06 10:31:08

标签: excel vba

我正在搜索表中的空白单元格。如果没有空白单元格,则希望有一个味精或运行命令。我尝试了以下版本,但没有一个起作用

Sub Macro1() 
    ActiveSheet.ListObjects("Tabel1").DataBodyRange.Select
    Selection.SpecialCells(xlCellTypeBlanks).Select
    On Error GoTo Line1
Line1:
    MsgBox "no blank cell is found"
End Sub

还有这个

Sub Macro1()
    ActiveSheet.ListObjects("Tabel1").DataBodyRange.Select
    Selection.SpecialCells(xlCellTypeBlanks).Select
    If Selection = "" Then
        MsgBox "no blank cell is found"
    End If
End Sub

2 个答案:

答案 0 :(得分:0)

不需要选择和选择,您可以尝试:

Sub try()

On Error GoTo noblanks
  MsgBox ActiveSheet.ListObjects("Tabel1").DataBodyRange.SpecialCells(xlCellTypeBlanks).Count & " blank cells are found"
  Exit Sub
noblanks:
MsgBox "no blank cell is found"

End Sub

答案 1 :(得分:0)

我建议抓住错误并检查BlankCells是否为Nothing

Sub Macro1() 
    Dim BlankCells As Range
    On Error Resume Next 'supress all error messages until …Goto 0
    Set BlankCells = ActiveSheet.ListObjects("Tabel1").DataBodyRange.SpecialCells(xlCellTypeBlanks)
    On Error GoTo 0 'never forget to re-activate error reporting immedeately!

    If BlankCells Is Nothing Then
        MsgBox "no blank cell is found"
    Else
        MsgBox BlankCells.Cells.Count & " blank cell(s) found"
    End If
End Sub

您可能会从阅读中受益……