简体   繁体   English

在Excel VBA中应用过滤器后计算选定单元格的范围

[英]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. 过滤后的行为21,但似乎包括所有行。 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. 工作表的本机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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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