字典中的 Excel vba 类

Got*_*ekk 2 excel vba dictionary class

我正在将课程项目添加到字典中,但我无法取回它们。我需要循环还是我做错了什么?

我的课程模块“cOgg”有:

Public desc As String
Public alt As Single
Run Code Online (Sandbox Code Playgroud)

我的潜艇有:

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
Run Code Online (Sandbox Code Playgroud)

如果我运行 sub,我会得到:

10
10
Run Code Online (Sandbox Code Playgroud)

代替

5
10
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

问候

JNe*_*ill 5

添加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
Run Code Online (Sandbox Code Playgroud)

如果您不这样做,那么条目中的oMatin 将"Uno"在被添加为 10 后更新。然后您将cOgg保持在相同的实例中添加oMat"due"字典的条目中。因此,无论"uno""due"保持对象,相同的同一实例,并且具有alt10