我是OOP的新手,所以可能有一个明显的解释为什么这不起作用。我正在尝试将对象添加到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次“Bob Brown”。我希望它能返回我输入的3个名字。
答案 0 :(得分:1)
当您在第2次和第3次更改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
答案 1 :(得分:0)
不要在p1
中重复For Each
,这样就可以了;)
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
答案 2 :(得分:0)
p1
是一个引用变量,它指向您在使用clsPerson
时创建的New
的单个特定实例。
当您向集合添加引用变量时,您正在添加引用本身,而不是副本,这意味着集合中的p1
始终指向同一个clsPerson
实例,包含您分配给它的最后一个值。
您需要使用New
创建一个新的,独立的类实例,并将其添加到集合中,例如
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