我有一个“输入数组”(列表计数不固定)。我需要为“输入数组”中的每个项创建一个新数组,并将每个项添加为其自己数组的第一项。
我无法定义数组的大小数组,因为子数组的数量不固定。
应如何定义?
答案 0 :(得分:1)
根据您提供的说明,请遵循我的建议。
请给我们您的反馈。
Private Function AmazingFunction(inputArray As Variant)
Dim size As Long
Dim i As Long
Dim tmp As Variant
Dim newArray() As Variant
size = UBound(inputArray) ' Array size
ReDim newArray(size) ' Resizes another array to the same size
For i = 0 To size ' For each value
tmp = CreateArray(length:=0) ' Allows you to dynamically create arrays
' In this case, an array of only one element is created.
tmp(0) = inputArray(i) ' Sets the value of the first array element
newArray(i) = tmp
Next
AmazingFunction = newArray
End Function
动态创建数组的辅助功能:
Private Function CreateArray(length As Long)
Dim arr() As Variant
ReDim arr(length)
CreateArray = arr
End Function
以下是如何使用该功能的示例:
Private Sub UseTest()
Dim outArray As Variant
Dim intArray As Variant
Dim element As Variant
Dim inputArray(2) As Variant
inputArray(0) = "a"
inputArray(1) = "b"
inputArray(2) = "c"
outArray = AmazingFunction(inputArray)
For Each intArray In outArray
For Each element In intArray
Debug.Print element
Next
Next
End Sub