简体   繁体   中英

Get row number of autofiletred lines in Excel with VBA

I want to get the row number of autofiltered lines.

I used this code

With xlsWkSheet      
    With .Range("A1").CurrentRegion
        .AutoFilter Field:=4, Criteria1:="88684240"
        .AutoFilter Field:=19, Criteria1:="88684239"            
        Set xlsRangeAutoFilter = .SpecialCells(xlCellTypeVisible)
    End With
End With

But I have no idea how to use xlsRangeAutoFilter to get row number of autofiltered (Visible) lines

Thanks a lot for your help

You can use the WorksheetFunction.Subtotal method to count the rows that are visible and have data in it (note visible blanks will not be counted):

NumberOfRows = Application.WorksheetFunction.Subtotal(3, xlsWkSheet.Range("A1:A" & xlsWkSheet.Range("A1").CurrentRegion.Rows.Count))

or alternatively a more reliable method:

xlsWkSheet.AutoFilter.Range.Columns(1).SpecialCells(xlCellTypeVisible).Cells.Count - 1

Edit according to comment:

To output all filtered row numbers you must loop through the areas.

    With .Range("A1").CurrentRegion
        Dim Area As Range
        For Each Area In .Columns(1).SpecialCells(xlCellTypeVisible).Cells.Rows.Areas
            Dim AreaRow As Range
            For Each AreaRow In Area.Rows

                Debug.Print AreaRow.Row 'output each row number in intermediate window

            Next AreaRow
        Next Area
    End With

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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