How do I execute a saved query in MS Access 2007 in VBA?
I do not want to copy and paste the SQL into VBA. I rather just execute the name of the query.
This
You should investigate why VBA can't find queryname.
I have a saved query named qryAddLoginfoRow. It inserts a row with the current time into my loginfo table. That query runs successfully when called by name by CurrentDb.Execute
.
CurrentDb.Execute "qryAddLoginfoRow"
My guess is that either queryname is a variable holding the name of a query which doesn't exist in the current database's QueryDefs collection, or queryname is the literal name of an existing query but you didn't enclose it in quotes.
Edit:
You need to find a way to accept that queryname does not exist in the current db's QueryDefs collection. Add these 2 lines to your VBA code just before the CurrentDb.Execute
line.
Debug.Print "queryname = '" & queryname & "'"
Debug.Print CurrentDb.QueryDefs(queryname).Name
The second of those 2 lines will trigger run-time error 3265, "Item not found in this collection." Then go to the Immediate window to verify the name of the query you're asking CurrentDb
to Execute
.
You can do it the following way:
DoCmd.OpenQuery "yourQueryName", acViewNormal, acEdit
OR
CurrentDb.OpenRecordset("yourQueryName")
To use CurrentDb.Execute, your query must be an action query, AND in quotes.
CurrentDb.Execute "queryname"