Modify select Query with VBA

rhesus

Registered User.
Local time
Today, 12:28
Joined
Dec 11, 2002
Messages
22
HELP-- I'm Stuck: Modify select Query with VBA

I've searched for this topic but was unable to find the answer. How do I modify the WHERE clause of a previously created Select Query, using VB? TIA!
 
Last edited:
Assuming there is a query Query1:-
SELECT *
FROM TableName
WHERE ID>=2;

the following code uses a DAO QueryDef object to change the criteria to ID=2.
-----------------------------
Private Sub Command0_Click()
Dim db As DAO.Database
Dim qDef As DAO.QueryDef
Dim SQL As String

Set db = CurrentDb
Set qDef = db.QueryDefs("Query1")

SQL = qDef.SQL

' view SQL statement before edit.
MsgBox SQL

' use functions to manipulate the SQL statement.
SQL = Left(SQL, InStr(SQL, ">") - 1) & Mid(SQL, InStr(SQL, ">") + 1)

' view SQL statement after edit.
MsgBox SQL

' save the edited SQL statement.
qDef.SQL = SQL

End Sub
------------------------------

Note
Once the query is saved, running the code again will result in an error.

The code was written in Access 97, so DAO was used. If you write the code in Access 2000, you must make a reference to DAO (when the code window is open, choose menu Tools, References... and select Microsoft DAO 3.6 Object Library from the Available References list.)
 

Users who are viewing this thread

Back
Top Bottom