VBA - For Loops


Advertisements

A for loop is a repetition control structure that allows a developer to efficiently write a loop that needs to be executed a specific number of times.

Syntax

Following is the syntax of a for loop in VBA.

For counter = start To end [Step stepcount]
   [statement 1]
   [statement 2]
   ....
   [statement n]
   [Exit For]
   [statement 11]
   [statement 22]
   ....
   [statement n]
Next

Flow Diagram

VBScript For Loops

Following is the flow of control in a For Loop −

  • The For step is executed first. This step allows you to initialize any loop control variables and increment the step counter variable.

  • Secondly, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and the flow of control jumps to the next statement, just after the For Loop.

  • After the body of the For loop executes, the flow of control jumps to the next statement. This statement allows you to update any loop control variables. It is updated based on the step counter value.

  • The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the For Loop terminates.

Example

Add a button and add the following function.

Private Sub Constant_demo_Click()
   Dim a As Integer
   a = 10
   
   For i = 0 To a Step 2
      MsgBox "The value is i is : " & i
   Next
End Sub

When the above code is compiled and executed, it produces the following result.

The value is i is : 0

The value is i is : 2

The value is i is : 4

The value is i is : 6

The value is i is : 8

The value is i is : 10
vba_loops.htm
Advertisements