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 支持这种做法。