【发布时间】:2019-05-10 14:50:23
【问题描述】:
我正在尝试添加一个集合,我最终会扔到一个列表框上。
这些案例来自我工作簿中的两列单元格区域。
我尝试使用自定义对象类,既可以直接从我的 for each 循环中识别感兴趣的单元格(注释部分),也可以将它们添加到数组并循环遍历以将它们添加到我的集合中。在这两种情况下,我以前的添加都被下一个覆盖。
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-乙基己酯”是唯一的对象,然后有两个对象是“甲基丙烯酸”,然后是三个是我之前提到的苯乙烯。
我有理由确定我可以直接将它们全部添加,而不是使用对象类和调用添加的子例程,但我想了解为什么会发生这种情况以供将来参考。
【问题讨论】:
标签: excel vba object collections foreach