With...End Statement
Use a With statement to simplify references to complex objects in code. You can establish a base object using a With statement and then use a shorthand notation to refer to objects, collections, properties, or methods on that object until you terminate the With statement. When you plan to reference an object many times within a block of code, using With also improves execution speed.
Syntax
With <object reference> [<procedure statements>] End With
Example
To use shorthand notation on a recordset object to add a new row to a table, enter the following:
Dim rcd As DAO.Recordset, db As DAO.Database Set db = CurrentDb Set rcd = db.OpenRecordset("MyTable", _ dbOpenDynaset, dbAppendOnly) With rcd Start a new record .Addnew ' Set the field values ![FieldOne] = "1" ![FieldTwo] = "John" ![FieldThree] = "Viescas" .Update .Close End With
To write the same code without the With, you would have to say:
Dim rcd As DAO.Recordset, db As DAO.Database Set db = CurrentDb Set rcd = db.OpenRecordset("MyTable", _ dbOpenDynaset, dbAppendOnly) ' Start a new record rcd.Addnew ' Set the field values rcd![FieldOne] = "1" rcd![FieldTwo] = "John" rcd![FieldThree] = "Viescas" rcd.Update rcd.Close
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