[英]How to have sum formula VBA for a specific row on each sheet?
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
I suggest to avoid using .Select
and .Activate
: See How to avoid using Select in Excel VBA . 我建议避免使用.Select
和.Activate
:请参阅如何避免在Excel VBA中使用Select 。 You can access the sheets and ranges directly. 您可以直接访问图纸和范围。
Also your If
statements can be combined by using And
. 同样,您的If
语句也可以使用And
组合。
And you can use .Formula
to set the formula for a cell. 您可以使用.Formula
设置单元格的公式。
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. 我建议使用有意义的过程名称,例如Sub SetFormatAndSumFormula
或类似的名称。 That makes your code much easier to read. 这使您的代码更易于阅读。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.