下面的代码仅显示可见行的计数,但是,在运行代码之前对行进行过滤时,它不会检测隐藏的行。
Total_rows_Pick = Workbooks("Job Production Monitoring.xlsm").Worksheets("Pick-ups").Range("B" & Rows.count).End(xlUp).Row
我该怎样做才能获得包含检测隐藏/过滤掉的文字的等效代码?
运行上面的代码行后,locals窗口只计算标题,但不计算第2行。
答案 0 :(得分:1)
循环使用范围内的数据字段数组
实体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