分享

VBA字典

 先生草堂 2016-12-02

'1 什么是VBA字典?

'字典(dictionary)是一个储存数据的小仓库。共有两列。

'第一列叫key , 不允许有重复的元素。

'第二列是item,每一个key对应一个item,本列允许为重复

'Key item

'A 10

'B 20

'C 30

'Z 10


'2 即然有数组,为什么还要学字典?

'原因:提速,具体表现在

'1) A列只能装入非重复的元素,利用这个特点可以很方便的提取不重复的值

'2) 每一个key对应一个唯一的item,只要指点key的值,就可以马上返回其对应的item,利用字典可以实现快速的查找


'3 字典有什么局限?

'字典只有两列,如果要处理多列的数据,还需要通过字符串的组合和拆分来实现。

'字典调用会耗费一定时间,如果是数据量不大,字典的优势就无法体现出来。

'4 字典在哪里?如何创建字典?

'字典是由scrrun.dll链接库提供的,要调用字典有两种方法

'第一种方法:直接创建法

'Set d = CreateObject('scripting.dictionary')

'第二种方法:引用法

'工具-引用-浏览-找到scrrun.dll-确定




'1 装入数据

Sub t1()

Dim d As New Dictionary

Dim x As Integer

For x = 2 To 4

d.Add Cells(x, 1).Value, Cells(x, 2).Value

Next x

MsgBox d.Keys(1)

'Stop

End Sub

'2 读取数据

Sub t2()

Dim d

Dim arr

Dim x As Integer

Set d = CreateObject('scripting.dictionary')

For x = 2 To 4

d.Add Cells(x, 1).Value, Cells(x, 2).Value

Next x

'MsgBox d('李四')

'MsgBox d.Keys(2)

Range('d1').Resize(d.Count) = Application.Transpose(d.Keys)

Range('e1').Resize(d.Count) = Application.Transpose(d.Items)

arr = d.Items

End Sub


'3 修改数据

Sub t3()

Dim d As New Dictionary

Dim x As Integer

For x = 2 To 4

d.Add Cells(x, 1).Value, Cells(x, 2).Value

Next x

d('李四') = 78

MsgBox d('李四')

d('赵六') = 100

MsgBox d('赵六')

End Sub


'4 删除数据

Sub t4()

Dim d As New Dictionary

Dim x As Integer

For x = 2 To 4

d(Cells(x, 1).Value) = Cells(x, 2).Value

Next x

d.Remove '李四'

' MsgBox d.Exists('李四')

d.RemoveAll

MsgBox d.Count

End Sub

'区分大小写

Sub t5()

Dim d As New Dictionary

Dim x

For x = 1 To 5

d(Cells(x, 1).Value) = ''

Next x

Stop

End Sub


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多