我正在将类(class)项目添加到字典中,但无法将它们取回。我需要循环还是我做错了什么?
我的类模块“cOgg”有:
Public desc As String
Public alt As Single
我的子有:
sub pivo()
Dim oMat As New cOgg
Dim sosdb As New Dictionary
Set sosdb = Nothing
oMat.desc= "unodesc"
oMat.alt= 5
sosdb.Add "uno", oMat
oMat.desc= "duedesc"
oMat.alt= 10
sosdb.Add "due", oMat
Debug.Print (sosdb("uno").alt)
Debug.Print (sosdb("due").alt)
end sub
如果我运行子程序,我会得到:
10
10
而不是
5
10
有什么想法吗?
问候
最佳答案
添加后,您必须将 oMat
变量设置为 cOgg
类的新实例,以便在字典中拥有该类对象的两个实例。
sub pivo()
Dim oMat As New cOgg
Dim sosdb As New Dictionary
Set sosdb = Nothing
oMat.desc= "unodesc"
oMat.alt= 5
sosdb.Add "uno", oMat
Set oMat = New cOgg
oMat.desc= "duedesc"
oMat.alt= 10
sosdb.Add "due", oMat
Debug.Print (sosdb("uno").alt)
Debug.Print (sosdb("due").alt)
end sub
如果您不这样做,那么 "Uno"
条目中的 oMat
在添加为 10 后将会更新。然后您添加相同的精确值保存在 oMat
中的 cOgg
实例到字典的 “due”
条目。因此,"uno"
和 "due"
都持有相同的对象实例,它们是相同的,并且 alt
为 10
关于字典中的 Excel VBA 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50238546/