'字典对象的方法有6个:
'Add 添加一条关键字与条目
'Keys 返回所有关键字(形成1维数组)
'Items 返回所有条目(形成1维数组)
'Exists 关键字是否存在(TRUE/FALSE)
'Remove 移除关键字与对应的条目
'RemoveAll 移除所有关键字与对应的条
注意:
字典对象的属性有4个:CompareMode属性、Count属性、Key属性、Item属性。
d.CompareMode = 0 '1则不区分大小写,0则区分大小写
字典案例:
案例:
Sub 多列合并计算()
Dim arr1()
Set d = CreateObject("scripting.dictionary")
arr = Range("a2:d" & Cells(Rows.Count, 2).End(xlUp).Row)
For i = 1 To UBound(arr)
If Not d.exists(arr(i, 1)) Then
n = n + 1
d(arr(i, 1)) = n
ReDim Preserve arr1(1 To 4, 1 To n)
arr1(1, n) = arr(i, 1)
arr1(2, n) = arr(i, 2)
arr1(3, n) = arr(i, 3)
arr1(4, n) = arr(i, 4)
Else
m = d(arr(i, 1))
arr1(2, m) = arr1(2, m) + arr(i, 2)
arr1(3, m) = arr1(3, m) + arr(i, 3)
arr1(4, m) = arr1(4, m) + arr(i, 4)
End If
Next
[f2].Resize(n, 4) = Application.Transpose(arr1)
End Sub
案例2
Sub test() '条目数组用法,进行多列在不同表格中进行匹配
Set d = CreateObject("scripting.dictionary")
With Sheets("data")
arr = .Range("a2:e" & .Cells(Rows.Count, 1).End(xlUp).Row)
End With
For i = 1 To UBound(arr)
d(arr(i, 1)) = Array(arr(i, 2), arr(i, 3), arr(i, 4), arr(i, 5))
j = d(arr(i, 1))
Next
For Each Rng In Range("a3:a" & Cells(Rows.Count, 1).End(xlUp).Row)
Rng.Offset(0, 1).Resize(1, 4) = d(Rng.Value)
Next
End Sub