Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending a dynamic array in VBA

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
like image 412
KingKong Avatar asked Feb 23 '15 22:02

KingKong


People also ask

How do you add elements to a dynamic array in VBA?

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.

How do I use a dynamic array in Excel VBA?

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.

How do you append in VBA?

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.

How do I fill an array in Excel VBA?

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.


2 Answers

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
like image 157
Dan Donoghue Avatar answered Oct 21 '22 03:10

Dan Donoghue


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
like image 39
Jeanno Avatar answered Oct 21 '22 04:10

Jeanno