创建一个类模块,命名为MyCollection 
代码如下: 

 
  
  1. Option   Explicit   
  2.  
  3. Private   colKey   As   New   Collection   
  4. Private   colVal   As   New   Collection   
  5.  
  6. Public   Property   Get   Count()   As   Long   
  7.         Count   =   colKey.Count   
  8. End   Property   
  9. Public   Property   Get   RealCol()   As   Collection   
  10.         Set   RealCol   =   colVal   
  11. End   Property   
  12. Public   Sub   Add(Item,   Optional   Key,   Optional   Before,   Optional   After)   
  13.         colKey.Add   Key,   Key,   Before,   After   
  14.         colVal.Add   Item,   Key,   Before,   After   
  15. End   Sub   
  16. Public   Sub   Remove(index)   
  17.         colKey.Remove   index   
  18.         colVal.Remove   index   
  19. End   Sub   
  20.  
  21. Public   Function   getKey(index)   As   String   
  22.         getKey   =   colKey.Item(index)   
  23. End   Function   



下面我们用一些代码来测试一下collection特性是否保留,并且我们能不能通过索引号获得key 
建个窗体,放个按钮 

 
  
  1. Private   Sub   Command1_Click()   
  2. Dim   a   As   New   MyCollection   '创建实例   
  3.  
  4. '加入对象   
  5. a.Add   "test1 ",   "key1 "   
  6. a.Add   "test2 ",   "key2 "   
  7. a.Add   "test3 ",   "key3 "   
  8. a.Add   "test4 ",   "key4 "   
  9. a.Add   "test5 ",   "key5 "   
  10. Debug.Print   "用索引号方式获取对象 "   
  11. Debug.Print   a.RealCol(2)   
  12. Debug.Print   "用key获取对象 "   
  13. Debug.Print   a.RealCol( "key3 ")   
  14. Debug.Print   "remove对象 "   
  15. a.Remove   "key2 "   
  16.  
  17. Debug.Print   "for   each访问 "   
  18. Dim   b   
  19. For   Each   b   In   a.RealCol   
  20.         Debug.Print   b   
  21. Next   
  22. Debug.Print   "罗列所有key "   
  23. Dim   i   As   Integer   
  24. For   i   =   1   To   a.Count   
  25.         Debug.Print   a.getKey(i)   
  26. Next   
  27.  
  28. Debug.Print   "异常测试 "   
  29. a.Add   "asdad ",   "key5 "   '重复key   
  30. a.Remove   "key6 "           '删除不存在的对象   
  31. a.getKey   8   '获取不存在的key   
  32. End   Sub