原日期: 2017-12-14
Sub dictest()
' 字典简介
' 字典对象相当于一种联合数组,它是由具有唯一性的关键字(Key)和它的项(Item)联合组成
' VBA字典有6个方法Add , Keys, Items, Exists, Remove, RemoveAll
' VBA字典有4个属性Count , Key, Item, CompareMode
' 创建字典"d"
Dim d As Object
Set d = CreateObject("Scripting.Dictionary")
' 添加
d.Add "a", "example1"
d.Add "b", 9
'd.Add "b", 7 'add重复key会报错
d("b") = 7 '这样会直接覆盖,不会报错
'd.Item("b") = 7 '与上者相同
d("c") = "example2"
'通常使用Sting文本字符串作为字典key关键词,也可以使用数字、数值作为key
'速度:纯数字>纯文本字符>>>文本/数值混合型
' 输出
Cells(1, 1) = d("a")
'Cells(1, 1) = d.Item("a") '与上者相同
Cells(1, 2) = d("b")
Cells(1, 3) = d("c")
' 字典成员个数
Cells(1, 4) = d.Count
'移除
d.Remove ("b")
'd.RemoveAll '移除所有
' key是否存在
Cells(2, 1) = d.Exists("b")
d.Add "b", 7
Cells(2, 2) = d.Exists("b")
' 替换key
d.Key("a") = "e"
'所有key所在的数组和所有item所在的数组
d_keys = d.Keys
Cells(3, 1) = d_keys(0)
Cells(3, 2) = d_keys(1)
d_items = d.Items
Cells(4, 1) = d_items(0)
Cells(4, 2) = d_items(1)
'更改字符串关键字比较时所使用的比较模式
'd.CompareMode = 0(二进制)/1(文本)/2(数据库)
End Sub
'获取不重复的name和每个name的income总计
Sub dictest1()
Dim data_count As Long
data_count = 188
Dim data_name, data_income, i
data_name = Application.Transpose(Worksheets("数据").Cells(2, 1).Resize(data_count, 1))
data_income = Application.Transpose(Worksheets("数据").Cells(2, 2).Resize(data_count, 1))
Dim d1 As Object
Set d1 = CreateObject("Scripting.Dictionary")
For i = 1 To data_count
If d1.exists(data_name(i)) Then
d1.Item(data_name(i)) = d1.Item(data_name(i)) + data_income(i)
Else
d1.Item(data_name(i)) = data_income(i)
End If
Next
d1_keys = d1.keys
d1_items = d1.items
Worksheets("结果").Cells(2, 1).Resize(UBound(d1_keys) + 1, 1) = Application.Transpose(d1_keys)
Worksheets("结果").Cells(2, 2).Resize(UBound(d1_items) + 1, 1) = Application.Transpose(d1_items)
End Sub