Count selected rows after auto filter
当我的数据是未过滤的原始数据时,我可以选择它们,并且
自动筛选后,它会返回一个数字,就像我选择了不可见的行一样,即使
如何获取所选行的有效计数?
我尝试了
编辑
我在另一个宏中使用过滤器,然后手动选择要添加到另一个工作表中的行。
我做了两个按钮,一个按钮过滤我的表,第二个按钮将选定的行移动到另一张纸上。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | Sub ajout_commande() Set DataSheet = ThisWorkbook.Worksheets("Prepa Commandes") Dim a As Range, b As Range Set a = Selection i = 0 s = Selection.SpecialCells(xlCellTypeVisible).Count For Each b In a.Rows i = i + 1 DataSheet.Cells(6, 1).EntireRow.Insert DataSheet.Range("A1:Z1").Copy DataSheet.Cells(6, 1).EntireRow Next Dim r1 As Range, r2 As Range, r3 As Range Let copyrange1 ="E1" &":" &"I" & i Let copyrange2 ="BK1" &":" &"BM" & i Set r1 = a.Range(copyrange1) Set r2 = a.Range(copyrange2) Set r3 = Union(r1, r2) r3.Copy DataSheet.Cells(6, 1).PasteSpecial xlPasteValues MsgBox s &" and" & i End Sub |
这里我的表已被过滤,我想将选择的行添加到另一张表中,但是Selection.Rows.Count返回的行数比我选择的还要多,因为即使
在此示例中Selection.Rows.Count = 28,因为第10和20、21和25等行之间的行不可见。
是否有获取我想要的电话号码的功能(在此图像16上)?
我知道这是该问题的最新发布,但也许这会在将来对某人有所帮助。我发现以下代码片段非常适合在过滤后计算范围内的可见行数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | Sub CountVisibleRows() 'only count the visible rows in the range Dim lRow As Long, vis_lr As Long, DstWs As Worksheet Set DstWs = ActiveSheet lRow = DstWs.UsedRange.Rows.Count 'vis_lr = DstWs.Range("B2:B" & lRow).SpecialCells(xlCellTypeVisible).Count 'doesn't seem to work with non-contiguous rows With DstWs vis_lr = Application.WorksheetFunction.Subtotal(3, Range("B2:B" & lRow)) End With Debug.Print vis_lr End Sub |
这取决于您的使用方式。这对我来说很好用
1 2 3 4 5 6 7 8 9 10 11 | '~~> Remove any filters ActiveSheet.AutoFilterMode = False '~~> Specifying the complete address is the key part With Range("A1:C6") '<~~ Filter, offset(to exclude headers) .AutoFilter Field:=YOURFIELDNUMBER, Criteria1:=YOURCRITERIA Debug.Print .Offset(1, 0).SpecialCells(xlCellTypeVisible).Rows.Count End With '~~> Remove any filters ActiveSheet.AutoFilterMode = False |
测试
1 2 3 4 5 6 7 8 9 10 11 12 | Sub Sample() '~~> Remove any filters ActiveSheet.AutoFilterMode = False With Range("A1:C6") '<~~ Filter, offset(to exclude headers) .AutoFilter Field:=1, Criteria1:="Sid" MsgBox .Offset(1, 0).SpecialCells(xlCellTypeVisible).Rows.Count End With '~~> Remove any filters ActiveSheet.AutoFilterMode = False End Sub |
好吧,如果您的选择是连续的,则以下内容将起作用:
1 | Selection.Columns(1).SpecialCells(xlCellTypeVisible).Count |
但是,从屏幕快照中我可以看到您的选择可能是不连续的范围(也就是选择了多个区域),因此您可以使用我创建的此功能作为起点:
1 2 3 4 5 6 7 8 | Function countVisibleSelectedRows() Dim count As Integer count = 0 For Each Area In Selection.Areas count = count + Area.Columns(1).SpecialCells(xlCellTypeVisible).count Next countVisibleSelectedRows = count End Function |
当您选择了多个范围时,Excel会将这些范围中的每一个称为"区域"。在此函数中,我们遍历Selection.Areas集合中的每个"区域"。