Vba excel сумма по условию

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

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

WorksheetFunction.SumIf (Диапазон_условия, Условие, Диапазон_суммирования)

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

* Если «Диапазон_суммирования» не указан, его роль выполняет «Диапазон_условия». Другими словами, если условие проверяется в тех же ячейках, значения которых суммируются при выполнении условия, то параметр «Диапазон_суммирования» можно не указывать.

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

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

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

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

Склад Товар Кол-во Цена Сумма
№1 Апельсины 10 65,00 650,00
№1 Бананы 20 55,00 1100,00
№1 Лимоны 20 110,00 2200,00
№1 Мандарины 30 70,00 2100,00
№1 Яблоки 25 50,00 1250,00
№2 Апельсины 15 65,00 975,00
№2 Бананы 40 55,00 2200,00
№2 Лимоны 15 110,00 1650,00
№2 Мандарины 5 70,00 350,00
№2 Яблоки 10 50,00 500,00

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

Пример 1
Использование параметра «Диапазон_условия» в качестве параметра «Диапазон_суммирования». Значения ячеек указанного диапазона сравниваются с условием и они же суммируются при выполнении условия:

Sub Primer1()

Dim a As Double

a = WorksheetFunction.SumIf(Range(«E2:E11»), «>2000»)

MsgBox a

End Sub

В этом примере складываются все значения в диапазоне E2:E11, которые превышают 2000. Обратите внимание, что условие заключено в прямые кавычки.

Другие варианты использования параметра «Условие»: «<1000», «<>2200», «=2200».

Пример 2
Определяем общую сумму товаров на складе №2:

Sub Primer2()

Dim a As Double

a = WorksheetFunction.SumIf(Range(«A2:A11»), _

«№2», Range(«E2:E11»))

MsgBox a

End Sub

Совпадение с условием ищется в диапазоне A2:A11. Значения ячеек диапазона E2:E11 суммируются в тех строках, где выполняется условие.

Пример 3
Применение знаков подстановки в параметре «Условие»:

Sub Primer3()

Dim a As Double

a = WorksheetFunction.SumIf(Range(«B2:B11»), _

«*ины», Range(«E2:E11»))

MsgBox a

a = WorksheetFunction.SumIf(Range(«B2:B11»), _

«??????ины», Range(«E2:E11»))

MsgBox a

End Sub

В этом примере мы двумя способами определяем общую сумму апельсинов и мандаринов на обоих складах. В первом случае используем звездочку (*), которая заменяет любую последовательность символов. Во втором случае используем знак вопроса (?), который обозначает один любой символ.

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

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.

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.

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 будет формула.

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

DESCRIPTION
The Excel SUMIF function returns the sum of all numbers in a specified range based on a single criteria.

SYNTAX
=SUMIF(range, criteria, [sum_range])

ARGUMENTS
range: (Required) The range of cells you want to test the criteria against.
criteria: (Required) The criteria that is used to determine which of the cells, from the specified range, should be summed.
sum_range: (Optional) The range of cells you want to sum from.

ADDITIONAL NOTES
Note 1: The SUMIF function allows the use of logical elements (>,<,<>,=).
Note 2: The SUMIF function allows the use of wildcards:
* searches to find a match for the sequence of characters.
? searches to find a match to any single character.

Задача по условию на листе 1 в столбце V, найти значения соответствующие условию на лиcте ЧС в столбце F, если данные совпадают, то на лист 1 просуммировать значения из листа ЧС столбца T в  соответствующую ячейку столбца X на листе  1.  у меня получилось, что поиск работает, но упирается в первое найденное значение на листе  ЧС и вставляет только его, как продолжить проверку значений и просуммировать все значения, удовлетворяющие условию.

Код
Dim a%, b%, sx,
Dim Sh1 As Worksheet

Set Sh1 = Sheets("ЧС")
 
For a = 9 To Cells(Rows.Count, 8.End(xlUp).Row
    For b = 4 To Sh1.Cells(Rows.Count, 2).End(xlUp).Row
        If Cells(a, 22) = Sh1.Cells(b, 6) Then
          sx = Application.WorksheetFunction.Sum(Sh1.Cells(b, 20))
           Cells(a, 24).Value =sx
End If
Next b
Next a

13 / 13 / 0

Регистрация: 24.10.2015

Сообщений: 267

1

Суммирование по условию

04.02.2016, 19:45. Показов 16721. Ответов 14


Студворк — интернет-сервис помощи студентам

Доброго дня, уважаемые. Подскажите, не могу сообразить, как просуммировать изменяющийся диапазон по условию. Что вроде суммесли. Условие подразумевается вводить через InputBox, а результат выводить через MsgBox. Т.е. есть два столбца (допустим 1 и 2). Через InputBox вводится значение, и если оно встречается в столбце 1, то суммируются значения из столбца 2 для строк, в которых это значение встречается. В MsgBox выводятся общая сумма всех значений. Количество заполненных строк в столбце 1 равно количеству заполненных строк в столбце 1 и это количество периодически добавляется.
Спасибо.



0



11482 / 3773 / 677

Регистрация: 13.02.2009

Сообщений: 11,145

04.02.2016, 19:49

2

и если оно встречается в столбце 1,

А где находятся эти столбцы?
На вскидку если на листе: сначала считать два столбца в массив, потом загнать в словарь и потом уже спрашивая значения, проверять наличие ключа в словаре суммировать



0



13 / 13 / 0

Регистрация: 24.10.2015

Сообщений: 267

04.02.2016, 19:59

 [ТС]

3

Цитата
Сообщение от Alex77755
Посмотреть сообщение

А где находятся эти столбцы?

Допустим, столбец 1 — это столбец А, а столбец 2 — это столбец С.
Вася 35
Петя 40
Вася 40
В данном примере, если в InputBox завести «Вася», то в MsgBox должно отобразиться 75



0



11482 / 3773 / 677

Регистрация: 13.02.2009

Сообщений: 11,145

04.02.2016, 20:05

4

А, допустим:
Без файла я могу только предложить вариант решения…

Добавлено через 2 минуты

Допустим, столбец 1 — это столбец А, а столбец 2 — это столбец С.

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



0



pashulka

4131 / 2235 / 940

Регистрация: 01.12.2010

Сообщений: 4,624

04.02.2016, 20:05

5

A что =СУММЕСЛИ() уже исчезла из Excel

Visual Basic
1
MsgBox Application.SumIf([A:A], InputBox("Введите имя"), [C:C])



1



13 / 13 / 0

Регистрация: 24.10.2015

Сообщений: 267

04.02.2016, 20:12

 [ТС]

6

Цитата
Сообщение от pashulka
Посмотреть сообщение

1
MsgBox Application.SumIf([A:A], InputBox(«Введите имя»), [C:C])

Суммесли мне известна, но не в VBA Спасибо, это то, что надо.



0



4131 / 2235 / 940

Регистрация: 01.12.2010

Сообщений: 4,624

04.02.2016, 20:21

7

teplovdl, Сорри, прочитал в Вашем сообщение, как счётесли катастрофически быстро теряю зрение



0



13 / 13 / 0

Регистрация: 24.10.2015

Сообщений: 267

04.02.2016, 20:25

 [ТС]

8

Это нормально…

Добавлено через 1 минуту
А скажите, а если придется суммировать диапазон, состоящий из двух столбцов, то как?



0



4131 / 2235 / 940

Регистрация: 01.12.2010

Сообщений: 4,624

04.02.2016, 20:54

9

Результат для товарища Вася должен быть 105 ?

Миниатюры

Суммирование по условию
 



0



13 / 13 / 0

Регистрация: 24.10.2015

Сообщений: 267

04.02.2016, 20:57

 [ТС]

10

Да



0



pashulka

4131 / 2235 / 940

Регистрация: 01.12.2010

Сообщений: 4,624

04.02.2016, 21:32

11

Как вариант, просто суммировать каждый столбец, т.е.

Visual Basic
1
2
iText = InputBox("Введите имя", , "Вася")
MsgBox Application.SumIf([A:A], iText, [B:B]) + Application.SumIf([A:A], iText, [D:D])

Если столбцов более двух

Visual Basic
1
2
3
4
5
iText = InputBox("Введите имя", , "Вася")
For Each iColumn In Array("B", "D", "F")
    iResult = iResult + Application.SumIf(Columns("A"), iText, Columns(iColumn))
Next
MsgBox iResult

Или программно вычислять формулу :

Visual Basic
1
2
=СУММ((A1:A10="Вася")*(B1:B10+D1:D10))
=СУММПРОИЗВ((A1:A10="Вася")*(B1:B10+D1:D10))



1



13 / 13 / 0

Регистрация: 24.10.2015

Сообщений: 267

04.02.2016, 22:09

 [ТС]

12

Цитата
Сообщение от pashulka
Посмотреть сообщение

Visual BasicВыделить код
1
2
3
4
5
iText = InputBox(«Введите имя», , «Вася»)
For Each iColumn In Array(«B», «D», «F»)
* * iResult = iResult + Application.SumIf(Columns(«A»), iText, Columns(iColumn))
Next
MsgBox iResult

Прошу прощения, а выйти из цикла так?
If cells(i,1) = iText Then exit For

Добавлено через 1 минуту
Это правда для цикла типа For i = 1 to 10



0



4131 / 2235 / 940

Регистрация: 01.12.2010

Сообщений: 4,624

04.02.2016, 22:13

13

А не нужно никуда выходить т.к. цикл в моём примере предназначен для перебора столбцов («B», «D», «F»), а не строк.

P.S. С какой целью Вы перебираете строки ?



0



teplovdl

13 / 13 / 0

Регистрация: 24.10.2015

Сообщений: 267

04.02.2016, 22:20

 [ТС]

14

А если пример вот такой

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
Sub zarplata()
lastrow = Cells.SpecialCells(xlLastCell).Row
Temp1 = (InputBox("Укажите начало периода"))
Temp2 = (InputBox("Укажите конец периода"))
Temp3 = (InputBox("Введите Ф.И.О. работника"))
For i = 3 To lastrow
        If Cells(i, 1) >= Temp1 Or Cells(i, 1) <= Temp2 Then
            MsgBox "Зарплата за период " & " с " & Temp1 & " по " & Temp2 & " составила " & Application.SumIf([C:C], Temp3, [Z:Z]) + Application.SumIf([C:C], Temp3, [AA:AA]) & " руб", , "Зарплата"
        
        End If
        If Cells(i, 3) = Temp3 Then Exit For
Next
End Sub

Это реальный пример. Все работает хорошо, но нужно, чтобы цикл прерывался как только в столбце 1 повстречается Temp3. Иначе бесконечно много раз вылезает MsgBox. Вроде все правильно написано, но че то цикл не прерывается.



0



pashulka

4131 / 2235 / 940

Регистрация: 01.12.2010

Сообщений: 4,624

04.02.2016, 22:55

15

Если воспользуетесь функцией СУММЕСЛИМН (Excel 2007 и старше), то сможете отказаться от цикла.

P.S. В более ранних версиях — можно использовать другие возможности.

Добавлено через 16 минут
Если же для подсчёта зарплаты использовать именно перебор ячеек, то можно и так :

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Option Compare Text
 
Private Sub Zarplata()
    On Error GoTo ErrHandler
    
    Dim LastRow&, Row&, Zarplata#
    Dim Temp1 As Date, Temp2 As Date, Temp3$
 
    LastRow = Cells.SpecialCells(xlLastCell).Row
    Temp1 = CDate(InputBox("Укажите начало периода"))
    Temp2 = CDate(InputBox("Укажите конец периода"))
    Temp3 = Trim(InputBox("Введите Ф.И.О. работника"))
 
    For Row = 3 To LastRow
        If Cells(Row, 3) = Temp3 Then
           Select Case Cells(Row, 1)
               Case Temp1 To Temp2
               Zarplata = Zarplata + Cells(Row, 26) + Cells(Row, 27)
           End Select
       End If
    Next
    MsgBox Zarplata: Exit Sub
    
ErrHandler:
    MsgBox Err.Description, vbCritical, Err.Number
End Sub



2



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

04.02.2016, 22:55

15

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