我在名为 ProcessBook 的应用程序中使用 VBA,并且希望在字典中存储一些静态信息。
我试图干净地初始化这个字典,而不需要调用单独的过程,但我尝试的方法似乎都不是预期的。
这是我迄今为止尝试过的:
Dim myDict As New Dictionary(Of String, String) (("key1", "item1"), ("key2", "item2"))
Dim myDict As Variant
Set myDict = New Dictionary( ("key1", "item1"), ("key2", "item2") )
基本上是一堆涉及类似形式的猜测。
到目前为止,我能做的最好的事情是:
With myDict
.add "key1", "item1"
.add "key2", "item2"
End With
但是当它不在例行公事范围内时,这会让我大吃一惊,我想避免这种情况。
我相信 (Of type, type) From { } 语法超出了 VBA 6.5
有人知道在 VBA 6.5 中初始化 scripting.dictionary 的一些干净方法吗?
最佳答案
6.5 大概是指 VBA?如果是这样,则无法在例程之外操作/初始化对象实例。
唯一的方法是将其封装在一个类(cDict
)中并使用构造函数:
Private mDict As Scripting.Dictionary
Private Sub Class_Initialize()
Set mDict = New Scripting.Dictionary
With mDict
.Add "key1", "item1"
.Add "key2", "item2"
End With
End Sub
Public Property Get Dict() As Scripting.Dictionary
Set Dict = mDict
End Property
然后在客户端模块中;
Private Dict As New cDict
Sub foo()
MsgBox Dict.Dict.Item("key1")
Dict.Dict.Add "key3", "item3"
MsgBox Dict.Dict.Item("key3")
End Sub
(类型
与 VB.Net 泛型相关)
关于vba - Scripting.Dictionary 的干净初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21025756/