0

Hello so a part of my macro is going through each sheet and putting the sum of that column at the end of it on each of the sheets. But currently it is printing the sum as is, I also want it to show the formula.

Sub GoNext()
    Dim i As Integer

    For Each ws In ThisWorkbook.Worksheets
    Columns("E:E").Select
    Selection.NumberFormat = "$#,##0.00"

    i = ActiveSheet.Index + 1
    If i > Sheets.Count Then i = 1
    Sheets(i).Activate

    If ActiveSheet.Name <> "CPOA Report Macro" Then
    If ActiveSheet.Name <> "Summary" Then
    LastRow = Cells(Cells.Rows.Count, "E").End(xlUp).Row + 1
    Range("E" & LastRow).Font.Bold = True
    Range("E" & LastRow) = WorksheetFunction.Sum(Range("E2:E" & LastRow - 1))
    End If
    End If

    Next ws

End Sub
Pᴇʜ
  • 56,719
  • 10
  • 49
  • 73

1 Answers1

0

I suggest to avoid using .Select and .Activate: See How to avoid using Select in Excel VBA. You can access the sheets and ranges directly.

Also your If statements can be combined by using And.

And you can use .Formula to set the formula for a cell.

Option Explicit

Public Sub GoNext()
    Dim LastRow As Long

    Dim ws As Worksheet
    For Each ws In ThisWorkbook.Worksheets
        ws.Columns("E").NumberFormat = "$#,##0.00"

        If ws.Name <> "CPOA Report Macro" And ws.Name <> "Summary" Then
            LastRow = ws.Cells(ws.Rows.Count, "E").End(xlUp).Row + 1
            ws.Range("E" & LastRow).Font.Bold = True
            ws.Range("E" & LastRow).Formula = "=SUM(E2:E" & LastRow - 1 & ")"
        End If
    Next ws
End Sub

I recommend to use meaningful procedure names like Sub SetFormatAndSumFormula or something like this. That makes your code much easier to read.

Pᴇʜ
  • 56,719
  • 10
  • 49
  • 73