过滤后如何选择范围?

在过滤后,我试图选择一个范围,其中包含前16个可见行。

不应用过滤器就可以。

Range("A1").AutoFilter
    activeSheet.ListObjects("Empty_Locations").Range.AutoFilter Field:=3,Criteria1:=BrandSelection
    activeSheet.ListObjects("Empty_Locations").Range.AutoFilter Field:=4,Criteria1:="<>Printed",Criteria2:="<>Occupied"

        With activeSheet.Range("A1")
        With .Offset(1,0).Resize(Rows.Count - .Row,1)
            .SpecialCells(xlCellTypeVisible).Cells(1,1).Select
        End With
        End With

Dim SelectedCell16 As Range
Set SelectedCell16 = Selection.Offset(15,3).SpecialCells(xlCellTypeVisible)

activeSheet.Range(Selection,SelectedCell16).Select

我知道以某种方式涉及SpecialCells(xlCellTypeVisible)方法,但我无法克服。选择是完全错误的。

我们将不胜感激。

susewxy 回答:过滤后如何选择范围?

不幸的是,在这种情况下,无法使用.Offset,因为它会返回所选内容下方15行的任何范围,无论该范围是可见的还是隐藏的。但是,Range.SpecialCells(xlCellTypeVisible)将具有多个.Areas,并且每个区域仅包含可见的单元格。您可以遍历.Areas,直到获得至少16行并选择它们,如下所示:

Sub test()
    Dim area As Range
    Dim CellCount As Integer
    Dim firstCell As Range
    Dim lastCell As Range

    With ActiveSheet.Range("A1").Offset(1,0).Resize(Rows.Count - ActiveSheet.Range("A1").Row,1)

        'first cell will be the the first cell of Areas(1)
        Set firstCell = .SpecialCells(xlCellTypeVisible).Areas(1).Cells(1,1)

        'Get last cell by looping through areas until their total cell count reaches 16.
        For Each area In .SpecialCells(xlCellTypeVisible).Areas
            'first area may already contain more than 16 cells,in which case we just get its 16th cell and exit.
            'If this is not the case,we add up rows.Count of each area until we get more than 16,and when that happens,'we get the cell of last area which is needed to get to 16.
            If CellCount + area.Rows.Count >= 16 Then
                Set lastCell = area.Cells(16 - CellCount,1)
                Exit For
            End If
            CellCount = CellCount + area.Rows.Count
        Next
    End With

    'finally,from the firstCell and lastCell we can get the range of first 16 visible cells.
    ActiveSheet.Range(firstCell,lastCell).Select
End Sub
本文链接:https://www.f2er.com/3057519.html

大家都在问