arrays - 在 VBA 中组合多个数组
问题描述
我目前正在尝试将 46 个数组组合成一个数组。我已经搜索了互联网,没有占上风,我希望这里有人可以提供帮助。我确实找到了下面的页面,但我需要能够在嵌套的 for 循环中查看新数组的每个元素,所以使用下面的方法并不能完全达到我的最终目标。
基本上,我需要以这样一种方式组合我的 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
非常感谢任何帮助和/或指导!
解决方案
由于您在评论中写道,您的最终目标是创建一个独特元素的数组,因此您最好使用字典,您可以在将每个元素添加到字典时测试其唯一性。就像是:
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
推荐阅读
- java - Spring Boot 将值从一个控制器更改为另一个
- amazon-web-services - aws sqs fifo队列与标准队列之间的转换
- azure - 如何从 Azure webjob 访问共享网络驱动器
- eclipse - 开始使用 pentaho 水壶做出贡献并解决与之相关的问题
- javascript - 合并两个 observables,单个输出
- javascript - 删除来自材料 ui 的文本框的填充
- vim - Visual Studio Code - 如何添加 vim 编辑器命令?
- java - 如何在循环中将不同的子类转换为超类?
- javascript - LinkedIn SDK 注销错误:“此页面没有可用的 XD 对象”
- c# - MVVM Light RelayCommand 绑定在用户控件中不起作用