Excel 类的动态集合
它能工作,但我不知道如何: 我想创建一个动态数量的类,所以我使用了字典。 但我不能为字典的每个类添加一个键。 当我将第一个字典中的每个条目作为一对条目/键添加到第二个字典中时,它就会起作用Excel 类的动态集合,excel,vba,dictionary,Excel,Vba,Dictionary,它能工作,但我不知道如何: 我想创建一个动态数量的类,所以我使用了字典。 但我不能为字典的每个类添加一个键。 当我将第一个字典中的每个条目作为一对条目/键添加到第二个字典中时,它就会起作用 sub test() Dim dict As New Dictionary Dim dict2 As New Dictionary For i = 1 To 2 Set dict(i) = New Cfgadress dict(i).Col1 = i dict2.Add "d" &a
sub test()
Dim dict As New Dictionary
Dim dict2 As New Dictionary
For i = 1 To 2
Set dict(i) = New Cfgadress
dict(i).Col1 = i
dict2.Add "d" & i, dict(i)
Next i
Debug.Print dict2("d1").Col1
Debug.Print dict2("d2").Col1
End Sub
这是一个猜测,我不确定我是否理解它的工作原理:第一个字典的条目是类对象,而第二个字典的条目是字典对象(耦合项/键)?不需要第二个字典。只使用一个会有什么错误 这是我的工作代码: 添加模块:
Module1
Sub test()
Dim col1 As Dictionary
Dim classInstance As Class1
Dim counter As Long
' Init the collection
Set col1 = New Dictionary
For counter = 1 To 2
' Set new instance of class
Set classInstance = New Class1
' Set properties in new class instance
classInstance.testfield = "Test value" & counter
' Add it to the collection
col1.Add "test" & counter, classInstance
Next counter
Debug.Print col1.Item("test1").testfield
Debug.Print col1.Item("test2").testfield
End Sub
类别:Class1
Public testfield As String
我想我明白了,如果我错了就纠正我 当我用
Set dict(i) = New Cfgadress
它创建一个新的字典条目:与键i关联的类Cfgadress的空白对象
Dict(i)指字典Dict条目i中包含的项,即包含的类对象
要更改键,我需要分配一个新的耦合项/键,但该项仅作为词汇表的条目I存在。因此,我需要:
- 将字典条目用作与新字典/集合/数组中的键关联的项(我在代码中所做的)
- 或者,要将dict(i)分配给对象,请使用正确的键将其添加到,然后删除前一个
Set Wb = ThisWorkbook '==================
Set WsCfg = Wb.Sheets("Cfg") '==================
Dim dict_cfg As New Dictionary
Dim coll As New Collection
Set tcfg_adress = New Cfgadress
For i = 3 To 4 '22
If WsCfg.Cells(i, 10) = 1 And WsCfg.Cells(i, 11) = 1 Then
tcfg_adress.Row1 = WsCfg.Cells(i, 4).Value
tcfg_adress.Col1 = WsCfg.Cells(i, 5).Value
tcfg_adress.Lrow = WsCfg.Cells(i, 6).Value
tcfg_adress.Lcol = WsCfg.Cells(i, 7).Value
tcfg_adress.Nbrow = WsCfg.Cells(i, 8).Value
tcfg_adress.Nbcol = WsCfg.Cells(i, 9).Value
coll.Add tcfg_adress, WsCfg.Cells(i, 1)
End If
Next i
正如我在代码中看到的那样,在每个循环中设置一个新的类实例解决了我的问题。我以为没什么事可做,正在四处调查。非常感谢
Set Wb = ThisWorkbook '==================
Set WsCfg = Wb.Sheets("Cfg") '==================
Dim dict_cfg As New Dictionary
Dim coll As New Collection
Set tcfg_adress = New Cfgadress
For i = 3 To 4 '22
If WsCfg.Cells(i, 10) = 1 And WsCfg.Cells(i, 11) = 1 Then
tcfg_adress.Row1 = WsCfg.Cells(i, 4).Value
tcfg_adress.Col1 = WsCfg.Cells(i, 5).Value
tcfg_adress.Lrow = WsCfg.Cells(i, 6).Value
tcfg_adress.Lcol = WsCfg.Cells(i, 7).Value
tcfg_adress.Nbrow = WsCfg.Cells(i, 8).Value
tcfg_adress.Nbcol = WsCfg.Cells(i, 9).Value
coll.Add tcfg_adress, WsCfg.Cells(i, 1)
End If
Next i