Sum function in VBA
Solution 1:
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)"
Solution 2:
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.
Solution 3:
Range("A1").Function="=SUM(Range(Cells(2,1),Cells(3,2)))"
won't work because worksheet functions (when actually used on a worksheet) don't understand Range
or Cell
Try
Range("A1").Formula="=SUM(" & Range(Cells(2,1),Cells(3,2)).Address(False,False) & ")"