A family of Microsoft spreadsheet software with tools for analyzing, charting, and communicating data.
Try the following code.
When you ReDim an array, you destroy all previous data in the array.
If you want to resize the array without losing the existing data then use ReDim Preserve.
To use ReDim Preserve, the array must have at least one element. Therefore ReDim the array with one element before commencing the loop. The element will be blank until data is assigned to it.
You will see in the example where I ReDimmed and created one element before the loop and then used ReDim Preserve to create another element each time a value needs to be added. The interesting thing here is that the first time Redim Preserve is used, it does not add another element because you can use the command with the same initial values that were initially used to create one element and it will not add another element.
The variable J is used and initialized to one. It is then used to ReDim to create the first element and then it is still one when the First ReDim Preserve is used but after that it is incremented for the next ReDim Preserve.
I have added a MsgBox test to view the results.
Sub PopulateDynamicArray()
Dim cell As Range
Dim cellArray() As Variant
Dim i As Long
Dim j As Long
j = 1
'Following creates a One based array
ReDim cellArray(1 To j) 'Initialize to one element otherwise Redim Preserve does not work
For Each cell In Range("A8:H8")
If (IsEmpty(cell.Value)) And (cell.Style <> "Bad") Then
ReDim Preserve cellArray(1 To j) 'Does not change array size on first iteration
cellArray(j) = cell.Address(False, False)
j = j + 1
Range(cell.Address(False, False)).Style = "Good"
End If
Next cell
'Following code to test the array.
For i = LBound(cellArray) To UBound(cellArray)
MsgBox cellArray(i)
Next i
End Sub