VBA有字典结构吗?比如key<>value array?
当前回答
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
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()。
你可以通过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的引用),以便枚举键:值对。
是的。适用于VB6, VBA (Excel), VB。网
所有其他人都已经提到了Dictionary类的scripting.runtime版本的使用。如果您无法使用此DLL,您也可以使用此版本,只需将其添加到代码中。
https://github.com/VBA-tools/VBA-Dictionary/blob/master/Dictionary.cls
它与微软的版本完全相同。
推荐文章
- 从IEnumerable<KeyValuePair<>>重新创建字典
- 如何获得字典中的键列表?
- 为什么我们使用数组而不是其他数据结构?
- 如何实现一个有序的,默认字典?
- 如何从字典中获得一个随机值?
- 在Java中从HashMap获取键
- 数组与链表
- Visual Basic 6.0与VBA的区别
- 从csv文件创建字典?
- set()是如何实现的?
- 哈希字典?
- 如何将字典列表合并为一个字典?
- .Net数据结构:ArrayList, List, HashTable, Dictionary, SortedList, SortedDictionary—速度,内存,以及何时使用每个?
- 为什么std::map被实现为红黑树?
- 在Python中创建一个初始容量的列表