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 >>




By the way, if you got or are getting value from the VBA information, please give me a tip, thanks!


These posts may help answer your question too...

What is the purpose of the Me keyword in Access VBA?

What does the Me keyword mean? “Me” refers to the Access form currently in focus. Instead of writing out the entire form reference, you can just use the keyword “Me” which is easier. Like: Me.txtbox = “I am a textbox on the form that currently has the focus.” or you can update a label’s caption […]

How can I interact with other Office applications (Excel) using VBA in Access?

Need to write your Access data or query to an Excel file? Here is the how to do it: Most people are familiar with Excel and know how to use it well (enough), and when you start talking about Access, they get scared off, and don’t know what to do anymore. Well, here you are […]

How To Exit A VBA Loop

Hi, there are times when you need to exit a loop after a certain condition has been met. How do you exit function in VBA? In the following example, you are going to see how to exit a function in VBA: Sub StartNumbers() Dim intNumber As Integer intNumber = ExitTest ‘the number is going to […]

How To Generate A XML File With Access VBA

XML is used to structure your data. You can send a CSV file to another person, but using XML, you can structure your data in a more elegant format, and get very specific about your fields, and what data is contained within your tags (your field names). This is different than a basic CSV file […]

Previous Post

Recordset In VBA – PT1

Next Post

VBA Do Loop

Leave a Reply

Your email address will not be published. Required fields are marked *