用VBA循环过滤列表最简单的方法是什么?
如果我在Excel中设置了一个自动filter,并且我想用VBA代码遍历一列中的所有可见数据,那么最简单的方法是什么?
所有已被过滤掉的隐藏行都不应该包含在内,所以从上到下的简单范围不会有帮助。
任何好主意? 谢谢。
假设在单元格A2:A11
有数字1到10 A2:A11
在A1
使用我的自动filter。 我现在过滤只显示数字大于5(即6,7,8,9,10)。
这段代码只会打印可见的单元格:
Sub SpecialLoop() Dim cl As Range, rng As Range Set rng = Range("A2:A11") For Each cl In rng If cl.EntireRow.Hidden = False Then //Use Hidden property to check if filtered or not Debug.Print cl End If Next End Sub
也许有一个与SpecialCells
更好的方法,但上述工作在Excel 2003中为我。
编辑
只要find一个更好的方式与SpecialCells
:
Sub SpecialLoop() Dim cl As Range, rng As Range Set rng = Range("A2:A11") For Each cl In rng.SpecialCells(xlCellTypeVisible) Debug.Print cl Next cl End Sub
我会build议使用Offset
假设头在第1行。看到这个例子
Option Explicit Sub Sample() Dim rRange As Range, filRange As Range, Rng as Range 'Remove any filters ActiveSheet.AutoFilterMode = False '~~> Set your range Set rRange = Sheets("Sheet1").Range("A1:E10") With rRange '~~> Set your criteria and filter .AutoFilter Field:=1, Criteria1:="=1" '~~> Filter, offset(to exclude headers) Set filRange = .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow Debug.Print filRange.Address For Each Rng In filRange '~~> Your Code Next End With 'Remove any filters ActiveSheet.AutoFilterMode = False End Sub
一种方法假设A1中的过滤数据向下;
dim Rng as Range set Rng = Range("A2", Range("A2").End(xlDown)).Cells.SpecialCells(xlCellTypeVisible) ... for each cell in Rng ...
Call MyMacro() ActiveCell.Offset(1, 0).Activate Do Until Selection.EntireRow.Hidden = False If Selection.EntireRow.Hidden = True Then ActiveCell.Offset(1, 0).Activate End If Loop