Excel vba if sum of range

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

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

  • #2

How about?:

Code:

'if the sum of cell A2 thru A4 is not greater than 7 then....
    If Application.WorksheetFunction.Sum(Range("A2:A4")) < 7 Then MsgBox "Sum less than 7"

Hope that helps!

  • #3

Reply to «If Sum <» in VBA

I should have made myself more clear. The columns can vary. Here it may be A2.A4. The nex time in my loop it may be B2.B4.

Thanks for any help.
Mike

  • #4

Then you could use an inputbox, for the user to enter a range:

Code:

Sub test7a()
Dim myRange As Range

    Set myRange = Application.InputBox("Enter range to sum:", , , , , , , 8)
    If Application.WorksheetFunction.Sum(myRange) < 7 Then MsgBox "Sum less than 7"

End Sub

HTH

  • #5

Still getting type mismatch error

Here’s some of the code I’m trying to run. I’m looping thru A1 to C1, checking the totals of row 3 thru 5 to see if the total is equal to 7 . I don’t know if my TimeOff should be a Range or a Double. I’m getting type mismatch whenever I try either.

Dim rng As Range
Dim rngTarget As Range
Dim rngTimeOff As Range

Set rngTarget = Range(«a1:c1»)
For Each rng In rngTarget
Set rngTimeOff = «SUM(» & rng.Offset(2, 0).Address & «:» & rng.Offset(4, 0).Address & «)»
If rngTimeOff = 7 Then MsgBox «Time Off is seven»
Next

thanks for any help
Mike

  • #6

Code:

Public Sub TestForSumOf7()
Dim SumRng As Range

'SET TOP AND BOTTOM ROWS THAT YOU WANT SUM'd
TopRow = 3
BottomRow = 5

'LOOP THRU EACH COLUMN THAT YOU WANT SUM'd
For Col = 1 To 3

    ' SET THE RANGE to the CURRENT COLUMN and SPECEFIED ROWS
    Set SumRng = Range(Cells(TopRow, Col), Cells(BottomRow, Col))
    
    'TEST SUM WITHIN SPECIFIED RANGE of CURRENT COLUMN
    If WorksheetFunction.Sum(SumRng) = 7 Then _
    MsgBox "Time Off is seven for " & SumRng.Address

Next Col
End Sub

  • #7

Getting error using range addrss

Nimrod, I tried using your formula with a range address and got a «type mismatch» in the line Set rngTimeOff. Can I use that code there?

Thanks for any help
Mike

Sub TestFor7()

Dim rng As Range
Dim rngTarget As Range
Dim wks As Worksheet
Dim rngTimeOff As Range

Set wks = ActiveSheet

‘For Each wks In ActiveWorkbook.Worksheets
Set rngTarget = wks.Range(«H27:Q27»)
For Each rng In rngTarget
Set rngTimeOff = Range(Cells(rng.Offset(2, 0).Address), Cells(rng.Offset(4, 0).Address))
If WorksheetFunction.Sum(rngTimeOff) = 7 Then
MsgBox «Time off is 7 for » & rngTimeOff.Address
End If
Next
‘Next

End Sub

Содержание

  1. Функции VBA СУММЕСЛИ и СУММЕСЛИМН
  2. Рабочий лист СУММЕСЛИ
  3. Присвоение результата СУММЕСЛИ переменной
  4. Использование СУММЕСЛИМН
  5. Использование СУММЕСЛИ с объектом диапазона
  6. Использование СУММЕСЛИМН для объектов с несколькими диапазонами
  7. Формула СУММЕСЛИ
  8. Формула Метод
  9. Метод FormulaR1C1
  10. VBA Excel. Метод WorksheetFunction.SumIf
  11. Синтаксис метода WorksheetFunction.SumIf
  12. Примеры вычисления сумм с одним условием
  13. VBA SUMIF and SUMIFS Functions
  14. SUMIF WorksheetFunction
  15. Assigning a SUMIF result to a Variable
  16. Using SUMIFS
  17. Using SUMIF with a Range Object
  18. Using SUMIFS on Multiple Range Objects
  19. SUMIF Formula
  20. VBA Coding Made Easy
  21. Formula Method
  22. FormulaR1C1 Method
  23. VBA Code Examples Add-in
  24. Метод WorksheetFunction.SumIf (Excel)
  25. Синтаксис
  26. Параметры
  27. Возвращаемое значение
  28. Замечания
  29. Поддержка и обратная связь

Функции VBA СУММЕСЛИ и СУММЕСЛИМН

Из этого туториала Вы узнаете, как использовать функции 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 будет формула.

Источник

VBA Excel. Метод WorksheetFunction.SumIf

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

Синтаксис метода 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
Использование параметра «Диапазон_условия» в качестве параметра «Диапазон_суммирования». Значения ячеек указанного диапазона сравниваются с условием и они же суммируются при выполнении условия:

Источник

VBA SUMIF and SUMIFS Functions

In this Article

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.

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

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.

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.

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.

Using SUMIFS on Multiple Range Objects

Similarly, you can use SUMIFS on multiple Range Objects.

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.

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!

Formula Method

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

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.

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

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.

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Источник

Метод WorksheetFunction.SumIf (Excel)

Добавляет ячейки, заданные заданными критериями.

Синтаксис

expression. SumIf (Arg1, Arg2, Arg3)

Выражение Переменная, представляющая объект WorksheetFunction .

Параметры

Имя Обязательный или необязательный Тип данных Описание
Arg1 Обязательный Range Range — диапазон ячеек, который требуется оценить по критериям.
Arg2 Обязательный Variant Условия — критерии в виде числа, выражения или текста, определяющие, какие ячейки будут добавлены. Например, критерии можно выразить как 32, «32», «>32» или «яблоки».
Arg3 Необязательный Variant Sum_range — фактические ячейки, добавляемые, если соответствующие ячейки в диапазоне соответствуют условиям. Если sum_range опущен, ячейки в диапазоне оцениваются по критериям и добавляются, если они соответствуют условиям.

Возвращаемое значение

Double

Замечания

Sum_range не обязательно должен иметь тот же размер и форму, что и диапазон. Фактические добавляемые ячейки определяются с помощью верхней, левой ячейки в sum_range в качестве начальной ячейки, а затем включает ячейки, соответствующие по размеру и форме диапазону. Например:

Если диапазон имеет значение И sum_range Фактические ячейки:
A1:A5 B1:B5 B1:B5
A1:A5 B1:B3 B1:B5
A1:B4 C1:D4 C1:D4
A1:B4 C1:C2 C1:D4

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

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

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.

To totally unlock this section you need to Log-in

Login
The Microsoft Excel SUMIF function adds all numbers in a range of cells, based on a given criteria. If we want to use or automize some operations with VBA in Excel there are three ways we can be involved with SUMIF() when we are using VBA: The Range.Formula(), Range.FormulaR1C1(), Range.FormulaArray() properties.

This is a straightforward process. To enter a formula containing SUMIF() we use the Range.Formula or Range.FormulaR1C1 properties:

Sub Example1()
 
'=SUM(SUMIF(B2:B7,{"Smith";"Williams"},D2:D7))
Sheet1.Range("C1").Formula = "=SUM(SUMIF(B2:B7,{""Smith"";""Williams""},D2:D7))"
End Sub

If the formula needs to be a CSE formula, we use the Range.FormulaArray property:

Sub Example2()
 
'{=SUM(SUMIF(B2:B7,F2:F3,D2:D7))}
Sheet1.Range("C1").FormulaArray = "=SUM(SUMIF(B2:B7,F2:F3,D2:D7))"
End Sub

Just as when you manually type in an array formula, you should not include the { } at the beginning and end. Excel will automatically add these for you.

The WorksheetFunction Class

If we want to conditionally sum using the SUMIF() worksheet function in VBA, we can access it via the WorksheetFunction class.

Sub Example3()
 
Dim varResult As Variant
'=SUMIF(B2:B7,"Smith",D2:D7)
varResult = Application.WorksheetFunction.SumIf( _
Arg1:=Sheet1.Range("B2:B7"), _
Arg2:="Smith", _
Arg3:=Sheet1.Range("D2:D7"))
End Sub

With this method, if SUMIF() returns an error then we have to add an error handler in VBA to handle it. I have included the named arguments in the example so you can see how uninformative they are and the little benefit intellisense gives us. Ideally we would like to see range, criteria and sum_range, but instead we have to work with arg1,arg2 and arg3.

Another way is to call it from the Application class:

Sub Example4()
 
Dim varResult As Variant
'=SUMIF(B2:B7,"Smith",D2:D7)
varResult = Application.SumIf( _
Sheet1.Range("B2:B7"), _
"Smith", _
Sheet1.Range("D2:D7"))
End Sub

Using this approach, an error returned by SUMIF() will be held within the vResult variable which we can then handle with the CVErr() function. For further information and comparisons between these approaches have a read of this thread at dailydoseofexcel.

We come back to the earlier point that the 1st and 3rd parameters expect range references. When you are calling SUMIF() via the WorksheetFunction class, do not be tempted to include any additional brackets around the range argument you are passing in.

Sub Example5()
 
Dim varResult As Variant
'type mismatch or object required error
varResult = Application.WorksheetFunction.SumIf( _
(Sheet1.Range("B2:B7")), _
"Smith", _
Sheet1.Range("D2:D7"))
End Sub

The extra brackets around Sheet1.Range(«B2:B7») cause that range to be de-referenced into an array which, as was mentioned the previous blog post, is unacceptable.

Application.Evaluate() and Worksheet.Evaluate() Methods

For the more complex SUMIF() formulas, the easiest way to calculate them directly within VBA is to use the Worksheet.Evaluate method. This method (more often than not) gives the same result as when the formula has been CSE entered, so we can treat normal and CSE formulas in the same way.

Sub Example6()
 
Dim varResult As Variant
'=SUM(SUMIF(B2:B7,{"Smith";"Williams"},D2:D7))
varResult = Sheet1.Evaluate("=SUM(SUMIF(B2:B7,{""Smith"";""Williams""},D2:D7))")
'{=SUM(SUMIF(B2:B7,F2:F3,D2:D7))}
varResult = Sheet1.Evaluate("=SUM(SUMIF(B2:B7,F2:F3,D2:D7))")
End Sub

Again, errors returned by the evaluated expression will be stored within the variant variable. The Evaluate method is qualified by the Sheet1 codename, so all of the unqualified range references within the string expression will be considered to belong to that sheet.

FAQs

Question: I have a question about how to write the following formula in Excel.

I have a few cells, but I only need the sum of all the negative cells. So if I have 8 values, A1 to A8 and only A1, A4 and A6 are negative then I want B1 to be sum(A1,A4,A6).

Answer: You can use the SUMIF function to sum only the negative values as you described above. For example:

=SUMIF(A1:A8,"<0")

This formula would sum only the values in cells A1:A8 where the value is negative (ie: <0).

Question: In Microsoft Excel I’m trying to achieve the following with IF function:

If a value in any cell in column F is «food» then add the value of its corresponding cell in column G (eg a corresponding cell for F3 is G3). The IF function is performed in another cell altogether. I can do it for a single pair of cells but I don’t know how to do it for an entire column. Could you help?

At the moment, I’ve got this:

=IF(F3="food"; G3; 0)

Answer: This formula can be created using the SUMIF formula instead of using the IF function:

=SUMIF(F1:F10,"=food",G1:G10)

This will evaluate the first 10 rows of data in your spreadsheet. You may need to adjust the ranges accordingly.

I notice that you separate your parameters with semi-colons, so you might need to replace the commas in the formula above with semi-colons.

Понравилась статья? Поделить с друзьями:
  • Excel vba if statements and
  • Excel vba if starts with
  • Excel vba if sheet visible
  • Excel vba if shape selected
  • Excel vba if range then