Scripting.Dictionary adding elements without using Dictionary.Add - BUG?

Scripting.Dictionary likes to add values ​​for no reason when you look up! Demonstrated with a 30 second example:

Create a new sheet and fill out A1:A4 = {1,2,3,4}

Insert the new vba module and add this code

Public Sub test()

    Dim rowIndex As Integer
    '
    Dim dict As Scripting.Dictionary
    Set dict = New Scripting.Dictionary

    For rowIndex = 1 To 4

        dict.Add Trim(Sheet1.Cells(rowIndex, 1).Value), rowIndex

        Dim notEvenAddingSoWhyAreYouAdding As Variant
        notEvenAddingSoWhyAreYouAdding = dict(Sheet1.Cells(rowIndex, 1).Value)

    Next rowIndex

End Sub

Put a breakpoint on Next rowIndex

Run sub and check the value dict. Now it has two meanings: "1"and 1, as you can see in the image below:

enter image description here

What the hell ?!

I understand that I have a function Trim(...)in the string dict.Add(), which means that two different keys are used, but why does this add an extra value when it does a search ?! It makes no sense - now dict.Countit won’t give the meaning that I would expect.

+4
2

, 1 (, "1"), - 1, dict.Add < key <item> .

1 . add/overwrite dict.item(1) = "abc", .

tbh, , .CompareMode = vbTextCompare strin 1 1. vbBinaryCompare, , .

+3

, : 1 "1". , , . .

- :

If dict.Exists(something) Then
    myVariable = dict.Item(something)
End If
+3

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


All Articles