网站首页 > 技术文章 正文
字典是一门编程语言里面很重要的一个数据结构,应用很普遍,务必好好掌握。VBA字典使用起来比较简单。
导入字典引用库
VBA里面使用字典,建议提前导入VBA脚本运行时。
导入方式,在VBA编辑器的菜单里面找到 工具 -> 引用,然后找到Microsoft Scripting Runtime,勾选该选项。
创建字典
三种方式任选其一都可以。
Sub createDictionary()
' 方式1
Dim dict1 As New Dictionary
' 方式2
Dim dict2 As Dictionary
Set dict2 = New Dictionary
' 方式3
Dim dict3 As Dictionary
Set dict3 = CreateObject("Scripting.Dictionary")
End Sub
添加元素方法
可以通过Add向字典添加元素,也可以直接用下标添加元素。值得注意的是,如果用Add添加值,添加的key如果存在,则会报错。直接用下标这则不会。
Sub testAddElementToDict()
Dim dict As New Dictionary
dict.Add "name", "Excel VBA"
' dict.Add "name", "name已经存在,如果通过Add方法添加则会报错,所以注释掉该行"
dict("app") = "Visual Basic Application"
dict("app") = "下标赋值写法,不会报错"
End Sub
判断元素是否存在
VBA字典提供了Exists方法判断是否包含某个元素,返回布尔值。True表示存在该元素,False表示不存在。
Sub testDictionaryExists()
Dim dict As New Dictionary
dict("app") = "Visual Basic Application"
Debug.Print dict.Exists("app") ' True
Debug.Print dict.Exists("不存在的key") ' False
End Sub
删除元素
VBA字典提供了删除某个元素的方法Remove,和删除所有元素的方法RemoveAll。
Sub testDictionaryRemove()
Dim dict As New Dictionary
dict("key") = "value"
dict("name") = "vba"
dict.Remove "key"
Debug.Print dict("key") ' 元素被删除,打印内容为空
dict.RemoveAll
Debug.Print dict.Count ' 返回0,元素被清空
End Sub
获取所有的键和值
Sub testDictKeyAndValues()
Dim dict As New Dictionary
dict("key") = "value"
dict("any-key") = "any-value"
For Each Key In dict.Keys
Debug.Print Key ' 分别输出key, any-key
Next
For Each value In dict.Items
Debug.Print value ' 分别输出value,any-value
Next
End Sub
获取元素个数
VBA字典提供Count方法,返回字典包含元素总个数。
Sub testDictCount()
Dim dict As New Dictionary
dict("key") = "value"
Debug.Print dict.Count ' 返回1
End Sub
遍历字典
VBA字典可以通过遍历key,然后分别拿到对应的值。
Sub testDictIterate()
Dim dict As New Dictionary
dict("key1") = "value1"
dict("key2") = "value2"
For Each Key In dict.Keys
Debug.Print Key & "->" & dict(Key)
Next
End Sub
- 上一篇: EXCEL表格VBA中字典的写入技巧
- 下一篇: Python合并2个字典成1个新字典的9种方法
猜你喜欢
- 2024-12-07 C# “字典” Dictionary 的简单用法:轻松管理键值对
- 2024-12-07 以专业方式在 Python 中进行调试:将 print() 替换为 ic()
- 2024-12-07 python基础——字典详解
- 2024-12-07 Python教程-字典
- 2024-12-07 「教程10」国产编程语言Cbrother 字典
- 2024-12-07 Python数据类型——字典
- 2024-12-07 Python字典和集合
- 2024-12-07 128.C# Dictionary字典
- 2024-12-07 pthon每天学习一点点(字典推导式)
- 2024-12-07 Python字典:定义、基本操作与方法详解
- 最近发表
- 标签列表
-
- cmd/c (90)
- c++中::是什么意思 (84)
- 标签用于 (71)
- 主键只能有一个吗 (77)
- c#console.writeline不显示 (95)
- pythoncase语句 (88)
- es6includes (74)
- sqlset (76)
- apt-getinstall-y (100)
- node_modules怎么生成 (87)
- chromepost (71)
- flexdirection (73)
- c++int转char (80)
- mysqlany_value (79)
- static函数和普通函数 (84)
- el-date-picker开始日期早于结束日期 (76)
- js判断是否是json字符串 (75)
- c语言min函数头文件 (77)
- asynccallback (87)
- localstorage.removeitem (74)
- vector线程安全吗 (70)
- java (73)
- js数组插入 (83)
- mac安装java (72)
- 无效的列索引 (74)