如何在VBA中设置“锯齿arrays”?

我有一个充满了孩子的教室,每个孩子都必须列出他们最喜欢的玩具。 有些孩子只列出1个玩具,而其他孩子列出更多。

如何创build一个锯齿状的数组,使Kids(x)(y)…其中x是我class上孩子的数量,y是他们列为最爱的玩具列表?

“Jagged数组”是数组数组的俚语。 VBA的Variant数据types可以包含任何*,包括一个数组。 所以你创build一个Varianttypes的数组,并为它的每个元素分配一个任意长度的数组(即不是所有的元素都必须具有相同的长度)。

这是一个例子:

 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 (eg 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 

*一个明显的例外是用户定义的types。 变体不能包含这些。

您可以使用集合的集合

 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 

哪个输出Kid 4, Toy 2 = Kid4Toy2

让 – 弗朗索瓦指出,每个元素可以是一个不同长度的数组。 我会补充说,每个元素也可以是其他types,不需要是数组。 例如:

 Dim c as New Collection Dim a(1 to 5) as Variant c.Add "a","a" c.Add "b","b" a(1) = 5 a(2) = Array(2,3,4) set a(3) = c a(4) = "abcd" a(5) = Range("A1:A4").Value 

然后可以引用各个子元素,具体取决于每个元素的隐式types:

a(2)(1)= 3

a(3)(1)=“a”

a(5)(2,1)=无论在单元格A2中。

您还可以将玩具列表连接成例如pipe道分隔的string,然后在需要时使用拆分将string转换为数组:

 Sub UntangleTheString() Dim sToys As String Dim aToys() As String Dim x As Long sToys = "baseball|doll|yoyo" aToys = Split(sToys, "|") For x = LBound(aToys) To UBound(aToys) Debug.Print aToys(x) Next End Sub 

你不一定需要锯齿arrays来处理你的场景,因为二维数组(r,c)也可以工作。 每个孩子一行,每个礼物一列。 数组的尺寸将是(#的孩子,MAX礼物),这只是意味着一些插槽将为空或0(取决于您的数据types)。 但是至less这样你每次给孩子添加礼物时都不需要重新设置数组。