从 vba 中的字典获取对象成员

Getting Object member from dictionary in vba

我有一个 class,其成员是一个双精度数组

'cls_Person
Public Name as String
Public InAMeeting as Variant
'InAMeeting: Type: Array of Double.
'Sometimes with dimensions of 1 to 8, sometimes of 1 to 10.

我在一个循环中填充我的class,然后将它们填充到一个以字符串为键的全局字典中。

当我尝试直接从字典访问 InAMeeting 成员时,我的问题来了:

'g_dict_People is a globally defined dictionary.
'KeyPerson is a unique key in the dictionary matching a filled object of type cls_Person
Dim Bravo as Double
Bravo = g_dict_People(KeyPerson).InAMeeting(3)

导致错误: 属性 let 过程未定义并且 属性 get 过程没有 return 对象(错误 451)

但是,如果我先从字典中创建对象的副本,那么它就可以工作了:

Dim Bravo as Double
Set temp_cls_Person = g_dict_People(KeyPerson)
Bravo = temp_cls_Person.InAMeeting(3)

我可以直接访问 Name 成员 - 这有效:

Dim Alpha as string
Alpha = g_dict_People(KeyPerson).Name

为什么不同?这与我在 class 定义中声明 InAMeeting 成员的方式有关吗?有什么方法可以直接访问数组类型的对象成员吗?

抱歉,我没有详细说明最小的工作示例 - 代码分布在多个模块和 classes.

我无法测试您的代码,因为我们没有 MCVE,但以下代码对我有用。修改自 。直到 () 的另一个用例! 尝试:

Bravo = g_dict_People(KeyPerson).InAMeeting()(3)
                          ' extra parens!  ^^

InAMeeting 显然是作为 属性 实现的,即,您必须调用该函数才能获取要索引的数组。额外的 () 进行调用。

我的测试用例:

Class1.cls

Public v As Variant

ThisDocument.bas

Public Sub foo()
    Dim v As Variant
    v = Array(1#, 2#, 3#, 4#, 5#)    ' Assuming you're doing something like this

    Dim o As Class1          ' Put the variant array in the object
    Set o = New Class1
    o.v = v

    Dim c As Collection      ' Put the object in the collection
    Set c = New Collection
    c.Add o, "key"

    On Error Resume Next

    Err.Clear
    Debug.Print "Direct"
    Debug.Print v(3)         ' Works OK
    Debug.Print Err.Number, Err.Description

    Err.Clear
    Debug.Print "From collection with ()"
    Debug.Print c("key").v()(3)             ' <== Your use case - works OK
    '        Extra parens ^^
    Debug.Print Err.Number, Err.Description

    ' Reproducing the problem

    Err.Clear
    Debug.Print "From collection"
    Debug.Print c("key").v(3)      ' <== Bombs --- I think this is analogous to your use case
    Debug.Print Err.Number, Err.Description

    Err.Clear
    Dim o1 As Object
    Set o1 = c("key")
    Debug.Print "Intermediate object"
    Debug.Print o1.v(3)         ' Trying what you tried, but it didn't work for me.
    Debug.Print Err.Number, Err.Description

    ' Another thing that works

    Err.Clear
    Debug.Print "Intermediate object with ()"
    Debug.Print o1.v()(3)               ' <== This works
    '   Those extra ^^ parens
    Debug.Print Err.Number, Err.Description

End Sub