我正在尝试使用修改后的值添加对象两次但是在集合的末尾包含两个项目的相同值。我哪里错了?
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
答案 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