I need a function to extract values from a dynamic range generated by an excel spilling function and saving them into a dynamic array. For this purpose I use a For Each loop. It should work independently if the dynamic range comes from a EXCEL spilling function taken directly from a string parameter or through a reference to a spilling function in a worksheet. For some strange reason the order is different.
The cell A1 in the active sheet contains following formula:
=SEQUENCE(5,4,1,1)
Sub eval1()
Dim v As Variant
Dim s As String
For Each v In Evaluate("=A1#")
s = s & v & " "
Next
Debug.Print s
End Sub
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Sub eval2()
Dim v As Variant
Dim s As String
For Each v In Evaluate("=SEQUENCE(5,4,1,1)")
s = s & v & " "
Next
Debug.Print s
End Sub
Output:
1 5 9 13 17 2 6 10 14 18 3 7 11 15 19 4 8 12 16 20
The output I expected was for both subs:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
or at least for both the same.
The difference is
row major ordervscolumn major ordertraversal. Microsoft docs don't specify whichFor Eachloop uses. All conclusions are based on code testing results.For a range : Row Major Order
Output:
For an array : Column Major Order
Output:
I'm not sure why there is a difference. But it looks like:
For Each v In Evaluate("=A1#")is equivalent toFor Each v In Range("A1:D5")For Each v In Evaluate("=SEQUENCE(5,4,1,1)")is equivalent toUsing a nested
Forloop to iterate the result is more reliable.