如何在VBA中设置"锯齿状阵列"?

pha*_*han 21 arrays vba jagged-arrays

我有一个满是孩子的教室,每个孩子都必须列出他们最喜欢的玩具作为作业.有些孩子只列出1个玩具而有些孩子列出更多.

如何创建一个锯齿状的数组,使得Kids(x)(y)...其中x是我班级中的孩子数量,y是他们列为最喜欢的玩具列表?

Jea*_*ett 30

"锯齿状数组"是数组数组的俚语.VBA的Variant数据类型可以包含任何*,包括数组.因此,您创建一个类型数组Variant,并为其每个元素分配一个任意长度的数组(即,并非所有数组都必须具有相同的长度).

这是一个例子:

Dim nStudents As Long
Dim iStudent As Long
Dim toys() As Variant
Dim nToys As Long
Dim thisStudentsToys() As Variant

nStudents = 5 ' or whatever

ReDim toys(1 To nStudents) ' this will be your jagged array

For iStudent = 1 To nStudents
    'give a random number of toys to this student (e.g. up to 10)
    nToys = Int((10 * Rnd) + 1)
    ReDim thisStudentsToys(1 To nToys)

    'code goes here to fill thisStudentsToys()
    'with their actual toys

    toys(iStudent) = thisStudentsToys
Next iStudent

' toys array is now jagged.

' To get student #3's toy #7:
MsgBox toys(3)(7)
'will throw an error if student #3 has less than 7 toys
Run Code Online (Sandbox Code Playgroud)

*一个值得注意的例外是用户定义的类型.变体不能包含这些.


ja7*_*a72 6

您可以使用集合的集合

Public Sub Test()

    Dim list As New Collection
    Dim i As Integer, j As Integer
    Dim item As Collection
    For i = 1 To 10
        Set item = New Collection
        For j = 1 To i
            item.Add "Kid" & CStr(i) & "Toy" & CStr(j)
        Next j
        list.Add item
    Next i

    Debug.Print "Kid 4, Toy 2 = " & list(4)(2)
End Sub
Run Code Online (Sandbox Code Playgroud)

哪个输出 Kid 4, Toy 2 = Kid4Toy2

  • 您可以在集合中添加和删除项目,但不能从阵列中添加和删除项目.如果需要,除了索引之外,您还可以使用键访问项目.也许你使用孩子的名字或ID作为收藏的钥匙. (2认同)