2

Good evening

Please see the attached image for an example of my data. The strings in column A are grouped together.

enter image description here

The below code is a WIP to achieve the following...

  1. Find the last occurrence of each delivery location & add a new row after.
  2. In the newly created row, in the columns named Header11-14, add a formula to total the values in the above rows
  3. Do some formatting

So far it adds the new row after each delivery location but what I can't figure out is how to add the sum formula. I know how to add the string but I can't figure out how to reference the cells above...

enter image description here

The image above what i'm trying to achieve.

Sub insertRow_totals()
Dim changeRow, counter As Integer

counter = 2

While Cells(counter, 1) <> ""
    If Cells(counter, 1) <> Cells(counter - 1, 1) Then
        Rows(counter).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove

        counter = counter + 2
    End If
    counter = counter + 1
Wend

Rows(2).EntireRow.Delete
End Sub
3
  • 1
    Ok, why not just use the subtotals? Read about them here Commented Jun 16, 2015 at 20:08
  • Thanks for your quick response. The data will be pulled from Access and may vary in length. The groupings will vary in size. Commented Jun 16, 2015 at 20:13
  • I agree with @vacip. Use Subtotals. Record a macro for subtotals. Simply amend the code so that works on realtime data of varying lengths. Commented Jun 16, 2015 at 20:18

1 Answer 1

1

you need to count how many rows with the same name there are (or remember the row index of the first one), then something like this should work

Sub insertRow_totals()
Dim changeRow, counter As Integer

counter = 2
FirstRow = 2

While Cells(counter, 1) <> ""
    If Cells(counter, 1) <> Cells(counter - 1, 1) Then
        Rows(counter).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
    For i = 11 To 14
        ActiveSheet.Cells(counter, i).Formula = "=SUM(" & Cells(FirstRow, i).Address & ":" & Cells(counter - 1, i).Address & ")"
    Next i

    counter = counter + 1
    FirstRow = counter
End If
    counter = counter + 1
Wend

Rows(2).EntireRow.Delete
End Sub
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.