How can I write a function to extract a single dimension array from a multidimension one in VBA?
Suppose I have:
a(3,3,3)
, then now I want to extract:
a(1,1,1)
,
a(1,2,1)
and a(1,3,1)
into a new array.
I use here 3-or-more dimension array. It's because I already know we can use Application.WorksheetFunction.Index
to do extraction from a 2-dimension array.
Thank you in advance.
答案 0 :(得分:0)
虽然工作表的INDEX function可以切出一行'或者'列'对于二维阵列,我不知道如何使用它来剥离一个3D阵列的切片。您似乎需要手动分配值#。
。Sub peel_out_arr()
Dim i As Long, j As Long, k As Long
Dim a() As Variant, b As Variant
ReDim a(1 To 3, 1 To 3, 1 To 3)
For i = LBound(a, 1) To UBound(a, 1)
For j = LBound(a, 2) To UBound(a, 2)
For k = LBound(a, 3) To UBound(a, 3)
a(i, j, k) = i + j + k
Next k
Next j
Next i
b = Array(a(1, 1, 1), a(1, 2, 1), a(1, 3, 1))
For i = LBound(b) To UBound(b)
Debug.Print b(i) '<~~ results are 3, 4, 5
Next i
End Sub
答案 1 :(得分:0)
谢谢大家的帮助。我决定编写一个sub使用循环来获取数组的第二个维度。
Sub slicearray(vArr As Variant, result As Variant, i As Long, j As Long)
Dim k As Long
ReDim result(LBound(vArr, 2) To UBound(vArr, 2))
For k = LBound(vArr, 2) To UBound(vArr, 2)
result(k) = vArr(i, k, j)
Next k
End Sub
通过这个子句,如果我将变量b
声明为Variant
类型的动态数组,我可以通过
Call slicearray(a,b,1,1)