Add to a collection in a loop
我正试图添加到一个集合中,最终将其放入列表框。
案例来自我工作簿中的两列单元格。
我尝试直接在每个循环中使用自定义对象类来标识感兴趣的单元格(注释部分),并将它们添加到数组中并循环遍历以将它们添加到我的集合中。在这两种情况下,我以前的添加内容都将被下一个覆盖。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 | Private Sub formulas_Change() Dim i As Integer Dim cl As Range Dim mr As Worksheet Dim itemID As colClass Set itemID = New colClass Dim formArr(2, 2) As Variant Set mr = Worksheets("Monomer Ref") If cols.Count <> 0 Then For i = 1 To cols.Count cols.Remove i Next i End If monCount = 0 ListBox1.Clear i = 0 For Each cl In Range("MonomerList") Select Case cl Case"2-Ethylhexyl acrylate" formArr(i, 0) = cl formArr(i, 1) = cl.Offset(0, 1) i = i + 1 ' With itemID ' .name = cl ' .tGlass = cl.Offset(0, 1) ' End With ' monCount = monCount + 1 ' pushCollection itemID Case"Methacrylic acid" formArr(i, 0) = cl formArr(i, 1) = cl.Offset(0, 1) i = i + 1 ' With itemID ' .name = cl ' .tGlass = cl.Offset(0, 1) ' End With ' monCount = monCount + 1 ' pushCollection itemID Case"Styrene, atactic" formArr(i, 0) = cl formArr(i, 1) = cl.Offset(0, 1) i = i + 1 ' With itemID ' .name = cl ' .tGlass = cl.Offset(0, 1) ' End With ' monCount = monCount + 1 ' pushCollection itemID ' For Each itemID In cols ' MsgBox itemID.quants ' Next itemID End Select Next cl For i = 0 To 2 MsgBox i &"" & formArr(i, 0) With itemID .name = formArr(i, 0) .tGlass = formArr(i, 1) End With monCount = monCount + 1 pushCollection itemID Next i Select Case formulas Case"-7" i = 0 For Each itemID In cols ListBox1.AddItem ListBox1.List(i, 0) = itemID.name ListBox1.List(i, 1) = itemID.tGlass ListBox1.List(i, 1) = 23 i = i + 1 Next itemID End Select End Sub Private Sub pushCollection(itemID As colClass) cols.Add itemID End Sub |
运行代码时,我的集合包含三个对象,所有对象均为" Styrene,atactic "。
我知道以前的对象已添加,并且.Count在每种情况下都增加一个。例如,"丙烯酸2-乙基己酯"是唯一的对象,然后有两个对象是"甲基丙烯酸",然后是我之前提到的苯乙烯。三个对象。
我可以肯定地说,我可以直接添加它们,而不必使用对象类和调用该添加的子例程,但是我想了解为什么会发生这种情况,以供将来参考。
我很难知道您在做什么。但是,如果我想拥有一组集合,每个集合都与一个特定的键相关联,我通常将使用Dictionary对象来保存它。
首先,出于速度和简便性的考虑,我将读取要处理为VBA阵列的范围:
示例代码如下所示:
1 2 3 4 5 6 7 8 9 10 11 | Set D = New Dictionary For i = 1 to ubound(myDataArr,1) myKey = myDataArr(i,1) If Not D.Exists(myKey) then set COL = new Collection COL.Add myDataArr(i,2) D.Add key:=mykey, item:=COL Else D(myKey).Add myDataArr(i,2) End If Next I |
然后您可以输出结果。