总结集合的元素

Sum Up the Elements of a Collection

我有一个包含一系列组合框的用户窗体(框的数量会根据另一个用户窗体中的另一个组合框而变化),当用户更改组合框并单击按钮时,代码会查找每件商品的价格与选择相关联并将其传递给集合。这部分代码有效。

我想获取集合中的每个价格并将它们相加。

Private Sub Button_Add_Click()

Dim coll as Collection
Dim priceColl As Collection
Dim item As Variant
Dim i As Long
Dim d As Long
Dim priceDrawer As Integer
Dim tableArray As Range 
Dim ws As Worksheet

Set coll = New Collection
Set priceColl = New Collection
d = Me.cbo_DrawerNumber.Value
Set ws = ThisWorkbook.Sheets("LookupTables")
With ws
    Set tableArray = .Range(.Cells(3, 7), .Cells(100000, 9))
End With

'adds items from combobox to a collection
For i = 1 To d
    item = Me.Controls("ComboBox" & i).Value
    coll.Add item
Next i
 
'looks up price associated with each item and adds it to a different collection
For Each item In coll
    priceDrawer = WorksheetFunction.VLookup(item, tableArray, 3, False)
    priceColl.Add priceDrawer
    MsgBox priceDrawer & vbNewLine
Next item

'here I want to take all the prices in the second collection and add them together. 
' Note, the  number of times in this collection will vary depending on how many 
' comboboxes have shown up in the userform

End Sub

总结集合的元素

Dim Item As Variant
Dim Total As Double

For Each Item In priceColl
    If IsNumeric(Item) Then
        Total = Total + Item
    End If
Next Item
  • 但也许在 For Each...Next 循环中 priceColl.Add priceDrawer:

    行下方使用 Total 变量更简单
    Total = Total + priceDrawer
    

    如果您确定这是一个数字。