2011-08-20 41 views
2

我試圖添加一個對象與集合的修改值兩次,但在集合的結尾包含兩個項目相同的值。我錯在哪裏?VBA和集合 - 在添加到集合之前需要設置一個實例爲空?

Private Sub MySub() 
    Dim ClientList As Collection 
    Set ClientList = New Collection 

    Dim Inst1 As Client 

    Set Inst1 = New Client 

    Inst1.Code = 1 
    Inst1.Name = "First Client" 
    'Adding first client 
    ClientList.Add Inst1 

    Inst1.Code = 2 
    Inst1.Name = "Second Client" 
    'Adding second client 
    ClientList.Add Inst1 

    Set Inst1 = ClientList(1) 
    MsgBox Inst1.Name 'Show "Second Client" 

    Set Inst1 = ClientList(2) 
    MsgBox Inst1.Name 'Show "Second Client" too 


End Sub 

回答

5

集合被存儲到你的對象INST1, 你需要或者使用第二個變量,或將現有變量=一個新的實例

Private Sub MySub() 
     Dim ClientList As Collection 
     Set ClientList = New Collection 

     Dim Inst1 As Client 

     Set Inst1 = New Client 

     Inst1.Code = 1 
     Inst1.Name = "First Client" 
     'Adding first client 
     ClientList.Add Inst1 

     'Setting Inst1 to a new instance 
     Set Inst1 = New Client 

     Inst1.Code = 2 
     Inst1.Name = "Second Client" 
     'Adding second client 
     ClientList.Add Inst1 

     Set Inst1 = ClientList(1) 
     MsgBox Inst1.Name 'Show "Second Client" 

     Set Inst1 = ClientList(2) 
     MsgBox Inst1.Name 'Show "Second Client" too 


    End Sub 
參考
相關問題