Below function will create a named query from an SQL string.
Code:
'---------------------------------------------------------------------------------------
' Procedure : fcnCustomizeSQL
' DateTime : 9/26/2006 20:57
' Author : Davegri
' Purpose : Attach new SQL property to an existing querydef. If the Query doesn't exist,
' : create it with the passed SQL. Created query name passed in string qName.
'---------------------------------------------------------------------------------------
'
Function fcnCustomizeSQL(qName As String, strPassedSQL As String)
Dim qthisQuery As DAO.QueryDef
On Error GoTo fcnCustomizeSQL_Error
'if the query has been deleted, create it
If DCount("Name", "MSysObjects", "[Name] = " & Chr$(39) & qName & Chr$(39)) = 0 Then
Set qthisQuery = CurrentDb.CreateQueryDef(qName, strPassedSQL)
Set qthisQuery = Nothing
Exit Function
End If
'else modify it
Set qthisQuery = CurrentDb.QueryDefs(qName)
qthisQuery.SQL = strPassedSQL
fcnCustomizeSQL_EXIT:
Set qthisQuery = Nothing
Exit Function
fcnCustomizeSQL_Error:
MsgBox Err.Number & ", " & Err.Description & ", fcnCustomizeSQL"
Resume fcnCustomizeSQL_EXIT
End Function