Adding an element to the end of an array
Try this [EDITED]:
Dim arr() As Variant ' let brackets empty, not Dim arr(1) As Variant !
For Each a In range.Cells
' change / adjust the size of array
ReDim Preserve arr(1 To UBound(arr) + 1) As Variant
' add value on the end of the array
arr (UBound(arr)) = a.value
Next
I solved the issue by using a Collection and copy it afterwards to an array.
Dim col As New Collection
For Each a In range.Cells
col.Add a.Value ' dynamically add value to the end
Next
Dim arr() As Variant
arr = toArray(col) 'convert collection to an array
Function toArray(col As Collection)
Dim arr() As Variant
ReDim arr(0 To col.Count-1) As Variant
For i = 1 To col.Count
arr(i-1) = col(i)
Next
toArray = arr
End Function
This is how I do it, using a Variant (array) variable:
Dim a As Range
Dim arr As Variant 'Just a Variant variable (i.e. don't pre-define it as an array)
For Each a In Range.Cells
If IsEmpty(arr) Then
arr = Array(a.value) 'Make the Variant an array with a single element
Else
ReDim Preserve arr(UBound(arr) + 1) 'Add next array element
arr(UBound(arr)) = a.value 'Assign the array element
End If
Next
Or, if you actually do need an array of Variants (to pass to a property like Shapes.Range, for example), then you can do it this way:
Dim a As Range
Dim arr() As Variant
ReDim arr(0 To 0) 'Allocate first element
For Each a In Range.Cells
arr(UBound(arr)) = a.value 'Assign the array element
ReDim Preserve arr(UBound(arr) + 1) 'Allocate next element
Next
ReDim Preserve arr(LBound(arr) To UBound(arr) - 1) 'Deallocate the last, unused element