Reffering to
CHill60[
^] answer, i'd avoid of
ActiveSheet
,
ActiveCell
, etc. usage, because this might provide several issues!
Imagine, you've activated
Sheet2
, where there's a lot of data, but your code should insert
SUM
formulas in
Sheet1
. What happens, when you use "non-contextual" code?
You'll lose data in Sheet2
!
Take a look at below code:
Option Explicit
Sub CalculateSUM()
Dim NoOfRows As Integer, NoOfCols As Integer, i As Integer
Dim wsh As Worksheet, SumRow As Range
Set wsh = ThisWorkbook.Worksheets("Sheet1")
NoOfRows = wsh.Range("G1")
Set SumRow = wsh.Range("G2")
NoOfCols = 59
For i = 0 To NoOfCols
SumRow.Offset(ColumnOffset:=i).Formula = "=SUM(" & _
SumRow.Offset(RowOffset:=1, ColumnOffset:=i).Address & ":" & _
SumRow.Offset(RowOffset:=NoOfRows, ColumnOffset:=i).Address & ")"
Next
End Sub
For further details, please see:
Range.Offset Property (Excel)[
^]
Good luck!