Add 方法

將索引鍵和項目組新增至 Dictionary 物件。

語法

object.Add(key, item)

引數:

  • Object必要。一律是 Dictionary 物件的名稱。

  • Key必要。與正在新增之項目關聯的索引鍵。

  • Item必要。與正在新增之索引鍵關聯的項目。

備註

如果金鑰已經存在,就會發生錯誤。

下列範例說明 Add 方法的用法。

範例 1:

Dim d   ' Create a variable.
Set d = CreateObject("Scripting.Dictionary")

' Add some keys and items.
d.Add "a", "Athens"
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
' Output: Dictionary Object Contains Keys: a,b,c Items: Athens,Belgrade,Cairo

範例 2:

Dim d
Set d = CreateObject("Scripting.Dictionary")

' Add some keys and items.
If Not d.Exists("a") Then
    d.Add "a", "Athens"
End If

If Not d.Exists("b") Then
    d.Add "b", "Belgrade"
End If

If Not d.Exists("c") Then
    d.Add "c", "Cairo"
End If
' Output: Dictionary Object Contains Keys: a,b,c Items: Athens,Belgrade,Cairo

範例 3:

Dim d
Set d = CreateObject("Scripting.Dictionary")

Dim arrKeys, arrItems
arrKeys = Array("a", "b", "c")
arrItems = Array("Athens", "Belgrade", "Cairo")

For i = 0 To UBound(arrKeys)
    d.Add arrKeys(i), arrItems(i)
Next
' Output: Dictionary Object Contains Keys: a,b,c Items: Athens,Belgrade,Cairo

Note:

不支援在 Dictionary Add 呼叫中直接使用新物件建立。

例如:

Set d = CreateObject("Scripting.Dictionary")

'Create an object first and then add it to the dictionary.

Set obj = new class

d.add key, obj 提供以上支援。