一、什么是字典对象
1.1 字典的基本概念和特点
字典(Dictionary)对象是VBA中一个强大的数据结构,它存储键-值对(Key-Value Pair),类似于现实生活中的字典:
主要特点:
快速查找:通过键可以快速定位对应的值
键必须唯一:相同的键只能存在一次
动态大小:无需预先声明大小,可动态添加/删除
支持多种数据类型:键和值可以是各种数据类型
' 示例1:创建字典并添加数据
Sub DictionaryBasicDemo()
' 创建字典对象
Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")
' 添加键值对
dict.Add "Apple", 3.5 ' 键: Apple, 值: 3.5(价格)
dict.Add "Banana", 2.8
dict.Add "Orange", 4.2
' 访问值
Debug.Print "Apple的价格: " & dict("Apple") ' 输出: 3.5
' 检查键是否存在
If dict.Exists("Apple") Then
Debug.Print "Apple在字典中"
End If
' 遍历字典
Dim key As Variant
For Each key In dict.Keys
Debug.Print key & ": " & dict(key)
Next key
' 清理
Set dict = Nothing
End Sub