访问非连续可见单元的索引
我有一个数据表,根据用户的自动筛选器select过滤一列“产品”。 我也将“Product”定义为一个dynamic命名的范围,在这个例子中我们定义为A2:A30。 之后,我想进一步操纵可见的细胞。 我的debugging代码片段:
Dim xName As Range Set xName = ThisWorkbook.Names("Product").RefersToRange.SpecialCells(xlCellTypeVisible) Debug.Print xName.Count Debug.Print xName(3)
xName.Count将始终返回正确数量的可见单元格,但访问xName的索引certificate在处理非连续的隐藏单元格时会遇到麻烦。 例如,如果A2:A5和A8:A11是隐藏的单元格,则xName(1)将返回A6的值,但是xName(3)将返回A8的值而不是A12的值。 这使我几乎不可能循环通过可见的单元格。
有没有索引操作,我可以做只能使用可见的单元格? 任何帮助,将不胜感激!
对于非连续的范围,您可以使用For Each
循环。
例如
Sub Tester() Dim rng As Range, rw As Range 'create a non-contiguous test range Set rng = Range("A3:D4,A7:D7,A10:D16") 'loop over each row in the range For Each rw In rng.Rows Debug.Print rw.Address() Next rw End Sub
我的build议:
Sub test() Dim xName As Range Set xName = ThisWorkbook.Names("Product").RefersToRange.SpecialCells(xlCellTypeVisible) Debug.Print xName.Count Debug.Print VisibleCell(xName, 3) End Sub Function VisibleCell(rng As Range, index As Long) As Range Dim i As Long Dim r As Long i = 0 r = 1 Do Do While rng(r).EntireRow.RowHeight = 0 Or rng(r).EntireColumn.ColumnWidth = 0 r = r + 1 Loop i = i + 1 If i = index Then Set VisibleCell = rng(r) Exit Do End If r = r + 1 Loop End Function
也许这是你想要做的:迭代范围的区域,因为它已经被分割成许多区域,由于隐藏的范围。
Set xName =ThisWorkbook.Names("Product").RefersToRange.SpecialCells(xlCellTypeVisible) For i = 1 to xName.Areas.Count For j = 1 to XName.Areas(i).Count Debug.Print i, j, XName.Areas(i).Cells(j) Next Next