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


当前回答

你可以通过System.Collections.HashTable访问一个非本地哈希表。

哈希表

表示基于的键/值对的集合 键的哈希码。

不确定你会想要使用这个脚本。字典,但在这里添加为完整起见。你可以回顾这些方法,如果有一些感兴趣的,例如克隆,CopyTo

例子:

Option Explicit

Public Sub UsingHashTable()

    Dim h As Object
    Set h = CreateObject("System.Collections.HashTable")
   
    h.Add "A", 1
    ' h.Add "A", 1  ''<< Will throw duplicate key error
    h.Add "B", 2
    h("B") = 2
      
    Dim keys As mscorlib.IEnumerable 'Need to cast in order to enumerate  'https://stackoverflow.com/a/56705428/6241235
    
    Set keys = h.keys
    
    Dim k As Variant
    
    For Each k In keys
        Debug.Print k, h(k)                      'outputs the key and its associated value
    Next
    
End Sub

@MathieuGuindon的回答给出了很多关于HashTable的细节,以及为什么需要使用mscorlib。IEnumerable(早期绑定到mscorlib的引用),以便枚举键:值对。


其他回答

VBA可以使用Scripting.Runtime的字典结构。

它的实现实际上是一个很奇特的——只要执行myDict(x) = y,它就会检查字典中是否有键x,如果没有,它甚至会创建一个键x。如果它在那里,它就利用它。

而且它不会对这个“幕后”执行的额外步骤“大喊大叫”或“抱怨”。当然,您可以显式地使用Dictionary.Exists(key)检查键是否存在。因此,这5行:

If myDict.exists("B") Then
    myDict("B") = myDict("B") + i * 3
Else
    myDict.Add "B", i * 3
End If

myDict("B") = myDict("B") + i * 3。看看吧:

Sub TestMe()

    Dim myDict As Object, i As Long, myKey As Variant
    Set myDict = CreateObject("Scripting.Dictionary")
    
    For i = 1 To 3
        Debug.Print myDict.Exists("A")
        myDict("A") = myDict("A") + i
        myDict("B") = myDict("B") + 5
    Next i
    
    For Each myKey In myDict.keys
        Debug.Print myKey; myDict(myKey)
    Next myKey

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 

如果由于任何原因,您不能或不想在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

VBA没有字典的内部实现,但是在VBA中你仍然可以使用MS Scripting Runtime Library中的字典对象。

Dim d
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "aaa"
d.Add "b", "bbb"
d.Add "c", "ccc"

If d.Exists("c") Then
    MsgBox d("c")
End If

所有其他人都已经提到了Dictionary类的scripting.runtime版本的使用。如果您无法使用此DLL,您也可以使用此版本,只需将其添加到代码中。

https://github.com/VBA-tools/VBA-Dictionary/blob/master/Dictionary.cls

它与微软的版本完全相同。