I'm looping through a named range and appending an array based on if the cell is empty or not. I'm not too familiar with arrays in VBA, so perhaps my logic is incorrect. The code keeps overwriting the 1st element in the array and it never gets incremented. I"m not sure why the UBound(myArray) always stays at 0 even after an element has been assigned to the 1st index.
My code looks something like:
Dim myArray() As Double
ReDim Preserve myArray(0)
For Each cell In [myRange]
If cell <> "" Then
If UBound(myArray) > 0 Then
ReDim Preserve myArray(0 To UBound(myArray) + 1)
End If
myArray(UBound(myArray)) = cell.value
End If
Next
Create a Dynamic Array in VBAFirst, declare an array with its name. After that, the elements count left the parentheses empty. Now, use the ReDim statement. In the end, specify the count of elements you want to add to the array.
Step 1: Insert a new module inside Visual Basic Editor (VBE). Click on Insert tab > select Module. Step 2: Define the subprocedure where we will declare our first dynamic array. Step 3: So declare an array for the dynamic array.
VBA Code to Append an existing text file – Macro ExplainedAssigning the Existing File path to the variable strFile_Path. Opening the text file for Append with FileNumber as 1. Writing to the sample text to the File using FileNumber and Write Command. Closing the File using FileNumber.
To Fill a Dynamic ArrayOn the Tools menu, point to Macro and then click Macros. In the Macro dialog box, click fill_array, and then click Run.
Use a variable and increment it, it makes no difference if the variable is larger than the ubound when the code completes:
Sub Test()
Dim myArray() As Double, X As Long
X = 0
ReDim Preserve myArray(X)
For Each cell In Range("Hello")
If cell <> "" Then
ReDim Preserve myArray(0 To X)
myArray(X) = cell.Value
X = X + 1
End If
Next
End Sub
Change If UBound(myArray) > 0 Then
to If UBound(myArray) >= 0 Then
that will solve the problem.
Sub Test()
Dim myArray() As Double
ReDim Preserve myArray(0)
For Each cell In Range("Hello")
If cell <> "" Then
If UBound(myArray) >= 0 Then
myArray(UBound(myArray)) = cell.Value
ReDim Preserve myArray(0 To UBound(myArray) + 1)
End If
End If
Next
End Sub
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With