VBA和集合 - 在添加到集合之前需要将实例设置为空?

时间:2011-08-20 01:18:48

标签: vba collections multiple-instances

我正在尝试使用修改后的值添加对象两次但是在集合的末尾包含两个项目的相同值。我哪里错了?

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

1 个答案:

答案 0 :(得分: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