How do I Merge two Arrays in VBA? How do I Merge two Arrays in VBA? vba vba

How do I Merge two Arrays in VBA?


Try this:

arr3 = Split(Join(arr1, ",") & "," & Join(arr2, ","), ",") 


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 VariantDim arr2() As VariantDim arr3() As Variantarr1() = Array("A", 1, "B", 2)arr2() = Array("C", 3, "D", 4)ReDim arr3(UBound(arr1) + UBound(arr2) + 1)Dim i As IntegerFor 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.


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 = holdarrEnd Function