excel - 访问类中的公共(public)字典

标签 excel vba

这是一个基本类:

Public MyData As Dictionary

Private Sub Class_Initialize()
    Set MyData = New Dictionary
End Sub

无法访问公共(public)字典:
Sub Test()
    Dim myClass As New cMyClass
    myClass.MyData("A") = 1
    Debug.Print myClass.MyData("A")
End Sub

错误:
Compile error: Wrong number of arguments or invalid property assignment

我想这与我们不能在类中拥有公共(public)数组的事实有关。

根本原因是 VBA 提供了 索引属性所以在表达式 myClass.MyData VBA 认为 MyData只能是 索引属性 并且不会搜索任何其他内容,例如公共(public)词典。

按照这条路,我确实可以写:
Private pMyData As Dictionary

Private Sub Class_Initialize()
    Set pMyData = New Dictionary
End Sub

Public Property Get MyData(key As String) As Variant
    MyData = pMyData(key)
End Property

Public Property Let MyData(key As String, value As Variant)
    pMyData(key) = value
End Property

还有我的Test上面的示例工作正常。

你确认这个限制的起源吗?

还有其他方法吗?
我试过(myClass.MyData)("A") = 1但它也失败了 Syntax error .

最佳答案

首先,让我们明确一点。在您的示例代码中,MyData不是属性,而是字段。如果它是一个属性,则需要像这样声明:

Private memberData As Dictionary

Private Sub Class_Initialize()
    Set memberData = New Dictionary
End Sub

Public Property Get MyData() As Dictionary
    Set MyData = memberData
End Property

使用该类声明,您的示例调用代码可以正常工作:
Sub Test()
    Dim myClass As New cMyClass
    myClass.MyData("A") = 1
    Debug.Print myClass.MyData("A")
End Sub

这里显而易见的是,VBA 要么不公开公共(public)字段 Public MyData As Dictionary。作为 Property Get在类的内部 TypeInfo 中,或将其声明为字段而不是 propget混淆了 VBA 的运行时绑定(bind)器。

不幸的是,我无法访问用于检查内部 VBA TypeInfos ATM 的工具,但我可以在可用时使用更多信息更新此答案......

关于excel - 访问类中的公共(public)字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53006470/

相关文章:

Excel宏查找文本并将结果存储在新工作表中

excel - 在公式单元格上使用 Range.Replace

r - 在 VBA 函数内使用 RInterface.GetArrayToVBA 和数组

VBA - 范围 ("All cells but a few")

vba - VB.net 中的延迟

mysql - VBA代码中的SQL语法

excel - 使用带有六个条件的图标集的条件格式

返回给定版本字符串的父版本的 Excel 公式

Excel VBA 将多个工作表从一个范围保存到一个 PDF

vba - 如何在 Visio 中使用 VBA 将形状添加到组中