VB6 Dictionary This key is already associated with an element of this collection

冷暖自知 提交于 2019-12-11 09:18:11

问题


This may sound a little weird but here it goes:

My form iterated through each customer (+-10 000) and opened a recordset to get the last visit. Since it is poorly optimized I decided to do a single query, and I need to store it for easy access.

I decided to take a dictionary because, unlike arrays, I will be able to search with a key string (the client number) and get my item (string: client's last visit).

Dim dict As Dictionary
Set dict = CreateObject("Scripting.Dictionary")


dict.RemoveAll
dict.CompareMode = TextCompare    ' BinaryCompare does not change anything
rsLastVisits.Open "SELECT CUST_NO, MAX(DATE) AS LAST FROM [...] GROUP BY CUST_NO", DBHandle, adOpenDynamic, adLockOptimistic
Do While Not rsLastVisits.EOF
   dict.Add rsLastVisits!CUST_NO, rsLastVisits!LAST
   rsLastVisits.MoveNext
Loop
rsLastVisits.Close

I get the runtime error "This key is already associated with an element of this collection".

This is where the fun part starts, because my query does not return duplicates (I double checked).

When Debugging, these are the values added:

First Iteration : "0000000.", "2012/05/27"

Second Iteration : "00000001", "2011/06/14" ERROR trying to insert this line.

In the immediate window, If i write

dict.add "00000001", "2011/06/14"

It gets added without any problem.

If I clear the dictionary (dict.removeall), it will enter one item (no matter what cust. no), and the next one will always fail. If I type it by hand (no variables) in the immediate window, it works.

Do any of you have an idea ? Thanks !


回答1:


Your example should work fine. The only issue I can think about is if CUST_NO is not a string. Try this and check if it makes a difference:

dict.Add CSTR(rsLastVisits!CUST_NO), CSTR(rsLastVisits!LAST)

EDIT:

Can you post the DB definition of CUST_NO ?




回答2:


I found a workaround...

If I change

dict.Add rsLastVisits!CUST_NO, rsLastVisits!LAST

to

dict.Add "" & rsLastVisits!CUST_NO, "" & rsLastVisits!LAST

It works...

Though this does not make any sense, because my variables were already Strings..

I'll just leave this here as "answered". If any of you guys with a better knowledge of Vb6 internals can explain to me what is going on, I would appreciate.

Thanks



来源:https://stackoverflow.com/questions/13050941/vb6-dictionary-this-key-is-already-associated-with-an-element-of-this-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!