# 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:

The complete VBA code:

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

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

SUMIF in VBA

### Dinesh Kumar Takyar

Welcome to exceltrainingvideos.com! My aim is to help you learn MS Excel including VBA. I always felt that a good way to learn something was to find solutions to problems in that domain. That is why I share these Excel videos with you. Mostly these are questions asked during my corporate training sessions. I've been training individuals and companies in computers since 1991. I did my B. Sc. (Vordiplom), M. Sc. (Diplom) and Ph.D. (Dr. rer. nat.) from Hamburg, Germany. The best thing about solving some of my visitor's questions is that I also gain new insights. For more Excel VBA solutions you may like to visit my YouTube channel: http://youtube.com/familycomputerclub For a structured Excel VBA training course online you can visit: https://www.youtube.com/excelvbaonline

## One thought on “How to use SUMIF in VBA”

1. Xavier says:

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 !!
XY