繁体   English   中英

如何使用excel VBA计算隐藏/过滤出的行中包含内容的行?

[英]How to count hidden/filtered out rows that has content in them using excel VBA?

下面的代码仅显示可见行的计数,但是,在运行代码之前对行进行过滤时,它不会检测到隐藏的行。

Total_rows_Pick = Workbooks("Job Production Monitoring.xlsm").Worksheets("Pick-ups").Range("B" & Rows.count).End(xlUp).Row

我应该怎么做才能得到等效的代码,包括检测甚至隐藏/过滤掉的行中写有文本的代码?

我过滤后的工作表的示例是(注意第2行被过滤掉): 筛选的工作表

运行上面的代码行后,locals窗口仅计算标题,而不计算第2行。

变量的屏幕截图,如本地窗口所示: 仅标头

在使用范围内循环遍历数据字段数组

牢固的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM