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:
Public Function PopQuerySQL(strSQL As String, strQueryName As String)Dim qdf As DAO.QueryDefOn Error GoTo PopQuerySQL_ErrorDoCmd.Close acQuery, strQueryNameDoCmd.DeleteObject acQuery, strQueryNameSet qdf = CurrentDb.CreateQueryDef(strQueryName, strSQL)Set qdf = NothingDoCmd.OpenQuery strQueryName, acViewNormalOn Error GoTo 0Exit FunctionPopQuerySQL_Error:If Err.Number = 7874 ThenResume Next ‘Query does not existEnd IfMsgBox “Error ” & Err.Number & ” (” & Err.Description & “) in procedure PopQuerySQL of Module mdlAPI”End FunctionI 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!
Juan
In a VBA module
Example:
Ok = PopQuerySQL( “Select Top 1 From tbCustomers”, “e_QryTemp”
or
Ok = PopQuerySQL( “Select sum(Qty) as Tot From tbSalesDetail”, “e_QryTemp”
Hey Juan,
I tried to use your function but I still don’t get where should I put the line PopQuery strSQL, “qryTemp”.
Can you explain a little bit?
Thanks,
Diego