MS-Access / Getting Started

For...Next Statement

Use a For...Next statement to execute a series of statements a specific number of times.

Syntax

For counter = first To last [Step stepamount]
    [<procedure statements>]
    [Exit For]
    [<procedure statements>]
Next [counter]

Notes

The counter must be a numeric variable that is not an array or a record element. Visual Basic initially sets the value of counter to first. If you do not specify a stepamount, the default stepamount value is +1. If the stepamount value is positive or 0, Visual Basic executes the loop so long as counter is less than or equal to last. If the stepamount value is negative, Visual Basic executes the loop so long as counter is greater than or equal to last. Visual Basic adds stepamount to counter when it encounters the corresponding Next statement. You can change the value of counter within the For loop, but this might make your procedure more difficult to test and debug. Changing the value of last within the loop does not affect execution of the loop. You can place one or more Exit For statements anywhere within the loop to exit the loop before reaching the Next statement. Generally you'll use the Exit For statement as part of some other evaluation statement structure, such as an If...Then...Else statement.

You can nest one For loop inside another. When you do, you must choose a different counter name for each loop.

Example

To list in the Immediate window the names of the first five queries in the Conrad Systems Contacts database, enter the following in a function or sub:

Dim dbContacts As DAO.Database
Dim intI As Integer
Set dbContacts = CurrentDb
For intI = 0 To 4
    Debug.Print dbContacts.QueryDefs(intI).Name
Next intI
[Previous] [Contents] [Next]