MS Access - execute a saved query by name in VBA MS Access - execute a saved query by name in VBA vba vba

MS Access - execute a saved query by name in VBA


You can do it the following way:

DoCmd.OpenQuery "yourQueryName", acViewNormal, acEdit

OR

CurrentDb.OpenRecordset("yourQueryName")


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.


To use CurrentDb.Execute, your query must be an action query, AND in quotes.

CurrentDb.Execute "queryname"