2015-01-21 58 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