Axel
Axel

Reputation: 53

VBA Dictionary - Adding an item overwrites all items

I have a Problem with a Dictionary. If I add an Object to the Dictionary, it overwrites the whole containing Items with the added item.

After adding all elements, the Dictionary contains the right number of items, but the items are all the last added item.

For Each shp In pg.Shapes

    Dim tmp As New cls_dtyp_link
    //Filling tmp with Variables - not Displayed - tmp.link_obj is the Key

    If link_dic.Exists(tmp.link_obj) Then
        Debug.Print "not added:" & tmp.link_obj
    Else
        link_dic.Add tmp.link_obj, tmp

    End If
Next

The cls_dtyp_link Class:

Public link_ne As String
Public link_obj As String
Public link_ref As Visio.Shape
Public obj_left As String
Public obj_right As String
Public ref_left As Visio.Shape
Public ref_right As Visio.Shape
Public basekey_left As String
Public basekey_right As String
Public root_site_ne_left As String
Public root_site_ne_right As String
Public root_obj_left As String
Public root_obj_right As String
Public ref_root_left As Visio.Shape
Public ref_root_right As Visio.Shape
Public hops As Integer
Public geht_zu_konzentrator As Boolean

Thank you for your help!

Upvotes: 2

Views: 493

Answers (1)

Ioannis
Ioannis

Reputation: 5388

The problem comes from the Dim tmp As New cls_dtyp_link statement: what is does is adding a reference to the existing cls_dtyp_link object, it does not instantiate a new one as you would expect. If you want to create a new object, kill the existing one explicitly at the end of your loop: Set cls_dtyp_link = Nothing. Then a new instance will be created every time you re-enter the loop.

Generally, declaring and instantiating in one go is considered bad practice in VBA, because of issues like the one you encountered. I would suggest Dim-ing the object outside the loop, and Set-ting it inside the loop.

Also, have a look here: VBA: Difference in two ways of declaring a new object? (Trying to understand why my solution works)

I hope that helps!

Upvotes: 3

Related Questions