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 ??
 

Excel Facts

Which Excel functions can ignore hidden rows?
The SUBTOTAL and AGGREGATE functions ignore hidden rows. AGGREGATE can also exclude error cells and more.
Try the following edited macro :

VBA Code:
Option Explicit

Sub InsertTotalsAndRemoveBlanks()
    Dim ws As Worksheet
    Dim lastRow As Long
    Dim area As Range
    Dim totalRow As Range
    Dim rowNum As Long
    
    ' Set the worksheet
    Set ws = ThisWorkbook.ActiveSheet
    
    ' Determine the last used row in Column H
    lastRow = ws.Cells(ws.Rows.Count, "H").End(xlUp).Row
    Debug.Print "Last Row: " & lastRow
    
    ' Insert "Total" rows with formulas for each data block in Column H
    On Error Resume Next ' Handle potential cases where no constants are found
    With ws.Range("H6:H" & lastRow)
        For Each area In .SpecialCells(xlConstants).Areas
            On Error GoTo 0
            
            ' Check if the last row of the area already contains "Total"
            Debug.Print "Area Address: " & area.Address
            If area.Cells(area.Rows.Count, 1).Value <> "Total" Then
                ' Insert "Total" row below the current area
                Set totalRow = area.Cells(area.Rows.Count, 1).Offset(1)
                totalRow.Value = "Total"
                
                ' Add formulas in adjacent columns (I and J)
                With totalRow.Offset(0, 1).Resize(1, 2)
                    .Formula = "=SUM(" & area.Offset(0, 1).Resize(area.Rows.Count, 1).Address(False, False) & ")"
                End With
                Debug.Print "Inserted Total at: " & totalRow.Address
            End If
        Next area
    End With
    
    On Error GoTo 0 ' Disable error handling after inserting totals
    
    ' Update lastRow after all "Total" rows are added
    lastRow = ws.Cells(ws.Rows.Count, "H").End(xlUp).Row
    Debug.Print "Updated Last Row: " & lastRow
    
    ' Remove any blank rows above the last "Total" row, starting from row 3
    For rowNum = lastRow - 1 To 3 Step -1
        If ws.Cells(rowNum, 8).Value = "" Then ' Check if Column H is empty
            ws.Rows(rowNum).Delete
            Debug.Print "Deleted Row: " & rowNum
        End If
    Next rowNum
End Sub
 
Upvote 0
Try the following edited macro :

VBA Code:
Option Explicit

Sub InsertTotalsAndRemoveBlanks()
    Dim ws As Worksheet
    Dim lastRow As Long
    Dim area As Range
    Dim totalRow As Range
    Dim rowNum As Long
  
    ' Set the worksheet
    Set ws = ThisWorkbook.ActiveSheet
  
    ' Determine the last used row in Column H
    lastRow = ws.Cells(ws.Rows.Count, "H").End(xlUp).Row
    Debug.Print "Last Row: " & lastRow
  
    ' Insert "Total" rows with formulas for each data block in Column H
    On Error Resume Next ' Handle potential cases where no constants are found
    With ws.Range("H6:H" & lastRow)
        For Each area In .SpecialCells(xlConstants).Areas
            On Error GoTo 0
          
            ' Check if the last row of the area already contains "Total"
            Debug.Print "Area Address: " & area.Address
            If area.Cells(area.Rows.Count, 1).Value <> "Total" Then
                ' Insert "Total" row below the current area
                Set totalRow = area.Cells(area.Rows.Count, 1).Offset(1)
                totalRow.Value = "Total"
              
                ' Add formulas in adjacent columns (I and J)
                With totalRow.Offset(0, 1).Resize(1, 2)
                    .Formula = "=SUM(" & area.Offset(0, 1).Resize(area.Rows.Count, 1).Address(False, False) & ")"
                End With
                Debug.Print "Inserted Total at: " & totalRow.Address
            End If
        Next area
    End With
  
    On Error GoTo 0 ' Disable error handling after inserting totals
  
    ' Update lastRow after all "Total" rows are added
    lastRow = ws.Cells(ws.Rows.Count, "H").End(xlUp).Row
    Debug.Print "Updated Last Row: " & lastRow
  
    ' Remove any blank rows above the last "Total" row, starting from row 3
    For rowNum = lastRow - 1 To 3 Step -1
        If ws.Cells(rowNum, 8).Value = "" Then ' Check if Column H is empty
            ws.Rows(rowNum).Delete
            Debug.Print "Deleted Row: " & rowNum
        End If
    Next rowNum
End Sub
Thank you for the response but its not working, the result came like this, it did not add the "Total" after end of the each serial in Column G, it only inserted the Total at the end of all values

Screenshot 2025-01-05 193404.png
 
Upvote 0
Ok, let's try this edited macro version :

VBA Code:
Sub InsertTotalsAndRemoveBlanks()
    Dim ws As Worksheet
    Dim lastRow As Long
    Dim area As Range
    Dim totalRow As Range
    Dim rowNum As Long
    
    ' Set the worksheet
    Set ws = ThisWorkbook.ActiveSheet
    
    ' Move rows 16 and 17 down one row
    ws.Rows("16:17").Insert Shift:=xlDown
    
    ' Insert "Total" in H16
    ws.Cells(16, 8).Value = "Total"
    
    ' Determine the last used row in Column H
    lastRow = ws.Cells(ws.Rows.Count, "H").End(xlUp).Row
    Debug.Print "Last Row: " & lastRow
    
    ' Insert "Total" rows with formulas for each data block in Column H
    On Error Resume Next ' Handle potential cases where no constants are found
    With ws.Range("H6:H" & lastRow)
        For Each area In .SpecialCells(xlConstants).Areas
            On Error GoTo 0
            
            ' Check if the last row of the area already contains "Total"
            Debug.Print "Area Address: " & area.Address
            If area.Cells(area.Rows.Count, 1).Value <> "Total" Then
                ' Insert "Total" row below the current area
                Set totalRow = area.Cells(area.Rows.Count, 1).Offset(1)
                totalRow.Value = "Total"
                
                ' Add formulas in adjacent columns (I and J)
                With totalRow.Offset(0, 1).Resize(1, 2)
                    .Formula = "=SUM(" & area.Offset(0, 1).Resize(area.Rows.Count, 1).Address(False, False) & ")"
                End With
                Debug.Print "Inserted Total at: " & totalRow.Address
            End If
        Next area
    End With
    
    On Error GoTo 0 ' Disable error handling after inserting totals
    
    ' Update lastRow after all "Total" rows are added
    lastRow = ws.Cells(ws.Rows.Count, "H").End(xlUp).Row
    Debug.Print "Updated Last Row: " & lastRow
    
    ' Remove any blank rows above the last "Total" row, starting from row 3
    For rowNum = lastRow - 1 To 3 Step -1
        If ws.Cells(rowNum, 8).Value = "" Then ' Check if Column H is empty
            ws.Rows(rowNum).Delete
            Debug.Print "Deleted Row: " & rowNum
        End If
    Next rowNum
End Sub
 
Upvote 0
Ok, let's try this edited macro version :

VBA Code:
Sub InsertTotalsAndRemoveBlanks()
    Dim ws As Worksheet
    Dim lastRow As Long
    Dim area As Range
    Dim totalRow As Range
    Dim rowNum As Long
  
    ' Set the worksheet
    Set ws = ThisWorkbook.ActiveSheet
  
    ' Move rows 16 and 17 down one row
    ws.Rows("16:17").Insert Shift:=xlDown
  
    ' Insert "Total" in H16
    ws.Cells(16, 8).Value = "Total"
  
    ' Determine the last used row in Column H
    lastRow = ws.Cells(ws.Rows.Count, "H").End(xlUp).Row
    Debug.Print "Last Row: " & lastRow
  
    ' Insert "Total" rows with formulas for each data block in Column H
    On Error Resume Next ' Handle potential cases where no constants are found
    With ws.Range("H6:H" & lastRow)
        For Each area In .SpecialCells(xlConstants).Areas
            On Error GoTo 0
          
            ' Check if the last row of the area already contains "Total"
            Debug.Print "Area Address: " & area.Address
            If area.Cells(area.Rows.Count, 1).Value <> "Total" Then
                ' Insert "Total" row below the current area
                Set totalRow = area.Cells(area.Rows.Count, 1).Offset(1)
                totalRow.Value = "Total"
              
                ' Add formulas in adjacent columns (I and J)
                With totalRow.Offset(0, 1).Resize(1, 2)
                    .Formula = "=SUM(" & area.Offset(0, 1).Resize(area.Rows.Count, 1).Address(False, False) & ")"
                End With
                Debug.Print "Inserted Total at: " & totalRow.Address
            End If
        Next area
    End With
  
    On Error GoTo 0 ' Disable error handling after inserting totals
  
    ' Update lastRow after all "Total" rows are added
    lastRow = ws.Cells(ws.Rows.Count, "H").End(xlUp).Row
    Debug.Print "Updated Last Row: " & lastRow
  
    ' Remove any blank rows above the last "Total" row, starting from row 3
    For rowNum = lastRow - 1 To 3 Step -1
        If ws.Cells(rowNum, 8).Value = "" Then ' Check if Column H is empty
            ws.Rows(rowNum).Delete
            Debug.Print "Deleted Row: " & rowNum
        End If
    Next rowNum
End Sub
This one looks like this and I want the TOTAL text in G Column, its coming in H and coming at the end only. Please check to help me
Screenshot 2025-01-05 210352.png
 
Upvote 0
Hopefully this version will produce the results you are seeking :

VBA Code:
Option Explicit

Sub InsertTotalsAndRemoveBlanks()
    Dim ws As Worksheet
    Dim lastRow As Long
    Dim area As Range
    Dim totalRow As Range
    Dim rowNum As Long
    
    ' Set the worksheet
    Set ws = ThisWorkbook.ActiveSheet
    
    ' Determine the last used row in Column G
    lastRow = ws.Cells(ws.Rows.Count, "G").End(xlUp).Row
    Debug.Print "Last Row: " & lastRow
    
    ' Insert "Total" rows with formulas for each data block in Column G
    On Error Resume Next ' Handle potential cases where no constants are found
    With ws.Range("G6:G" & lastRow)
        For Each area In .SpecialCells(xlConstants).Areas
            On Error GoTo 0
            
            ' Check if the last row of the area already contains "Total"
            Debug.Print "Area Address: " & area.Address
            If area.Cells(area.Rows.Count, 1).Value <> "Total" Then
                ' Insert "Total" row below the current area
                Set totalRow = area.Cells(area.Rows.Count, 1).Offset(1)
                totalRow.Value = "Total"
                
                ' Add formulas in adjacent columns (H and I)
                With totalRow.Offset(0, 1).Resize(1, 2)
                    .Formula = "=SUM(" & area.Offset(0, 1).Resize(area.Rows.Count, 1).Address(False, False) & ")"
                End With
                Debug.Print "Inserted Total at: " & totalRow.Address

                ' Center align the "Total" cell
                totalRow.HorizontalAlignment = xlCenter
            End If
        Next area
    End With
    
    On Error GoTo 0 ' Disable error handling after inserting totals
    
    ' Update lastRow after all "Total" rows are added
    lastRow = ws.Cells(ws.Rows.Count, "G").End(xlUp).Row
    Debug.Print "Updated Last Row: " & lastRow
    
    ' Remove any blank rows above the last "Total" row, starting from row 3
    For rowNum = lastRow - 1 To 3 Step -1
        If ws.Cells(rowNum, 7).Value = "" Then ' Check if Column G is empty
            ws.Rows(rowNum).Delete
            Debug.Print "Deleted Row: " & rowNum
        End If
    Next rowNum
    
    ' Center align specific cells
    ws.Range("G3:I3").HorizontalAlignment = xlCenter
    
    ' Center align all cells containing the term "Total"
    For rowNum = 6 To lastRow
        If ws.Cells(rowNum, 7).Value = "Total" Then
            ws.Cells(rowNum, 7).HorizontalAlignment = xlCenter
        End If
    Next rowNum
    
    Worksheets("Sheet1").Columns("A:K").AutoFit

    
End Sub
 
Upvote 0
Solution
Interesting. The result on stackoverflow.com doesn't match the image he posted above. ???
 
Upvote 0
Hi all,

@Logit the answer on stackoverflow.com is correct and working, but was not understood by the person who opened the post.

See you soon.
 
Upvote 0
I'm still confused but it really doesn't matter I guess. It's all in what the OP is acceptable to.


My Macro Results Which He Accepted
Serial NumberQuantity AQuantity B
1170.50.4
180.40.4
Total0.90.8
2320.50.4
270.40.4
450.50.4
770.40.4
Total1.81.6
34440.660.75
47890.4780.489
Total1.1381.239


Stackoverflow Answer
Serial NumberQuantity AQuantity B
1170.50.4
180.40.4
Total0.90.8
Total1.31.2
2320.50.4
270.40.4
450.50.4
770.40.4
Total1.81.6
Total3.63.2
34440.660.75
Total0.660.75
47890.4780.489
Total1.1381.239
Total1.6161.728

The don't match.

Life goes on......
 
Upvote 0

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