Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum function in VBA

Tags:

excel

vba

sum

cells

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.

like image 915
haver24 Avatar asked Jul 29 '12 08:07

haver24


People also ask

Is there a sum function in VBA?

In Excel, you can use VBA to calculate the sum of values from a range of cells or multiple ranges.

How do you sum a macro in Excel?

You can use the SUM function in a macro in Excel by first selecting the cell or range of cells that you want to sum. Then, click on the "Formulas" tab and select "Function Library." Scroll down to the "Math & Trig" section and select "SUM." In the "Number1" field, enter the cell or range of cells that you want to sum.

What is the function of sum ()?

The SUM function adds values. You can add individual values, cell references or ranges or a mix of all three. For example: =SUM(A2:A10) Adds the values in cells A2:10.


2 Answers

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)"
like image 120
CaBieberach Avatar answered Sep 23 '22 16:09

CaBieberach


Place the function value into the cell

Application.Sum often does not work well in my experience (or at least the VBA developer environment does not like it for whatever reason).

The function that works best for me is Excel.WorksheetFunction.Sum()

Example:

Dim Report As Worksheet 'Set up your new worksheet variable.
Set Report = Excel.ActiveSheet 'Assign the active sheet to the variable.

Report.Cells(11, 1).Value = Excel.WorksheetFunction.Sum(Report.Range("A1:A10")) 'Add the function result.

Place the function directly into the cell

The other method which you were looking for I think is to place the function directly into the cell. This can be done by inputting the function string into the cell value. Here is an example that provides the same result as above, except the cell value is given the function and not the result of the function:

    Dim Report As Worksheet 'Set up your new worksheet variable.
    Set Report = Excel.ActiveSheet 'Assign the active sheet to the variable.

    Report.Cells(11, 1).Value = "=Sum(A1:A10)" 'Add the function.
like image 21
Ross Brasseaux Avatar answered Sep 22 '22 16:09

Ross Brasseaux