Error This key is already associated with an eleme

2020-02-28 05:22发布

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

3条回答
太酷不给撩
2楼-- · 2020-02-28 05:59

You can also add some very basic error handling, if all you wish to do is skip over the record throwing this error. I simply inserted the below line immediately above the one which was generating this error for me, and now it happily moves along, ignoring duplicate keys which used to throw this error.

On Error Resume Next
查看更多
孤傲高冷的网名
3楼-- · 2020-02-28 06:04

I was getting the same error message: "Error This key is already associated with an element of this collection". In my case, the problem was that I had this:

'assign values to properties
Property Let EmployeeName(Valor As String)
    m_employeename = Valor
End Property
Property Let EmployeeID(Valor As String)
    m_employeename = Valor
End Property

I was supposed to have this:

'assign values to properties
Property Let EmployeeName(Valor As String)
    m_employeename = Valor
End Property
Property Let EmployeeID(Valor As String)
    m_employeeid = Valor
End Property

Maybe you just have to double check your "Property Let" code to see if you are using appropriate names for those variables that are private in your class.

查看更多
疯言疯语
4楼-- · 2020-02-28 06:10

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
查看更多
登录 后发表回答