I do this kind of thing all the time! I've used VBA to rewrite Access queries as well as queries that "pass through" to a MySQL database. Rewriting a query in VBA depends on how complicated you want to get.
I've always used DAO
, which is older technology (see comments below for clarifcation on DAO vs ADO), but it's worked for me in this instance. You'll need to add a reference to DAO in VBA by going to Tools > References, and then add "Microsoft DAO 3.6 Object Library."
You might write a procedure that looks like this:
Sub RewriteQuerySQL(strQueryName As String, strParameter As String)
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Set db = CurrentDb()
Set qdf = db.QueryDefs(strQueryName)
qdf.SQL = "SELECT [Table].Field1, [Table].Field2 " & vbCrLf & _
"FROM [Table] " & vbCrLf & _
"WHERE ([Table].Field1 = " & chr(34) & strParameter & chr(34) & ");"
End Sub
The above code is going to change the SQL for the query you specify with the query SQL in the VBA code with the strParameter
embedded in the SQL query.
Here's another way of doing it. This is code I used in a sales reporting application to rewrite a query based on a salesperson's number:
Sub rewriteAccountsBySalesRepSortSQL(lngSalesRep As Long)
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim strSQL As String
Dim strOriginal As String
Dim strReplacePart As String
Dim strSQLReplace As String
Dim lngLocSalesperson As Long
Dim lngLocMyRoundUp As Long
Dim lngLocParen As Long
Dim lngLocEndParen As Long
Set db = CurrentDb()
Set qdf = db.QueryDefs("qryS Accounts by Sales Rep Sorted by Diff DESC")
strSQL = qdf.SQL
lngLocSalesperson = InStr(strSQL, "Salesperson1)=")
lngLocEndParen = InStr(lngLocSalesperson + 14, strSQL, ")")
strOriginal = Mid(strSQL, lngLocSalesperson, lngLocEndParen - lngLocSalesperson)
'lngLocParen = InStrRev(strSQL, "(", lngLocSalesperson)
strReplacePart = "Salesperson1)=" & lngSalesRep
strSQLReplace = Replace(strSQL, strOriginal, strReplacePart)
qdf.SQL = strSQLReplace
End Sub
Instead of writing out the whole query, the code simply finds the current sales rep number and replaces it with the new number. I actually prefer the latter method. The latter method was used to send a query directly to MySQL, so the syntax with an Access query may be slightly different.