Set query SQL using VBA

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have a query that is used by a number of other queries. Depending on what
is entered in a form I want to use VBA to put a different SQL statement in
the query. For example if they select option 1 from an option box, the SQL
statement would be different to if they select option 2. Is this possible?
Basically I want to change the SQL of a stored query based on an option box.
 
You can modify the SQL property of the DAO.QueryDef object ...

Private Sub cmdTest_Click()

If Me.Frame0.Value = 1 Then
CurrentDb.QueryDefs("qryTest").SQL = _
"SELECT * FROM tblTest ORDER BY TestID ASC"
Else
CurrentDb.QueryDefs("qryTest").SQL = _
"SELECT * FROM tblTest ORDER BY TestID DESC"
End If
DoCmd.OpenQuery "qryTest"

End Sub
 
Thanks Brendan. I will give it a try.

Brendan Reynolds said:
You can modify the SQL property of the DAO.QueryDef object ...

Private Sub cmdTest_Click()

If Me.Frame0.Value = 1 Then
CurrentDb.QueryDefs("qryTest").SQL = _
"SELECT * FROM tblTest ORDER BY TestID ASC"
Else
CurrentDb.QueryDefs("qryTest").SQL = _
"SELECT * FROM tblTest ORDER BY TestID DESC"
End If
DoCmd.OpenQuery "qryTest"

End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top