使用ArrayToText() 函数扩展Split approach (MS365)
如果您弃用 MS/Excel 365,您可以通过传递所谓的 锯齿状数组 来简化连接和拆分 (请参阅 @user3286479 最受好评的 post ) (也称为数组数组) 作为主要参数。这个锯齿状数组可能包含两个甚至更多个数组,而不仅仅是arr1和arr2。
作为进一步的好处,我包括了决定数组是否返回合并数组元素的选项连续(默认值additive=True)或不(即与显式参数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
调用示例
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
VB 编辑器的即时窗口中的结果
additive ~~> A, 1, B, 2, C, 3, D, 4
alternating ~~> A, C, 1, 3, B, D, 2, 4
警告
上述方法的一个可能缺点是所有元素都将作为字符串返回,因此也包括所有数值。为了避免这种情况,您可以使用以下函数或者使用FilterXML()(从 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