title: VBA Cells as Keys in Dictionary
body: <p>I wrote a function that would builds a dictionary with Key => Value pairs from an Excel sheet. This works fine so far but I figured out that my dictinary can have duplicated keys, when cells have the same value. </p>
  
  <p>Can anyone explain me this behavior?</p>
  
  <pre><code>Function CreateDictionaryBySheet( _
  SheetName As String, _
  Optional KeyColumn As Long = 1, _
  Optional ValueColumn As Long = 2, _
  Optional StartRow As Long = 2 _
  ) As Object
  
  Dim MyDictionary As Object
  Set MyDictionary = CreateObject("Scripting.Dictionary")
  Worksheets(SheetName).Activate
  
  Dim MaxRows As Long
  MaxRows = GetNumberOfRows(SheetName, KeyColumn)
  
  Dim Row As Long
  For Row = StartRow To MaxRows
  
      MyDictionary.Item(Cells(Row, KeyColumn)) = Cells(Row, ValueColumn)
  
  Next Row
  
  Set CreateDictionaryBySheet = MyDictionary
  
  End Function
  </code></pre>
  
  <p>I wrote this Loop to check my Code:</p>
  
  <pre><code>Sub Test()
  
  Dim Key As Variant
  Dim MyDictionary As Object
  Set MyDictionary = CreateDictionaryBySheet("Config")
  
  For Each Key In MyDictionary
  
  MsgBox (Key &amp; " =&gt; " &amp; MyDictionary(Key))
  
  Next Key
  
  End Sub
  </code></pre>
  
  <p>Assuming that cells(2,1) and cells(3,1) both are "a" and cells(2,2) = 1 and cells(3,2) = 2 I will see two msgboxes: one with "a => 1" and one with "a => 2" </p>
  
  <p>This seems odd to me because I did assume to see just one msgbox namely "a => 2"</p>
  
  <p>Thanks for your help!
  Peter</p>