'Class ClsUser
Public User As String
Public Company As String
Public Function AddUser(ByVal UserName As String, ByVal CompanyName As String)
User = UserName
Company = CompanyName
End Function
在模块中
Public User_Collection As New Collection
Function Main()
Dim User_Data As ClsUser
Set User_Data = New ClsUser
Call Load_Collection(User_Data)
End Function
Function Load_Collection(ByRef ByRef oUser As ClsUser)
Set oUser = New ClsUser
Set User_Collection = New Collection
Dim arr(1) As String
arr(0) = "Jack"
arr(1) = "Jill"
For x = 0 to 1
oUser.User = arr(x)
User_Collection.Add oUser, oUser.User
next
End Function
每当更新oUser时,集合中的每个项目也都会更新。最终结果是完全相同的项目集合。我做错了什么?
*注意:我已将代码简化为仅显示与我的问题最相关的内容。
答案 0 :(得分:2)
因为您使用的是oUser
的单个实例。
此外,此代码还有其他问题。
在VBA函数中有一个返回值。如果他们没有返回值,则应使用Sub
s。这有效......
Public User_Collection As New Collection
Sub Main()
Dim User_Data As ClsUser
Set User_Data = New ClsUser
Call Load_Collection
End Sub
Sub Load_Collection()
Dim oUser As ClsUser
Set User_Collection = New Collection
Dim arr(1) As String
arr(0) = "Jack"
arr(1) = "Jill"
For x = 0 To 1
Set oUser = New ClsUser
oUser.User = arr(x)
User_Collection.Add oUser, oUser.User
Next
End Sub
答案 1 :(得分:0)
Function Load_Collection(ByRef ByRef oUser As ClsUser)
Set oUser = New ClsUser
此处功能输入为oUser,接下来将oUser设置为New ClsUser
。在我看来,它没有意义。