Dictionary.Exists Returns various values ​​for a variable and constant key

I use MS Scripting runtime dictionaries as my goto data structure for the VBA project that I am currently working on, and I just ran into a problem that makes me think that they may not really be as good as I thought. The method .Existsseems like a very useful method, but I get some weird behavior when I try to use it inside a For loop. When I run this code, I get strange behavior:

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

-, , , ( ). , , , Exists, lColLen , lColLen. Set dColLenFreqs = New Dictionary: How can this viewport ever be possible?

, .

, , (dRowsInEachCol - , , , ), dRowsInEachCol dRowsInEachCol .

:

  • Scripting.Dictionary, - ?
  • Scripting.Dictionary, ? , Mac, this , , . ? - excel , , . .

.

: - , , , , , , , . , , , , , , , .

+2
1

- , Exists watch .

? , Exists: Dictionary.

. :

: ,

dColLenFreqs.Item(lColLen) 

dColLenFreqs.Exists(lColLen) 

True.

Debug, , .

+2

Source: https://habr.com/ru/post/1693991/


All Articles