简体   繁体   中英

How do I access just the filtered rows in a range from VBA?

I want to be able to use the results of an AutoFilter method within VBA. I can apply the AutoFilter method (using a named range), but can't figure out how to create a Range variable in VBA that only includes the results. I then want to loop through this result range. I can't figure out how to do this without simply checking every row for its Visible property and acting on those rows.

Public Sub CopyFilteredRows()
   Dim sourceRg As Range, filteredRg As Range, objRow As Range

   Set sourceRg = ThisWorkbook.Names("FY10CountsRg").RefersToRange
   sourceRg.AutoFilter Field:=1, Criteria1:="=D-144", Operator:=xlOr, _
     Criteria2:="=D-200"

   For Each objRow In filteredRg.Rows
      ''do something
   Next

End Sub

Try this - it should just hit the visible cells & print their values - you should be able to tweak it do the job:

Dim rgAreas As Range: Set rgAreas = FilteredRg.SpecialCells(xlCellTypeVisible)
Dim rgArea  As Range
Dim rgCell  As Range

For Each rgArea In rgAreas.Areas
    For Each rgCell In rgArea.Cells
        Debug.Print rgCell.Address & ": " & rgCell.Value
    Next rgCell
Next rgArea

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