不循环获取行位置

Get the Row Positions without Looping

是否可以在不执行循环的情况下在 excel 中获取大 table 中的行位置? 我想做的是点击一个特定的 ID,然后来自同一 ID 的最后 3 条记录将显示在 UI.

我是编程的初学者,除了循环方法(这是非常耗费资源和内存的方法,考虑到我们在每个循环中循环大量且不断增长的 table 100k 行,我不知道该怎么做来自用户的点击)。

例如:如果用户点击“A123”,那么我们知道他们的行位置是:5、8、10

循环筛选列表

Option Explicit
Sub Filtered()

    Dim rng as Range, ID As Range, a As Range
    Dim ar(2) As Long, i As Integer, j As Integer
    
    ' apply filter
    With Sheet1
        .AutoFilterMode = False
        .UsedRange.AutoFilter 1, "A123"
        Set rng = .UsedRange.Columns(1).SpecialCells(xlCellTypeVisible)
    End With

    ' count
    For Each a In rng.Areas
        For Each ID In a.Cells
            If ID.Row > 1 Then
                i = (i + 1) Mod 3
                ar(i) = ID.Row
            End If
        Next
    Next
    For j = 1 To 3
        Debug.Print ar((j + i) Mod 3)
    Next
End Sub

与发布的 CDP1802 相同,但查找最后 3 行的速度更快。

Sub FilteredAdvanced()
    Const nValues As Long = 3 'amount of rows you want to find from the end
    
    Dim ar() As Long
    ReDim ar(nValues - 1) As Long
    
    ' apply filter
    With Sheet1
        .AutoFilterMode = False
        .UsedRange.AutoFilter 1, "A123"
        Dim rng As Range
        Set rng = .UsedRange.Columns(1).SpecialCells(xlCellTypeVisible)
        .UsedRange.AutoFilter 'remove filter
    End With
    
    Dim n As Long
    n = nValues - 1

    Dim iArea As Long
    For iArea = rng.Areas.Count To 1 Step -1
        Dim iRow As Long
        For iRow = rng.Areas(iArea).Rows.Count To 1 Step -1
            ar(n) = rng.Areas(iArea).Rows(iRow).Row
            n = n - 1
            If n < 0 Then Exit For
        Next iRow
        If n < 0 Then Exit For
    Next iArea

    Dim j As Long
    For j = 0 To nValues - 1
        Debug.Print ar(j)
    Next
End Sub