2015-01-21 57 views
-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 

所以,我只是想有一个数组作为集合的成员。

任何帮助,非常感谢。

回答

1

你不是在寻找一个集合,而是一个字典。

  1. Microsoft Scripting Runtime添加到您的参考(工具/参考);

  2. 使用,而不是一个集合的字典稍微修改代码:

    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 
    

至于错误(“下标越界”),这取决于一个坏的使用数组。您将其定义为A(0 to 0, 0 to 1),因此您不能像使用单维一样使用它。

+1

“你不是在寻找一个集合,而是一本字典。”你为什么这么说?答案的第二部分是解决方案,但我对第一部分感到好奇。为什么不使用集合。 – 2015-01-22 02:53:16