Search code examples
arraysvbavb6merge

How do I Merge two Arrays in VBA?


Given

Dim arr1 As Variant
Dim arr2 As Variant
Dim arr3 As Variant

arr1 = Array("A", 1, "B", 2)
arr2 = Array("C", 3, "D", 4)

Question

What kind of operations can I perform on arr1 and arr2 and assign the result to arr3 getting something like that:

arr3 = ("A", "C", 1, 3, "B", "D", 2, 4)

Hint (due to comment): "1) the elements in arr1 are names and in arr2 are values, the final elements in arr3 are actually name-value pairs, so as long as they as paired I won't care if they are not in order."


Solution

  • Unfortunately, the Array type in VB6 didn't have all that many razzmatazz features. You are pretty much going to have to just iterate through the arrays and insert them manually into the third

    Assuming both arrays are of the same length

    Dim arr1() As Variant
    Dim arr2() As Variant
    Dim arr3() As Variant
    
    arr1() = Array("A", 1, "B", 2)
    arr2() = Array("C", 3, "D", 4)
    
    ReDim arr3(UBound(arr1) + UBound(arr2) + 1)
    
    Dim i As Integer
    For i = 0 To UBound(arr1)
        arr3(i * 2) = arr1(i)
        arr3(i * 2 + 1) = arr2(i)
    Next i
    

    Updated: Fixed the code. Sorry about the previous buggy version. Took me a few minutes to get access to a VB6 compiler to check it.