数组数组
Vityata 提出的创建数组列表(又名锯齿状数组或数组数组)可能接近您的需求并执行 sub 调用以重新调整任何“子”数组的大小。
For idx = 1 To 10 ' << example loop from idx = 1 to n
Standardize a(idx), 1, 5 ' << sub call redimension e.g. from 1 to 5
Next idx
主要程序包括部分数组项的测试显示
注意:分配了一些数字和字母测试值,减少了子数组和循环的数量,并使用常量来引用子数组(例如,通过 a(NUMS) 和 a(ALPHA));单个项目,例如a(ALPHA)(5) 因此将返回一个字符串值“五”(注意特殊语法!)。
Sub ArrayOfArrays()
' [0] provide for a variant container array
Dim a()
' [1] fill container with empty "sub" arrays
' (note that first sub array remains empty just to allow 1-based enumeration)
a = Array(Array(), Array(), Array())
' [2] assign values to variant "sub" arrays - temporarily zero-based
' (note that at this point you are assigning arrays of different lengths)
Const NUMS& = 1, ALPHA& = 2 ' << change to your needs
a(NUMS) = Array(1, 2, 3, 4) ' << test items
a(ALPHA) = Array("one", "two", "three", "four", "five", "six")
' [3] >> standardize all "sub" arrays to the same boundaries 1 To 6 in a loop
' (note that you'd change here from 0-based to 1-based "sub" arrays)
Dim idx&
For idx = NUMS To ALPHA ' << example loop from idx = 1 to 2
Standardize a(idx), 1, 6 ' << sub call redimension from 1 to 6
Next idx
' ================= Some display examples ===============================
' [4a] display some test items from NUMS and ALPHA (including empty ones)
' (note the differing syntax)
Debug.Print "* [4a] Display test items:"
Debug.Print "* NUMS - " & UBound(a(NUMS)) & " items: ", _
Join(a(NUMS), ",")
Debug.Print " e.g. a(NUMS)(1) =" & a(NUMS)(1) '--> 1
Debug.Print " e.g. a(NUMS)(2) =" & a(NUMS)(2) '--> 2
Debug.Print "* ALPHA - " & UBound(a(ALPHA)) & " items: ", _
Join(a(ALPHA), ",")
Debug.Print " e.g. a(ALPHA)(5) =" & a(ALPHA)(5) '--> "five"
Debug.Print " e.g. a(ALPHA)(6) =" & a(ALPHA)(6) '--> "six"
' [4b] display each first and last item of each category
Debug.Print "* [4b] Display first and last item of each category:"
Dim i&, first&, last&, categories$
categories = "Dummy,Nums,Alpha"
For i = NUMS To ALPHA
first = LBound(a(i)): last = UBound(a(i)) ' 1 to 6
Debug.Print " " & Split(categories, ",")(i) & ": " & vbTab & _
"1st item: |" & a(i)(first) & "|," & vbTab & _
"last item: |" & a(i)(last) & "|"
Next i
End Sub
转接电话Standardize
Sub Standardize(arr, lowerBoundary&, upperBoundary&)
' Purpose: change jagged array boundaries by preserving included items
' Note: argument arr is passed ByRef (by default)
Dim tmpArr
tmpArr = arr
ReDim Preserve tmpArr(lowerBoundary To upperBoundary)
arr = tmpArr
End Sub
测试显示在 VBEditor 的即时窗口中
* [4a] Display test items:
* NUMS - 6 items: 1,2,3,4,,
e.g. a(NUMS)(1) =1
e.g. a(NUMS)(2) =2
* ALPHA - 6 items: one,two,three,four,five,six
e.g. a(ALPHA)(5) =five
e.g. a(ALPHA)(6) =six
* [4b] Display first and last item of each category:
Nums: 1st item: |1|, last item: ||
Alpha: 1st item: |one|, last item: |six|