If you know the array size you are going to need, Matthewâs answer will solve your problem. (You would still need to incorporate Matthewâs answer into maxpottersâ answer to avoid the error youâre getting, because you still would have an array with no dimensions or elements...)
(It looks as if you never use more than 1 dimension of vaSelect, so I am going to address this presuming a 1-dimension array is suitable.) If you do not know in advance what the size of the array needs to be, you can declare it as you have been doing, then immediately resize it to have 1 element
Then, in your loop, repeatedly resize the array to accomodate what you are about to add to it, using the keyword âPreserve.â
When you resize an array, a different contiguous block of memory is allocated for the array. That is the end of the story if you do not specify âPreserve.â But if you
do specify âPreserve,â then
VB (and VBA) follows that step by copying all of the former data into the new block of memory before relinquishing its hold on the old memory.
Code:
j = 1
For i = 1 To UBound(vaTest, 1)
If vaTest(i, 1) > 10 Then
Redim Preserve vaSelect(j)
vaSelect(j) = vaTest(i, 1)
j = j + 1
End If
Next i
If a couple of numbers get skipped because of the > 10 test, when the array is redimmed, the elements in between that last one that was filled in and the current one getting filled in will be initialized to the default value of the data type of the array. Since you have not specified a data type, the array is an array of Variants, so the interposing elements will be equal to Variant(Empty). If you specify the array as a numeric type they will equal zero.