7

I have been accustomed to do recordssets in the following format:

Dim rs As DAO.Recordset
Dim strSQL As String

strSQL = "Select field1, field2 from myTable where field1 > 30"

Set rs = CurrentDb.OpenRecordset(strSQL)

'... Do wahtever using rs.

Is it possible to use an already created query instead of text and giving it the where clause?

This is a linked table to a SQL Server 2008 Database. I like to save simple queries in Access.

1

1 Answer 1

15

You can either

  • Use a query that has parameters and specify values for parameters provided that the query uses parameters.

    Dim dbs As DAO.Database
    Dim qdf As DAO.QueryDef
    Dim prm As DAO.Parameter
    Dim rst As DAO.Recordset
    
    Set qdf = CurrentDb.QueryDefs("qry_SomeQueryWithParameters")
    
    qdf.Parameters("SomeParam").Value = "whatever"
    
    Set rst = qdf.OpenRecordset
    

or

  • Specify a query name as the command and use the Filter property on the recordset

    Dim rs As DAO.Recordset
    Dim rsFiltered As DAO.Recordset


    Set rs = CurrentDb.OpenRecordset(qry_SomeQueryWithoutParameters)

    rs.Filter = "field1 > 30"
    set rsFiltered  = rs.OpenRecordset


Sign up to request clarification or add additional context in comments.

4 Comments

Using the second example had to add a statement to set another recordset initialized from the filterd recordset and use that, per the example you provided. Thanks
@Rick nice. I've updated my answer to include the correction.
@ConradFrix I get "Syntaxfehler(fehlender Operator) in Abfrageausdruck 'massnahme=bankett'. My code: abfrage = "SELECT * FROM tab1" ;Set rs = db.OpenRecordset(abfrage) rs.Filter = "15massnahme=bankett" rsf = rs.OpenRecordset
@ConradFrix checking your first solution: I get "Error 3265, Element not found in this list" if I write abfrage = "SELECT * FROM tab1"; Set qdf = db.QueryDefs(abfrage)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.