For Next Loop (Excel VBA )

For Next loop repeats a statement for a specified number of times. This is your basic loop for alot of situations.  You will use it quite often and you will like it 🙂

for next loop*Please note that I don’t claim that code examples are the most efficient or best for the jobs that theya re written for. They are presented for explainatoy purposes only.
Here is how it’s syntax is:

For counter [ As datatype ] = start To end [ Step step ]

[ statements ]

[ Continue For ] optional

[ statements ]

[ Exit For ] optional

[ statements ]

Next [ counter ]

Here is a couple of examples about how to use For Next loop:

Example 1: This sub procedure loops through numbers 1 to 50 and sums them and show the result with a message box.

Sub ForNext_Example1()

Dim i As Integer

Dim j As Integer

For i = 1 To 50

j = j + i

Next i

MsgBox j

End Sub

Example 2: This sub procedure loops through the first 100 customers and performs the tast you give them.

Sub ForNext_Example2()

Dim custnr as integer

For custnr = 1 to 100

‘               More code here (like fetching data and wrting near customer names,  calculatingspecial discounts, etc)

Next custnr

End Sub

Since loop is defined for custnr (customer number) from 1 to 100, macro will start with custnr as 1 and perform given actions, then itarate custnr to 2 and perform given actions, and so on. Macro will continue to loop until custnr equals 100. Then macro will stop looping and start next procedure.

For more Excel VBA related tutorials, please visit VBA Category.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.