Sum Column B based on Column A using Excel VBA Macro

后端 未结 6 709
清酒与你
清酒与你 2021-01-17 00:59

OK, I have a simple problem that I need help with in a VBA Macro. I have an excel sheet that looks like this...

Product #     Count
101              1
102          


        
6条回答
  •  梦谈多话
    2021-01-17 01:46

    I know it' late... but I've been brought here by Sum up column B based on colum C values and so I post a solution with the same "formula" approach I used there but adapted to this actual need

    Option Explicit
    
    Sub main()
    
        With ActiveSheet
            With .Range("A:B").Resize(.cells(.Rows.Count, 1).End(xlUp).row) '<== here adjust "A:B" to whatever colums range you need
                With .Offset(1).Resize(.Rows.Count - 1)
                    .Offset(, .Columns.Count).Resize(, 1).FormulaR1C1 = "=SUMIF(C1,RC1,C2)" ' "helper" column: it's the 1st column right of data columns (since ".Offset(, .Columns.Count)")
                    .Columns(2).Value = .Offset(, .Columns.Count).Resize(, 1).Value 'update "count" with sum-up from "helper" column
    
                    With .Offset(, .Columns.Count).Resize(, 1) ' reference to "helper" column
                        .FormulaR1C1 = "=IF(countIF(R1C1:RC1,RC1)=1,1,"""")" ' locate Product# repetition with blank cells
                        .Value = .Value 'fix values
                        .SpecialCells(xlCellTypeBlanks).EntireRow.Delete 'delete rows corresponding to blank cells
                        .ClearContents ' clear "helper" column
                    End With
                End With
            End With
        End With
    
        End Sub
    

    it makes use of a "helper" columns, which I assumed could be the one adjacent to the last data columns (i.e.: if data columns are "A:B" then helper column is "C")

    should different "helper" column be needed then see comments about how it's located and change code accordingly

提交回复
热议问题