語法
物件。新增項目、 鑰匙、 前置、 加後
Add 方法語法具有以下物件限定符及命名參數:
| 部分 | 描述 |
|---|---|
| 物件 | 此為必要動作。 一個物件 表達式 ,能評估到「 應用到 」清單中的物件。 |
| 款 | 此為必要動作。 任何類型的 表達 式,指定要加入 集合的成員。 |
| key | 選用。 一個獨特的 字串表達式 ,指定一個鍵串,可取代位置索引,來存取集合中的成員。 |
| 以前 | 選用。 一個表示式,用來指定集合中的相對位置。 待加入的成員會被放在集合中,優先於由 before參數所識別的成員之前。 若數 值表達式, before 必須是從1到集合 Count 性質值的數字。 若字串表達式 before ,必須對應於被引用成員加入集合時指定的 鍵 。 你可以指定 一個前 置或 後 置,但不能同時指定。 |
| 後 | 選用。 一個表示式,用來指定集合中的相對位置。 待新增成員會置於集合中,位於由 after 參數識別的成員之後。 若為數值, 後 必須是從 1 到集合 Count 性質值的數字。 若字串 after 必須對應於被加入集合時指定的 鍵 。 你可以指定 一個前 置或 後 置,但不能同時指定。 |
註解
無論 before 或 after 參數是字串表達式還是數字表達式,都必須指向集合中已有的成員,否則會發生錯誤。
若指定 金鑰 與集合中現有成員的 金鑰 重複,也會出現錯誤。
範例
本範例使用 Add 方法,將包含 Public 變數 InstanceName) 的類別Class1實例 (物件Inst加入名為 MyClasses的集合。 為了了解運作原理,插入一個類別模組,並在模組層級宣告一個 (型別Public InstanceName為 Class1) 的公開變數InstanceName,用來儲存每個實例的名稱。 預設名稱保持為 Class1。 將以下程式碼複製並貼上到 Form_Load 表單模組的事件程序中。
Dim MyClasses As New Collection ' Create a Collection object.
Dim Num As Integer ' Counter for individualizing keys.
Dim Msg
Dim TheName ' Holder for names user enters.
Do
Dim Inst As New Class1 ' Create a new instance of Class1.
Num = Num + 1 ' Increment Num, then get a name.
Msg = "Please enter a name for this object." & Chr(13) _
& "Press Cancel to see names in collection."
TheName = InputBox(Msg, "Name the Collection Items")
Inst.InstanceName = TheName ' Put name in object instance.
' If user entered name, add it to the collection.
If Inst.InstanceName <> "" Then
' Add the named object to the collection.
MyClasses. Add item := Inst, key := CStr(Num)
End If
' Clear the current reference in preparation for next one.
Set Inst = Nothing
Loop Until TheName = ""
For Each x In MyClasses
MsgBox x.instancename, , "Instance Name"
Next
另請參閱
支援和意見反應
有關於 Office VBA 或這份文件的問題或意見反應嗎? 如需取得支援服務並提供意見反應的相關指導,請參閱 Office VBA 支援與意見反應。