VBA For Loop
A For loop is a repetition control structure allows a developer to be logical write a loop which needs to be executed a specific number of times.
Here is some flow of control in for loop as given below, such as:
- First, for loop is executed. This allows you to initialize any loop control variables and increment the step counter variable.
- Second, for loop conditions is evaluated. If it is True, then the body of the loop is executed. And if it is false, the body does not execute. The flow of the control jumps to the next statement after For loop.
- Then the body of for loop will execute, the flow of control jumps to the next statement. And this statement allows you to update any loop control variables. It updates based on the step counter value.
- Now, the condition is re-evaluated. If it is true, the loop is executed, and the whole process repeats itself. And if the condition is false then for loop will terminate.
The For loop executes a block of code a specific number of times.
- The counter variable is i, which is required to be declared.
- The Start_value of the counter is 1, and its End_value of the counter is 10, both are the numeric values.
- The keyword "Step" is optional, and it is a numeric value by which the counter is incremented each time when the loop is run.
- The next statement is increment the counter by the step value and returns to the for the statement, which repeats the code if the counter value does not exceed the "End_value" of 10.
- If the counter is equal to the End_value, the loop will be continued, or it will be stopped only when the End_value exceeds.
Nested For Next loops
You also can use the nested for loop to get the more complex automation done in excel. There would be a "For Next" loop within a "For Next" loop.
For example: Suppose you want to protect all the worksheets in all open workbooks in your system.
Exit For statement
You can exit the for loop statement without completing the full cycle by using the exit for the statement. The Exit for command will immediately stop the execution of the existing loop.
For example, It is a more efficient way to check if there are any negative values or not. But in this case, there are no negative values, and we can exit the loop and save some VBA processing time.