VBA For Loop

Use the VBA For Loop when you know how many iterations the code should make. Using this VBA For Loop will allow you to loop for a specific number of times.

Take a look at the video:

The syntax for the VBA For Loop is:

******************************************

For counter= start To end [Step backward count (how many steps backward to the "start')]
     [statements]
Next counter

******************************************

You specify the start and end values for the counter, and by default, the code steps forward from less to greater.


Private Sub ForNext()
    Dim intCounter As Integer
    
    'increment intCounter
    
    For intCounter = 1 To 15
    
        MsgBox intCounter

    Next
    
End Sub

 

By using the “Step” keyword you can alter the increments, other than 1, the code moves forward through.

 

Private Sub ForNextStep()
	Dim intCounter As Integer

	'show evens:

	For intCounter = 0 To 16 Step 4
		MsgBox intCounter
	Next
End Sub

 

You can also use the VBA For Loop in reverse by specifying “Step -1”


Private Sub ForNextStepBack()
	Dim intCounter As Integer

	'backwards from 20:

	For intCounter = 20 To 1 Step -1
		MsgBox intCounter
	Next

End Sub


Exit a VBA For Loop by using the Exit For statement.

<< VBA Do Loop | Recordset In VBA – PT1 >>

Offsite Related Information:

“Go Fund Me” Page


($5 suggested amount)

(…10% of your gift amount will go to charity)

Free! Subscribe To Our YouTube Channel!

Free MS Access VBA Programming Course

Facebooktwitterredditpinterestlinkedinmailby feather
Tags: , , , , ,