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

Содержание

  • Итоговый рабочий лист
  • Присвоение результата суммы переменной
  • Суммировать объект диапазона
  • Суммировать несколько объектов диапазона
  • Суммировать весь столбец или строку
  • Суммировать массив
  • Использование функции SumIf
  • Формула суммы

Из этого туториала Вы узнаете, как использовать функцию Excel Sum в VBA.

Функция суммы — одна из наиболее широко используемых функций Excel и, вероятно, первая, которую пользователи Excel научились использовать. VBA фактически не имеет эквивалента — пользователь должен использовать встроенную функцию Excel в VBA, используя Рабочий лист объект.

Итоговый рабочий лист

Объект WorksheetFunction можно использовать для вызова большинства функций Excel, доступных в диалоговом окне «Вставить функцию» в Excel. Функция СУММ — одна из них.

123 Sub TestFunctionДиапазон («D33») = Application.WorksheetFunction.Sum («D1: D32»)Конец подписки

В функции СУММ может быть до 30 аргументов. Каждый из аргументов также может относиться к диапазону ячеек.

В этом примере ниже добавляются ячейки с D1 по D9.

123 Sub TestSum ()Диапазон («D10») = Application.WorksheetFunction.SUM («D1: D9»)Конец подписки

В приведенном ниже примере добавляется диапазон в столбце D и диапазон в столбце F. Если вы не введете объект Application, он будет принят.

123 Sub TestSum ()Диапазон («D25») = WorksheetFunction.SUM (Диапазон («D1: D24»), Диапазон («F1: F24»))Конец подписки

Обратите внимание, что для одного диапазона ячеек вам не нужно указывать слово «Диапазон» в формуле перед ячейками, это предполагается кодом. Однако, если вы используете несколько аргументов, вам нужно это сделать.

Присвоение результата суммы переменной

Возможно, вы захотите использовать результат своей формулы в другом месте кода, а не записывать его непосредственно обратно в Excel Range. В этом случае вы можете присвоить результат переменной, которая будет использоваться позже в вашем коде.

1234567 Sub AssignSumVariable ()Тусклый результат как двойной’Назначьте переменнуюрезультат = WorksheetFunction.SUM (Диапазон («G2: G7»), Диапазон («H2: H7»))’Показать результатMsgBox «Всего диапазонов» & результатКонец подписки

Суммировать объект диапазона

Вы можете назначить группу ячеек объекту Range, а затем использовать этот объект Range с Рабочий лист объект.

123456789 Sub TestSumRange ()Dim rng As Range’назначить диапазон ячеекУстановить rng = Range («D2: E10»)’используйте диапазон в формулеДиапазон («E11») = WorksheetFunction.SUM (rng)’отпустить объект диапазонаУстановить rng = ничегоКонец подписки

Суммировать несколько объектов диапазона

Точно так же вы можете суммировать несколько объектов диапазона.

123456789101112 Sub TestSumMultipleRanges ()Dim rngA As ДиапазонDim rngB as Range’назначить диапазон ячеекУстановите rngA = Range («D2: D10»)Установите rngB = Range («E2: E10»)’используйте диапазон в формулеДиапазон («E11») = WorksheetFunction.SUM (rngA, rngB)’отпустить объект диапазонаУстановите rngA = NothingУстановить rngB = НичегоКонец подписки

Суммировать весь столбец или строку

Вы также можете использовать функцию Sum, чтобы сложить весь столбец или всю строку

Эта процедура ниже суммирует все числовые ячейки в столбце D.

123 Sub TestSum ()Диапазон («F1») = WorksheetFunction.SUM (Диапазон («D: D»)Конец подписки

В то время как эта процедура ниже суммирует все числовые ячейки в строке 9.

123 Sub TestSum ()Диапазон («F2») = WorksheetFunction.SUM (Диапазон («9: 9»)Конец подписки

Суммировать массив

Вы также можете использовать WorksheetFunction.Sum для суммирования значений в массиве.

123456789101112 Sub TestArray ()Dim intA (от 1 до 5) как целое числоDim SumArray как целое число’заполнить массивintA (1) = 15intA (2) = 20intA (3) = 25intA (4) = 30intA (5) = 40’сложите массив и покажите результатMsgBox WorksheetFunction.SUM (intA)Конец подписки

Использование функции SumIf

Еще одна функция рабочего листа, которую можно использовать, — это функция СУММЕСЛИ.

123 Sub TestSumIf ()Диапазон («D11») = WorksheetFunction.SUMIF (Диапазон («C2: C10»), 150, Диапазон («D2: D10»))Конец подписки

Приведенная выше процедура суммирует только ячейки в диапазоне (D2: D10), если соответствующая ячейка в столбце C = 150.

Формула суммы

Когда вы используете Рабочий лист Функция. СУММ чтобы добавить сумму к диапазону на листе, возвращается статическая сумма, а не гибкая формула. Это означает, что при изменении ваших цифр в Excel значение, возвращаемое Рабочий лист не изменится.

В приведенном выше примере процедура TestSum суммировала диапазон (D2: D10), и результат был помещен в D11. Как вы можете видеть в строке формул, это число, а не формула.

Если любое из значений изменится в диапазоне (D2: D10), результат в D11 будет НЕТ изменение.

Вместо использования Рабочий лист Функция. СУММ, вы можете использовать VBA для применения функции суммы к ячейке с помощью Формула или Формула R1C1 методы.

Формула Метод

Метод формулы позволяет указать конкретный диапазон ячеек, например: D2: D10, как показано ниже.

123 Sub TestSumFormulaДиапазон («D11»). Формула = «= СУММ (D2: D10)»Конец подписки

Метод FormulaR1C1

Метод FromulaR1C1 более гибкий, поскольку он не ограничивает вас заданным диапазоном ячеек. Пример ниже даст нам тот же ответ, что и приведенный выше.

123 Sub TestSumFormula ()Диапазон («D11»). FormulaR1C1 = «= СУММ (R [-9] C: R [-1] C)»Конец подписки

Однако, чтобы сделать формулу более гибкой, мы могли бы изменить код, чтобы он выглядел так:

123 Sub TestSumFormula ()ActiveCell.FormulaR1C1 = «= СУММ (R [-9] C: R [-1] C)»Конец подписки

Где бы вы ни находились на своем листе, формула складывает 8 ячеек прямо над ней и помещает ответ в вашу ActiveCell. На диапазон внутри функции SUM следует ссылаться с использованием синтаксиса Row (R) и Column (C).

Оба эти метода позволяют использовать динамические формулы Excel в VBA.

Теперь вместо значения в D11 будет формула.

Вы поможете развитию сайта, поделившись страницей с друзьями

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    Visual Basic for Applications (VBA) is the programming language of Excel and other offices. It is an event-driven programming language from Microsoft.

    With Excel VBA one can automate many tasks in excel and all other office software. It helps in generating reports, preparing various charts, graphs and moreover, it performs calculation using its various functions. Let’s see Sum functions in Excel.

    1. SUM: Adds all the numbers in a range of cells.

      Syntax:

      =SUM(number1, number2…)
      

      Here,
      number 1: This is the first number in your cell to add. You can specify it upto 255 numbers.
      number 2: This is an Optional field. You can add upto 255 numbers.

      Example:

      sum

      Output:

      output

    2. SUMIF: Allows to add the cells depending upon the criteria you’ve provided.

      Syntax:

      =SUMIF(range, criteria, sum_range)
      

      range: It is the range of cells which you want to evaluate.
      The cells in range can be numbers, names or arrays or any other reference that contains numbers.

      criteria: It should be in the form of a number or any expression which defines which all cells to be added.

      For instance, “mango”, C6, “<35”
      

      sum_range: This field is Optional. If this is not mentioned, Excel will add only those cells on which criteria is applied, which are specified in the range argument.

      Example:
      sumif

      Output:
      out

    3. SUMIFS: Allows you to add all the arguments that meet multiple criteria.

      Syntax:

      =SUMIFS(sum_range, criteria_range1, criteria1 [criteria_range2, criteria2], …)
      

      sum_range: (Required) Actual cells to sum.

      criteria_range1: (Required) criteria_range1 and criteria1 makes up a search pair through which a range is searched for some specific criteria. When elements in the range are located, their corresponding values in sum_range are added.

      criteria1: This defines which all cells in criteria_range1 are to be added.

      For instance, criteria can be like this, “>32”, “apple”, “D7”
      

      Example:
      SUMIFS

      Output:
      out

    Like Article

    Save Article

    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(" &amp;amp;amp; Range(Cells(1, 1), Cells(3, 1)).Address(False, False) &amp;amp;amp; ")"
    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.

    1. HowTo
    2. VBA Howtos
    3. The Sum Function in VBA
    The Sum Function in VBA

    We will introduce how to use sum in VBA.

    The Sum Function in VBA

    The sum is the most commonly used function in excel. This function is very helpful because we can use the sum to get the sum from our financial sheets.

    We will learn how to use the sum function in VBA, assign the result to a variable, and use the sum function in single or multiple ranges. We can easily use the sum function using the WorksheetFunction.

    Let’s have an example where we will input some demo data into an excel sheet and get the sum of that data.

    Code:

    # VBA
    Sub sumFunction()
    Dim result As Double
    result = WorksheetFunction.Sum(Range("A2:A8"))
    MsgBox "Total is " & result
    End Sub
    

    Output:

    sum in vba first example assign value to a variable

    We can easily get the sum of the range using the sum function. If we want to get the result of the sum of two ranges, we can use the same function.

    Code:

    # VBA
    Sub sumFunction()
    Dim result As Double
    result = WorksheetFunction.Sum(Range("A2:A8"), Range("B2:B8"))
    MsgBox "Total is " & result
    End Sub
    

    Output:

    sum in vba second example using multiple ranges and assign value to a variable

    We can get the sum of multiple ranges using the same function. We can use more than 2 ranges to get the sum and assign the value of the result to a cell in excel.

    Let’s have an example in which we will assign the value of the result to a cell.

    Code:

    # VBA
    Sub sumFunction()
    Dim result As Double
    result = WorksheetFunction.Sum(Range("A2:A8"), Range("B2:B8"))
    Range("C2").value(result)
    End Sub
    

    Output:

    using sum function in VBA and assign the value to a cell

    Related Article — VBA Function

    • Exit Sub in VBA
    • Add New Line in VBA
    • VLOOKUP Function in VBA
    • The Use of Function in VBA

    Ezoic

    Понравилась статья? Поделить с друзьями:
  • Vba excel функции проверки
  • Vba excel функции массивы
  • Vba excel функции для работы со строками
  • Vba excel функции дата время
  • Vba excel функции sub