Chapter 26 Creating and Editing Queries in VBA
Chapter 26 Creating and Editing Queries in VBA
S
QL queries in Access are an essential tool for allowing the user to view and update
data. In a relational database, it is very rare to obtain meaningful data from a single
table. Queries join tables together, or they can be used to update, delete, or append
records.
When a form is being used, it is sometimes useful to either create a new query to do
something specific or to change the SQL to adapt to changes that the user is making.
Creating a New Query
VBA allows you to easily add a new query to theQueryDefscollection using the following
code. This example is based on the Orders table of the Northwind database. To access this
database, load Access and then click Sample in the left-hand Navigation pane of the opening
screen. Double-click the Northwind icon.
Sub CreateQuery()
Dim Qd As New QueryDef, Qds As QueryDefs
Set Qds = CurrentDb.QueryDefs
Qd.Name = "MyNewQuery"
Qd.SQL = "Select * from orders"
293