字典应用是一个十分高效的方法,可以成对数据处理,像一把利器,各种应用能力体现。
下面重点介绍创建和应用字典的方法。
创建字典很简单只需要一行代码,如下所示:
Set dic = CreateObject("Scripting.Dictionary")
没技巧可言,记住就行了。
需要了解一下字典的几个属性和方法,如下图所示:
下面用一个实例来,具体进行演示一下,如何进行字典应用。
示例:
本示例分别把两列赋值给一个字典对象,然后将字典值添加到ListBox列表框中,按钮可实现添加字典、删除字典和删除字典值的功能,实现过程如下。
新建字典代码:
Public dic As Object
Private Sub CommandButton1_Click()
Dim arr1, arr2, i As Integer
arr1 = ActiveSheet.Range("B3:B12")
arr2 = ActiveSheet.Range("C3:C12")
Set dic = CreateObject("Scripting.Dictionary")
For i = 1 To UBound(arr1) - 1
dic.Add arr1(i, 1), arr2(i, 1)
Next i
Me.ListBox1.Clear
For i = 1 To dic.Count
With Me.ListBox1
.AddItem
.List(i - 1, 0) = arr1(i, 1) '
.List(i - 1, 1) = dic.Item(i)
End With
Next i
'MsgBox Join(dic.items)
'MsgBox Join(dic.keys)
End Sub
删除字典
Private Sub CommandButton2_Click()
If Not VBA.IsObject(dic) Then Exit Sub
If dic Is Nothing Then Exit Sub
dic.RemoveAll
Me.ListBox1.Clear
MsgBox "字典已经删除!"
End Sub
删除单项字典值
Private Sub CommandButton3_Click()
Dim dStr As String
If Not VBA.IsObject(dic) Then Exit Sub
If dic Is Nothing Then Exit Sub
If Me.ListBox1.ListIndex < 0 Then Exit Sub
If Me.ListBox1.Value = Null Then Exit Sub
If dic.exists(VBA.CInt(Me.ListBox1.Value)) Then '如果存在键
dStr = dic.Item(VBA.CInt(Me.ListBox1.Value))
dic.Remove VBA.CInt(Me.ListBox1.Value)
Me.ListBox1.RemoveItem (Me.ListBox1.ListIndex)
MsgBox "你已经删除" & dStr, vbInformation, "提示"
End If
End Sub
代码相对复杂,主要是对一些可能是错误进行了判断筛选,不做过多讨论。
重点说一下字典的几个方法:
添加键和值:Add key,item
删除字典:RemoveAll
删除某个键值:Remove key
搜索键是否存在:exists
返回Key数组:Keys
返回Item数组:Items
返回字典数:Count
返回或设置Item:Item(Key)=[newItem]
设置Key:Key(key)=NewKey
对照程序进行查看,使用方法,可进一步掌握字典方法和属性分别代表的内容。
总之,字典是成双成对的出现,一个Key对应着一个Item值,如果Key没有了,也就没有值了。可以理解为量子纠缠的理论一样,一一对应,不可以分开。
联系客服