VBA字典高效数据处理技巧分享
创作时间:
作者:
@小白创作中心
VBA字典高效数据处理技巧分享
Sub DictionaryExample()
' 创建字典对象
Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")
' 添加键值对
dict.Add "A", 100
dict.Add "B", 200
dict.Add "C", 300
' 检查键是否存在
If dict.Exists("B") Then
MsgBox "Key B exists. Value: " & dict("B")
End If
' 修改值
dict("B") = 250
' 删除键
dict.Remove "C"
' 遍历字典
Dim key As Variant
For Each key In dict.Keys
Debug.Print "Key: " & key & ", Value: " & dict(key)
Next
' 统计元素数量
MsgBox "Total items: " & dict.Count
' 清空字典
dict.RemoveAll
End Sub
Sub DictionaryAdvancedUsage()
' 创建字典对象
Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")
' 数据去重示例
Dim arr As Variant
arr = Array("apple", "banana", "apple", "orange", "banana", "grape")
Dim i As Long
For i = LBound(arr) To UBound(arr)
dict(arr(i)) = 1 ' 任意值,关键是键的唯一性
Next
' 去重后的数组
Dim uniqueArr() As String
ReDim uniqueArr(dict.Count - 1)
i = 0
For Each key In dict.Keys
uniqueArr(i) = key
i = i + 1
Next
' 输出去重后的数组
For i = LBound(uniqueArr) To UBound(uniqueArr)
Debug.Print uniqueArr(i)
Next
' 数据查找示例
Dim searchKey As String
searchKey = "banana"
If dict.Exists(searchKey) Then
MsgBox "Found: " & searchKey
Else
MsgBox "Not found: " & searchKey
End If
' 字典排序示例
Dim sortedKeys() As Variant
sortedKeys = dict.Keys
Call QuickSort(sortedKeys, LBound(sortedKeys), UBound(sortedKeys))
' 输出排序后的键值对
For i = LBound(sortedKeys) To UBound(sortedKeys)
Debug.Print "Sorted Key: " & sortedKeys(i) & ", Value: " & dict(sortedKeys(i))
Next
' 多字典操作示例
Dim dict2 As Object
Set dict2 = CreateObject("Scripting.Dictionary")
dict2.Add "D", 400
dict2.Add "E", 500
' 合并字典
Dim combinedDict As Object
Set combinedDict = CreateObject("Scripting.Dictionary")
For Each key In dict.Keys
combinedDict.Add key, dict(key)
Next
For Each key In dict2.Keys
combinedDict.Add key, dict2(key)
Next
' 输出合并后的字典
For Each key In combinedDict.Keys
Debug.Print "Combined Key: " & key & ", Value: " & combinedDict(key)
Next
End Sub
' 快速排序算法用于排序数组
Sub QuickSort(arr() As Variant, first As Long, last As Long)
Dim pivot As Variant
Dim temp As Variant
Dim i As Long
Dim j As Long
If first < last Then
pivot = arr((first + last) \ 2)
i = first - 1
j = last + 1
Do
Do
i = i + 1
Loop While arr(i) < pivot
Do
j = j - 1
Loop While arr(j) > pivot
If i <= j Then
temp = arr(i)
arr(i) = arr(j)
arr(j) = temp
End If
Loop While i <= j
QuickSort arr, first, j
QuickSort arr, j + 1, last
End If
End Sub
热门推荐
如何排痰?六种科学方法助你轻松应对
程序初学者推荐学习的三种热门编程语言
实验大鼠和小鼠的区别:选择合适的实验动物,助力科研进展
国家历史文化名城:从何而来,如何更新?
师德师风与教师绩效考核
秧歌+杂耍,宁武非遗文化活动展演走进忻州古城
忻州古城:“保护+传承” 让非遗焕发新生
入住久了才明白,卧室里最实用的设计是这7个,少一个都可惜
泡沫保温箱运输途中注意哪些
英语七选五答题技巧
奥鲁制度的发展与演变
巧用“她力量”:湖北浠水县陆家河村妇女议事会创新基层治理实践
深瞳丨微生物耐药性:人类健康的重大威胁
自制低卡路里美味巧克力
塑料电镀工艺:技术挑战与创新突破
孔子:当老师,我是认真的
岳麓高新区:一条道路聚起一条“产业动脉”
事实证明:父母的层次,就是孩子的命运
保质期对食物浪费的影响:神话与现实
Excel价格表格制作教程:从入门到精通
淋巴细胞绝对值偏高如何应对
当“安宫牛黄丸”遇上“苏合香丸”——谁才是中风急救用药?
如何预防血栓?这些小习惯帮你远离危险
聚宝之盆——新疆文物珍品展
网络运维的入门知识有哪些
香港中文大学于君教授:肠道菌群帮助改善癌症免疫治疗
基金要怎么买才能把风险降到最低?全面解析与实战指南
解码中国高铁发展:从技术引进到自主创新的突破
没钱怎么办:如何通过合法途径实现财富积累与增值
如何避免熬夜带来的负面影响