Excel vba сумма значений ячеек

Вычисление суммы числовых аргументов или значений диапазона ячеек с помощью кода 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 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

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.

Содержание

  • Итоговый рабочий лист
  • Присвоение результата суммы переменной
  • Суммировать объект диапазона
  • Суммировать несколько объектов диапазона
  • Суммировать весь столбец или строку
  • Суммировать массив
  • Использование функции 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 будет формула.

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

Summing up cells based on specific conditions using SUMIFS is one of the most common tasks Excel users do. You may need to perform those sums using VBA when doing some parts of an automation task. In this post, we will show you how to write Excel SUMIFS in VBA with examples.

VBA SUMIFS function 

SUMIFS is an Excel worksheet function. In VBA, you can access SUMIFS by its function name, prefixed by WorksheetFunction, as follows:

WorksheetFunction.SumIfs(...)

Or,

Application.WorksheetFunction.SumIfs(...)

When working with VBA code in Excel, you will be using the objects provided by the Excel object model. The top of the hierarchy is the Application object, and it has many properties, including the WorksheetFunction. If a worksheet function is used without an object being specified, then Application is automatically supplied as the object. So, in this case, you can safely omit the Application object qualifier to make your code shorter.

Excel VBA SUMIFS syntax and parameters

When you access SUMIFS in VBA, you’ll see the following syntax:

Figure 01. The Excel SUMIFS VBA syntax

As you can see in the above image, SUMIFS returns Double. The last argument is [Arg29], but actually, the function has up to 255 arguments, which allows for 127 range-criteria pairs. This makes SUMIFS great for summing up values based on multiple criteria.

See the following explanation of the SUMIFS arguments.

Arguments or parameters

Name Required/Optional Description
Arg1 Required sum_range. The range of cells to sum.
Arg2, Arg3 Required criteria_range1, criteria1. The pair of the first criteria range and criteria.
[Arg4, Arg5], … Optional [criteria_range2, criteria2], …Additional pairs of criteria range and criteria.

Notice that the first pair of the criteria range and the criteria is required, while the rest are not. Thus, you can also use it for single criteria like SUMIF Excel. 

Advanced filters using operators & wildcards in SUMIFS VBA

When using SUMIFS to filter cells based on certain criteria, you can use operators and wildcards for partial matching. This is part of the reason why this function is so powerful when used correctly!

Operators

Here are the operators you can use with your criteria: 

  • >” (greater than)
  • >=” (greater than or equal to)
  • <” (less than)
  • <=” (less than or equal to)
  • <>” (not equal to)
  • =” (equal to — but it’s optional to use this operator when using “is equal to” criteria)

Wildcards

Use the following wildcard characters in the criteria to help you find similar but not exact matches.

  • A question mark (?) matches any single character. 
    For example, Ja?e matches “Jade” and “Jane”
  • An asterisk (*) matches any sequence of characters.
    For example, Ja* matches “Jane”, “Jade”, “Jake”, and “James”
  • A tilde (~) followed by ?, *, or ~ matches a question mark, asterisk, or tilde.
    For example, Discount~* matches “Discount*”

Knowing how to perform Excel functions in VBA can be a great benefit if you’re dealing with Excel every day. You may need to write SUMIFS in VBA as part of a bigger task. For example, every week, you need to automatically import data from multiple sources, process the data, summarize it using SUMIFS, and finally send a report in MS Word or Powerpoint. 

Using VBA, you can import data from multiple external sources, clean it, and prepare it for further analysis and reporting. However, if you want an alternative to importing data without coding, take a look at Coupler.io. It’s a solution that allows you to import data from different sources such as Shopify, Jira, Airtable, etc., into Excel, Google Sheets, or BigQuery. 

Now, let’s see a basic example of writing Excel SUMIFS in VBA. You can download the following file to follow along: 

SumIfs – Basic example.xlsm

VBA SUMIFS: Basic example

Suppose you have a workbook containing order data in Sheet1, as shown in the following screenshot. Using VBA, you want to sum the Order Total for orders with a discount based on the value in cell I4, which is $15

Figure 02. VBA SUMIFS basic example with numeric criteria

If you look closely at the above screenshot, the result is expected to be $955, which results from $185+$285+$485. The following steps show you how to create a sub-procedure (macro) in VBA to get the result using SUMIFS:

  1. Press Alt+11 to open the Visual Basic Editor (VBE). Alternatively, you can open the VBE by clicking the Visual Basic button of the Developer tab.

Figure 03. The VBE

  1. On the menu, click Insert > Module.

Figure 04. Inserting a new VBA Module

  1. In the code window, type the following procedure:
Sub SumOrderTotalByDiscount()
    Range("J4") = WorksheetFunction.SumIfs(Range("G2:G11"), Range("F2:F11"), Range("I4"))
End Sub

The code adds up the cells in range G2:G11 if the discount value in F2:F11 equals the value in I4. Then, it outputs the result in J4.

Figure 05. A SUMIFS VBA code basic example

  1. Run the code by pressing F5
  2. Check your worksheet. In cell J4, you should see $955.

Figure 06. A result of SUMIFS in J4

VBA SUMIFS: How to use variables

You can use variables to label the data with more descriptive names. This way, your code can be more legible and easier to understand by other people. Take a look at the following procedure that uses variables and outputs the result of SUMIFS in a message box. 

Sub SumOrderTotalByDiscountUsingVariables()
    ' Declaring variables
    Dim sumRange As Range
    Dim criteriaRange As Range
    Dim criteria As Integer
    Dim result As Double

    ' Assigning values to variables
    Set sumRange = Range("G2:G11")
    Set criteriaRange = Range("F2:F11")
    criteria = Range("I4")
    
    ' Calculating the result using the SUMIFS function
    result = WorksheetFunction.SumIfs(sumRange, criteriaRange, criteria)
    
    ' Displaying the result in a message box
    MsgBox "The sum of Total Order with a discount of $" & criteria & " is $" & result & "."
End Sub

Result:

Figure 07. A message box shows the result of SUMIFS VBA

In the above SumOrderTotalByDiscountUsingVariables() code, we declared variables within the scope of the procedure. This means they can only be used in the procedure and will no longer exist once it ends. So, in this case, there’s no need to add Set variable = Nothing for each variable just before they go out of scope.

Executing SUMIFS in VBA macro using a button

Let’s say you need to build code in VBA for someone who may not be familiar with the VBE. They might not know how to run the code using the editor or even what the Macro dialog box looks like. In this case, using buttons can be very useful because even a novice will know that clicking on one typically makes something happen.

In this example, we will take the running SumOrderTotalByDiscountUsingVariables() procedure one step further by executing it on a button click.

Here are the steps:

  1. Click the Developer tab, then click Insert > Button (Form Control).

Figure 08. Inserting a button

  1. Click and drag anywhere on the worksheet to create a button. 
  2. In the “Assign Macro” dialog, select SumOrderTotalByDiscountUsingVariables, then click OK.

Figure 09. Assigning a macro to a button

  1. If you want, click the button’s text and edit it to “Calculate” to give it a more descriptive name.

Figure 10. Editing the button s text

  1. Now, test the button by clicking on it. You’ll see a message box appear showing the result.

Figure 11. Result of assigning SUMIFS VBA macro to a button

More VBA SUMIFS examples: Single & multiple criteria

Now, let’s take a look at some SUMIFS examples below in VBA. We cover examples with single and multiple criteria, as well as examples with different data types for the criteria.

VBA SUMIFS less than numeric criteria

The following SUMIFS VBA code sums the Order Total for orders with numbers less than 1004006.

Figure 12. An example of VBA SUMIFS less than

Sub SumIfOrderNumberLessThan()
    Dim sumRange As Range
    Dim criteriaRange As Range
    Dim criteria As Long

    Set sumRange = Range("G2:G11")
    Set criteriaRange = Range("A2:A11")
    criteria = Range("I4").Value
   
    Range("J4") = WorksheetFunction.SumIfs(sumRange, criteriaRange, "<" & criteria)
End Sub

We assign the criteria variable with the value from cell I4. Then, to make the “less than” filter work, we combine the “<” operator with criteria using an ampersand symbol. Also, notice that we use a Long data type for the criteria variable because Integer won’t be enough to store a 7 digit order number value.

VBA SUMIFS date criteria

In this example, we’re summing the total discounts for orders made on 11/18/2021

Figure 13. VBA SUMIFS date example

Sub SumDiscountsByOrderDate()
    Dim sumRange As Range
    Dim criteriaRange As Range
    Dim criteria As String

    Set sumRange = Range("F2:F11")
    Set criteriaRange = Range("B2:B11")
    criteria = Range("I4").Value
   
    Range("J4") = WorksheetFunction.SumIfs(sumRange, criteriaRange, criteria)
End Sub

We use a String data type for the criteria variable. After assigning it with the value from I4, the value will be “11/18/2021“. The “is equal to” criteria is used in the SUMIFS function, but as you can see, it’s not necessary to use the “=” operator. 

VBA SUMIFS string criteria with wildcards

The following SUMIFS VBA sums the total discounts for orders made by customers with names containing “Diaz”.

Figure 14. VBA SUMIFS string

Sub SumIfCustomerNameContains()
    Dim sumRange As Range
    Dim criteriaRange As Range
    Dim criteria As String
   
    Set sumRange = Range("F2:F11")
    Set criteriaRange = Range("C2:C11")
    criteria = Range("I4").Value

    Range("J4") = WorksheetFunction.SumIfs(sumRange, criteriaRange, "*" & criteria & "*")
End Sub

Notice that we use the “*” wildcard at the beginning and end of the criteria. It will match the customer names that contain “Diaz” in any position: beginning, middle, or end. 

Excel VBA SUMIFS between dates 

The following SUMIFS VBA procedure sums the Total Order for orders made between October 20, 2021, and November 15, 2021.

Figure 15. Excel VBA SUMIFS between dates

Sub SumIfBetweenDates()
    Dim sumRange As Range
    Dim criteriaRange As Range
    Dim criteria1, criteria2 As String
   
    Set sumRange = Range("G2:G11")
    Set criteriaRange = Range("B2:B11")
   
    criteria1 = "10/20/2021"
    criteria2 = "11/15/2021"
   
    Range("I4") = WorksheetFunction.SumIfs(sumRange, _
                    criteriaRange, ">=" & criteria1, _
                    criteriaRange, "<=" & criteria2)
End Sub

To sum values between dates, notice that we use two criteria in our SUMIFS function.

  • The first criteria is for order dates that are on or after “10/20/2021”. For this, we use the “greater than or equal to” operator (>=). 
  • The second criteria is for order dates that are on or before “11/15/2021”. And for this, we use the “less than or equal to” operator (<=).  

Excel VBA SUMIFS for the current month

Now, assume this month is November 2021, and you want to calculate the total discounts for orders placed this month. The solution is similar to the previous SUMIFS between dates example. You just need to change the date criteria with the start and end date of the current month.

Figure 16. VBA SUMIFS for current month

Sub SumIfOrdersAreInCurrentMonth()
    Dim sumRange As Range
    Dim criteriaRange As Range
    Dim criteria1, criteria2 As String
   
    Set sumRange = Range("G2:G11")
    Set criteriaRange = Range("B2:B11")
   
    criteria1 = DateSerial(Year(Date), Month(Date), 1)
    criteria2 = DateSerial(Year(Date), Month(Date) + 1, 0)
   
    Range("I4") = WorksheetFunction.SumIfs(sumRange, _
                    criteriaRange, ">=" & criteria1, _
                    criteriaRange, "<=" & criteria2)
End Sub

In the above sub procedure, we use the following VBA functions to get the first and end date of the current month:

  • DateSerial(Year(Date), Month(Date), 1) — returns “11/1/2021”, which is the first day of the current month.
  • DateSerial(Year(Date), Month(Date) + 1, 0) — returns “11/30/2021”, which is the last date of the current month.

How to combine SUMIFS with other functions in VBA

SUMIFS can be combined with other functions in VBA. For example, you can combine SUMIFS with VLOOKUP or SUM for more complex scenarios. Take a look at the following examples.

Excel VBA SUMIFS + VLOOKUP 

Suppose you have the following tables and want to sum up the total of wholesale orders for “Shining Rose”. You want to do the calculation using VBA and put the result in J6.

Figure 17. Excel SUMIFS VLOOKUP example

However, the Orders table does not have a Product Name, but instead it has a Product Number column. So, you need to get the Product Number of “Shining Rose” from the Products table first, then use it as one of the criteria to find the result from the Orders table using SUMIFS.

Here’s an example solution in VBA. Notice that we use WorksheetFunction.VLookup inside the SUMIFS function.

Sub SumIfsWithVLookup()
    Dim sumRange As Range
    Dim criteriaRange1, criteriaRange2 As Range
    Dim vlRange As Range
    Dim vlValue As String
   
    Set sumRange = Range("D3:D14")
    Set criteriaRange1 = Range("B3:B14")
    Set criteriaRange2 = Range("C3:C14")
   
    ' VLOOKUP range and value
    Set xRange = Range("F3:G5")
    vlValue = Range("J2").Value
   
    Range("J6") = WorksheetFunction.SumIfs(sumRange, _
                    criteriaRange1, Range("J3").Value, _
                    criteriaRange2, WorksheetFunction.VLookup(vlValue, vlRange, 2, False))
   
End Sub

Result:

Figure 18. Excel SUMIFS VLOOKUP result

Excel VBA SUMIFS  + SUM across multiple sheets

Suppose you have identical ranges in separate worksheets and want to summarize the order total by customer name in the first worksheet, as shown in the following image:

Figure 19. Excel VBA SUMIFS across multiple sheets example

Here’s an example solution using VBA: 

Sub GetOrderTotalByCustomerName()
    Dim criteria As String
    Dim result As Double
    Dim ws As Worksheet
    
    ' Activating the first worksheet
    Worksheets("Summary").Activate
    
    ' Selecting the first customer name
    Range("A2").Select
    
    ' Loop for each customer name
    Do Until ActiveCell.Value = ""
        criteria = ActiveCell.Value
        result = 0
        
        ' Loop for each worksheet other than the Summary worksheet
        For Each ws In Worksheets
            If ws.Name <> "Summary" Then
            
                result = WorksheetFunction.Sum(result, _
                    WorksheetFunction.SumIfs(ws.Range("C2:C6"), ws.Range("A2:A6"), criteria))
            End If
        Next ws
        
        ActiveCell.Offset(0, 1) = result
        ActiveCell.Offset(1, 0).Select
    Loop

End Sub

Code explanation:

  • First, the code activates the Summary worksheet and selects the first customer name in cell A2. 
  • Then, it loops for each customer from A2, A3, … until the value in the cell is blank. Inside the loop, there’s another loop that iterates through each worksheet and performs a sum of SUMIFS.
  • For each customer, their total order is output in column B.

After executing the procedure from VBE, here’s the result:

Figure 20. Excel VBA SUMIFS across multiple sheets

Bonus: SUMIFS VBA with array arguments for multiple OR criteria not working + solution

With the following table, suppose you want to sum the total order made by either Thomas Walker OR Tamara Chen.

Figure 21. SUMIFS VBA with multiple OR criteria example

When using a formula in a cell, you can simply use the following combination of SUM and SUMIFS with an array in its criteria argument:

=SUM(SUMIFS(G2:G11,C2:C11, {"Thomas Walker","Tamara Chen"}))

However, the following VBA code will not work:

Worksheetfunction.Sum(Worksheetfunction.SumIfs(Range("G2:G11"), Range("C2:C11"), {"Thomas Walker","Tamara Chen"}))

One of the solutions is to sum up the SUMIFS results for each criteria one by one in a loop, as follows:

Sub SumIfsMultipleOR()
    Dim sumRange As Range
    Dim criteriaRange As Range
    Dim result As Double
    Dim i As Integer
   
    Set sumRange = Range("G2:G11")
    Set criteriaRange = Range("C2:C11")
   
    Dim criteria As Variant
    criteria = Array("Thomas Walker", "Tamara Chen")

    For i = 0 To UBound(criteria)
        result = WorksheetFunction.Sum(result, _
                    WorksheetFunction.SumIfs(sumRange, criteriaRange, criteria(i)))
    Next i
   
    Range("I4") = result
End Sub

Result:

Figure 22. SUMIFS VBA with multiple OR criteria result

Wrapping up – SUMIFS VBA

The SUMIFS function is one of the most powerful functions in Excel. It can be used for summing up values based on multiple criteria, which makes it a valuable tool for data analysis and reporting. We’ve covered various examples of writing SUMIFS in VBA, including the syntax it uses, parameters, and examples of how to use it with other functions in VBA.

Interested in learning how to import data from multiple different sources into Excel with Coupler.io? Check out the Microsoft Excel integration Coupler.io offers today, as well as how this tool can help you save time and eliminate repetitive work.

  • Fitrianingrum Seto

    Senior analyst programmer

Back to Blog

Focus on your business

goals while we take care of your data!

Try Coupler.io

Понравилась статья? Поделить с друзьями:
  • Excel vba сумма значений в столбце
  • Excel vba сумма диапазона ячеек
  • Excel vba строки с объединенной ячейкой
  • Excel vba строки регистр
  • Excel vba строки по формату