[英]Excel-VBA creating a 3d array from 3 1d arrays
I have 3 one dimensional Arrays namely Topic(), SubTopic() and Description()
. 我有3个一维数组,即Topic(), SubTopic() and Description()
。 The Maximum number of entries in each of These Arrays is limited by a variable noDescription
. 这些数组中每个数组的最大条目数受变量noDescription
限制。 I Need to make a 3d Array out of These Arrays and Display it. 我需要从这些数组中制作一个3d数组并显示它。 My code is : 我的代码是:
ReDim info(1 To Topic(), 1 To SubTopic(), 1 To Description())
p = 1
Do
info(p, 0, 0) = Topic(p)
info(p, 1, 0) = SubTopic(p)
info(p, 0, 2) = Description(p)
MsgBox "array value" & info(p, 0, 0) & "and" & info(p, 1, 0) & "and" & info(p, 0, 2)
p = p + 1
Loop Until p > noDescription
It gives a type mismatch error on Dimensioning the Array. 它在确定数组尺寸时给出类型不匹配错误。 I feel I am wrong somewhere. 我觉得我在某个地方错了。 Any help ? 有什么帮助吗?
Here is a function which can be used to glue together any number of 1-dimensional arrays: 这是一个可用于将任意数量的一维数组粘合在一起的函数:
Function CombineArrays(ParamArray Arrays() As Variant) As Variant
'Takes a list of 1-dimensional arrays
'And returns a single array
'The arrays are assumed to have the same base
'But not necessarily the same length
'The arrays form the columns of the result
Dim A As Variant
Dim i As Long, j As Long, lb As Long, ub As Long, m As Long
'first find LBound -- assumed to be common
lb = LBound(Arrays(0))
'now find the maximum ubound:
For i = LBound(Arrays) To UBound(Arrays)
If UBound(Arrays(i)) > ub Then ub = UBound(Arrays(i))
Next i
'now redim and return final array
m = lb + UBound(Arrays)
ReDim A(lb To ub, lb To m)
For j = lb To m
For i = lb To UBound(Arrays(j - lb))
A(i, j) = Arrays(j - lb)(i)
Next i
Next j
CombineArrays = A
End Function
Tested like: 测试像:
Sub Test()
Dim Larry(1 To 4)
Dim Curly(1 To 2)
Dim Moe(1 To 3)
Dim A As Variant
Larry(1) = 1
Larry(2) = 2
Larry(3) = 3
Larry(4) = 4
Curly(1) = "A"
Curly(2) = "B"
Moe(1) = "X"
Moe(2) = "Y"
Moe(3) = "Z"
A = CombineArrays(Larry, Curly, Moe)
Range("A1:C4").Value = A
End Sub
After running the sub, A1:C4 looks like: 运行该子程序后,A1:C4如下所示:
1 A X
2 B Y
3 Z
4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.