Forum Discussion
Need help with Excel formula or VBA to list same data found with a sum of a related field
From your example and description, a simple formula-based approach can work.
Formula-based (No VBA) – Using UNIQUE + SUMIF (Excel 365)
F2:F100 = Object Code
I2:I100 = Amounts (the "% of Org Code" applied to transaction)
The output summary table will be in columns K and L.
In K2:
=UNIQUE(F2:F100)
In L2:
=SUMIF(F2:F100, K2, I2:I100)
Then drag down.
Wrap it in SORT() if you want it alphabetically sorted:
=SORT(UNIQUE(F2:F100))
Of course you can use VBA too…your choice
VBA Script to Auto-Summarize Object Codes
This is a great option if:
You want a "clean button click", or you don't want formulas all over your sheet, or you want to paste in new data and auto-refresh the summary.
Sub SummarizeObjectCodes()
Dim ws As Worksheet
Dim lastRow As Long
Dim dict As Object
Dim objCode As String
Dim amount As Double
Dim i As Long
Dim outRow As Long
Set ws = ActiveSheet
Set dict = CreateObject("Scripting.Dictionary")
' Identify last row with data
lastRow = ws.Cells(ws.Rows.Count, "F").End(xlUp).Row
' Loop through object codes
For i = 2 To lastRow ' assuming headers in row 1
objCode = Trim(ws.Cells(i, "F").Value)
If objCode <> "" Then
amount = ws.Cells(i, "I").Value
If dict.exists(objCode) Then
dict(objCode) = dict(objCode) + amount
Else
dict.Add objCode, amount
End If
End If
Next i
' Output summary starting from column K
outRow = 2
ws.Cells(1, "K").Value = "Object Code"
ws.Cells(1, "L").Value = "% of Org Code (Total)"
For Each objCode In dict.Keys
ws.Cells(outRow, "K").Value = objCode
ws.Cells(outRow, "L").Value = dict(objCode)
outRow = outRow + 1
Next objCode
MsgBox "Object Code Summary Generated!", vbInformation
End Sub
'Code is untested back up your file first.Don’t forget to Save the file as .xlsm
My answers are voluntary and without guarantee!
Hope this will help you.