Sum of all the iterations of a variable in VBA

Viewed 120

I have the following code

Dim i As Integer
For i = 3 To 10

    If Range("H3").Value = Cells(i, 2).Value And Range("I3").Value < Cells(i, 4).Value And _
            Range("I3").Value >= Cells(i, 3).Value Then

        Range("J3").Value = Cells(i, 5).Value

    End If

Next i

I want the value of J3 to represent the sum of all the iterations and not just the last iteration if i. Can it be done?

2 Answers

Change this line

Range("J3").Value = Cells(i, 5).Value

To:

Range("J3").Value = Range("J3").Value + Cells(i, 5).Value

While there are certainly better methods of adding up cells, for your particular method this should work.

Dim i As long, lTotal as long    
For i = 3 To 10

    If Range("H3").Value = Cells(i, 2).Value And Range("I3").Value < Cells(i, 4).Value And _
            Range("I3").Value >= Cells(i, 3).Value Then

        lTotal = Cells(i, 5).Value + lTotal

    End If

Next i

Range("J3").Value = lTotal

Keep a running total of of your loop, then use the running total as your cell's value after you've finished the loop

Related