VBA 属性和方法
示例
脚本字典对象将信息存储在“键/项”对中。键必须是唯一的,而不是数组,但是关联的项可以重复(其唯一性由伴随键保持),并且可以是任何类型的变体或对象。
字典可以被认为是两字段内存数据库,在第一个“字段”(Key)上具有主要的唯一索引。Keys属性上的唯一索引允许非常快速的“查找”来检索Key的关联Item值。
物产
方法
样例代码
'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