How to SUM / merge similar rows in Excel using VBA?

后端 未结 4 1411
半阙折子戏
半阙折子戏 2020-12-10 09:30

I\'m trying to build a simple macro in VBA for Excel that would SUM [merge] all the rows that have the same name (value in the first columns). So for example



        
相关标签:
4条回答
  • 2020-12-10 10:06

    'if you have to run the macro twice, idk put a 1: on top of your macro and on the bottom put goto 1 'that will run it twice for you 'or you can call it twice in a different macro. up to you

    0 讨论(0)
  • 2020-12-10 10:08

    This code is easier to read and does the job:

    Sub Macro1()
        Dim ColumnsCount As Integer
    
        ColumnsCount = ActiveSheet.UsedRange.Columns.Count
    
        ActiveSheet.UsedRange.Activate
    
    
        Do While ActiveCell.Row <= ActiveSheet.UsedRange.Rows.Count
            If ActiveCell.Value = ActiveCell.Offset(1, 0).Value Then
                For i = 1 To ColumnsCount - 1
                    ActiveCell.Offset(0, i).Value = ActiveCell.Offset(0, i).Value + ActiveCell.Offset(1, i).Value
                Next
                ActiveCell.Offset(1, 0).EntireRow.Delete shift:=xlShiftUp
            Else
                ActiveCell.Offset(1, 0).Select
            End If
        Loop
    
    
    End Sub
    
    0 讨论(0)
  • 2020-12-10 10:17

    Try somthing like this:

    LastRow = ActiveSheet.UsedRange.Rows.Count
    Set r = ActiveSheet.UsedRange.Resize(1)
    With Application.WorksheetFunction
    
        For iRow = LastRow-1 to 2 step -1
            do while Cells(iRow, 1) = Cells(iRow + 1, 1) 
                LastCol = r(r.Count).Column
                SumCol = LastCol + 1
                   For iCol = 2 To SumCol
                   Cells(iRow, iCol) = .Sum(Range(Cells(iRow, iCol), Cells(iRow + 1, iCol)))
                   Next iCol
                Rows(iRow + 1).Delete
            loop
        Next iRow
    
    End With
    
    0 讨论(0)
  • 2020-12-10 10:31

    For your Problem, you don't need the Macros or any VBA code.

    You can start by opening the sheet with Table containing duplicate values. Follow Steps:

    1. Place the Excel Cursor, where you want the merged Data.Then, go to Data Tab > Consolidate.
    2. Consolidate Dialog box will appear.
    3. Here enter the Table which has the duplicated values and Click add to Add those values.
    4. Then, select the row/column, whichever has duplicate values. In this its the left column.
    5. Just Click OK and you are done.
    0 讨论(0)
提交回复
热议问题