I\'d like to be able to create a parameterized query in MS Access 2003 and feed the values of certain form elements to that query and then get the corresponding resultset ba
There are three traditional ways to get around this issue:
I think it's just wrong to me that you would ave to inject something like [?enter ISO code of the country]
or references to fields on your form like : [Forms]![MyForm]![LastName]
.
It means we can't re-use the same query in more than one place, with different fields supplying the data or have to rely on the user not to foul up the data entry when the query is run. As I recall, it may be hard to use the same value more than once with the user entered parameter.
Typically I've chosen the last option an built the query on the fly, and updated the query object as needed. However, that's rife for an SQL injection attack (accidental or on purpose knowing my users), and it's just icky.
So I did some digging and I found the following here (http://forums.devarticles.com/microsoft-access-development-49/pass-parameters-from-vba-to-query-62367.html):
'Ed. Start - for completion of the example
dim qryStartDate as date
dim qryEndDate as date
qryStartDate = #2001-01-01#
qryEndDate = #2010-01-01#
'Ed. End
'QUOTEING "stallyon": To pass parameters to a query in VBA
' is really quite simple:
'First we'll set some variables:
Dim qdf As Querydef
Dim rst As Recordset
'then we'll open up the query:
Set qdf = CurrentDB.QueryDefs(qryname)
'Now we'll assign values to the query using the parameters option:
qdf.Parameters(0) = qryStartDate
qdf.Parameters(1) = qryEndDate
'Now we'll convert the querydef to a recordset and run it
Set rst = qdf.OpenRecordset
'Run some code on the recordset
'Close all objects
rst.Close
qdf.Close
Set rst = Nothing
Set qdf = Nothing
(I haven't tested it myself, just something I collected in my travels, because every once in a while I've wanted to do this to, but ended up using one of my previously mentioned kludges)
Edit I finally had cause to use this. Here's the actual code.
'...
Dim qdf As DAO.QueryDef
Dim prmOne As DAO.Parameter
Dim prmTwo As DAO.Parameter
Dim rst as recordset
'...
'open up the query:
Set qdf = db.QueryDefs("my_two_param_query") 'params called param_one and
'param_two
'link your DAP.Parameters to the query
Set prmOne = qdf.Parameters!param_one
Set prmTwo = qdf.Parameters!param_two
'set the values of the parameters
prmOne = 1
prmTwo = 2
Set rst = qdf.OpenRecordset(dbOpenDynaset, _
dbSeeChanges)
'... treat the recordset as normal
'make sure you clean up after your self
Set rst = Nothing
Set prmOne = Nothing
Set prmTwo = Nothing
Set qdf = Nothing