这是一个基本类:
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/