从过滤的范围获取最后一行

当您的工作表中的数据被过滤时,如何查找最后一行数据? 我一直玩Special CellsVisible Cells但无法find解决scheme。 我认为这一定是我下面的一些变化:

  ... With ws LR = .Range("A" & Rows.Count).End(xlUp).Row .Range("A1:E" & LR).AutoFilter Field:=2, Criteria1:="=4" LRfilt = .Range("A" & Rows.SpecialCells(xlCellTypeVisible).Count).End(xlUp).Row Debug.Print LR Debug.Print LRfilt End With ... 

文件可以在这里find:

wikisend.com/download/443370/FindLRFilteredData.xls

编辑:

与Siddharth讨论后意识到,我不希望Last Row属性,我需要find导致Sid的解决scheme下面的可见行数…

编辑:邮政聊天后续

 Option Explicit Sub FilterTest() Dim rRange As Range, fltrdRng As Range, aCell As Range, rngToCopy As Range Dim ws As Worksheet Dim LR As Long '~~> Change this to the relevant sheet For Each ws In ThisWorkbook.Worksheets If Not ws.Name = "Sheet1" Then With ws '~~> Remove any filters .AutoFilterMode = False LR = .Range("A" & Rows.Count).End(xlUp).Row '~~> Change this to the relevant range Set rRange = .Range("A1:E" & LR) With rRange '~~> Some Filter. Change as applicable .AutoFilter Field:=2, Criteria1:=">10" '~~> Get the filtered range Set fltrdRng = .SpecialCells(xlCellTypeVisible) End With For Each aCell In fltrdRng If aCell.Column = 1 Then If rngToCopy Is Nothing Then Set rngToCopy = aCell Else Set rngToCopy = Union(rngToCopy, aCell) End If End If Next Debug.Print ws.Name Debug.Print rngToCopy.Address 'rngToCopy.Copy Set rngToCopy = Nothing '~~> Remove any filters .AutoFilterMode = False End With End If Next End Sub 

filter后,使用相同的公式为lastrow将返回最后过滤行:

 ... With ws LR = .Range("A" & Rows.Count).End(xlUp).Row .Range("A1:E" & LR).AutoFilter Field:=2, Criteria1:="=4" LRfilt = .Range("A" & Rows.Count).End(xlUp).Row Debug.Print LR Debug.Print LRfilt End With ... 

这似乎工作。 当filter处于正常状态时.end(xlUp)给出过滤范围的最后一行,但不是表单的最后一行。 我build议你使用这个技巧来得到最后一行:

 Sub GetLastRow ' Find last row regardless of filter If Not (ActiveSheet.AutoFilterMode) Then ' see if filtering is on if already on don't turn it on Rows(1).Select ' Select top row to filter on Selection.AutoFilter ' Turn on filtering End if b = Split(ActiveSheet.AutoFilter.Range.Address, "$") ' Split the Address range into an array based on "$" as a delimiter. The address would yeild something like $A$1:$H$100 LastRow= Val(b(4)) ' The last value of the array will be "100" so find the value End sub 

这是最简单的解决scheme

 ... With ws .Range("A1:E1").AutoFilter Field:=2, Criteria1:="=4" LRfilt=.Range("A1", .Range("A1").End(xlDown)).End(xlDown).Row Debug.Print LRfilt End With ...