Vba excel суммирование диапазона ячеек

Вычисление суммы числовых аргументов или значений диапазона ячеек с помощью кода VBA Excel. Метод WorksheetFunction.Sum – синтаксис, примеры.

Метод Sum объекта WorksheetFunction возвращает сумму значений своих аргументов. Аргументы могут быть числами, переменными и выражениями, возвращающими числовые значения.

Синтаксис метода WorksheetFunction.Sum:

WorksheetFunction.Sum(Arg1, Arg2, Arg3, ..., Arg30)

  • Arg – аргумент, который может быть числом, переменной, выражением. Тип данных — Variant. Максимальное количество аргументов – 30.
  • Метод WorksheetFunction.Sum возвращает значение типа Double.

Значение функции рабочего листа Sum может быть присвоено:

  • переменной числового типа Double или универсального типа Variant (при использовании числовых переменных других типов возможны недопустимые округления значений, возвращаемых методом WorksheetFunction.Sum);
  • выражению, возвращающему диапазон ячеек (точнее, возвращающему свойство Value диапазона, которое является свойством по умолчанию и его в выражениях можно не указывать);
  • другой функции в качестве аргумента.

Примеры вычисления сумм в коде VBA

Пример 1

Присвоение значений, вычисленных методом WorksheetFunction.Sum, переменной:

Sub Primer1()

Dim a As Integer

  a = WorksheetFunction.Sum(5.5, 25, 8, 28)

MsgBox a

  a = WorksheetFunction.Sum(4.5, 25, 8, 28)

MsgBox a

End Sub

Наверно, вы удивитесь, но информационное окно MsgBox дважды покажет одно и то же число 10. Почему так происходит?

Дело в том, что переменная a объявлена как целочисленная (Integer). Дробные числа, возвращенные функцией рабочего листа Sum, были округлены, а в VBA Excel применяется бухгалтерское округление, которое отличается от общепринятого.

При бухгалтерском округлении 10.5 и 9.5 округляются до 10. Будьте внимательны при выборе типа переменной.

Пример 2

Вычисление суммы значений диапазона ячеек, расположенного на текущем листе:

Sub Primer2()

‘Итог в 6 ячейке столбца «A»

Cells(6, 1) = WorksheetFunction.Sum(Cells(1, 1), Cells(2, 1), _

Cells(3, 1), Cells(4, 1), Cells(5, 1))

‘Итог в 6 ячейке столбца «B»

Range(«B6») = WorksheetFunction.Sum(Range(Cells(1, 2), Cells(5, 2)))

‘Итог в 6 ячейке столбца «C»

Range(«B6»).Offset(, 1) = WorksheetFunction.Sum(Range(«C1:C5»))

‘Присвоение суммы диапазону ячеек

Range(«A8:C10») = WorksheetFunction.Sum(Range(«A1:C5»))

End Sub

Если хотите проверить работу кода в своем редакторе VBA, заполните на рабочем листе Excel диапазон A1:C5 любыми числами.

Самая удобная формулировка по моему мнению:

Cells(10, 6) = WorksheetFunction.Sum(Range(Cells(2, 6), Cells(9, 6))) ,

где вместо номеров строк и столбцов можно использовать переменные.

Пример 3

Вычисление суммы значений диапазона ячеек, расположенного на другом листе:

Sub Primer3()

Лист1.Cells(3, 10) = WorksheetFunction.Sum(Range(Лист2.Cells(2, 5), Лист2.Cells(100, 5)))

End Sub

Пример 4

Самый простой пример, где метод WorksheetFunction.Sum используется в качестве аргумента другой функции:

Sub Primer4()

MsgBox WorksheetFunction.Sum(24, 5, 8 * 2)

End Sub

В данном случае значение функции рабочего листа Sum является аргументом функции MsgBox.


Возможно, вам интересно, откуда я взял, что функция рабочего листа (WorksheetFunction) является объектом, а сумма (Sum) ее методом? Из справки Microsoft.

Смотрите также статьи о методах WorksheetFunction.SumIf (суммирование с одним условием) и WorksheetFunction.SumIfs (суммирование с несколькими условиями).


In this Article

  • Sum WorksheetFunction
  • Assigning a Sum result to a Variable
  • Sum a Range Object
  • Sum Multiple Range Objects
  • Sum Entire Column or Row
  • Sum an Array
  • Using the SumIf Function
  • Sum Formula
    • Formula Method
    • FormulaR1C1 Method

This tutorial will show you how to use the Excel Sum function in VBA

The sum function is one of the most widely used Excel functions, and probably the first one that Excel users learn to use. VBA does not actually have an equivalent – a user has to use the built-in Excel function in VBA using the WorkSheetFunction object.

Sum WorksheetFunction

The WorksheetFunction object can be used to call most of the Excel functions that are available within the Insert Function dialog box in Excel. The SUM function is one of them.

Sub TestFunction
  Range("D33") = Application.WorksheetFunction.Sum("D1:D32")
End Sub

vba sum syntax

You are able to have up to 30 arguments in the SUM function. Each of the arguments can also refer to a range of cells.

This example below will add up cells D1 to D9

Sub TestSum()   
   Range("D10") = Application.WorksheetFunction.SUM("D1:D9")
End Sub

The example below will add up a range in column D and a range in column F. If you do not type the Application object, it will be assumed.

Sub TestSum()
   Range("D25") = WorksheetFunction.SUM (Range("D1:D24"), Range("F1:F24"))
End Sub

Notice for a single range of cells you do not have to specify the word ‘Range’ in the formula in front of the cells,  it is assumed by the code. However, if you are using multiple arguments, you do need to do so.

Assigning a Sum result to a Variable

You may want to use the result of your formula elsewhere in code rather than writing it directly back to and Excel Range. If this is the case, you can assign the result to a variable to use later in your code.

Sub AssignSumVariable()
   Dim result as Double
'Assign the variable
   result = WorksheetFunction.SUM(Range("G2:G7"), Range("H2:H7"))
'Show the result
  MsgBox "The total of the ranges is " &  result
End Sub

vba sum result

Sum a Range Object

You can assign a group of cells to the Range object, and then use that Range object with the WorksheetFunction object.

Sub TestSumRange()
   Dim rng As Range
'assign the range of cells
   Set rng = Range("D2:E10")
'use the range in the  formula
   Range("E11") = WorksheetFunction.SUM(rng)
'release the range object
  Set rng = Nothing
End Sub

Sum Multiple Range Objects

Similarly, you can sum multiple Range Objects.

Sub TestSumMultipleRanges() 
   Dim rngA As Range 
   Dim rngB as Range
'assign the range of cells 
   Set rngA = Range("D2:D10") 
   Set rngB = Range("E2:E10")   
'use the range in the formula 
Range("E11") = WorksheetFunction.SUM(rngA, rngB)
 'release the range object
  Set rngA = Nothing 
  Set rngB = Nothing
End Sub

Sum Entire Column or Row

You can also use the Sum function to add up an entire column or an entire row

This procedure below will add up all the numeric cells in column D.

Sub TestSum()    
   Range("F1") = WorksheetFunction.SUM(Range("D:D")
End Sub

While this procedure below will add up all the numeric cells in Row 9.

Sub TestSum()     
   Range("F2") = WorksheetFunction.SUM(Range("9:9") 
End Sub

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

automacro

Learn More

Sum an Array

You can also use the WorksheetFunction.Sum to add up values in an array.

Sub TestArray()
   Dim intA(1 To 5) As Integer
   Dim SumArray As Integer
'populate the array
   intA(1) = 15
   intA(2) = 20
   intA(3) = 25
   intA(4) = 30
   intA(5) = 40
'add up the array and show the result
   MsgBox WorksheetFunction.SUM(intA)
End Sub

Using the SumIf Function

Another worksheet function that can be used is the SUMIF function.

Sub TestSumIf()
Range("D11") = WorksheetFunction.SUMIF(Range("C2:C10"), 150, Range("D2:D10"))
End Sub

The procedure above will only add up the cells in Range(D2:D10) if the corresponding cell in column C = 150.

vba sumif value

Sum Formula

When you use the WorksheetFunction.SUM to add a sum to a range in your worksheet, a static sum is returned, not a flexible formula. This means that when your figures in Excel change, the value that has been returned by the WorksheetFunction will not change.

vba sum static

In the example above, the procedure TestSum has added up Range(D2:D10) and the result has been put in D11. As you can see in the formula bar, this result is a figure and not a formula.

If any of the values change therefore in the Range(D2:D10), the result in D11 will NOT change.

Instead of using the WorksheetFunction.SUM, you can use VBA to apply a Sum Function to a cell using the Formula or FormulaR1C1 methods.

VBA Programming | Code Generator does work for you!

Formula Method

The formula method allows you to point specifically to a range of cells eg: D2:D10 as shown below.

Sub TestSumFormula
  Range("D11").Formula = "=SUM(D2:D10)"
End Sub

vba sum formula 1

FormulaR1C1 Method

The FromulaR1C1 method is more flexible in that it does not restrict you to a set range of cells. The example below will give us the same answer as the one above.

Sub TestSumFormula()
   Range("D11").FormulaR1C1 = "=SUM(R[-9]C:R[-1]C)"
End Sub

vba sum formula

However, to make the formula more flexible, we could amend the code to look like this:

Sub TestSumFormula() 
   ActiveCell.FormulaR1C1 = "=SUM(R[-9]C:R[-1]C)" 
End Sub

Wherever you are in your worksheet, the formula will then add up the 8 cells directly above it and place the answer into your ActiveCell. The Range inside the SUM function has to be referred to using the Row (R) and Column (C) syntax.

Both these methods enable you to use Dynamic Excel formulas within VBA.

There will now be a formula in D11 instead of a value.

In Excel, you can use VBA to calculate the sum of values from a range of cells or multiple ranges. And, in this tutorial, we are going to learn the different ways that we can use this.

Sum in VBA using WorksheetFunction

In VBA, there are multiple functions that you can use, but there’s no specific function for this purpose. That does not mean we can’t do a sum. In VBA, there’s a property called WorksheetFunction that can help you to call functions into a VBA code.

sum-in-vba-using-worksheet

Let sum values from the range A1:A10.

  1. First, enter the worksheet function property and then select the SUM function from the list.
    2-enter-worksheet-function
  2. Next, you need to enter starting parenthesis as you do while entering a function in the worksheet.
    3-starting-parenthesis
  3. After that, we need to use the range object to refer to the range for which we want to calculate the sum.
    4-use-the-range-object
  4. In the end, type closing parenthesis and assign the function’s returning value to cell B1.
    5-closing-parenthesis
Range("B1") = Application.WorksheetFunction.Sum(Range("A1:A10"))

Now when you run this code, it will calculate the sum for the values that you have in the range A1:A10 and enter the value in cell B1.

run-the-code-to-calculate

Sum Values from an Entire Column or a Row

In that just need to specify a row or column instead of the range that we have used in the earlier example.

'for the entire column A
Range("B1") = Application.WorksheetFunction.Sum(Range("A:A"))

'for entire row 1
Range("B1") = Application.WorksheetFunction.Sum(Range("1:1"))

Use VBA to Sum Values from the Selection

Now let’s say you want to sum value from the selected cells only in that you can use a code just like the following.

Sub vba_sum_selection()

Dim sRange As Range
Dim iSum As Long

On Error GoTo errorHandler

Set sRange = Selection

iSum = WorksheetFunction.Sum(Range(sRange.Address))
MsgBox iSum

errorHandler:
MsgBox "make sure to select a valid range of cells"

End Sub

In the above code, we have used the selection and then specified it to the variable “sRange” and then use that range variable’s address to get the sum.

The following code takes all the cells and sum values from them and enters the result in the selected cell.

Sub vba_auto_sum()

Dim iFirst As String
Dim iLast As String
Dim iRange As Range

On Error GoTo errorHandler

iFirst = Selection.End(xlUp).End(xlUp).Address
iLast = Selection.End(xlUp).Address

Set iRange = Range(iFirst & ":" & iLast)
ActiveCell = WorksheetFunction.Sum(iRange)

Exit Sub

errorHandler:
MsgBox "make sure to select a valid range of cells"

End Sub

Sum a Dynamic Range using VBA

And in the same way, you can use a dynamic range while using VBA to sum values.

Sub vba_dynamic_range_sum()

Dim iFirst As String
Dim iLast As String
Dim iRange As Range

On Error GoTo errorHandler

iFirst = Selection.Offset(1, 1).Address
iLast = Selection.Offset(5, 5).Address

Set iRange = Range(iFirst & ":" & iLast)
ActiveCell = WorksheetFunction.Sum(iRange)

Exit Sub

errorHandler:
MsgBox "make sure to select a valid range of cells"

End Sub

Sum a Dynamic Column or a Row

In the same way, if you want to use a dynamic column you can use the following code where it will take the column of the active cell and sum for all the values that you have in it.

Sub vba_dynamic_column()

Dim iCol As Long

On Error GoTo errorHandler

iCol = ActiveCell.Column
MsgBox WorksheetFunction.Sum(Columns(iCol))

Exit Sub

errorHandler:
MsgBox "make sure to select a valid range of cells"

End Sub

And for a row.

Sub vba_dynamic_row()

Dim iRow As Long

On Error GoTo errorHandler

iRow = ActiveCell.Row

MsgBox WorksheetFunction.Sum(Rows(iCol))

Exit Sub

errorHandler:
MsgBox "make sure to select a valid range of cells"

End Sub

Using SUMIF with VBA

Just like sum you can use the SUMIF function to sum values with criteria just like the following example.

sumif-with-vba
Sub vba_sumif()

Dim cRange As Range
Dim sRange As Range

Set cRange = Range("A2:A13")
Set sRange = Range("B2:B13")

Range("C2") = _
WorksheetFunction.SumIf(cRange, "Product B", sRange)

End Sub

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.

Brian Webster's user avatar

Brian Webster

29.8k48 gold badges150 silver badges225 bronze badges

asked Jul 29, 2012 at 8:42

haver24's user avatar

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)"

answered Jul 29, 2012 at 10:00

CaBieberach's user avatar

CaBieberachCaBieberach

1,7482 gold badges17 silver badges26 bronze badges

3

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.

answered Jul 16, 2013 at 21:40

Ross Brasseaux's user avatar

Ross BrasseauxRoss Brasseaux

3,8511 gold badge27 silver badges47 bronze badges

1

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) & ")"

answered Jul 30, 2012 at 4:36

Tim Williams's user avatar

Tim WilliamsTim Williams

150k8 gold badges96 silver badges124 bronze badges

4

Range("A10") = WorksheetFunction.Sum(Worksheets("Sheet1").Range("A1", "A9"))

Where

Range("A10") is the answer cell

Range("A1", "A9") is the range to calculate

Ram's user avatar

Ram

3,08410 gold badges40 silver badges56 bronze badges

answered Jun 26, 2015 at 20:18

Mohamed Khairt's user avatar

The Sum function in Excel is one of the most widely used functions, and in fact, probably one of the first functions that an Excel user learns when they are learning to use Excel!  Simply stated, the Sum function adds up a range of cells for the user.  This function, along with all the Excel built-in functions, can also be used in VBA Code.

Sum Function Syntax

As with the function that is used within Excel, the syntax of the sum function has the name of the function, and then the range of cells to add up.

 =SUM(A1:A3)

Using the Sum Function in VBA Code

To use this function in VBA code, the line of code could be:

Sub TestSum()
Range("A4") = "=Sum(A1:A3)"
End Sub

Note that the function has to be within quotation marks to work.

Using the Sum function with Cell References

You can also use a Range object and use cell references in VBA code when using the sum function

Sub TestSum2()
Range("A4") = "=SUM(" & Range(Cells(1, 1), Cells(3, 1)).Address(False, False) & ")"
End Sub

The Range object allows you to refer to the cells you want to add up by referring to the row and column position of the cells – in the above example, the Row is referenced first, and then the column. Cells(1,1) for example is the same as saying A1, and Cells(3,1) is the same as saying A3. 

In both of these instances, when you run the code, a Sum formula will be put into your Excel sheet.

Excel sheet with sum formula automatically inserted

Using the Sum Function With the Worksheet Function Command

Instead of putting the formula in quotation marks, we can use the VBA sum function.

WorksheetFunction.Sum(Range("A1:A3")

To use this function in VBA code, the line of code could be:

Sub TestSum()
Range("A4") = WorksheetFunction.Sum(Range("A1:A3")
End Sub

OR using cell references

Sub TestSum2()
Range("A4") = WorksheetFunction.Sum(Range("A1:A3")
End Sub

In both these instances, when you run the code, it will put the value in the code – NOT a formula!

Excel sheet with value but no formula inserted

That may cause issues if the values in A1 to A3 were to change in the future.

In this article you learned how to use the Excel sum function in VBA code, as well as the WorksheetFunction.Sum in VBA code.  The Excel sum function is definitely more flexible in that if your values in the cells in Excel change, then the answer in the sum will change without having to re-run the procedure you have created to sum the cells.

Понравилась статья? Поделить с друзьями:
  • Vba excel суммеслимн в коде vba
  • Vba excel сумма ячеек в диапазоне
  • Vba excel сравнить два массива
  • Vba excel сравнить два диапазона
  • Vba excel сравнение ячейка