首页 > 解决方案 > 在 VBA 中组合多个数组

问题描述

我目前正在尝试将 46 个数组组合成一个数组。我已经搜索了互联网,没有占上风,我希望这里有人可以提供帮助。我确实找到了下面的页面,但我需要能够在嵌套的 for 循环中查看新数组的每个元素,所以使用下面的方法并不能完全达到我的最终目标。

Excel vba - 将多个数组合并为一个

基本上,我需要以这样一种方式组合我的 46 个数组集,然后我可以使用嵌套的 for 循环遍历每个元素。IE。

数组集:

myArray1 = (1, 2, 3, 4)
myArray2 = (5, 6, 7)
myArray3 = (8, 9)
myArray4 = (10, 11, 12, 13, 14)
.
.
.
myArray46 = (101, 102, 103)

将它们组合成新的数组:

myNewArray = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14... 101, 102, 103)

在嵌套的 for 循环中循环以根据我的主数组检查每个元素:

For i = LBound(mainArray) to UBound(mainArray)
    For j = LBound(myArray) to UBound(myArray)

    If mainArray(i) = myArray(j) Then
    'do something
    End If

    Next j
Next i

非常感谢任何帮助和/或指导!

标签: arraysexcelvba

解决方案


由于您在评论中写道,您的最终目标是创建一个独特元素的数组,因此您最好使用字典,您可以在将每个元素添加到字典时测试其唯一性。就像是:

Option Explicit
Function uniqueArr(ParamArray myArr() As Variant) As Variant()
    Dim dict As Object
    Dim V As Variant, W As Variant
    Dim I As Long

Set dict = CreateObject("Scripting.Dictionary")
For Each V In myArr 'loop through each myArr
    For Each W In V 'loop through the contents of each myArr
        If Not dict.exists(W) Then dict.Add W, W
    Next W
Next V


uniqueArr = dict.keys

End Function

Sub tester()
    Dim myArray1, myArray2, myArray3, myArray4, myArray5
    myArray1 = Array(1, 2, 3, 4)
    myArray2 = Array(5, 6, 7, 8)
    myArray3 = Array(9, 10, 11, 12, 13, 14)
    myArray4 = Array(15, 16)
    myArray5 = Array(1, 3, 25, 100)

Dim mainArray

mainArray = uniqueArr(myArray1, myArray2, myArray3, myArray4, myArray5)

End Sub

如果你运行Tester,你会看到mainArray包含:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
25
100

推荐阅读