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

Dav*_*vis 2 collections vba 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
Run Code Online (Sandbox Code Playgroud)

cms*_*sjr 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
Run Code Online (Sandbox Code Playgroud)