过滤行VBA的计数不正确

时间:2016-08-03 12:12:40

标签: excel vba excel-vba

我有一个Excel ws"每月数据"。我正在尝试应用自动过滤器(xlFilterLastMonth)并计算过滤行数。

With Sheets("Monthly Data")                     
    .Range("A1:BB" & lastrow1).AutoFilter Field:=21, Criteria1:=xlFilterLastMonth, Operator:=xlFilterDynamic

MsgBox ws2.UsedRange.SpecialCells(xlCellTypeVisible).Rows.Count

End With

3 个答案:

答案 0 :(得分:1)

试试这个:

With Sheets("Monthly Data")
    .Range("A1:BB" & lastrow1).AutoFilter Field:=21, Criteria1:=xlFilterLastMonth, Operator:=xlFilterDynamic

    Set r = Intersect(ActiveSheet.AutoFilter.Range, Range("A:A"))
    Filtred_Rows_Count = Application.WorksheetFunction.Subtotal(103, r) - 1

    MsgBox Filtred_Rows_Count
End With

答案 1 :(得分:0)

假设每列都有标题,那么试试这个

Dim Data1 As Range, Data2 As Range


Set Data1 = Sheets("Monthly Data").Range("A1:BB" & LastRow1)

Data1.AutoFilter Field:=21, Criteria1:=xlFilterLastMonth, Operator:=xlFilterDynamic

Set Data2 = Range(Cells(2, 21), Cells(LastRow1, 21)).SpecialCells(xlCellTypeVisible)

For Each cell In Data2
    i = i + 1
Next

Worksheets("Monthly Data").AutoFilterMode = False
MsgBox "The number of filtered rows is " & i

答案 2 :(得分:0)

基于J.B.s回答:

With Sheets("Monthly Data")
    .Range("A1:BB" & lastrow1).AutoFilter Field:=21, Criteria1:=xlFilterLastMonth, Operator:=xlFilterDynamic

    Set r = Intersect(.AutoFilter.Range, .Range("A:A"))
    Filtred_Rows_Count = Application.WorksheetFunction.Subtotal(103, r) - 1

    MsgBox Filtred_Rows_Count
End With