I’m writing a Macro which loops though the Excel data, which is sorted by column A and inserts a blank row if the the values for coulmn are different from the one above. This separates my data in groups by column A.
I then want to sum the value of column d of the separated groups. I have most of my code working underneath, however its the startCell variable I am having trouble with. I know what I want to do, but cant get the logic right, can someone please help sum up those individual groups.
Sub PutARowInWithFormula() Range("A3").Select Dim startCell As Integer Dim endCell As Integer startCell = 3 endCell = 0 Do Until ActiveCell.Value = "" If ActiveCell.Value = ActiveCell.Offset(-1, 0).Value Then ActiveCell.Offset(1, 0).Select Else ' I need the bottom code to execute only once in the loop ' startCell = ActiveCell.Row ActiveCell.EntireRow.Insert ' move to column d ActiveCell.Offset(0, 3).Select endCell = ActiveCell.Row - 1 ActiveCell.Formula = "=Sum(d" & startCell & ":d" & endCell & ")" ' move back to column a ActiveCell.Offset(0, -3).Select 'move 2 rows down ActiveCell.Offset(3, 0).Select End If Loop End Sub
I am too wondering, why you don’t use a PivotTable or just create this using worksheet functions, which is possible too. Also I do not really like this attempt with selections, but its your way, and I respect that. It even seems to be a quite good example of a situation, when it might be a good idea to use them. Because right now, any other way I could think of, to do this in VBA, seems to be more complicated.
So here is a fix up of your code:
Sub PutARowInWithFormula() Range("A2").Select Do Until ActiveCell.Value = "" If ActiveCell.Value = ActiveCell.Offset(-1, 0).Value Then ActiveCell.Offset(1, 0).Select Else ActiveCell.EntireRow.Insert 'you can use the offset directly 'by using an improved formula, you do not need to know start and end row. ActiveCell.Offset(0, 3).Formula = _ "=SUMIF(A:A,OFFSET(INDIRECT(""A""&ROW()),-1,0),D:D)" ' move back to column a and move 2 rows down ActiveCell.Offset(2, 0).Select End If Loop End Sub
Ok, found a way easier way to do nearly the same thing:
Public Sub demo() UsedRange.Subtotal GroupBy:=1, Function:=xlSum, TotalList:=4 End Sub
This function is also available through the ribbon-menu -> data -> sumsum
To avoid the error-message, you just need to have a title-row for your data, like:
DATE | NAME | COUNTER | VALUE