OzGrid

For Loop Step

< Back to Search results

 Category: [Excel]  Demo Available 

For Loop Step

 

For Loop. For Next...Loop With Step

Got any Excel Questions? Free Excel Help

For Loop Step

A For Loop is used to repeat a block of code a specified number of times. In this example we make use of the Step statement in 2 different ways. The first tell Excel to increment by 2 each loop, while the second tells Excel to count backwards from 10 to 1 and increment each time by -1. We can force an exit from a For loop with the Exit For Statement. E.g. If lNum=5 Then Exit For

Sub For_Loop_With_Step()

Dim lCount As Long, lNum As Long



    For lCount = 1 To 10 Step 2

        lNum = lNum + 1

    Next lCount

    

    MsgBox "The For loop made " & lNum & " loop(s). lNum is equal to " & lNum

End Sub



Sub For_Loop_With_Step_Backwards()

Dim lCount As Long, lNum As Long



    For lCount = 10 To 1 Step -1

        lNum = lNum + 1

    Next lCount

    

    MsgBox "The For loop made " & lNum & " loop(s). lNum is equal to " & lNum

End Sub

For...Next Loop

Syntax
For counter = Start To end [Step step]
[statements]
[Exit For]
[statements]
Next [counter]

 
 

See also:

Excel VBA: Extract Word From a Text String
Excel VBA: Find Number Between 2 Numbers
Find Method to Find Dates
Excel VBA Find Method
Force Text to Upper Case/Proper Case
Used to Loop Through a Collection or Array
For Loop

 

See also Index to Excel VBA Code and Index to Excel Freebies and Lesson 1 - Excel Fundamentals and Index to how to… providing a range of solutions.

 

Click here to visit our Free 24/7 Excel/VBA Help Forum where there are thousands of posts you can get information from, or you can join the Forum and post your own questions.


Gallery



stars (0 Reviews)