Search code examples
excelvbacountrow

Row.Count counts invisible cells even when using xlCelltypevisible


I am trying to filter a table that at times can result in no data. I am trying to count the rows visible to make this determination.

If only a Header row - "No Cells" If has visible rows - "Has Provider"

In the code below it seems to count the filtered rows still...

Sub Add_New_Name()

    Dim pTable1 As Range
    Dim pVisible As Range

    'Application.DisplayAlerts = False
    'Application.ScreenUpdating = False
            
    ' Select Roster & Clear Roster Table Filters
    Sheet8.Activate
    Sheet8.ListObjects("Table1").AutoFilter.ShowAllData
                    
    ' Set Variables
    Set pTable1 = Range("B2").CurrentRegion
    Set pVisible = pTable1.SpecialCells(xlCellTypeVisible)
                    
    ' Check for New Associate
    With Sheet8.ListObjects("Table1")
        .Range.AutoFilter Field:=23, Criteria1:="0"
        .Range.AutoFilter Field:=22, Criteria1:="Associate"
    End With
                    
    If pVisible.Rows.Count > 1 Then
        MsgBox "No Cells"
    Else
        MsgBox "Has Provider"
    End If
                    
End Sub

Solution

  • Set pVisible after the autofilter.

    With Sheet8.ListObjects("Table1")
        .Range.AutoFilter Field:=23, Criteria1:="0"
        Range.AutoFilter Field:=22, Criteria1:="Associate"
    End With
    
    Set pVisible = pTable1.SpecialCells(xlCellTypeVisible)
    

    Alternative Solution

    Dim pTable As ListObject      'use instead of range
    Dim pVisible As Range
    
    Set pTable = Sheet8.ListObjects("Table1")
    
    With pTable              
        .Range.AutoFilter Field:=23, Criteria1:="0"
        .Range.AutoFilter Field:=22, Criteria1:="Associate"                    
    End With
    
    On Error Resume Next
        Set pVisible = pTable.DataBodyRange.SpecialCells(xlCellTypeVisible)
    On Error GoTo 0
    'Stores range of visible cells. Does not raise error in case of not data.
    
    If Not pVisible Is Nothing Then    'Checks if some info is present.
        MsgBox "Has Provider"
    Else
        MsgBox "No Provider"
    End If