Excel VBA Macro to Auto Insert row and insert Total and sum

Jyotirmaya

Board Regular
Joined
Dec 2, 2015
Messages
214
Office Version
  1. 2019
Platform
  1. Windows
I am using the below code to insert total in the rows based on the Serial Number in Row A starting from Row 6, there are more than 5000 rows in a sheet.
But when there are two serial numbers like in this example A15 and A16, the below code doesn't add a new row Total below the A15. it inserted the total in A17 and inserted a blank row in A14. instead of inserting total in A16 and the last total in A17.





VBA Code:
Sub InsertTotals()

   Dim Rng As Range
   
   With Range("A7:A" & Range("G" & Rows.Count).End(xlUp).Row)
      .SpecialCells(xlConstants).EntireRow.Insert
   End With
   
   With Range("G6", Range("G" & Rows.Count).End(xlUp))
      For Each Rng In .SpecialCells(xlConstants).Areas
         If Rng.Offset(Rng.Count - 1).Resize(1).Value = "Total" Then Rng.Offset(Rng.Count - 1).Resize(1).EntireRow.Delete
         Rng.Offset(Rng.Count).Resize(1).Value = "Total"
         With Rng.Offset(Rng.Count, 1).Resize(1, 2)
            .Formula = "=sum(" & Rng.Offset(, 1).Address(False, False) & ")"
         End With
      Next Rng
   End With
End Sub

Getting Result like this


Screenshot 2025-01-05 150050.png




I want result like this

Screenshot 2025-01-05 150349.png




Please help me, what to change the code ??
 
Hi Logit,

I don't know why, but that is how it works for me

Here below starting data:
Start_Screenshot 2025-01-06 180355.png


and this is the result:
End_Screenshot 2025-01-06 180512.png


See you soon.

P.s.: Read this ...

Do not use_Screenshot 2025-01-06 181252.png
 
Upvote 0

Excel Facts

What is the last column in Excel?
Excel columns run from A to Z, AA to AZ, AAA to XFD. The last column is XFD.

Forum statistics

Threads
1,225,295
Messages
6,184,130
Members
453,215
Latest member
pschatzow

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top