Excel VBA字典基础概念详解3
- 2026-11-05 05:07:40
Excel VBA字典基础概念详解3
三种数据结构对比表:
| 键类型 | |||
| 值类型 | |||
| 键唯一性 | |||
| 查找速度 | |||
| 检查存在 | |||
| 排序 | |||
| 添加元素 | |||
| 内存效率 |
字典在数据处理中的优势比较
' 示例:字典在数据处理中的实际应用Sub DictionaryAdvantagesDemo()Dim dict As ObjectSet dict = CreateObject("Scripting.Dictionary")' 优势1:快速去重Debug.Print "=== 优势1:快速去重 ==="Dim data() As Variantdata = Array("Apple", "Banana", "Apple", _"Orange", "Banana", "Apple")' 传统方法:使用循环和集合Dim uniqueFruitsColl As New CollectionOn Error Resume NextFor i = 0 To UBound(data)uniqueFruitsColl.Add data(i), CStr(data(i))Next iOn Error GoTo 0Debug.Print "集合去重结果: " & uniqueFruitsColl.Count & " 个唯一水果"' 字典方法:更直观For i = 0 To UBound(data)dict(data(i)) = 1' 值不重要,我们只关心键Next iDebug.Print "字典去重结果: " & dict.Count & " 个唯一水果"' 优势2:快速统计频率Debug.Print vbNewLine & "=== 优势2:快速统计频率 ==="dict.RemoveAll ' 清空字典' 统计每个水果出现的次数For i = 0 To UBound(data)If dict.Exists(data(i)) Thendict(data(i)) = dict(data(i)) + 1Elsedict(data(i)) = 1End IfNext i' 输出统计结果Dim key As VariantFor Each key In dict.KeysDebug.Print key & ": 出现 " & dict(key) & " 次"Next key' 优势3:快速查找和分组Debug.Print vbNewLine & "=== 优势3:快速查找和分组 ==="dict.RemoveAll' 模拟销售数据 Dim salesData As VariantsalesData = Array(Array("Apple", 10),Array("Banana", 5), _Array("Apple", 8),Array("Orange", 12),Array("Banana", 7), _Array("Apple", 6))' 按产品分组汇总销量For i = 0 To UBound(salesData)Dim product As StringDim quantity As Longproduct = salesData(i)(0)quantity = salesData(i)(1)If dict.Exists(product) Thendict(product) = dict(product) + quantityElsedict(product) = quantityEnd IfNext iDebug.Print "产品销量汇总:"For Each key In dict.KeysDebug.Print key & ": 总销量 " & dict(key)Next keyEnd Sub
本文来自网友投稿或网络内容,如有侵犯您的权益请联系我们删除,联系邮箱:wyl860211@qq.com 。