Hello Jon1234,
Here is another method, though longer, that will provide you with
flexibility. You can set the starting row, which sheet the data is on,
and the summary sheet. The original currency formats are saved and later
restored for each entry on the summary sheet.
Code:
--------------------
Sub SumByName()
Dim DSO As Object
Dim DstWks As Worksheet
Dim Item, Key, Keys
Dim LastRow As Long
Dim NumFormats() As String
Dim R As Long
Dim Rng As Range
Dim SrcWks As Worksheet
Dim StartRow As Long
'Specify the Source and Destination worksheets
Set SrcWks = Worksheets("Sheet1")
Set DstWks = Worksheets("Sheet2")
'Determine the data table's size and range
With SrcWks
StartRow = 2
LastRow = .Cells(Rows.Count, "A").End(xlUp).Row
LastRow = IIf(LastRow < StartRow, StartRow, LastRow)
Set Rng = .Range(.Cells(StartRow, "A"), .Cells(LastRow, "B"))
End With
'Create a Dictionary object
Set DSO = CreateObject("Scripting.Dictionary")
DSO.CompareMode = 1
'Add the names and amounts to the Dictionary
For R = StartRow To LastRow
Key = Rng.Cells(R, 1)
Item = Rng.Cells(R, 2)
If DSO.Exists(Key) Then
Item = DSO(Key)
DSO(Key) = Item + Rng.Cells(R, 2)
Else
DSO.Add Key, Item
ReDim Preserve NumFormats(DSO.Count)
'Save the number format for this cell
NumFormats(DSO.Count - 1) = Rng.Cells(R, 2).NumberFormat
End If
Next R
'List the names and amount on the Destination worksheet
Keys = DSO.Keys
For I = 0 To DSO.Count - 1
R = StartRow + I
DstWks.Cells(R, "A") = Keys(I)
'Restore the original number format for the amount
With DstWks.Cells(R, "B")
.NumberFormat = NumFormats(I)
.Value = DSO(Keys(I))
End With
Next I
'Free the object and memory
Set DSO = Nothing
End Sub
--------------------
ADDING THE MACRO
1. *Copy* the macro above pressing the keys *CTRL+C*
2. Open your workbook
3. Press the keys *ALT+F11* to open the Visual Basic Editor
4. Press the keys *ALT+I* to activate the *Insert menu*
5. *Press M* to insert a *Standard Module*
6. *Paste* the code by pressing the keys *CTRL+V*
7. Make any custom changes to the macro if needed at this time.
8. *Save the Macro* by pressing the keys *CTRL+S*
9. Press the keys *ALT+Q* to exit the Editor, and return to Excel.
TO RUN THE MACRO...
To run the macro from Excel, open the workbook, and press *ALT+F8* to
display the *Run Macro Dialog*. Double Click the macro's name to *Run*
it.
Sincerely,
Leith Ross