VBA Collection:为什么我的 collection 每次迭代都会被替换
VBA Collection: Why does my collection get replaced with each iteration
'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 更新时,collection 中的每个项目也会更新。最终结果是 collection 个完全相同的项目。我做错了什么?
*注意:我已简化代码以仅显示与我的问题最相关的内容。
Function Load_Collection(ByRef ByRef oUser As ClsUser)
Set oUser = New ClsUser
这里的函数输入是oUser,接下来你设置oUser为New ClsUser
。在我看来没有意义。
因为您使用的是 oUser
的单个实例。
另外,这段代码还有其他问题。
在 VBA 函数中有一个 return 值。如果它们没有 return 值,您应该使用 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
'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 更新时,collection 中的每个项目也会更新。最终结果是 collection 个完全相同的项目。我做错了什么?
*注意:我已简化代码以仅显示与我的问题最相关的内容。
Function Load_Collection(ByRef ByRef oUser As ClsUser)
Set oUser = New ClsUser
这里的函数输入是oUser,接下来你设置oUser为New ClsUser
。在我看来没有意义。
因为您使用的是 oUser
的单个实例。
另外,这段代码还有其他问题。
在 VBA 函数中有一个 return 值。如果它们没有 return 值,您应该使用 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