Item 方法

設定或傳回 Dictionary 物件中指定索引鍵的項目。對於集合,會根據指定索引鍵傳回項目。讀取/寫入。

語法

object.Item(key)[ = newitem]

引數:

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

  • Key必要。與要擷取或新增之項目相關聯的索引鍵。

  • Newitem選擇性。僅用於 Dictionary 物件;不適用於集合。如有提供,則 newitem 是與指定索引鍵相關聯的新值。

備註

如果變更項目時找不到索引鍵,則會使用指定的 newitem 建立新的索引鍵。如果嘗試傳回現有項目時找不到索引鍵,則會建立新的索引鍵,並將其對應的項目保留空白。

下列範例說明 Item 特性的用法。

範例 1:

Function GetItem
    Dim d   ' Create some variables.
    Set d = CreateObject("Scripting.Dictionary")

    ' Add some keys and items.
    d.Add "a", "Athens"
    d.Add "b", "Belgrade"
    d.Add "c", "Cairo"

    ' Get the item for key "c".
    GetItem = d.Item("c")
End Function

' Usage
Dim result
result = GetItem()
' Output: Cairo

範例 2:

Function SetExistingItem
    Dim d   ' Create some variables.
    Set d = CreateObject("Scripting.Dictionary")

    ' Add some keys and items.
    d.Add "x", "Xenon"
    d.Add "y", "Yttrium"
    d.Add "z", "Zirconium"

    ' Set a new item for key "y".
    d.Item("y") = "Yosemite"

    ' Get the item for key "y".
    SetExistingItem = d.Item("y")
End Function

' Usage
Dim result
result = SetExistingItem()
' Output: Yosemite

範例 3:

Function AddNewItem
    Dim d   ' Create some variables.
    Set d = CreateObject("Scripting.Dictionary")

    ' Add some keys and items.
    d.Add "m", "Moscow"
    d.Add "n", "New York"
    d.Add "t", "Tokyo"

    ' Attempt to get an item for a non-existing key and set a new item.
    d.Item("p") = "Paris"

    ' Get the item for the newly added key "p".
    AddNewItem = d.Item("p")
End Function

' Usage
Dim result
result = AddNewItem()
' Output: Paris