VBA中Dictionary对象使用小结
2005-11-15
VBA中Dictionary对象使用小结
Dim dict
' 创建Dictionary
Set dict = CreateObject("Scripting.Dictionary")
' 增加项目
dict.Add "A", 300
dict.Add "B", 400
dict.Add "C", 500
' 统计项目数
n = dict.Count
' 删除项目
dict.Remove ("A")
' 判断字典中是否包含关键字
dict.exists ("B")
' 取关键字对应的值,注意在使用前需要判断是否存在key,否则dict中会多出一条记录
Value = dict.Item("B")
' 修改关键字对应的值,如不存在则创建新的项目
dict.Item("B") = 1000
dict.Item("D") = 800
' 对字典进行循环
k = dict.keys
v = dict.Items
For i = 0 To dict.Count - 1
key = k(i)
Value = v(i)
MsgBox key & Value
Next
' 删除所有项目
dict.Removeall
实例:
Sub 宏1()
Set dic = CreateObject("Scripting.Dictionary") '字典
For i = 1 To 10000
If Not i Like "4" Then
dic.Add i, "" '如果不包含“1”
End If
Next
Range("a2").Resize(dic.Count, 1) = Application.WorksheetFunction.Transpose(dic.keys) '从A2单元开始向下放置
End Sub