我有自定义类型:
Private Type invoiceLine
itemCode As String
packageSize As String
englishName As String
boxName As String
weight As Double
pieces As Double
End Type
我想总结重量和碎片以获得每个唯一itemCode的总和。
实施例: 我有
的项目itemCode=1564, weight=2, pieces=3
itemCode=1564, weight=1, pieces=1
itemCode=1564, weight=3, pieces=1
itemCode=3333, weight=2, pieces=4
我想要聚合这个来获得:
itemCode=1564, weight=6, pieces=5
itemCode=3333, weight=2, pieces=4
我该怎么做?
答案 0 :(得分:0)
您可以使用字典对象执行此操作。
Private Type InvoiceLine
itemCode As String
packageSize As String
englishName As String
boxName As String
weight As Double
pieces As Double
End Type
Sub Test()
Dim invoices() As InvoiceLine
Dim dict As Object ' we will use a scripting dictionary to compute your aggregation
Dim wt As Double, pcs As Double
Dim i As Long
Dim itm As Variant
ReDim invoices(4)
'#### INITIALIZE SOME DUMMY DATA ####
invoices(0).itemCode = 1
invoices(1).itemCode = 2
invoices(2).itemCode = 1
invoices(3).itemCode = 1
invoices(4).itemCode = 3
invoices(0).pieces = 3
invoices(1).pieces = 2
invoices(2).pieces = 5
invoices(3).pieces = 4
invoices(4).pieces = 7
invoices(0).weight = 100
invoices(1).weight = 200
invoices(2).weight = 59
invoices(3).weight = 43
invoices(4).weight = 77
Set dict = CreateObject("Scripting.Dictionary")
For i = LBound(invoices) To UBound(invoices)
wt = invoices(i).weight
pcs = invoices(i).pieces
If dict.Exists(invoices(i).itemCode) Then
'Update the dictionary Value for this entry
wt = wt + dict(invoices(i).itemCode)(0)
pcs = pcs + dict(invoices(i).itemCode)(1)
End If
'Add this item to the dictionary
dict(invoices(i).itemCode) = Array(wt, pcs)
Next
For Each itm In dict.Keys()
MsgBox "Item #: " & itm & vbCrLf & _
"Weight: " & dict(itm)(0) & vbCrLf & _
"Pieces: " & dict(itm)(1)
Next
End Sub