在excel vba中应用过滤器后计算所选的单元格范围

时间:2023-02-09 16:23:34

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.

感谢您查看我的情况:)我在应用过滤器后只计算特定列中所选行的尝试非常混乱。应用过滤器后,我计算列的选定行并报告所有行。过滤的行是21但似乎包括所有行。我只想在过滤后计算选定的行数。

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

2 个解决方案

#1


2  

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

工作表的本机SUBTOTAL函数可以很好地计算过滤后的单元格。

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

#2


3  

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

#1


2  

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

工作表的本机SUBTOTAL函数可以很好地计算过滤后的单元格。

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

#2


3  

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