Excel VBA修整过滤范围的最后一行

时间:2016-07-08 13:46:38

标签: excel vba excel-vba

我试图在工作表上找到过滤范围的行数。 LstRow2是我想要找到的变量。使用此代码,我得到未经过滤的行数。

   CSht.Range(CSht.Cells(1, 1), CSht.Cells(LstRow1, LstCol1)).AutoFilter Field:=2, Criteria1:="RA"
        With CSht
        LstRow2 = .UsedRange.SpecialCells(xlCellTypeLastCell).Row
        End With

Here is the data that I am filtering

5 个答案:

答案 0 :(得分:1)

您只需要处理可见单元格,因为它已被过滤。

试试这个:

 With CSht

     'load filter cells into Range object
     Dim rngFilter as Range
     Set rngFilter = Intersect(.UsedRange,.UsedRange.Offset(1)).SpecialCells(xlCellTypeVisible)

     'find the max number of elements split by $ in the range address
       'needs to be dynamic because of areas
     Dim lUpper as Long
     lUpper = UBound(Split(rngFilter.Address,"$"))

     'the last element will be the last row in the filtered range
       'the last number in the rngFilter.Address
     Dim LstRow2 as Long
     LstRow2 = Split(rngFilter.Address,"$")(lUpper)

End With

答案 1 :(得分:0)

为什么不替换此行

LstRow2 = .UsedRange.SpecialCells(xlCellTypeLastCell).Row

使用

LstRow2 = .Cells(.rows.count, 1).end(xlup).row

答案 2 :(得分:0)

过滤后可能会有多个区域,因此您需要使用Areashttps://stackoverflow.com/a/17287558/3733214的详细解释。这应该起作用:

Dim Line as Range
For Each Line In CSht.UsedRange.SpecialCells(xlCellTypeVisible).Areas
  LstRow2 = LstRow2 + Line.Rows.Count
Next

积分:https://www.mrexcel.com/board/threads/vba-code-to-count-visible-rows-after-autofiltering-a-table.602866/post-2988416

答案 3 :(得分:0)

此公式lastRow = Worksheets("Sheet1").Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row为我提供了已过滤范围的正确的最后一个可见行。

答案 4 :(得分:-1)

当前区域将在一行中为您完成

!((X) == (Y))