如何跳到下一个循环的第n个元素
我想返回Excel中第n个可见元素的过滤表。 当前的方法告诉我使用SpecialCells(xlCellTypeVisible)
方法,然后遍历元素,同时用For Each... Next
循环For Each... Next
它们进行计数。
这似乎不是最佳的; 我不想知道前19个范围,只有20个。 有没有办法直接跳到循环的第20个元素?
或者也许循环通过.Areas
并且计数它们的大小; 这意味着您只需进入包含第n个元素的Area
,然后在该区域内进行子循环以精确定位元素。 这会更快吗?
当然,如果你能想到一个更好的方法来获得过滤表的第n个元素,那也不错!
我的代码来获取表格范围是:
Dim inptTbl As Range Set inptTbl = ThisWorkbook.Sheets("compiled").ListObjects("Table2").ListColumns("Company").Range.SpecialCells(xlCellTypeVisible)
然后循环,以及我还没有写,但我猜:
i=0 Dim r As Range For Each r in inptTbl i=i+1 If i = 20 Then Exit For Next r Debug.Print r.Address
循环通过所描述的区域:
Set inptTbl = ThisWorkbook.Sheets("compiled").ListObjects("Table2") Set test = inptTbl.ListColumns("Company").Range.SpecialCells(xlCellTypeVisible) runningTot = 0 arIndex = 1 Do Until test.Areas(arIndex).Cells.Count + runningTot > 20 runningTot = runningTot + test.Areas(arIndex).Cells.Count arIndex = arIndex + 1 Loop i = 0 Dim r As Range For Each r In test.Areas(arIndex) If i = 20 - runningTot Then Exit For i = i + 1 Next r Debug.Print r.Address
最终更新
正如你所提到的,你正在寻找最有效的方法,我会循环而不是单个单元格的区域 。
Sub test2() Dim a As Range, rng As Range Dim n As Long, total As Long, adj As Long n = 20 Set rng = ThisWorkbook.Worksheets("Sheet1").Range("A1:A1000").SpecialCells(xlCellTypeVisible) For Each a In rng.Areas adj = n - total total = total + a.Cells.Count If total >= n Then Debug.Print a.Cells(adj, 1).Address Exit Sub End If Next a End Sub
更新#2
为了保持这个答案相对干净,我删除了我以前的努力。
最后,仍然使用xlCellTypeVisible
,这应该在任何情况下工作。 它调整你的范围的大小,直到有20个可见单元格,然后返回该范围内的最后一个单元格。
Sub test() Dim rng As Range, r As Range Dim n As Long n = 20 'update for your required value of n With ThisWorkbook.Worksheets("Sheet1") 'relevant sheet name Set r = .Range("A1") 'where to start? Set rng = r.Resize(n, 1) End With While rng.SpecialCells(xlCellTypeVisible).Count < n Set rng = rng.Resize(rng.Rows.Count + 1, 1) Wend Debug.Print rng.Cells(rng.Rows.Count + r.Row - 1, r.Column).Address End Sub
筛选的范围可能有许多不连续的区域(请参阅将Excel筛选结果导入到VBAarrays中 )。 如果你正在遍历可见单元格,那么使用区域,但是如果你想要跳到第20个可见元素,只需要遍历For Next循环,直到遇到想要检索的范围。
Dim r As Long, v As Long v = 20 With Selection For r = 1 To .Rows.Count v = v + (Not .Cells(r).EntireRow.Hidden) If v = 0 Then Exit For Next r Debug.Print .Cells(r).Value End With
我在这里使用Selection
权宜之计算; 您可以从表中检索实际的单元格区域。
需要理想地看到你的完整的代码,而不是使用For Each....Next
,你可以计数可见的单元格,并做类似的事情
Sub test() Dim vcells as Long vcells = Activesheet.Usedrange.SpecialCells(xlCellTypeVisible).Rows.Count For i = 20 to vcells `your code here Next i End Sub