如何跳到下一个循环的第n个元素

时间:2017-03-14 15:25:24

标签: excel vba excel-vba

我正在尝试在Excel中返回过滤表的第n个可见元素。 Current methods告诉我使用SpecialCells(xlCellTypeVisible)方法,然后循环遍历元素,同时使用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

3 个答案:

答案 0 :(得分:2)

最终更新

正如您所说,您正在寻找最有效的方法,我会遍历区域而不是单个单元格。

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

答案 1 :(得分:2)

过滤范围可能有许多不连续的区域(请参阅Get Excel filter results into VBA array)。如果你循环遍历可见单元格,那么使用区域但是如果你想要跳转到第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是为了权宜之计;您可以从表中检索实际的单元格范围。

答案 2 :(得分:1)

需要理想地查看完整代码,但不是使用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
相关问题