Vba excel суммеслимн в коде vba

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

WorksheetFunction.SumIfs – это метод VBA Excel, который вычисляет сумму числовых значений в диапазоне ячеек с учетом нескольких условий (критериев).

WorksheetFunction.SumIfs (ДСумм, ДУсл_1, Усл_1, ДУсл_2, Усл_2, ..., ДУсл_14, Усл_14)

  • ДСумм – диапазон суммирования, представляющий из себя часть таблицы, в ячейках которого, соответствующих условиям (критериям), суммируются значения.
  • ДУсл – диапазон условия, представляющий из себя часть обрабатываемой таблицы, в ячейках которого ищется совпадение с условием (критерием) суммирования.
  • Усл – это условие, которое применимо к диапазону, указанному перед ним, и определяющее критерий суммирования.

Первые три аргумента являются обязательными, остальные – необязательные. Всего выражение может содержать один диапазон суммирования (ДСумм) и четырнадцать пар диапазон+условие (ДУсл+Усл).

Диапазоны условий не должны повторяться – повторение приведет к ошибке. Диапазон суммирования можно один раз использовать как диапазон условия.

В параметре «Усл» метода WorksheetFunction.SumIfs можно использовать знаки подстановки:

  • вопросительный знак (?) – заменяет один любой символ;
  • звездочка (*) – заменяет любую последовательность символов (в том числе ни одного символа);
  • тильда (~) – ставится перед вопросительным знаком или звездочкой, чтобы они обозначали сами себя.

Вычисление сумм с несколькими условиями

Таблица, которая использовалась для реализации примеров в коде VBA Excel:

Дата Магазин Продавец Выручка
01.11.2019 Липка Лыкова 20000
01.11.2019 Берёзка Серёжкина 18000
01.11.2019 Дубок Бочкина 23000
02.11.2019 Липка Лаптева 30000
02.11.2019 Берёзка Брунькина 25000
02.11.2019 Дубок Жёлудева 17000
03.11.2019 Липка Лыкова 24000
03.11.2019 Берёзка Серёжкина 19000
03.11.2019 Дубок Бочкина 35000
04.11.2019 Липка Лаптева 27000
04.11.2019 Берёзка Брунькина 31000
04.11.2019 Дубок Жёлудева 26000
05.11.2019 Липка Лыкова 16000
05.11.2019 Берёзка Серёжкина 22000
05.11.2019 Дубок Бочкина 33000
06.11.2019 Липка Лаптева 16000
06.11.2019 Берёзка Брунькина 28000
06.11.2019 Дубок Жёлудева 29000

Если хотите повторить примеры, скопируйте эту таблицу и вставьте на рабочий лист Excel в ячейку A1. Таблица займет диапазон A1:D19.

Пример 1
Применение двух числовых условий в качестве критериев суммирования и использование диапазона суммирования в качестве диапазона условия:

Sub Primer1()

Dim a As Double

  a = WorksheetFunction.SumIfs(Range(«D2:D19»), _

  Range(«A2:A19»), DateValue(«03.11.2019»), _

  Range(«D2:D19»), «>20000»)

MsgBox a

End Sub

В этом примере кода VBA Excel складываются все значения в диапазоне D2:D19, которые соответствуют дате 03.11.2019 в диапазоне A2:A19 и превышают 20000 в диапазоне D2:D19. Обратите внимание, что условие «>20000» заключено в прямые кавычки.

Диапазон D2:D19 используется одновременно как диапазон суммирования и как диапазон условия.

Столбец «Дата» в исходной таблице содержит даты в числовом формате, поэтому мы текстовое отображение нужной даты преобразовали в число: DateValue(«03.11.2019»). Если ячейкам этого столбца присвоить текстовый формат, то в условии суммирования дату необходимо будет указать как строку: «03.11.2019».

Пример 2
Использование в условиях суммирования переменных и подстановочных знаков:

Sub Primer2()

Dim a As Double, b As String, c As String

  b = «>=» & CLng(DateValue(«04.11.2019»))

  c = «*ина»

  a = WorksheetFunction.SumIfs(Range(«D2:D19»), _

  Range(«A2:A19»), b, Range(«B2:B19»), «Берёзка», _

  Range(«C2:C19»), c)

MsgBox a

End Sub

В коде второго примера переменные в строке с методом WorksheetFunction.SumIfs можно заменить выражениями, которые присваиваются этим переменным.

Переменная «b» содержит условие, которое помогает отобрать из диапазона A2:A19 все даты, начиная с 04.11.2019 по 06.11.2019. Функция преобразования типа данных CLng необходима для того, чтобы при записи в строковую переменную дата записалась в виде числа, а не в формате «ДД.ММ.ГГГГ».

Из диапазона B2:B19 отбираются строки, содержащие текст «Берёзка».

Переменная «c» позволяет выбрать в диапазоне C2:C19 все фамилии, оканчивающиеся на «ина».

Третье условие на результаты выполнения кода примера 2 не влияет, так как фамилии всех продавцов «Берёзки» оканчиваются на «ина»: Серёжкина, Брунькина. Но вот если исключить второе условие, то к ним добавится Бочкина.

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

Содержание

  • Рабочий лист СУММЕСЛИ
  • Присвоение результата СУММЕСЛИ переменной
  • Использование СУММЕСЛИМН
  • Использование СУММЕСЛИ с объектом диапазона
  • Использование СУММЕСЛИМН для объектов с несколькими диапазонами
  • Формула СУММЕСЛИ

Из этого туториала Вы узнаете, как использовать функции Excel СУММЕСЛИ и СУММЕСЛИМН в VBA.

VBA не имеет эквивалента функций СУММЕСЛИ или СУММЕСЛИМН, которые вы можете использовать — пользователь должен использовать встроенные функции Excel в VBA, используя Рабочий лист объект.

Рабочий лист СУММЕСЛИ

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

123 Sub TestSumIf ()Диапазон («D10») = Application.WorksheetFunction.SumIf (Range («C2: C9»), 150, Range («D2: D9»))Конец подписки

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

Присвоение результата СУММЕСЛИ переменной

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

1234567 Sub AssignSumIfVariable ()Тусклый результат как двойной’Назначьте переменнуюresult = WorksheetFunction.SumIf (Range («C2: C9»), 150, Range («D2: D9»))’Показать результатMsgBox «Суммарный результат, соответствующий коду продажи 150:» & resultКонец подписки

Использование СУММЕСЛИМН

Функция СУММЕСЛИМН аналогична функции рабочего листа СУММЕСЛИ, но позволяет проверять более одного критерия. В приведенном ниже примере мы пытаемся сложить продажную цену, если код продажи равен 150 И Себестоимость больше 2. Обратите внимание, что в этой формуле диапазон ячеек для суммирования находится перед критериями, тогда как в функции СУММЕСЛИ — позади.

123 Sub MultipleSumIfs ()Range («D10») = WorksheetFunction.SumIfs (Range («D2: D9»), Range («C2: C9»), 150, Range («E2: E9»), «> 2»)Конец подписки

Использование СУММЕСЛИ с объектом диапазона

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

123456789101112 Sub TestSumIFRange ()Dim rngCriteria As RangeDim rngSum as Range’назначить диапазон ячеекУстановить rngCriteria = Range («C2: C9»)Установить rngSum = Range («D2: D9»)’используйте диапазон в формулеДиапазон («D10») = WorksheetFunction.SumIf (rngCriteria, 150, rngSum)’освободить объекты диапазонаУстановить rngCriteria = NothingУстановить rngSum = NothingКонец подписки

Использование СУММЕСЛИМН для объектов с несколькими диапазонами

Точно так же вы можете использовать СУММЕСЛИМН для нескольких объектов диапазона.

123456789101112131415 Sub TestSumMultipleRanges ()Dim rngCriteria1 As ДиапазонDim rngCriteria2 as RangeDim rngSum as Range’назначить диапазон ячеекУстановить rngCriteria1 = Range («C2: C9»)Установить rngCriteria2 = Range («E2: E10»)Установить rngSum = Range («D2: D10»)’используйте диапазоны в формулеДиапазон («D10») = WorksheetFunction.SumIfs (rngSum, rngCriteria1, 150, rngCriteria2, «> 2»)’отпустить объект диапазонаУстановить rngCriteria1 = NothingУстановить rngCriteria2 = NothingУстановить rngSum = NothingКонец подписки

Обратите внимание: поскольку вы используете знак «больше», критерии больше 2 должны быть заключены в круглые скобки.

Формула СУММЕСЛИ

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

В приведенном выше примере процедура суммировала Range (D2: D9), где SaleCode равняется 150 в столбце C, а результат был помещен в D10. Как вы можете видеть в строке формул, это число, а не формула.

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

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

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

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

123 Sub TestSumIf ()Диапазон («D10»). FormulaR1C1 = «= СУММЕСЛИ (C2: C9,150, D2: D9)»Конец подписки

Метод FormulaR1C1

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

123 Sub TestSumIf ()Диапазон («D10»). FormulaR1C1 = «= СУММЕСЛИ (R [-8] C [-1]: R [-1] C [-1], 150, R [-8] C: R [-1] C ) «Конец подписки

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

123 Sub TestSumIf ()ActiveCell.FormulaR1C1 = «= СУММЕСЛИ (R [-8] C [-1]: R [-1] C [-1], 150, R [-8] C: R [-1] C)»Конец подписки

Где бы вы ни находились на своем листе, формула складывает ячейки, соответствующие критериям, прямо над ней и помещает ответ в вашу ActiveCell. На диапазон внутри функции СУММЕСЛИ необходимо ссылаться с использованием синтаксиса строки (R) и столбца (C).

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

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

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

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

In this Article

  • SUMIF WorksheetFunction
  • Assigning a SUMIF result to a Variable
  • Using SUMIFS
  • Using SUMIF with a Range Object
  • Using SUMIFS on Multiple Range Objects
  • SUMIF Formula
    • Formula Method
    • FormulaR1C1 Method

This tutorial will show you how to use the Excel SUMIF and SUMIFS Functions in VBA.

VBA does not have an equivalent of the SUMIF or SUMIFS Functions that you can use – a user has to use the built-in Excel functions in VBA using the WorksheetFunction object.

SUMIF 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 SUMIF function is one of them.

Sub TestSumIf()
Range("D10") = Application.WorksheetFunction.SumIf(Range("C2:C9"), 150, Range("D2:D9"))
End Sub

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

vba sumif code sample

Assigning a SUMIF result to a Variable

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

Sub AssignSumIfVariable()
   Dim result as Double
'Assign the variable
   result = WorksheetFunction.SumIf(Range("C2:C9"), 150, Range("D2:D9"))
'Show the result
  MsgBox "The total of the result matching the 150 sales code is " &  result
End Sub

vba sum if result

Using SUMIFS

The SUMIFS function is similar to the SUMIF WorksheetFunction but it enables you to check for more than one criteria. In the example below, we are looking to add up the sale price if the sale code is 150 AND the Cost Price is greater than 2. Notice that in this formula, the range of cells to add up is in front of the criteria, whereas in the SUMIF function, it is behind.

Sub MultipleSumIfs()
   Range("D10") = WorksheetFunction.SumIfs(Range("D2:D9"), Range("C2:C9"), 150, Range("E2:E9"), ">2")
End Sub

vba sumif sumiffs

Using SUMIF with 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 TestSumIFRange()
   Dim rngCriteria As Range
   Dim rngSum as Range
'assign the range of cells
   Set rngCriteria = Range("C2:C9")
   Set rngSum = Range("D2:D9")
'use the range in the  formula
   Range("D10") = WorksheetFunction.SumIf(rngCriteria, 150, rngSum)
'release the range objects
  Set rngCriteria = Nothing
  Set rngSum = Nothing
End Sub

Using SUMIFS on Multiple Range Objects

Similarly, you can use SUMIFS on multiple Range Objects.

Sub TestSumMultipleRanges() 
   Dim rngCriteria1 As Range 
   Dim rngCriteria2 as Range
   Dim rngSum as Range
'assign the range of cells 
   Set rngCriteria1= Range("C2:C9")
   Set rngCriteria2 = Range("E2:E9")   
   Set rngSum = Range("D2:D9")
'use the ranges in the formula 
Range("D10") = WorksheetFunction.SumIfs(rngSum, rngCriteria1, 150, rngCriteria2, ">2")
 'release the range object
  Set rngCriteria1 = Nothing 
  Set rngCriteria2 = Nothing
  Set rngSum = Nothing
End Sub

Notice that because you are using a greater than sign, the criteria greater than 2 needs to be within parenthesis.

SUMIF Formula

When you use the WorksheetFunction.SUMIF 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 sumif static

In the example above, the procedure has added up Range(D2:D9) where the SaleCode equals 150 in column C, and the result was put in D10. As you can see in the formula bar, this result is a figure and not a formula.

If any of the values change in either Range(D2:D9) or Range(C2:D9), the result in D10 will NOT change.

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

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

Formula Method

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

Sub TestSumIf()
  Range("D10").Formula = "=SUMIF(C2:C9,150,D2:D9)"
End Sub

vba sumif statis eg

FormulaR1C1 Method

The FormulaR1C1 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 TestSumIf()
   Range("D10").FormulaR1C1 = "=SUMIF(R[-8]C[-1]:R[-1]C[-1],150,R[-8]C:R[-1]C)"
End Sub

vba sumif variable

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

Sub TestSumIf() 
   ActiveCell.FormulaR1C1 = "=SUMIF(R[-8]C[-1]:R[-1]C[-1],150,R[-8]C:R[-1]C)"
End Sub

Wherever you are in your worksheet, the formula will then add up the cells that meet the criteria directly above it and place the answer into your ActiveCell. The Range inside the SUMIF 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 D10 instead of a value.

 

Sovereign

Пользователь

Сообщений: 155
Регистрация: 01.01.1970

Раньше считал сумму итоговую через СУММЕСЛИМН или через СЧЕТ… но сейчас уже получились объемы (~6000 строк) Стало просто неудобно, может кто подскажет, как это все макросом заменить?    

  И еще вопрос есть по поиску в больших диапазонах, где надо много раз по одному и тому же столбцу (A) пройтись, причем на 10 листах(лист 1, лист2, лист3…лист10), но по поиску разных значений. Выбрать Петрова, скопировать на лист11 в определенную ячейку, потом Иванова, затем Сидорова и т.д. Есть ли какой-то способ облегчить макрос поиска? Если каждый раз записывать макрос через for each ws и for each r.Row, то это никакого места в коде не хватит…

 

Sovereign

Пользователь

Сообщений: 155
Регистрация: 01.01.1970

Извиняюсь, забыл прикрепить файл.

 

GIG_ant

Пользователь

Сообщений: 3102
Регистрация: 24.12.2012

Макросом можно сделать на массивах. Для этого от вас нужен пример по правилам форума.

 

Sovereign

Пользователь

Сообщений: 155
Регистрация: 01.01.1970

Забыл сохранить в 2003    

  На 1 листе, как есть сейчас, а на втором, как было бы здорово получать.

 

GIG_ant

Пользователь

Сообщений: 3102
Регистрация: 24.12.2012

А промежуточные итоги не помогут, делается нажатием пару раз на мышку, и макросов городить не надо ? см . файл

 

Sovereign

Пользователь

Сообщений: 155
Регистрация: 01.01.1970

{quote}{login=GIG_ant}{date=26.10.2011 10:57}{thema=}{post}А промежуточные итоги не помогут, делается нажатием пару раз на мышку, и макросов городить не надо ? см . файл{/post}{/quote}  

  Это хорошо, но количество позиций по Иванову и т.д. постоянно меняются и их несколько тысяч, поэтому наверно этим способом будет не так удобно. Итоговую сумму считать необходимости нет, так как общие суммы по сейлзам в разных валютах.

 
 

Sovereign

Пользователь

Сообщений: 155
Регистрация: 01.01.1970

{quote}{login=Михаил С.}{date=26.10.2011 11:17}{thema=}{post}А сводная не подходит?{/post}{/quote}  

  Нет, под эту задачу интересен макрос, мне надо суммировать только по одному условию, пока одинаковый элемент в A, то идет суммирование, как только элемент меняется, сумма записывается. Или что-то подобное, сам пытался найти решение, но не смог.

 

Sovereign

Пользователь

Сообщений: 155
Регистрация: 01.01.1970

«Время работы» макроса не критично, я его запускаю удаленно на сервере, так что работе основной он не помешает. Также интересно, можно ли такую же операцию проделать, при поиске в разных книгах, но сейчас хотя бы на одном листе без поиска по другим.

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

Как много записей на первом листе?

 

Sovereign

Пользователь

Сообщений: 155
Регистрация: 01.01.1970

{quote}{login=Юрий М}{date=26.10.2011 12:31}{thema=}{post}Как много записей на первом листе?{/post}{/quote}  

  На первом фиксировано 500.

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

Ещё вопрос: чем в принципе различаются первый и второй листы — только наличием итоговых сумм? Достаточно ли выводить ТОЛЬКО итоговые суммы по фамилиям, или нужна полная картина?

 

Sovereign

Пользователь

Сообщений: 155
Регистрация: 01.01.1970

{quote}{login=Юрий М}{date=26.10.2011 12:49}{thema=}{post}Ещё вопрос: чем в принципе различаются первый и второй листы — только наличием итоговых сумм? Достаточно ли выводить ТОЛЬКО итоговые суммы по фамилиям, или нужна полная картина?{/post}{/quote}  

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

 

GIG_ant

Пользователь

Сообщений: 3102
Регистрация: 24.12.2012

Чисто что бы услышать что макрос работает чуть не так, а хотелось бы по другому … )  
см файл. на первом листе кномпочка.

 

Sovereign

Пользователь

Сообщений: 155
Регистрация: 01.01.1970

{quote}{login=GIG_ant}{date=26.10.2011 01:02}{thema=}{post}Чисто что бы услышать что макрос работает чуть не так, а хотелось бы по другому … )  
см файл. на первом листе кномпочка.{/post}{/quote}  

  В примере работает все замечательно! Но вот вопрос в том, зачем нужна ссылка на «лист2» в моем примере он только показывает, как должно быть.

 

GIG_ant

Пользователь

Сообщений: 3102
Регистрация: 24.12.2012

Вам нужно что бы итоговые суммы проставлялись прямо на том листе где данные ?

 

Sovereign

Пользователь

Сообщений: 155
Регистрация: 01.01.1970

{quote}{login=GIG_ant}{date=26.10.2011 01:29}{thema=}{post}Вам нужно что бы итоговые суммы проставлялись прямо на том листе где данные ?{/post}{/quote}  

  Да, запустил макрос, получил результат, отослал его и очистил значения на листе.

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

{quote}{login=Евгений}{date=26.10.2011 01:16}{thema=Re: }{post}{quote}{login=GIG_ant}{date=26.10.2011 01:02}{thema=}{post}{/post}{/quote}В примере работает все замечательно! Но вот вопрос в том, зачем нужна ссылка на «лист2» в моем примере он только показывает, как должно быть.{/post}{/quote}А сразу нельзя было об этом сказать? Я вот тоже написал итоговые для другого листа…

 

GIG_ant

Пользователь

Сообщений: 3102
Регистрация: 24.12.2012

хорошо тогда вопрос, данные у вас всегда отсортированы по первому столбцу ?

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

 

Hugo

Пользователь

Сообщений: 23251
Регистрация: 22.12.2012

Если нужно получить только фамилии и суммы на новом листе, то есть готовый универсальный макрос  

http://www.planetaexcel.ru/forum.php?thread_id=26105  

Можете из него закопипастить данные куда угодно.  
Или другой макрос проверить :)

 

Sovereign

Пользователь

Сообщений: 155
Регистрация: 01.01.1970

{quote}{login=Юрий М}{date=26.10.2011 01:34}{thema=Re: Re: }А сразу нельзя было об этом сказать? Я вот тоже написал итоговые для другого листа…{/post}{/quote}  

  Простите, я думал всегда показывают 1 лист как есть, а второй, как хотят получить. Извините. Макрос ваш возьму, наверняка пригодится при формировании будущей отчетности у меня на работе. Спасибо!  

  {quote}{login=GIG_ant}{date=26.10.2011 01:34}{thema=}{post}хорошо тогда вопрос, данные у вас всегда отсортированы по первому столбцу ?{/post}{/quote}  

  Да, Антон, всегда отсортированы.

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

Если уж так необходимо — добавьте удаление исходного листа :-)

 

Sovereign

Пользователь

Сообщений: 155
Регистрация: 01.01.1970

{quote}{login=GIG_ant}{date=26.10.2011 01:34}{thema=}{post}хорошо тогда вопрос, данные у вас всегда отсортированы по первому столбцу ?{/post}{/quote}  

  Да, всегда все отсортировано

 

Sovereign

Пользователь

Сообщений: 155
Регистрация: 01.01.1970

{quote}{login=Юрий М}{date=26.10.2011 01:44}{thema=}{post}Если уж так необходимо — добавьте удаление исходного листа :-){/post}{/quote}  

  Тут дело в том, что мне надо формировать отчет именно на исходном листе(

 

GIG_ant

Пользователь

Сообщений: 3102
Регистрация: 24.12.2012

Вот вам на исходном листе, только при условии что данные будут отсортированы по первому столбцу.

 

Sovereign

Пользователь

Сообщений: 155
Регистрация: 01.01.1970

{quote}{login=GIG_ant}{date=26.10.2011 02:23}{thema=}{post}Вот вам на исходном листе, только при условии что данные будут отсортированы по первому столбцу.{/post}{/quote}  

  Великолепно! Большое спасибо, пришел с обеда и такая красота! Благодарю!

 

Sovereign

Пользователь

Сообщений: 155
Регистрация: 01.01.1970

{quote}{login=GIG_ant}{date=26.10.2011 02:23}{thema=}{post}Вот вам на исходном листе, только при условии что данные будут отсортированы по первому столбцу.{/post}{/quote}  

  Я явно что-то сделал не так на своем примере, у меня первый столбец, суммирую 22 в 23 столбец, попробовал убрать шапку таблицы, но так и не получилось просуммировать…    

  Sub test()  
   Dim inArr(), outArr(), i As Long, CurrSum As Double  
   inArr = Range(Cells(1, 1), Cells(Rows.Count, 1).End(xlUp).Offset(0, 21)).Value  
   ReDim outArr(1 To UBound(inArr, 1), 1 To 1)  
   CurrSum = Empty  
   For i = 2 To UBound(inArr, 1)  
       CurrSum = CurrSum + inArr(i — 1, 22)  
       If inArr(i — 1, 1) <> inArr(i, 1) Then  
           outArr(i — 1, 1) = CurrSum  
           CurrSum = Empty  
       End If  
   Next i  
   outArr(i — 1, 1) = CurrSum + inArr(i — 1, 22)  
   Cells(1, 23).Resize(i — 1, 1).Value = outArr  
End Sub

 

GIG_ant

Пользователь

Сообщений: 3102
Регистрация: 24.12.2012

желательно давать пример с расположением данных как в оригинале, тогда меньше будет переделывать, пока не увижу пример не смогу вам помочь.

 

Sovereign

Пользователь

Сообщений: 155
Регистрация: 01.01.1970

#30

26.10.2011 15:17:38

{quote}{login=GIG_ant}{date=26.10.2011 03:08}{thema=}{post}желательно давать пример с расположением данных как в оригинале, тогда меньше будет переделывать, пока не увижу пример не смогу вам помочь.{/post}{/quote}  

  Исправил свои кривые руки и не внимательность. Спасибо, отлично работает!

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