简体   繁体   中英

count the selected range of cells after applying filter in excel vba

Thank you for reviewing my situation :) My attempts for just counting the selected rows in a particular column after applying a filter are pretty messed up. After applying filter, I am counting the selected rows for a column & it reports all rows. The filtered rows are 21 but it seems to be including all rows. I just want the selected rows count after filter.

Sub Report()

    Dim sh As Worksheet
    Dim k As Long

    Set sh = ThisWorkbook.Sheets("Testing")

    sh.Range("F21").Activate

    ActiveSheet.Range("F" & Rows.Count).End(xlUp).AutoFilter Field:=6, Criteria1:="Fatal"

    ActiveSheet.Range("f21", ActiveSheet.Range("f21").End(xlDown)).Select

    MsgBox ActiveSheet.UsedRange.SpecialCells(xlCellTypeVisible).Rows.Count
    'FatCnt = Range("F21").Rows.SpecialCells(xlCellTypeVisible).Count
    'FatCnt = Selection.Count

    'MsgBox FatCnt    

    Selection.AutoFilter

End Sub

use the formula in cells to get the 'Fatal' count

=COUNTIF(F:F,"Fatal")

or

Sub Report()
    With ThisWorkbook.Worksheets("Testing")
        fatalcount = WorksheetFunction.CountIf(Range("F:F"), "Fatal")
    End With
End Sub

The worksheet's native SUBTOTAL function does a nice job of counting filtered cells.

Sub Report()
    Dim k As Long

    With ThisWorkbook.Worksheets("Testing")
        If .AutoFilterMode Then .AutoFilterMode = False
        With .Range(.Cells(21, "F"), .Cells(Rows.Count, "F").End(xlUp))
            .AutoFilter Field:=1, Criteria1:="Fatal"
            k = Application.Subtotal(103, .Cells) - 1 'minus 1 for the header
            Debug.Print k
        End With
        If .AutoFilterMode Then .AutoFilterMode = False
    End With

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM