I use SQL in my code a lot, I’m not a fan of creating queries and then referencing them in my code  since users may delete or change them.

Often I build SQL strings and then I need to debug them in the query Access grid, in the past I would get the value of my SQL string in the immediate window and paste the SQL in a new query window. I got tired of doing it all the time so I created a small function that will do it for me:

MS Access Report Generator

Public Function PopQuerySQL(strSQL As String, strQueryName As String)
Dim qdf As DAO.QueryDef
On Error GoTo PopQuerySQL_Error
DoCmd.Close acQuery, strQueryName
DoCmd.DeleteObject acQuery, strQueryName
Set qdf = CurrentDb.CreateQueryDef(strQueryName, strSQL)
Set qdf = Nothing
DoCmd.OpenQuery strQueryName, acViewNormal
On Error GoTo 0
Exit Function
If Err.Number = 7874 Then
Resume Next ‘Query does not exist
End If
MsgBox “Error ” & Err.Number & ” (” & Err.Description & “) in procedure PopQuerySQL of Module mdlAPI”
End Function
I now use the code with my SQL variable in the immediate window:
PopQuery strSQL, “qryTemp”
It saves me a lot of time and I hope it does the same for you!