脚本字典对象将信息存储在“键/项”对中。键必须是唯一的,而不是数组,但是关联的项可以重复(其唯一性由伴随键保持),并且可以是任何类型的变体或对象。
字典可以被认为是两字段内存数据库,在第一个“字段”(Key)上具有主要的唯一索引。Keys属性上的唯一索引允许非常快速的“查找”来检索Key的关联Item值。
物产
名称 | 读/写 | 类型 | 描述 |
---|---|---|---|
比较模式 | 读/写 | CompareMode常数 | 设置CompareMode只能在空字典上执行。接受的值为0(vbBinaryCompare),1(vbTextCompare),2(vbDatabaseCompare)。 |
计数 | 只读 | 无符号长整数 | 脚本字典对象中键/项对的基于一的计数。 |
键 | 读/写 | 非数组变异 | 字典中的每个唯一键。 |
项目(键) | 读/写 | 任何变体 | 默认属性。与字典中的键相关联的每个单独项目。请注意,尝试使用字典中不存在的键检索项目将隐式添加传递的键。 |
方法
名称 | 描述 |
---|---|
添加(键,项) | 将新的键和项添加到字典中。新关键字不能在字典的当前“关键字”集合中存在,但可以在许多唯一关键字之间重复一个项目。 |
存在(密钥) | 布尔测试,以确定字典中是否已存在键。 |
按键 | 返回唯一键的数组或集合。 |
物品 | 返回关联项的数组或集合。 |
删除(键) | 删除单个字典键及其关联的项。 |
移除所有 | 清除字典对象的所有键和项。 |
样例代码
'Populate, enumerate, locate and remove entries in a dictionary that was created 'with late binding Sub iterateDictionaryLate() Dim k As Variant, dict As Object Set dict = CreateObject("Scripting.Dictionary") dict.CompareMode= vbTextCompare 'non-case sensitive compare model 'populate the dictionary dict.AddKey:="Red", Item:="Balloon" dict.AddKey:="Green", Item:="Balloon" dict.AddKey:="Blue", Item:="Balloon" 'iterate through the keys For Each k In dict.Keys Debug.Printk & " - " & dict.Item(k) Next k 'locate the Item for Green Debug.Printdict.Item("Green") 'remove key/item pairs from the dictionary dict.Remove"blue" 'remove individual key/item pair by key dict.RemoveAll 'remove all remaining key/item pairs End Sub 'Populate, enumerate, locate and remove entries in a dictionary that was created 'with early binding (see Remarks) Sub iterateDictionaryEarly() Dim d As Long, k As Variant Dim dict As New Scripting.Dictionary dict.CompareMode= vbTextCompare 'non-case sensitive compare model 'populate the dictionary dict.AddKey:="Red", Item:="Balloon" dict.AddKey:="Green", Item:="Balloon" dict.AddKey:="Blue", Item:="Balloon" dict.AddKey:="White", Item:="Balloon" 'iterate through the keys For Each k In dict.Keys Debug.Printk & " - " & dict.Item(k) Next k 'iterate through the keys by the count For d = 0 Todict.Count- 1 Debug.Printdict.Keys(d) & " - " & dict.Items(d) Next d 'iterate through the keys by the boundaries of the keys collection For d = LBound(dict.Keys) To UBound(dict.Keys) Debug.Printdict.Keys(d) & " - " & dict.Items(d) Next d 'locate the Item for Green Debug.Printdict.Item("Green") 'locate the Item for the first key Debug.Printdict.Item(dict.Keys(0)) 'locate the Item for the last key Debug.Printdict.Item(dict.Keys(UBound(dict.Keys))) 'remove key/item pairs from the dictionary dict.Remove"blue" 'remove individual key/item pair by key dict.Removedict.Keys(0) 'remove first key/item by index position dict.Removedict.Keys(UBound(dict.Keys)) 'remove last key/item by index position dict.RemoveAll 'remove all remaining key/item pairs End Sub