计算自动过滤后的可见行数

时间:2014-05-10 13:59:32

标签: excel vba

在自动过滤器之后,如何计算可见/非空行的数量(从第3行开始,检查列A是否为空)?现在我只得到26 ......

完整代码:

Sub GetPrimaryContacts()

Dim Col As New Collection
Dim itm
Dim i As Long
Dim CellVell As Variant

'Get last row value
LastRow = Cells.SpecialCells(xlCellTypeLastCell).Row

'Loop between all rows to get unique values
For i = 3 To LastRow
    CellVal = Sheets("Master").Range("F" & i).Value
    On Error Resume Next
    Col.Add CellVal, Chr(34) & CellVal & Chr(34)
    On Error GoTo 0
Next i

' Create workbooks - Token Not activated
Call TokenNotActivated
For Each itm In Col
    ActiveSheet.Range("A2:Z2").Select
    Selection.AutoFilter Field:=6, Criteria1:=itm
    Call CountFilterAreaRows
Next

End Sub

3 个答案:

答案 0 :(得分:2)

这是一个计算自动过滤范围内可见行的函数,即使没有:

Function CountFilterAreaRows(ws As Excel.Worksheet) As Long
Dim FilterArea As Excel.Range
Dim RowsCount As Long

Set ws = ActiveSheet
For Each FilterArea In ws.AutoFilter.Range.SpecialCells(xlCellTypeVisible)
    RowsCount = RowsCount + FilterArea.Rows.Count
Next FilterArea
'don't count the header
RowsCount = RowsCount - 1
CountFilterAreaRows = RowsCount
End Function

要将其作为一项功能调用,请参阅上面的编辑。使用你的例子,你可以这样称呼它(未经测试):

Sub UseIt()
Dim ws As Excel.Worksheet
Dim itm
Dim col As Collection

'... your col logic

For Each itm In col
Set ws = ActiveSheet
    ActiveSheet.Range("A2:Z2").AutoFilter Field:=6, Criteria1:=itm
    Debug.Print CountFilterAreaRows(ws)
Next itm
End Sub

请注意,您应该avoid the use of Select

答案 1 :(得分:1)

我可能错了,因为我猜测你的代码实际上在做什么,但看看这是否能得到你想做的事。

For Each itm In Col
    RowCount = Sheets("Master").Rows(itm.Row).Count
    MsgBox RowCount 
Next

答案 2 :(得分:1)

假设我们有一个AutoFilter,第一行包含标题,并且在过滤表下面没有任何内容:

Sub visiCount()
    Dim r As Range, n as Long
    n = Cells(Rows.Count, 1).End(xlUp).Row
    Set r = Range("A1:A" & n).Cells.SpecialCells(xlCellTypeVisible)
    MsgBox r.Count - 1
End Sub

编辑 ............从 A1 开始,而不是 A2