First I am trying at sum up each column for each employee on column (A). starting from column E till last column.
the issue I have that the code below refering to original data but ignoring the rest of columns at bottom as the code adds new row which contains total
you will notice (last 5 rows have been ignored as below code added 5 new total rows to original data)
Looking for responds.
the issue I have that the code below refering to original data but ignoring the rest of columns at bottom as the code adds new row which contains total
you will notice (last 5 rows have been ignored as below code added 5 new total rows to original data)
Looking for responds.
VBA Code:
Sub SumColumnsForEachName()
Dim ws As Worksheet
Dim lastRow As Long, lastCol As Long
Dim i As Long, startRow As Long
Dim col As Long
Dim sumRange As Range
Dim isEmpty As Boolean
Set ws = ThisWorkbook.Sheets("Sheet1") ' Change to your sheet name
' Find the last row with data in column A (or any column in use)
lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
' Find the last column with data in row 1
lastCol = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column
startRow = 2 ' Assuming the first row has headers
For i = 2 To lastRow + 1 ' Loop through each row, including the last active row
' Check if the name changes or it's the last row
If ws.Cells(i, 1).Value <> ws.Cells(i - 1, 1).Value Or i = lastRow + 1 Then
If i > startRow Then
' Apply light gray background to existing data (excluding total row)
ws.Range(ws.Cells(startRow, 1), ws.Cells(i - 1, lastCol)).Interior.Color = RGB(211, 211, 211)
' Insert a new row to place the totals
ws.Rows(i).Insert Shift:=xlDown
' Sum each column for the range from startRow to i-1, only if not empty
For col = 5 To lastCol
' Define the range to sum
Set sumRange = ws.Range(ws.Cells(startRow, col), ws.Cells(i - 1, col))
' Check if the range is not completely empty
isEmpty = Application.WorksheetFunction.CountA(sumRange) = 0
If Not isEmpty Then
' Apply the sum formula if the column is not empty
ws.Cells(i, col).Formula = "=SUM(" & sumRange.Address & ")"
End If
Next col
' Apply formatting to the totals row
With ws.Cells(i, 2).Resize(1, lastCol - 1)
.Interior.Color = RGB(0, 0, 0) ' Black background
.Font.Color = RGB(255, 255, 255) ' White text
.Font.Bold = True
End With
' Update startRow for the next employee group
startRow = i + 1
End If
End If
Next i
End Sub
Last edited by a moderator: