2012-08-31 73 views
0

在下面的循環中,我將Class對象添加到另一個類對象中的集合,該對象本身位於集合中。將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 

第一個消息框給出了正確的機會名稱,但第二個消息框被設置爲加入,儘管約翰·史密斯是第一個集合中的最後機會。

因此,如果我有兩個業主,約翰史密斯與機會1和瑪麗樓與機會2從第二個消息框輸出將兩個記錄的機會2。

但是第一條消息將如預期的那樣成爲機會1和2。

這是從所有者類模塊代碼:

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 

回答

2

所以解決,這是實例化的機會環路之外,那麼像這樣每次重新初始化:

Set opportunity = New ClmOpportunity 
+0

打我吧! –

2

你'絕對不會添加「相同」機會對象的多個副本?很難說沒有完整的循環。如果您檢查集合中的所有項目,它們是否都具有相同的名稱?

這段代碼顯示了相同的行爲,如果你註釋掉標線...

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 
0

你總是添加相同ClmOpportunity對象,因爲灰暗的新實例只有一次,即使內部使用的新對象週期。

週期內創建新對象的正確的方法是:

For ... 

    Dim opportunity As ClmOpportunity 
    Set opportunity = New ClmOpportunity 

Next