将数组分配给集合
Assign an array to a collection
从代码中很容易看出我想要什么,但目前没有任何效果:
Sub test()
Dim C As New Collection
Dim A() As String
ReDim A(0, 1)
A(0, 0) = "row 0, col 0"
A(0, 1) = "row 0, col 1"
C.Add A(0), "first" ' subscript out of range error
Debug.Print C.Item("first")(0) & ", " & C.Item("first")(1)
End Sub
所以,我只想有一个数组作为集合的成员。
非常感谢任何帮助。
您不是要找合集,而是要找字典。
将 Microsoft Scripting Runtime
添加到您的参考文献 (Tools/References);
使用字典而不是集合稍微修改您的代码:
Sub test()
Dim C As New Scripting.Dictionary '<-- not collection
Dim A() As String
ReDim A(0, 1)
A(0, 0) = "row 0, col 0"
A(0, 1) = "row 0, col 1"
C.Add "first", A '<-- key first, item then
Debug.Print C("first")(0, 0) & ", " & C("first")(0,1) <-- you need to access the elements properly (bi-dimensional)
End Sub
至于报错("subscript out of range"),是数组使用不当造成的。您将其定义为 A(0 to 0, 0 to 1)
,因此您不能将其用作一维的。
从代码中很容易看出我想要什么,但目前没有任何效果:
Sub test()
Dim C As New Collection
Dim A() As String
ReDim A(0, 1)
A(0, 0) = "row 0, col 0"
A(0, 1) = "row 0, col 1"
C.Add A(0), "first" ' subscript out of range error
Debug.Print C.Item("first")(0) & ", " & C.Item("first")(1)
End Sub
所以,我只想有一个数组作为集合的成员。
非常感谢任何帮助。
您不是要找合集,而是要找字典。
将
Microsoft Scripting Runtime
添加到您的参考文献 (Tools/References);使用字典而不是集合稍微修改您的代码:
Sub test() Dim C As New Scripting.Dictionary '<-- not collection Dim A() As String ReDim A(0, 1) A(0, 0) = "row 0, col 0" A(0, 1) = "row 0, col 1" C.Add "first", A '<-- key first, item then Debug.Print C("first")(0, 0) & ", " & C("first")(0,1) <-- you need to access the elements properly (bi-dimensional) End Sub
至于报错("subscript out of range"),是数组使用不当造成的。您将其定义为 A(0 to 0, 0 to 1)
,因此您不能将其用作一维的。