Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error This key is already associated with an element of this collection

Tags:

excel

vba

I am working on vba macros. I was trying to use a dictionary. But it is giving error 457 with debugger pointing to toprow.Add ActiveCell.value, val. Can anyone please tell the issue? I even used Cstr(activecell.value), Cstr(val) as mentioned in one of the answer on similar issue.

Dim toprow As New Dictionary, Dictkey As Variant
Dim val As String

Range("A1").Activate 
i = 0
Do Until i = ColLen
    val = Chr(65 + i)
    toprow.Add ActiveCell.value, val
    i = i + 1
    ActiveCell.Offset(0, 1).Activate
Loop
like image 778
Aakash Goyal Avatar asked Feb 05 '14 09:02

Aakash Goyal


1 Answers

Adding keys with dictionaries is only possible when a key does not already exist. Accidentally you could entered the key before, or you are watching the key with the debug watcher, creating the key instanteneously. (= If you watch a certain key in a dictionary it gets created if it doesn't already exist).

You have to

  • make sure you are not watching the key with the debugger
  • create unique entries by testing on d.Exists(keyname) and then use the d.Add keyname, value method
  • alternatively you can default to overwrite existing keys by using d.Item(keyname) = value
like image 134
AutomatedChaos Avatar answered Nov 20 '22 20:11

AutomatedChaos