问题
I'm filtering a table in Excel but I only want the first line that appears.
回答1:
Use Range.SpecialCells method with the xlCellTypeVisible parameter on the filtered range. .Rows(1).Cells
should be what you want.
Sub first_row()
Dim rFirstFilteredRow As Range
With Worksheets("Sheet1")
With .Cells(1, 1).CurrentRegion
'do all the .autofilter stuff here
With .Resize(.Rows.Count - 1, .Columns.Count).Offset(1, 0)
If CBool(Application.Subtotal(103, .Cells)) Then
Set rFirstFilteredRow = _
.SpecialCells(xlCellTypeVisible).Rows(1).Cells
'~~> rFirstFilteredRow is not a copy of the first visible row
'do something with rFirstFilteredRow
End If
End With
End With
End With
End Sub
You will have to transcribe this to suit your own implementation of the AutoFilter Method.
The native worksheet SUBTOTAL function was used as it only counts visible cells. This is an easy non-destructive way of determining whether there are any cells to reference after the filter has been applied.
回答2:
Worksheets("Raw").AutoFilter.Range.Offset(1).SpecialCells(xlCellTypeVisible).Cells(Row, Column)
回答3:
I tried this and it worked beautifully for me. First piece of code that did. Thank you!
frow_main = Worksheets(main_sheet_name).AutoFilter.Range.Offset(1).SpecialCells(xlCellTypeVisible).Cells().Row
I was trying to find the first row after an autofilter, but other offset codes kept giving me row 1.
I needed row 27, but it wasn't guaranteed that it would be row 27 each time.
Your inspiration worked!
'Reset LastRow
LastRow = Range("A" & Rows.Count).End(xlUp).Row
'Remove the "Bear" invoice method
ActiveSheet.Range("$A$1:$E$" & LastRow).AutoFilter Field:=5, Criteria1:="=BEAR", Operator:=xlOr, Criteria2:="=#REF!"
FirstRow = Worksheets("testOriginalData").AutoFilter.Range.Offset(1).SpecialCells(xlCellTypeVisible).Cells().Row
Rows(FirstRow).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.SpecialCells(xlCellTypeVisible).Select
Selection.Delete Shift:=xlUp
ActiveSheet.ShowAllData
Range("A2").Select
来源:https://stackoverflow.com/questions/32864789/how-to-select-the-first-visible-row-after-applying-a-filter