Is it possible to fill an array with row numbers which match a certain criteria without looping?

前端 未结 8 1764
陌清茗
陌清茗 2020-11-27 17:33

I would like to fill an array in VBA with the row numbers of only rows which meet a certain criteria. I would like the fastest method possible (for example, something like <

相关标签:
8条回答
  • 2020-11-27 18:24

    I still have a loop, but only through the necessary rows to populate the array:

    Sub get_row_numbers()
    
    Dim RowArray() As Long
    Dim valRange As Range
    Dim valMatch As String
    
    Set valRange = ActiveSheet.Range("A1:A11")
    valMatch = "aa"
    ReDim RowArray(WorksheetFunction.CountIf(valRange, valMatch) - 1)
    
    Dim c As Range
    Dim x As Integer
    Set c = valRange.Find(What:=valMatch, LookIn:=xlFormulas, SearchOrder:=xlByRows, SearchDirection:=xlNext)
    
    Do
      RowArray(x) = c.Row
      Set c = valRange.FindNext(after:=c)
      x = x + 1
    Loop Until x = UBound(RowArray) + 1
    
    
    End Sub
    
    0 讨论(0)
  • You may want to look at Find vs Match vs Variant Array which concludes that the variant array approach is fastest unless the hit density is very low.

    But the fastest method of all is only for sorted data and exact match: use binary search to find the fisrt and last ocurrences and then get that subset of data into a variant array.

    0 讨论(0)
提交回复
热议问题