創建集合
Dim c As New Collection
集合常用屬性和方法
添加
- 語法:Collection.Add (item,key,before,after)
- item:添加到集合的項
- key:鍵,唯一性的,add方法如果重複報錯,注意的是key必須是
文本
- before:插入位置,在哪個位置前面,可以是索引(數字1到Collection.count之間的數字),也可以是鍵
- after:插入位置,在哪個位置後面,可以是索引(數字1到Collection.count之間的數字),也可以是鍵
集合大小
- 語法:Collection.Count
- 返回 Long(長整型),其中包含集合中的對象數。 只讀
Sub test()
Dim c As New Collection
'1是項,s是鍵,注意的是鍵是不可以重複的
c.Add 1, "s"
c.Add 2, "x"
Debug.Print c.Count
End Sub
上面結果:顯示2
,集合的數量是從1開始計算的
讀取集合特定元素內容
- Collection.item方法
- 裏面可以寫索引(1到Collection.Count之間的數字),或者鍵
Sub test()
Dim c As New Collection
c.Add 1, "s"
c.Add 2, "x"
Debug.Print "鍵的item方法:" & c.Item("s")
Debug.Print "鍵的直接方法:" & c("s")
Debug.Print "索引的item方法:" & c.Item(1)
Debug.Print "索引的直接方法:" & c(1)
End Sub
顯示結果
鍵的item方法:1
鍵的直接方法:1
索引的item方法:1
索引的直接方法:1
集合刪除辦法
- 對象中刪除成員:Collection.remove
- 因爲集合中沒辦全部刪除,只能一個一個刪除,所以,刪除的時候注意,如果要刪除多個,要倒序刪除
Sub test()
Dim c As New Collection, i As Long
c.Add 1, "s"
c.Add 2, "x"
c.Add 3, "z"
c.Add 4, "y"
c.Add 5, "q"
c.Add 6, "h"
For i = c.Count To 1 Step -1
c.Remove (i)
Next
End Sub
雖然沒有整個刪除的辦法,但是這裏可以用一個取巧的辦法
Set c = Nothing
或者Set c = New Collection
,直接清空了重新玩
Sub test()
Dim c As New Collection, i As Long
c.Add 1, "s"
c.Add 2, "x"
c.Add 3, "z"
c.Add 4, "y"
c.Add 5, "q"
c.Add 6, "h"
'Set c = Nothing '清空了集合,重新開始了
set c = new Collection
c.Add 1, "s"
End Sub
學習來源:Excelhome論壇裙子老師的一個集合帖子,感謝大佬無私分享