1. Create a query and name it "qryMySampleQuery" (template)
2. Read your querydef from template query:sqlIn = CurrentDb.QueryDefs("qryMySampleQuery").SQL
3. You can have a variable table name: strMyTable (or any other parm you want to change inside SQL code.)
sqlOut = Replace(sqlIn, "tblTableSampleName", strMyVariableTableName)
4. Pass new SQL code to change your production query "qryRealQueryname"
If ObjectExist("Query", "qryRealQueryname") Then
MakeMyQuery = ChangeQueryDef("qryRealQueryname", sqlOut)
Else
MakeMyQuery = MakeQueryDef("qryRealQueryname", sqlOut)
End If
For function ObjectExist check Does Access Object Exists
'Copy two functions below in your VBA Module:
'
'------------- Change Query Definition ---------------------'Change existing query SQL from the VBA code module
Function ChangeQueryDef(strQuery As String, strSQL As String) As Boolean
' strSQL is SQL string for the querydef of strQuery
If strQuery = "" Or strSQL = "" Then Exit Function
'
Dim qdf As QueryDef
'
Set qdf = CurrentDb.QueryDefs(strQuery)
qdf.SQL = strSQL
qdf.Close
'
RefreshDatabaseWindow
ChangeQueryDef = True
'
End Function
'------------- End Change Query Definition -----------------
'
'------------- Make Query Definition -----------------------
'Create new query from the VBA code module
Function MakeQueryDef(strQuery As String, strSQL As String) As Boolean
' Purpose: Create a querydef
' Arguments: Query name and the SQL string for the querydef
' Returns: True
If strSQL = "" Then Exit Function
'
Dim qdf As QueryDef
'Set qdf = CurrentDb.CreateQueryDef(strQuery)
qdf.SQL = strSQLqdf.Close
RefreshDatabaseWindow
'
MakeQueryDef = True
'End Function
'------------- End Make Query Definition -----------------------