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

查看:151
本文介绍了字典对象在.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

每个单元格包含字符串/唯一标识的位置。在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

Voila。每一次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天全站免登陆