VBA字典-添加项将覆盖所有项
我对字典有问题。如果我向字典中添加一个对象,它将用添加的项覆盖整个包含项VBA字典-添加项将覆盖所有项,vba,dictionary,Vba,Dictionary,我对字典有问题。如果我向字典中添加一个对象,它将用添加的项覆盖整个包含项 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:" &a
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
添加所有元素后,字典包含正确数量的项,但这些项都是最后添加的项
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\u dtyp\u链接类:
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
谢谢你的帮助 问题来自
Dim tmp As New cls_dtyp_link
语句:它只是添加了对现有cls_dtyp_link
对象的引用,并不像您所期望的那样实例化一个新的对象。如果要创建新对象,请在循环结束时显式终止现有对象:Set cls\u dtyp\u link=Nothing
。然后,每次重新进入循环时都会创建一个新实例
通常,在VBA中,一次性声明和实例化被认为是不好的做法,因为您遇到了类似的问题。我建议Dim
-将对象放置在循环外,并将其设置在循环内
另外,请看这里:
我希望这有帮助 或者,Dim tmp As cls_dtyp_link
后接set tmp=new cls_dtyp_link
应代替Dim tmp,因为新cls_dtyp_link
@shahkalpesh是的,第二段正好说明了这一点(我将在循环之外声明对象)。@shahkalpesh&@loannis感谢它的工作!我必须将tmp调暗为循环外部的cls\U dtyp\U链接
,并在循环开始时设置tmp=新的cls\U dtyp\U链接
。在循环结束时Set cls\u dtyp\u link=Nothing
Hi Axel,我很高兴它能帮上忙!:)