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
In this tutorial:
- Visual Basic Fundamentals
- Visual Basic Development Environment
- Visual Basic Editor Window
- Relationship Between Access and Visual Basic
- Visual Basic Debugging Tools
- Working with the Watch Window
- Variables and Constants
- Variable and Constant Scope
- Declaring Constants and Variables
- Dim Statement
- Enum Statement
- Event Statement
- Private Statement
- Public Statement
- Static Statement
- Type Statement
- Collections, Objects, Properties, and Methods
- DAO Architecture
- ADO Architecture
- Referencing Collections, Objects, and Properties
- Use Exclamation Points and Periods
- Assigning an Object Variable-Set Statement
- Object Methods
- Manipulating Complex Data Types Using DAO
- Working with ADO Recordsets
- Functions and Subroutines
- Sub Statement
- Understanding Class Modules
- Property Let
- Property Set
- Controlling the Flow of Statements
- Do...Loop Statement
- For...Next Statement
- For Each...Next Statement
- If...Then...Else Statement
- RaiseEvent Statement
- Stop Statement
- With...End Statement
- Running Macro Actions and Menu Commands
- Executing an Access Command
- Trapping Errors
- Working with 64-Bit Access Visual Basic for Applications
- Using LongPtr Data Types
- Supporting Older Versions of Access
- Using LongLong Data Types