在调用 .add() 之前添加项目的字典对象 [英] Dictionary object adding items before .add() is called

查看:22
本文介绍了在调用 .add() 之前添加项目的字典对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 MS 脚本运行库 中的字典对象来存储一系列数组并根据需要对数组单元执行操作.有一个 for 循环来完成创建所有这些条目的过程.我的问题是,当使用 .exists 属性时,它甚至在添加项目之前就返回 True.

I am using a dictionary object from the MS Scripting Runtime library to store a series of arrays and perform operations on the array cells as necessary. There is a for loop to go through the process of creating all of these entries. My issue is that when using the .exists property, it is returning True even before the item has been added.

更仔细的调试表明在 for 循环开始时将键添加到字典中,即使没有使用 .add 命令并且直到循环结束才会使用.

Closer debugging indicates that the key is being added to the dictionary at the beginning of the for loop, even though no .add command is used and will not be used until the end of the loop.

我尝试了几种不同的配置,但这是一个失败的简单示例:

I have tried a few different configurations, but here is a simple example that fails:

Dim dTotals As Dictionary
Set dTotals = New Dictionary

dTotals.CompareMode = BinaryCompare

For Each cell In rAppID
    If Not dTotals.Exists(cell) Then
    Set rAppIDCells = Find_Range(cell, rAppID)
    Set rAppIDValues = rAppIDCells.Offset(0, 6)
    dAppIDTotal = WorksheetFunction.Sum(rAppIDValues)
    dTotals.Add Key:=cell.Value, Item:=dAppIDTotal
    End If
Next cell

其中每个单元格包含一个字符串/唯一 ID.在 If 语句中,代码返回 false,即使在第一次迭代时也是如此.

Where each cell contains a string / unique id. At the If statement, the code is returning false, even on the first iteration.

推荐答案

官方文档‌ 用于脚本运行时它说如果在尝试返回现有项目时未找到密钥,则会创建一个新密钥并将其对应的项目留空."

In the official documentation‌​ for the scripting runtime it says "If key is not found when attempting to return an existing item, a new key is created and its corresponding item is left empty."

...是的,当您在循环中调试时,它似乎在.exists"函数被调用之前就突然出现了.一切都很好...

...and yea, when you're debugging in a loop, it appears to pop right out of the sky before the '.exists' function is even called. All is well...

而不是尝试添加刚刚添加的项目,如下所示:

Instead of attempting to add the item that just got added, as in:

dTotals.Add Key:=cell.Value, Item:=dAppIDTotal

...只需将当前键的空对象设置为新对象:

...just set the empty object currently at your key to your new one:

dTotals(cell.Value) = dAppIDTotal

所以你的代码块变成:

If Not dTotals.Exists(cell) Then
    Set rAppIDCells = Find_Range(cell, rAppID)
    Set rAppIDValues = rAppIDCells.Offset(0, 6)
    dAppIDTotal = WorksheetFunction.Sum(rAppIDValues)
    dTotals(cell.Value) = dAppIDTotal
End If

瞧.我倾向于在每次重新访问 VBA 时重新发现这个功能".如果您因添加不打算存储的新密钥而导致内存泄漏,您也可能会注意到它的影响.

Voila. I tend to rediscover this "feature" on every revisit to VBA. You may also notice the effects of it if you are having a memory leak caused by adding new keys that you do not intend to store.

这篇关于在调用 .add() 之前添加项目的字典对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆