我有一个字典问题。如果我将一个Object添加到Dictionary中,它会用添加的项覆盖整个包含Items的项。
添加所有元素后,“词典”包含正确数量的项目,但这些项目都是最后添加的项目。
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
cls_dtyp_link类:
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
感谢您的帮助!
答案 0 :(得分:3)
问题来自Dim tmp As New cls_dtyp_link
语句:添加对现有cls_dtyp_link
对象的引用是什么,它没有像您期望的那样实例化一个新对象。如果要创建新对象,请在循环结束时显式终止现有对象:Set cls_dtyp_link = Nothing
。然后每次重新进入循环时都会创建一个新实例。
通常,在VBA中一次性声明和实例化被认为是不好的做法,因为遇到了类似问题。我建议Dim
- 循环外的对象,Set
- 将它放在循环内。
另外,看看这里: VBA: Difference in two ways of declaring a new object? (Trying to understand why my solution works)
我希望有所帮助!