优秀的编程知识分享平台

网站首页 > 技术文章 正文

VBA字典操作方法

nanyue 2024-12-07 15:45:41 技术文章 8 ℃

字典是一门编程语言里面很重要的一个数据结构,应用很普遍,务必好好掌握。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
最近发表
标签列表