November 26, 2015

How to use SUMIF in VBA

How can we use the SUMIF function in VBA. The SUMIF function is useful to add values of items especially in inventory management. Watch the training video to see how we can automate calculations using the SUMIF function and a ‘for next’ looping process:

Watch this video on YouTube.

The complete VBA code:

Sub sumifFunction()
Range(“G2”) = “A”
Range(“H2”) = Application.WorksheetFunction.SumIf(Range(“A2:B8”), “A”, Range(“B2:B8”))
End Sub

Sub addingItemValues()
Dim a As Long, b As Long, c As Long
Dim lastrow As Long
a = 0
b = 0
c = 0
lastrow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Row

For i = 2 To lastrow
If Cells(i, 1) = “A” Then
a = Cells(i, 2) + a
ElseIf Cells(i, 1) = “B” Then
b = Cells(i, 2) + b
ElseIf Cells(i, 1) = “C” Then
c = Cells(i, 2) + c
End If
Next i
Range(“D2”) = “A”
Range(“E2”) = a
Range(“D3”) = “B”
Range(“E3”) = b
Range(“D4”) = “C”
Range(“E4”) = c

End Sub

Further reading:


2 thoughts on “How to use SUMIF in VBA

  1. Dear Mr. Takyar,
    I have found this video most useful, however, what would happen if the spreadsheet expands to more rows than just 3 ?
    Could there be a way to expand this video to include the SUMIF function to an unknown number of row elements?

    I thank you for all the other videos you have published !!

  2. Getting a error message”expected list separator” in the following line:
    Range(“H2”) = Application.WorksheetFunction.SumIf(Range(“A2:B8”), “A”, Range(“B2:B8”))
    I would be thankful if you let me know the solution.
    Nirmal Singh

Comments are closed.