我想将字典作为参数传递。 我的代码可能看起来有点奇怪,但无论如何我都会展示它:
Sub get_Insurers_Dictionary()
Dim cInsurers As c_Insurers
Dim myDictionary As Scripting.Dictionary
Set cInsurers = New c_Insurers
Set myDictionary = New Scripting.Dictionary
Set myDictionary = cInsurers.Get_Parameters_Dictionary(cInsurers, myDictionary)
End Sub
然后在c_Insurers类中:
Public Function Get_Parameters_Dictionary(cInsurers As c_Insurers, myDictionary As Dictionary) As Dictionary
Dim oSheet As Excel.Worksheet
Dim cParameters As c_Parameters
Set oSheet = ThisWorkbook.Sheets("Parameters_Insurers")
oSheet.Activate
Set cParameters = New c_Parameters
Set cParameters = cParameters.Get_Parameters(cParameters, oSheet)
Me.fPartner_ID_Col = cParameters.get_Header_Cols(oSheet, cParameters.fMax_Col, "INSURER_ID")
Me.fPartner_Name_Col = cParameters.get_Header_Cols(oSheet, cParameters.fMax_Col, "INSURER_NAME")
Me.fCountry_Col = cParameters.get_Header_Cols(oSheet, cParameters.fMax_Col, "COUNTRY")
For lcnt = 1 To UBound(cParameters.fArray)
myDictionary.Add cParameters.fArray(lcnt, Me.fPartner_ID_Col), Me.Get_Parameters_Class(cInsurers, cParameters, lcnt)
Next lcnt
Set Get_Parameters_Insurers = myDictionary
Set cParameters = Nothing
End Function
除了看似复杂的代码之外,我的问题很简单:是否可以将类对象添加为项目? (我不习惯使用字典)。我的字典填写在c_insurers类中,但是当我回到get_Insurers_Dictionary时为什么它是空的?
答案 0 :(得分:1)
你可以将任何你喜欢的东西添加到字典中,它的表现不像你期望的那样,因为你将字典传递给Get_Parameters_Dictionary
,但是你在填充之后再也没有将它归还,而是将它分配给别的东西; Set Get_Parameters_Insurers = myDictionary
。
这意味着Set myDictionary = cInsurers.Get_Parameters_Dictionary(cInsurers, myDictionary)
会将myDictionary
重置为Nothing
(因为未分配的返回类型)。
您需要Set Get_Parameters_Dictionary = myDictionary
中的Get_Parameters_Dictionary()
或......不要打扰;字典是一种引用类型,所以在:
Set myDictionary = New Scripting.Dictionary
cInsurers.Get_Parameters_Dictionary cInsurers, myDictionary
myDictionary
将反映Get_Parameters_Dictionary
中所做的更改。