Question posted 2012 · +11 upvotes
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
Accepted answer +11 upvotes
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
Excel VBA objects referenced (4)
ActiveSheet.Range— Refer to Cells by Using a Range ObjectActiveSheet.Range— Delete Duplicate Entries in a RangeApplication— Using events with the Application objectApplication— Working with Other Applications
Top excel-vba Q&A (6)
- How to clear the entire array? +58 (2010)
- How to change Format of a Cell to Text using VBA +55 (2011)
- Download attachment from Outlook and Open in Excel +43 (2012)
- Can a VBA function in Excel return a range? +36 (2009)
- 2 Dimensional array from range +34 (2013)
- Hiding an Excel worksheet with VBA +33 (2009)
excel-vba solutions on this site
.