Author: Oscar Cronquist Article last updated on January 19, 2018

The picture above demonstrates a FOR NEXT statement that goes through each cell value in cell range B3:B8 and adds it to a total.

The Message box then displays the sum. 4+2+5+3+6+4 is 24. Here is the subroutine:

```Sub Macro1()

For Each Value In Range("B3:B8")

Result = Result + Value

Next Value

MsgBox Result

End Sub
```

The Value variable stores the number from cell B3 in the first iteration then continues to B4 and overwrites the previous value, and so on. The Result variable adds each value in every iteration and builds a sum.

The macro repeats the lines between FOR and NEXT as many times as there are cells in Range("B3:B8).

The message box displays the sum and you then need to click on the OK button to proceed.

### FOR NEXT with counter variable

You can have a variable that counts for you, in this case it is variable i. The FOR NEXT statement executes the lines between FOR and NEXT ten times incrementing variable i with 1 each time. See picture above.

It starts with 1 and continues up to 10. 1+2+3+4+5+6+7+8+9+10 = 55. It is not necessary to include the variable name after the NEXT statement, however, it will be easier to read your code if you do so.

The message box then displays the sum. As soon as you click the OK button the macro ends.

### FOR NEXT with counter variable and STEP keyword

The STEP keyword allows you to increase or decrease the counter value with a number you specify.

If you use a negative step number make sure the end counter number is less than the start counter number to avoid your macro being in an endless loop.

In above example the counter variable is i and it starts with 10 and ends with 1, the STEP value is -2. 10+8+6+4+2=30.

### FOR NEXT and EXIT FOR statements

The EXIT FOR statement allows you to stop iterating through a FOR NEXT statement which is handy if, for example, an error value shows up.

The picture above uses the IF THEN statement to check if counter variable i is equal to 6. 10 + 8 + 6 = 24.