Closed Thread
Results 1 to 11 of 11

Sum and delete Duplicate Rows VBA MACRO FORMULA

Hybrid View

  1. #1
    Registered User
    Join Date
    04-24-2009
    Location
    USA
    MS-Off Ver
    Excel 2007
    Posts
    4

    Sum and delete Duplicate Rows VBA MACRO FORMULA

    Hello. I am in desparate need of a formula or VBA or MACRO for my problem. I have a about 5 spreadsheets of 3,000+ entries. All only have 2 columns, A & B. Column A has the model numbers and Column B has the quantity. There are many duplicates of different entries in Column A and I need to add up their quantities and make it into 1 row.
    Example:
    A B
    Model Number Quantity
    1234 2
    4321 1
    1234 2
    4321 1


    A B
    Model Number Quantity
    1234 4
    4321 2


    I cannot use a pivot table. Please help with this! Thank you!!

  2. #2
    Forum Guru
    Join Date
    08-26-2007
    Location
    London
    Posts
    4,606

    Re: Sum and delete Duplicate Rows VBA MACRO FORMULA

    Why can't you use a pivot table which would appear to be perfectly suited? In any case here is one VBA approach:
    Sub x()
    
    Dim rng As Range, rData As Range
    
    Application.ScreenUpdating = False
    Set rData = Range("A1", Range("A1").End(xlDown))
    rData.AdvancedFilter xlFilterCopy, copytorange:=Range("C1"), unique:=True
    For Each rng In Range("C2", Range("C2").End(xlDown))
        rng.Offset(, 1) = WorksheetFunction.SumIf(rData, rng, rData.Offset(, 1))
    Next rng
    Range("C:D").Cut Range("A:B")
    Application.ScreenUpdating = True
    
    End Sub

  3. #3
    Forum Moderator Leith Ross's Avatar
    Join Date
    01-15-2005
    Location
    San Francisco, Ca
    MS-Off Ver
    2000, 2003, & 2010
    Posts
    23,259

    Re: Sum and delete Duplicate Rows VBA MACRO FORMULA

    Hello ARNO,

    When this macro is run it will create a summary report. The data is listed alphabetically form A to Z by model number. Leading and trailing spaces and case are ignored when gathering the data. If the sheet doesn't already exist the macro will create it.
    Sub CreateSummaryReport()
    
      Dim Cell As Range
      Dim Data() As Variant
      Dim DSO As Object
      Dim Key As Variant
      Dim Keys As Variant
      Dim I As Long
      Dim Item As Variant
      Dim Items As Variant
      Dim Rng As Range
      Dim RngEnd As Range
      Dim SumWks As Worksheet
      Dim Wks As Worksheet
      
        On Error Resume Next
          Set SumWks = Worksheets("Summary Report")
            If Err = 9 Then
               Err.Clear
               Worksheets.Add.Name = "Summary Report"
                 Cells(1, "A") = "Model Number"
                 Cells(1, "B") = "Quantity"
                 Rows(1).Font.Bold = True
                 Columns("A:B").AutoFit
            End If
        On Error GoTo 0
        
        Set DSO = CreateObject("Scripting.Dictionary")
        DSO.CompareMode = vbTextCompare
        
          For Each Wks In Worksheets
            If Wks.Name <> SumWks.Name Then
               Set Rng = Wks.Range("A1")
               Set RngEnd = Rng.Cells(Rows.Count, Rng.Column).End(xlUp)
               Set Rng = IIf(RngEnd.Row < Rng.Row, Rng, Wks.Range(Rng, RngEnd))
                 For Each Cell In Rng
                   Key = Trim(Cell.Value)
                   Item = Cell.Offset(0, 1).Value
                   If Key <> "" Then
                     If Not DSO.Exists(Key) Then
                        DSO.Add Key, Item
                     Else
                        DSO(Key) = DSO(Key) + Item
                     End If
                   End If
                 Next Cell
            End If
          Next Wks
          
          With SumWks
            .UsedRange.Offset(1, 0).ClearContents
            Keys = DSO.Keys
            Items = DSO.Items
              For I = 0 To DSO.Count - 1
                .Cells(I + 2, "A") = Keys(I)
                .Cells(I + 2, "B") = Items(I)
              Next I
            .UsedRange.Sort Key1:=.Cells(2, 1), Order1:=xlAscending, _
                            Header:=xlYes, Orientation:=xlSortColumns
          End With
        
        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

    Remember To Do the Following....

    1. Use code tags. Place [CODE] before the first line of code and [/CODE] after the last line of code.
    2. Thank those who have helped you by clicking the Star below the post.
    3. Please mark your post [SOLVED] if it has been answered satisfactorily.


    Old Scottish Proverb...
    Luathaid gu deanamh maille! (Rushing causes delays!)

  4. #4
    Registered User
    Join Date
    04-24-2009
    Location
    USA
    MS-Off Ver
    Excel 2007
    Posts
    4

    Question Re: Sum and delete Duplicate Rows VBA MACRO FORMULA

    Leith Ross's approach did not work. It stated:

    Runtime error '91.'
    Object Variable or With Bock Variable not set.


    When I debugged it, it highlighted the following line:

    The If Wks.Name <> SumWks.Name Then
    StephenR's approach also did not work, it stated the following:

    Runtime error '1004'
    The extract range has a missing or illegal field name.

    debugged, highlighted line:
    rData.AdvancedFilter xlFilterCopy, copytorange:=Range("C1"), unique:=True

    How can I fix this? I need to delete the duplicate model numbers but sum their quantities in one row for each. Thanks for your responses!
    Last edited by VBA Noob; 05-01-2009 at 02:05 PM. Reason: added code tags as per forum rules

  5. #5
    Forum Moderator Leith Ross's Avatar
    Join Date
    01-15-2005
    Location
    San Francisco, Ca
    MS-Off Ver
    2000, 2003, & 2010
    Posts
    23,259

    Re: Sum and delete Duplicate Rows VBA MACRO FORMULA

    Hello ARNO,

    The macro I wrote works in Excel 2003. Which version of Excel are you using?

  6. #6
    Forum Moderator Leith Ross's Avatar
    Join Date
    01-15-2005
    Location
    San Francisco, Ca
    MS-Off Ver
    2000, 2003, & 2010
    Posts
    23,259

    Re: Sum and delete Duplicate Rows VBA MACRO FORMULA

    Hello ARNO,

    Sorry, it is my fault. I changed the macro but didn't post the corrected copy. The correction is in blue.
    Sub CreateSummaryReport()
    
      Dim Cell As Range
      Dim Data() As Variant
      Dim DSO As Object
      Dim Key As Variant
      Dim Keys As Variant
      Dim I As Long
      Dim Item As Variant
      Dim Items As Variant
      Dim Rng As Range
      Dim RngEnd As Range
      Dim SumWks As Worksheet
      Dim Wks As Worksheet
      
        On Error Resume Next
          Set SumWks = Worksheets("Summary Report")
            If Err = 9 Then
               Err.Clear
               Worksheets.Add.Name = "Summary Report"
               Set SumWks = ActiveSheet
                 Cells(1, "A") = "Model Number"
                 Cells(1, "B") = "Quantity"
                 Rows(1).Font.Bold = True
                 Columns("A:B").AutoFit
            End If
        On Error GoTo 0
        
        Set DSO = CreateObject("Scripting.Dictionary")
        DSO.CompareMode = vbTextCompare
        
          For Each Wks In Worksheets
            If Wks.Name <> SumWks.Name Then
               Set Rng = Wks.Range("A1")
               Set RngEnd = Rng.Cells(Rows.Count, Rng.Column).End(xlUp)
               Set Rng = IIf(RngEnd.Row < Rng.Row, Rng, Wks.Range(Rng, RngEnd))
                 For Each Cell In Rng
                   Key = Trim(Cell.Value)
                   Item = Cell.Offset(0, 1).Value
                   If Key <> "" Then
                     If Not DSO.Exists(Key) Then
                        DSO.Add Key, Item
                     Else
                        DSO(Key) = DSO(Key) + Item
                     End If
                   End If
                 Next Cell
            End If
          Next Wks
          
          With SumWks
            .UsedRange.Offset(1, 0).ClearContents
            Keys = DSO.Keys
            Items = DSO.Items
              For I = 0 To DSO.Count - 1
                .Cells(I + 2, "A") = Keys(I)
                .Cells(I + 2, "B") = Items(I)
              Next I
            .UsedRange.Sort Key1:=.Cells(2, 1), Order1:=xlAscending, _
                            Header:=xlYes, Orientation:=xlSortColumns
          End With
        
        Set DSO = Nothing
        
    End Sub

  7. #7
    Registered User
    Join Date
    07-15-2009
    Location
    Dallas
    MS-Off Ver
    Excel 2003
    Posts
    5

    Re: Sum and delete Duplicate Rows VBA MACRO FORMULA

    I found this post useful (stephenR's approach in particular) and would like to know how to modify it if the rows had 2 other items instead of just 1. And if possible the totals for each model in a new column E.



    for example:

    A B C D
    Model type1 type2 type3
    1234 2 1 4
    4321 1 4 3
    1234 2 3 1
    4321 1 1 4


    A B C D E
    Model type1 type2 type3 total
    1234 4 4 5 13
    4321 2 5 7 14

  8. #8
    Forum Expert shg's Avatar
    Join Date
    06-20-2007
    Location
    The Great State of Texas
    MS-Off Ver
    2010, 2019
    Posts
    40,689

    Re: Sum and delete Duplicate Rows VBA MACRO FORMULA

    Welcome to the forum.

    Please take a few minutes to read the forum rules, and then start your own thread.
    Entia non sunt multiplicanda sine necessitate

  9. #9
    Registered User
    Join Date
    06-11-2010
    Location
    india
    MS-Off Ver
    Excel 2003
    Posts
    1

    Re: Sum and delete Duplicate Rows VBA MACRO FORMULA

    Hi Ross

    Can you advise same for sheet , where summary has to be created for one sheet only, with 10 columns, say A,B,C,D,E,F,G,H,I,J, and duplicay is value is in "E" and amount is in "G"

    thanks in advance

  10. #10
    Forum Expert shg's Avatar
    Join Date
    06-20-2007
    Location
    The Great State of Texas
    MS-Off Ver
    2010, 2019
    Posts
    40,689

    Re: Sum and delete Duplicate Rows VBA MACRO FORMULA

    Same goes for you, vijay.

Closed Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1