Extension on Split
approach using ArrayToText()
function (MS365)
If you dispose of MS/Excel 365 you may simplify joins & splits ( see @user3286479 's most upvoted post ) by passing a so called jagged array (a.k.a. as array of arrays) as main argument. This jagged array may comprise two or even more arrays, not only arr1
and arr2
.
As a further benefit I included the option to decide whether the array returns the merged array elements consecutively (default value additive=True
) or not (i.e. intertwined with explicit argument additive=False
).
Function MergeArr(jagged As Variant, _
Optional ByVal additive As Boolean = True)
'Note: returns only string elements (needs arrays of same length)
If additive Then ' all elems of 1st array, then all elems of 2nd one etc.
MergeArr = Split(Application.ArrayToText(jagged), ", ")
Else ' intertwine first elems of each array, then all second elems etc.
MergeArr = Split(Application.ArrayToText(Application.Transpose(jagged)), ", ")
End If
End Function
Example call
Sub testMergeArr()
Dim arr1 As Variant
arr1 = Array("A", 1, "B", 2)
Dim arr2 As Variant
arr2 = Array("C", 3, "D", 4)
Dim arr3 As Variant
arr3 = MergeArr(Array(arr1, arr2))
Debug.Print "additive ~~> " & Application.ArrayToText(arr3)
arr3 = MergeArr(Array(arr1, arr2), False)
Debug.Print "alternating ~~> " & Application.ArrayToText(arr3)
End Sub
Results in VB Editor's immediate window
additive ~~> A, 1, B, 2, C, 3, D, 4
alternating ~~> A, C, 1, 3, B, D, 2, 4
Caveat
A possible disadvantage of the approach above is that all elements would be returned as strings, thus including all numeric values as well. To avoid this situation, you might use the following function alternatively using FilterXML()
(available btw since vers. 2013):
Function MergeArrXML(jagged As Variant, _
Optional ByVal additive As Boolean = True)
'Note: allows to maintain not only string elements, but also numeric values (doubles)
Dim content As String
If additive Then ' all elems of 1st array, then all elems of 2nd one etc.
content = Replace(Application.ArrayToText(jagged), ", ", "</i><i>")
Else ' intertwine first elems of each array, then all second elems etc.
content = Replace(Application.ArrayToText(Application.Transpose(jagged)), ", ", "</i><i>")
End If
MergeArrXML = Application.Transpose(Application.FilterXML("<r><i>" & content & "</i></r>", "//i"))
End Function