VBA合并不同维度数组的条目

时间:2018-11-16 15:48:25

标签: arrays excel vba merge

我想合并两个数组的条目,并将合并的内容保存在新数组中。

例如:

array1 = ("Name1", "Name2")
array2 = ("top","tip","tap")

结果应如下所示:

array3 = ("Name1top","Name1tip","Name1tap","Name2top","Name2tip","Name3tap")

我尝试使用坡度,但不知何故无法获得想要的结果。

1 个答案:

答案 0 :(得分:0)

坦率地说,做到这一点的一种方法是嵌套2个循环(斜率??)

'Create the two files starting at index 0
array1 = Split("Name1,Name2", ",")
array2 = Split("top,tip,tap", ",")

'get the length of the arrays
len1 = UBound(array1) - LBound(array1) + 1 
len2 = UBound(array2) - LBound(array2) + 1

'Create an array which holds all combinations. There are len1*len2 times of these
ReDim array3(0 To len1 * len2 - 1)

'Build all combinations with 2 nested loops
For i = LBound(array1) To UBound(array1)
    For k = LBound(array2) To UBound(array2)
        array3(i * len1 + k) = array1(i) & array2(k) 'the index of array3 is a bit tricky, take a bit of time why it is constructed this way
    Next k
Next i