Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

excel

vba

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 RowArray = index(valRange=valMatch).row)

Below is the code for the (slow) range loop.

Current Code

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)

For Each c In valRange
    If c.Value = valMatch Then RowArray(x) = c.Row: x = x + 1
Next c    
End Sub
like image 638
Steve Avatar asked Oct 16 '12 18:10

Steve


2 Answers

Still around 2-3 times the time of the efficient variant array from Chris, but the technique is powerful and has application beyond this question

One point to note is that Application.Transpose is limited to 65536 cells, so a longer range needs to be "chunked" into pieces.

Sub GetEm()
Dim x
x = Filter(Application.Transpose(Application.Evaluate("=IF(A1:A50000=""aa"",ROW(A1:a50000),""x"")")), "x", False)
End Sub
like image 166
brettdj Avatar answered Oct 25 '22 14:10

brettdj


First copy the range to a variant array , then loop over the array

Arr = rngval
For I = 1 to ubound(arr)
    If arr(I,1) = valMatch Then RowArray(x) = I: x = x + 1
Next
like image 20
chris neilsen Avatar answered Oct 25 '22 12:10

chris neilsen