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: