' 示例:字典在数据处理中的实际应用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)) Then dict(data(i)) = dict(data(i)) + 1 Else dict(data(i)) = 1 End IfNext i' 输出统计结果Dim key As VariantFor Each key In dict.Keys Debug.Print key & ": 出现 " & dict(key) & " 次" Next key' 优势3:快速查找和分组 Debug.Print vbNewLine & "=== 优势3:快速查找和分组 ===" dict.RemoveAll' 模拟销售数据 Dim salesData As Variant salesData = 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 String Dim quantity As Long product = salesData(i)(0) quantity = salesData(i)(1) If dict.Exists(product) Then dict(product) = dict(product) + quantity Else dict(product) = quantity End If Next i Debug.Print "产品销量汇总:" For Each key In dict.Keys Debug.Print key & ": 总销量 " & dict(key) Next keyEnd Sub