gpt4 book ai didi

excel - VBA : Error 457 : this key is already associated with an element of collection 中的嵌套字典

转载 作者:行者123 更新时间:2023-12-04 21:59:14 35 4
gpt4 key购买 nike

我正在尝试在 vba 中创建字典结构字典

基本上,我从 3 个列表开始:

产品编号 |客户编号 |资源

1 | 1 |一个

1 | 2 |一个

2 | 1 |一个

3 | 1 |乙

我想将它转换成一个主字典“DicByUser”,其中键是用户 ID,项目是另一个字典,其中包含客户端访问的产品作为键,源代码作为项目。

在那种情况下,我会

DicByUser= { 1 : { 1 : A , 2 : A , 3 : B}, 2 : {1 : A }}

我的方法是遍历我的初始表的所有行:

使用 Cid 客户 ID,

Pid产品ID,

来源 来源

If DicByUser.Exists(Cid) Then
If DicByUser.Item(Cid).Exists(Pid) Then
'We do something on the item
Else
DicByUser.Item(Cid).Add Pid, source
End If
Else
Dim dicotoadd As New Scripting.Dictionary
dicotoadd.Add Pid, source
DicByUser.Add Cid, dicotoadd

奇怪的是,最后一行之前的行给了我错误:vba 告诉我
Error 457 : this key is already associated with an element of collection

然后,如果我进入 Debug模式并尝试显示我的对象 dicotoadd 中的元素数,我发现 1,而对象是在前一行创建的。

我相信我将字典放在另一个字典中的方式可能存在问题,总是给它相同的名称,否则我不明白为什么我在上面创建的一行字典已经包含一个元素

我在 vba 中创建嵌套字典的过程中做错了什么?

编辑:按照 Mat's Mug 的建议,通过将我的代码更改为以下内容来解决
If DicByUser.Exists(Cid) Then
If DicByUser.Item(Cid).Exists(Pid) Then
'We do something on the item
Else
DicByUser.Item(Cid).Add Pid, source
End If
Else
Dim dicotoadd As Scripting.Dictionary
Set dicotoadd = New Scripting.Dictionary
dicotoadd.Add Pid, source
DicByUser.Add Cid, dicotoadd

最佳答案

经典陷阱。

  • VBA 中变量的最小作用域是过程级
  • As New在过程范围内更改对象的生命周期

  • 这是一个应该启发您的简单示例:
    Public Sub DoSomething()

    Dim c1 As New Collection 'notice: As New
    c1.Add "TEST"
    Set c1 = Nothing
    c1.Add "this will NOT throw runtime error 91"

    Dim c2 As Collection
    Set c2 = New Collection
    c2.Add "TEST"
    Set c2 = Nothing
    c2.Add "this WILL throw runtime error 91"

    End Sub

    您的代码声明 DicByUser As New - 它在 Else 中的事实分支不会改变它的范围,它仍然是过程范围的本地,并且 它不是 Else 分支运行时运行的可执行语句 .

    拆分声明和引用分配,您将修复您的错误。

    关于excel - VBA : Error 457 : this key is already associated with an element of collection 中的嵌套字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38128370/

    35 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com