Keyメソッド

Dictionaryオブジェクトのキーを設定します。

構文

object.Key(key) = newkey

引数:

  • Object: 必須。常にDictionaryオブジェクトの名前。

  • Key: 必須。変更するキー値。

  • Newkey: 必須。指定されたキーを置き換える新しい値。

備考

キーの変更時にキーが見つからない場合は、新しいキーが作成され、それに関連するアイテムは空のままになります。

次の例は、Keyプロパティの使用方法を示しています:

例1:

Function ChangeKey
    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"

    ' Change the key "c" to "d"
    d.Key("c") = "d"

    ' Return the associated item for the new key "d"
    ChangeKey = d.Item("d")
End Function

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

例2:

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

    ' Add some keys and items.
    d.Add "m", "Moscow"
    d.Add "n", "New York"
    d.Add "p", "Paris"

    ' Update keys
    d.Key("m") = "r"   ' Change "m" to "r"
    d.Key("n") = "s"   ' Change "n" to "s"

    ' Display all items with updated keys
    s = ""
    For Each Key In d.Keys
        s = s & "Key: " & Key & ", Item: " & d.Item(Key)
    Next

    UpdateKeysAndDisplay = s
End Function

' Usage
Dim result
result = UpdateKeysAndDisplay()
' Output: Key: r, Item: Moscow Key: s, Item: New York Key: p, Item: Paris