簡單的方法是使用Dictionary而不是Collection。該字典本質上是一個關鍵字項對的關聯數組,並且支持將其鍵作爲數組進行檢索。要使用Dictionary,您需要添加對Microsoft腳本運行時的引用。使用字典的缺點是它不能像集合一樣枚舉。更復雜的解決方案將包裝集合和字典以創建一個枚舉字典,如下所述。
NB要使NewEnum在VBA中正常工作,必須按如下方式導出並手動編輯類模塊,然後重新導入。
Public Property Get NewEnum() As IUnknown
Attribute NewEnum.VB_UserMemId = -4
Set NewEnum = someKeys.[_NewEnum]
End Property
例如
Option Explicit
Private someKeys As Dictionary
Private someCols As Collection
Public Function Add(o As Object, Key As String) As Object
someKeys.Add Key, o
someCols.Add o, Key
End Function
Public Property Get Count() As Long
Count = someCols.Count
End Property
Public Property Get Item(vKey As Variant) As Object
Set Item = someCols.Item(vKey)
End Property
Public Sub Remove(vKey As Variant)
someKeys.Remove vKey
someCols.Remove vKey
End Sub
Public Property Get NewEnum() As IUnknown
Set NewEnum = someCols.[_NewEnum]
End Property
Public Property Get Keys() As Variant
Keys = someKeys.Keys
End Property
Private Sub Class_Initialize()
Set someKeys = New Dictionary
Set someCols = New Collection
End Sub
某些代碼片段會很有幫助。 – boj 2009-04-10 18:29:34