Home > Back-end >  Merge 2 arrays in alternating order in VBA
Merge 2 arrays in alternating order in VBA

Time:10-13

I have 2 arrays which need to be merged in alternating order.

enter image description here

Result is a VBA array.

CodePudding user response:

I was bored. It is a matter of iterating the arrays and filling a third:

Sub mergit()
    Dim arr1 As Variant
    arr1 = Array(1, 2, 3, 4, 5)
    
    Dim arr2 As Variant
    arr2 = Array("a", "b", "c", "d", "e")
    
    Dim arr3 As Variant
    ReDim arr3(0 To UBound(arr1)   UBound(arr2)   1)
    
    Dim k As Long
    k = 0
    
    Dim i As Long
    For i = LBound(arr1) To UBound(arr1)
        arr3(k) = arr1(i)
        arr3(k   1) = arr2(i)
        k = k   2
    Next i
    
    Debug.Print Join(arr3, ",")
    
End Sub
  • Related