VBA有字典结构吗?比如key<>value array?


当前回答

是的。适用于VB6, VBA (Excel), VB。网

其他回答

是的。适用于VB6, VBA (Excel), VB。网

脚本运行时字典似乎有一个bug,可能会在高级阶段破坏您的设计。

如果字典值是数组,则不能通过对字典的引用更新数组中包含的元素的值。

VBA有收集对象:

    Dim c As Collection
    Set c = New Collection
    c.Add "Data1", "Key1"
    c.Add "Data2", "Key2"
    c.Add "Data3", "Key3"
    'Insert data via key into cell A1
    Range("A1").Value = c.Item("Key2")

Collection对象使用散列执行基于键的查找,因此速度很快。


你可以使用Contains()函数来检查一个特定的集合是否包含键:

Public Function Contains(col As Collection, key As Variant) As Boolean
    On Error Resume Next
    col(key) ' Just try it. If it fails, Err.Number will be nonzero.
    Contains = (Err.Number = 0)
    Err.Clear
End Function

编辑2015年6月24日:短包含()感谢@TWiStErRob。

2015年9月25日编辑:感谢@scipilot,添加了Err.Clear()。

如果由于任何原因,您不能或不想在Excel中安装额外的功能,您也可以使用数组,至少对于简单的问题。 你输入这个国家的名字,函数就会返回它的资本。

Sub arrays()
Dim WhatIsCapital As String, Country As Array, Capital As Array, Answer As String

WhatIsCapital = "Sweden"

Country = Array("UK", "Sweden", "Germany", "France")
Capital = Array("London", "Stockholm", "Berlin", "Paris")

For i = 0 To 10
    If WhatIsCapital = Country(i) Then Answer = Capital(i)
Next i

Debug.Print Answer

End Sub

Yes.

设置对MS脚本运行时('Microsoft脚本运行时')的引用。根据@regjo的评论,转到工具->参考,并勾选“微软脚本运行时”。

使用下面的代码创建一个字典实例:

Set dict = CreateObject("Scripting.Dictionary")

or

Dim dict As New Scripting.Dictionary 

使用示例:

If Not dict.Exists(key) Then 
    dict.Add key, value
End If 

当你用完字典时,别忘了把它设置为Nothing。

Set dict = Nothing