Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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."

like image 680
Kevin Boyd Avatar asked Oct 19 '09 14:10

Kevin Boyd


3 Answers

Try this:

arr3 = Split(Join(arr1, ",") & "," & Join(arr2, ","), ",") 
like image 164
user3286479 Avatar answered Oct 13 '22 14:10

user3286479


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.

like image 30
JohnFx Avatar answered Oct 13 '22 14:10

JohnFx


This function will do as JohnFx suggested and allow for varied lengths on the arrays

Function mergeArrays(ByVal arr1 As Variant, ByVal arr2 As Variant) As Variant
    Dim holdarr As Variant
    Dim ub1 As Long
    Dim ub2 As Long
    Dim bi As Long
    Dim i As Long
    Dim newind As Long

        ub1 = UBound(arr1) + 1
        ub2 = UBound(arr2) + 1

        bi = IIf(ub1 >= ub2, ub1, ub2)

        ReDim holdarr(ub1 + ub2 - 1)

        For i = 0 To bi
            If i < ub1 Then
                holdarr(newind) = arr1(i)
                newind = newind + 1
            End If

            If i < ub2 Then
                holdarr(newind) = arr2(i)
                newind = newind + 1
            End If
        Next i

        mergeArrays = holdarr
End Function
like image 41
Buggabill Avatar answered Oct 13 '22 15:10

Buggabill