计算自动筛选后可见行的数量

在自动过滤之后,如何计算可见/非空行数(从第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 

下面是一个函数,它将计算自动筛选范围中的可见行,即使没有:

 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 

要将其作为函数调用,请参阅上面的编辑。 使用你的例子,你可以把它称为这样(未经testing):

 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 

请注意,你应该避免使用Select

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

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

假设我们有一个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