You don't need any loop here. There is more efficient way:
With Worksheets("Total").Range("H3:H100")
.Formula = "=A3+B3+C3" ' or "=SUM(A3:C3)"
.Value = .Value
End With
Explanation:
1) line .Formula = "=A3+B3+C3"
writes formula in each cell. Excel automatically adjust this formula for each row:
- in
H3
formula would be =A3+B3+C3
- in
H4
formula would be =A4+B4+C4
- .....................
- in
H100
formula would be =A100+B100+C100
You can also use this formula instead: .Formula = "=SUM(A3:C3)"
- result would be the same.
2) line .Value = .Value
rewrites formulae with their result values. If you want to leave formulae, you can remove this line.
If you're still interesting how to do the same thing using loop, look at the following code:
Dim MyRange As Range, c As Range
With Worksheets("Total")
Set MyRange = .Range("H3:H100")
For Each c In MyRange
c.Value = .Range("A" & c.Row) + .Range("B" & c.Row) + .Range("C" & c.Row)
Next mycell
End With
code above loops through each cell in range H3:H100
and calculates sum of corresponding values from columns A
,B
,C
.
You can see how I do it here: .Range("A" & c.Row)
. Here c.Row
returns row number of "current" cell in range H3:H100
and "A" & c.Row
gives you A3
when c
referce to H3
, A4
- when c
referce to H4
and so on.
You may also want to read this: How to avoid using Select/Active statements