[英]How to count hidden/filtered out rows that has content in them using excel VBA?
在使用范围内循环遍历数据字段数组
牢固的End(xlUp)
方法对隐藏行失败,因为在可见范围内没有可移动的内容。 因此,我只是尝试遍历从B列的最后一行开始的使用范围,并检查值。
提示:最好使用变体数据字段数组 (在示例代码中称为v
),因为通过VBA循环范围很慢。
范例程式码
Sub FindLastRow()
Dim i As Long, Total_rows_Pick As Long
Dim ws As Worksheet, v As Variant
Set ws = ThisWorkbook.Worksheets("Pick-ups")
v = ws.Range("B1:B" & ws.UsedRange.Rows.Count) ' write data into 1-based 2-dim datafield array
For i = UBound(v) To 2 Step -1 ' start search in last row of used range
If Len(v(i, 1) & "") <> 0 Then ' take first value
Exit For
End If
Next i
total_rows_pic = i ' last row with value
MsgBox Total_rows_Pick
End Sub
通过临时工作表的替代解决方案
乔恩·克洛威尔(Jon Crowell)通过将原始数据表复制到临时表中,展示了一种替代解决方案。 取消隐藏那里的所有行允许使用原始方法找到最后一行:
Sub FindLastRow2()
' Modified source: https://stackoverflow.com/questions/14200392/finding-the-last-row-of-an-excel-spreadsheet-when-the-last-row-is-hidden
' Thx: Jon Crowell
Dim Total_rows_Pick As Long, ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Pick-ups")
' copy original data to temporary sheet and unhide all rows
ws.Copy Before:=ws
With ActiveSheet ' << temporary sheet only
' [1]turn off autofiltering
If .AutoFilterMode Then .AutoFilterMode = False
' [2] unhide all rows
.Columns("B:B").EntireRow.Hidden = False
' [3] get the last row there
Total_rows_Pick = .Range("B" & .Rows.Count).End(xlUp).Row
' [4] delete the temporary sheet
Application.DisplayAlerts = False
.Delete
Application.DisplayAlerts = True
End With
MsgBox Total_rows_Pick
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.