将对象添加到VBA中的集合 – > OOP-Basics?

我是面向对象的新手,所以可能有一个明显的解释,为什么这是行不通的。 我正在尝试添加对象到VBA中的集合。 我的课程模块是这样的:

Option Explicit 'the person class Public FirstName As String Public LastName As String Property Get FullName() As String 'return the person's full name FullName = FirstName & " " & LastName End Property 

我的代码是这样的:

 Sub myProg() 'create a new collection! Dim Persons As New Collection Dim p1 As New clsPerson 'give them names in "Loop" p1.FirstName = "Rita" p1.LastName = "Smith" Persons.Add p1 p1.FirstName = "Sue" p1.LastName = "Jones" Persons.Add p1 p1.FirstName = "Bob" p1.LastName = "Brown" Persons.Add p1 '"Loop" end For Each p1 In Persons Debug.Print p1.FullName Next p1 End Sub 

它返回3次“鲍勃·布朗”。 我希望它返回我input的3个名字。

p1是一个引用variables,它指向您在使用New时创build的clsPerson的单个特定实例。

当您将一个引用variables添加到集合中时,您将添加引用本身,而不是副本,这意味着集合中的p1总是指向相同的clsPerson实例,该实例将包含分配给它的最后一个值。

您需要使用New来创build一个新的,独立的类实例并将其添加到集合中,例如

 Set p1 = New clsPerson p1.FirstName = "Bob" p1.LastName = "Brown" Persons.Add p1 Set p1 = New clsPerson p1.FirstName = "Sue" p1.LastName = "Jones" Persons.Add p1 

当你第二次和第三次改变p1时,你正在改变集合中每个点的引用。 该集合持有对p1的引用,并且该引用可以从集合本身进行外部更改。 你需要制作三个人物。

 Sub myProg() 'create a new collection! Dim Persons As Collection Dim p1 As clsPerson Dim p2 As clsPerson Dim p3 As clsPerson Dim p As clsPerson 'give them names in "Loop" set Persons = New Collection set p1 = new clsPerson p1.FirstName = "Rita" p1.LastName = "Smith" Persons.Add p1 set p2 = new clsPerson p2.FirstName = "Sue" p2.LastName = "Jones" Persons.Add p2 set p3 = new clsPerson p3.FirstName = "Bob" p3.LastName = "Brown" Persons.Add p3 '"Loop" end For Each p In Persons Debug.Print p.FullName Next p 'alternate looping way where a new object is created each time For i = 1 To 5 Set p = New clsPerson p.FirstName = "First Name" & i p.LastName = "Last Name" & i Persons.Add p Set p = Nothing 'may not be necessary Next End Sub 

只是不要在For Each重复使用p1 ,这样做就可以了;)

 Sub myProg() 'create a new collection! Dim Persons As New Collection Dim p1 As New clsPerson Dim pT As clsPerson 'give them names in "Loop" p1.FirstName = "Rita" p1.LastName = "Smith" Persons.Add p1 p1.FirstName = "Sue" p1.LastName = "Jones" Persons.Add p1 p1.FirstName = "Bob" p1.LastName = "Brown" Persons.Add p1 '"Loop" end For Each pT In Persons Debug.Print pT.FullName Next pT End Sub