创建一个类模块,命名为MyCollection
代码如下:
- Option Explicit
- Private colKey As New Collection
- Private colVal As New Collection
- Public Property Get Count() As Long
- Count = colKey.Count
- End Property
- Public Property Get RealCol() As Collection
- Set RealCol = colVal
- End Property
- Public Sub Add(Item, Optional Key, Optional Before, Optional After)
- colKey.Add Key, Key, Before, After
- colVal.Add Item, Key, Before, After
- End Sub
- Public Sub Remove(index)
- colKey.Remove index
- colVal.Remove index
- End Sub
- Public Function getKey(index) As String
- getKey = colKey.Item(index)
- End Function
下面我们用一些代码来测试一下collection特性是否保留,并且我们能不能通过索引号获得key
建个窗体,放个按钮
- Private Sub Command1_Click()
- Dim a As New MyCollection '创建实例
- '加入对象
- a.Add "test1 ", "key1 "
- a.Add "test2 ", "key2 "
- a.Add "test3 ", "key3 "
- a.Add "test4 ", "key4 "
- a.Add "test5 ", "key5 "
- Debug.Print "用索引号方式获取对象 "
- Debug.Print a.RealCol(2)
- Debug.Print "用key获取对象 "
- Debug.Print a.RealCol( "key3 ")
- Debug.Print "remove对象 "
- a.Remove "key2 "
- Debug.Print "for each访问 "
- Dim b
- For Each b In a.RealCol
- Debug.Print b
- Next
- Debug.Print "罗列所有key "
- Dim i As Integer
- For i = 1 To a.Count
- Debug.Print a.getKey(i)
- Next
- Debug.Print "异常测试 "
- a.Add "asdad ", "key5 " '重复key
- a.Remove "key6 " '删除不存在的对象
- a.getKey 8 '获取不存在的key
- End Sub
转载于:https://blog.51cto.com/vbcodeworkers/726771