MS Access - execute a saved query by name in VBA

前端 未结 3 811
灰色年华
灰色年华 2020-12-30 23:33

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

相关标签:
3条回答
  • 2020-12-31 00:09

    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.

    0 讨论(0)
  • 2020-12-31 00:34

    You can do it the following way:

    DoCmd.OpenQuery "yourQueryName", acViewNormal, acEdit
    

    OR

    CurrentDb.OpenRecordset("yourQueryName")
    
    0 讨论(0)
  • 2020-12-31 00:35

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

    CurrentDb.Execute "queryname"
    
    0 讨论(0)
提交回复
热议问题