Sum function in VBA

haver24 picture haver24 · Jul 29, 2012 · Viewed 577.4k times · Source

I have a problem with summing cells in vba. I need to use Cells(a,b):

Range("A1").function="=SUM(Range(Cells(2,1),Cells(3,2)))"

but it doesn't work.

Answer

CaBieberach picture CaBieberach · Jul 29, 2012

Function is not a property/method from range.

If you want to sum values then use the following:

Range("A1").Value = Application.Sum(Range(Cells(2, 1), Cells(3, 2)))

EDIT:

if you want the formula then use as follows:

Range("A1").Formula = "=SUM(" & Range(Cells(2, 1), Cells(3, 2)).Address(False, False) & ")"

'The two false after Adress is to define the address as relative (A2:B3).
'If you omit the parenthesis clause or write True instead, you can set the address
'as absolute ($A$2:$B$3).

In case you are allways going to use the same range address then you can use as Rory sugested:

Range("A1").Formula ="=Sum(A2:B3)"