Hello,
I have a worksheet that I want to add an average row after each category. I can get the added row but how do write a formula to select the changing ranges for each category?
The example shows the original data and what is should look like after the macro runs.
Excel 2010
Excel 2010
Here is a snippet of the code:
Any help is appreciated.
I have a worksheet that I want to add an average row after each category. I can get the added row but how do write a formula to select the changing ranges for each category?
The example shows the original data and what is should look like after the macro runs.
Excel Workbook | ||||
---|---|---|---|---|
A | B | |||
1 | Category | Price | ||
2 | Electric | 123 | ||
3 | Electric | 145 | ||
4 | Electric | 62 | ||
5 | Electric | 39 | ||
6 | Landscape | 47 | ||
7 | Landscape | 921 | ||
8 | Plumb | 823 | ||
9 | Plumb | 333 | ||
10 | Plumb | 90 | ||
Sheet1 |
Excel Workbook | ||||
---|---|---|---|---|
A | B | |||
1 | Category | Price | ||
2 | Electric | 123 | ||
3 | Electric | 145 | ||
4 | Electric | 62 | ||
5 | Electric | 39 | ||
6 | Average | 92.25 | ||
7 | Landscape | 47 | ||
8 | Landscape | 921 | ||
9 | Average | 484.00 | ||
10 | Plumb | 823 | ||
11 | Plumb | 333 | ||
12 | Plumb | 90 | ||
13 | Average | 415.33 | ||
Sheet1 |
Cell Formulas | ||
---|---|---|
Range | Formula | |
B6 | =SUBTOTAL(1,B2:B5) | |
B9 | =SUBTOTAL(1,B7:B8) | |
B13 | =SUBTOTAL(1,B10:B12) |
Here is a snippet of the code:
Code:
Sub test()
lasta = Worksheets("Sheet2").Range("A65536").End(xlUp).Row
Set WorkRng = Range("a2:a" & lasta)
Application.ScreenUpdating = False
For i = WorkRng.Rows.Count To 2 Step -1
If WorkRng.Cells(i, 1).Value<> WorkRng.Cells(i - 1, 1).Value Then
WorkRng.Cells(i, 1).EntireRow.Insert
'add total line header
WorkRng.Cells(i, 1) = "Average " & WorkRng.Cells(i, 1).Offset(-1, 0)
'add averages
WorkRng.Cells(i, 1).Offset(0, 1) = "average formula"
End If
Next
End Sub
Any help is appreciated.