I believe I've done something similar to this where I was building a query from a form which allows the user to build the criteria and then saves the results as a query for use later.
Obviously, the query name must be one which you don't use anywhere else and you must have the confirmations of query updates, deletes, etc., turned off (in Tools).
Here's the relevant part of the code I used:
' set the database variable dbs to the
' current database
Set dbs = CurrentDb
' trap the error that occurs when trying
' to delete the query if it does not
' currently exist
On Error GoTo NoQuery
' delete previous definition of query
dbs.QueryDefs.Delete ("Yourqueryname")
NoQuery:
' set your SQL string (be sure to properly
' handle string and date variables when
' building the SQL string
strSQL = {enter your SQL statment here}
' create the query
Set qdf = dbs.CreateQueryDef ("Yourqueryname", strSQL)
' open the query (or do whatever you need,
' such as printing the reportbased on
' the query
DoCmd.OpenQuery qdf.Name, , acReadOnly
' reset the database variable
Set dbs = Nothing
This has worked quite well for me with a user form I made for the user to build the selection and sorting parameters, since I wanted the user to be able to look both at details and at summary (grouping) results to show subtotals based on the sorting selections made by the user.