如何仅访问 VBA 范围内的过滤行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5406734/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 12:53:13  来源:igfitidea点击:

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

excel-vbavbaexcel

提问by Stevil

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.

我希望能够在 VBA 中使用 AutoFilter 方法的结果。我可以应用 AutoFilter 方法(使用命名范围),但无法弄清楚如何在 VBA 中创建一个只包含结果的 Range 变量。然后我想遍历这个结果范围。如果不简单地检查每一行的 Visible 属性并对这些行进行操作,我就无法弄清楚如何做到这一点。

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

回答by tpascale

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