Open In App

How to Use For Next Loop in Excel VBA?

If you are familiar with the programming you must have an idea of what a loop is, In computer programming, a loop is a sequence of statements that are repeated until a specific condition is satisfied.

In Excel VBA the “For Next” loop is used to go through a block of code a specific number of times.



Syntax:

 For counter = start to end [step count]

statement 1
statement 2
statement 3
.
.
statement n
Next [counter]

Here we can use the counter or any other variable to run them as many times as we need. 



Example: 

When you are displaying numbers from 1 to 10 you may want to set the value of a variable to 1 and display it 10 times, increasing its value by 1 on each loop iteration. The same logic is used in VBA.

We specify how many times we have to run the loop, and then specify what code should our loop execute each time the loop runs.

A loop has 3 parts the first one is an initialization, the second is the condition under which the loop runs, and the last is increment or decrement.

The flow of the control in for loop:

Flow Diagram

Now let us look at an example to understand how the for loop works. Follow the below steps to work along with this article:

Step 1: Press Alt + F11 to open the VBA(visual basic editor where we can write the code).

Step 2: Right-click on the workbook name and then insert a module.

Note: The interface of Excel may change depending upon your version.

STEP 3: Once a module is inserted we can write our code. Let's say we are writing code of print sum  of first 10 numbers so our code will be as follows:

Sub Sumnumbers()
Dim Total as Integer
Dim Count as Integer  
Total = 0                   //initialised total as 0
For count = 1 to 10 // 
Total = Total + count //
Next count //increments counter N = N + 1
MsgBox Total //prints total sum 
End Sub   // code ended

So, what's happening in the above code:

Total = Total + count

Output:

55

Example 2: Printing product of odd +ve integers till 10

Sub ProductNumber()
Dim Product as Integer
Dim Total as Integer
Product = 1
For Count 1 to 10 Step 2   // when we use step 2 it tells compiler to increment
                           // count  by +2 such as 1,3,5,7,..
Product = Product * count
Next Count
Msgbox Product
End Sub

Output:

12150
Article Tags :