Renaming an item key in a collection using VBA in Excel

I have a collection as follows:

Set NodeColl = New Collection
NodeColl.Add "Node 1", "Node 1"
NodeColl.Add "Node 2", "Node 2"
NodeColl.Add "Node 3", "Node 3"

I am wondering if there is an easy way to rename keys of custom elements without affecting other elements or collection. For example, something like NodeColl.Items ("Node 1"). Key = "Some string"

+3
source share
1 answer

No, you will need to add and remove manually;

with NodeColl
    .add .Item("Node 2"), "New Key", , "Node 2"
    .remove "Node 2"
end with

Or use Dictionaryone that allows this by adding a link to the Microsoft Scripting Runtime or;

dim NodeColl as object: Set NodeColl = createobject("Scripting.dictionary")
NodeColl.add "key for Node 1", "Node 1"
NodeColl.add "key for Node 2", "Node 2"
NodeColl.add "key for Node 3", "Node 3"

'//direct rename allowed;
NodeColl.Key("key for Node 2") = "New Key here"
+3
source

All Articles