【问题标题】:Dictionary.Exists Returning Different Values for Variable and Constant Key [duplicate]Dictionary.Exists为变量和常量键返回不同的值[重复]
【发布时间】:2020-10-28 00:14:15
【问题描述】:

我一直在使用 MS Scripting Runtime Library 字典作为我目前正在处理的 VBA 项目的 goto 数据结构,但我遇到了一个令人沮丧的问题,这让我觉得它们可能真的没有那么好就像我想的那样。 .Exists 方法似乎是一个非常有用的方法,但是当我尝试在 For 循环中使用它时会出现一些奇怪的行为:

Sub TestExists()
Dim i As Long
Dim dRowsInEachCol As Dictionary
Set dRowsInEachCol = New Dictionary

Dim lColLen As Long, lColLenFreq As Long

For i = 0 To 100
    dRowsInEachCol.Add i, i
Next

Dim dColLenFreqs As Dictionary
For i = 0 To dRowsInEachCol.Count - 1
        
    lColLen = dRowsInEachCol.Items()(i)
    
    If i = 0 Then
        Set dColLenFreqs = New Dictionary
    End If
    Debug.Print dColLenFreqs.Exists(0), _
                dColLenFreqs.Exists(1), _
                dColLenFreqs.Exists(lColLen)
                
    If dColLenFreqs.Exists(lColLen) Then
         lColLenFreq = dColLenFreqs.Item(lColLen) + 1
    Else
        lColLenFreq = 1
    End If
    
'        'This will add a new item to dUniqColLengths _
'            w/ key = column length, or overwrite item w/ _
'            new column number if that key exists already _
'            (INTENDED result is unique col lengths only in dict):
    dColLenFreqs.Item(lColLen) = lColLenFreq
Next
End Sub

首先,当我创建字典(similar to the issue in this question) 时,似乎有一个没有项目的键被隐式添加。但是我不能仅仅接受这个问题并解决它,因为当我检查 lColLen 时,我实际上得到了 Exists 方法的不同结果,与具有相同值的常量 lColLen 相比。这是Set dColLenFreqs = New Dictionary 行执行后的监视窗口状态:

我已尝试切换到后期绑定并完全限定我的字典变量声明,但这并没有解决问题。

如果相关,该函数的目的是获取字典输入(dRowsInEachCol 是预期的输入,但我修改为在函数内创建字典以消除此问题并缩短代码),然后返回以 dRowsInEachCol 中的唯一项为键,以 dRowsInEachCol 中每个唯一项的频率为项的字典。

我想知道:

  1. 这只是 Scripting.Dictionary 对象中的一个错误,还是我遗漏了什么?
  2. 如果是 Scripting.Dictionary 对象中的错误,有哪些解决方法?我已经阅读了有关 mac 兼容字典类 like this onethis one 的信息,但我担心这些会导致其他故障。这些恐惧有根据吗?另一个想法是只切换到临时 excel 范围或集合和数组,可能包含在一个类中。我也愿意接受其他建议。

This previous question 似乎也与我的问题有些相关,可能对参考有用。

Edit wrt Duplicate:这被标记为重复因为this question,在阅读了蒂姆威廉姆斯的回答后,我明白了为什么这些问题是相关的,尽管另一个问题是不同的,因为它假设蒂姆威廉姆斯的答案,然后问为什么。我真的没有什么可以添加到我的问题中以进一步区分它,并且我同意链接到另一个问题是有帮助的,但是如果有人遇到与我相同的问题并且没有意识到这是由监视窗口引起的,他们将更有可能在搜索结果中找到此问题。

【问题讨论】:

    标签: vba excel dictionary watch


    【解决方案1】:

    无法在此处复制 - 在第一次通过循环时,所有三个 Exists 监视值都是错误的。

    您还设置了哪些其他手表?有可能另一个手表正在改变 Exists 结果:使用 Dictionary 对象时需要小心观察窗口。

    例如见:

    Dictionary is populated with an empty item after checking dictionary item in watch window

    编辑:怀疑,在添加手表后

    dColLenFreqs.Item(lColLen) 
    

    手表上

    dColLenFreqs.Exists(lColLen) 
    

    现在输出 True。

    如果您删除所有手表并仅查看调试输出,您也会看到它与预期的一样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-07
      • 2021-07-01
      相关资源
      最近更新 更多