VBA对象数据被覆盖在集合中

在下面的循环中,我将一个类对象添加到另一个类对象中的一个集合,这个对象本身就在一个集合中。

Dim opportunity As New ClmOpportunity opportunity.name = name owners.item(overallOwner).addOpportunity opportunity MsgBox opportunity.name Next i MsgBox owners("John Smith").opportunities(1).name 

第一个消息框提供了正确的机会名称,但是第二个消息框被设置为添加的最后一个机会,尽pipeJohn Smith是第一个收集的机会。

所以如果我有两个业主,约翰·史密斯(John Smith)和玛丽·卢(Mary Lou)将有机会从第二个消息框出来,这两个logging都是机会2。

但是第一个信息就是预期的机会1和2。

这是来自Owner类模块的代码:

 Public name As Variant Public opportunities As New collection Public Function addOpportunity(opp As ClmOpportunity) Dim OppID As String OppID = opportunities.count + 1 opp.ID = OppID opportunities.Add opp, OppID End Function 

所以对此的解决scheme是实例化循环之外的机会,然后每次像这样重新初始化:

 Set opportunity = New ClmOpportunity 

你绝对不是添加“相同”机会对象的多个副本? 很难说没有完整的循环。 如果您检查集合中的所有项目,他们都具有相同的名称?

此代码显示相同的行为,如果你注释掉标记的行…

 Sub Tester() Dim col As New Collection Dim o As clsTest 'has just a "name" property Set o = New clsTest o.name = "obj1" col.Add o, "key1" 'compare debug output with the next line ' commented/uncommented Set o = New clsTest o.name = "obj2" col.Add o, "key2" Debug.Print col(1).name, col(2).name End Sub 

您始终添加相同的ClmOpportunity对象,因为即使在一个循环内使用Dim,New也仅实例化一个新对象。

在周期内创build新对象的正确方法是:

 For ... Dim opportunity As ClmOpportunity Set opportunity = New ClmOpportunity Next