How to set parameter on query when using DoCmd.OpenQuery

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ncsthbell
    New Member
    • May 2007
    • 167

    How to set parameter on query when using DoCmd.OpenQuery

    Using MS Access 2007. I built a form that has a combo box of lists of 'actions' (cmboActions). This form also has a button to click that I want to run a query and display the results in datasheet view.
    I am trying to pass the value from the cmboActions box to the query via the following method:

    Code:
      Dim qdf As QueryDef
      Dim rst As Recordset
      
      Set qdf = CurrentDb.QueryDefs(qry_ActionTaken_parm)
      qdf.Parameters(0) = cmboActions.value
      Set rst = qdf.OpenRecordset
      
      DoCmd.OpenQuery [B]"qry_ActionTaken_parm"[/B]  rst.Close
      qdf.Close
      Set rst = Nothing
      Set qdf = Nothing
    I am not sure how to set the parm up on the query. In the column on the query for "ActionTake n", how do I define the parameter (I currently have: [Forms]![frm_Action]![cmboActions]? I am assuming that 'qdf.Parameters (0)' relates to the first parameter found defined on the query. When I run the code I am getting the following error:
    Set qdf = CurrentDb.Query Defs(qry_AssetActio nTaken_parm)"Variable not defined" on the query name

    OR.... is there a better way to accomplish what I am trying to do? Trying to avoid having to build a separate query for each different value of 'ActionTaken' Any help would be appreciated.
    Last edited by NeoPa; Mar 23 '11, 12:49 AM. Reason: I'm astounded you're still not using the CODE tags. They are required to post here!
  • NeoPa
    Recognized Expert Moderator MVP
    • Oct 2006
    • 32662

    #2
    I struggled with this concept manfully for many weeks, until I realised they really didn't support passing parameters to the query when opened from the interface (which is essentially the same as using DoCmd.OpenQuery ()). Maybe there's a good reason for that, but it always seemed an omission of something obviously beneficial to me.

    Another question recently had the same problem (though they weren't looking to use parameters). What you can do most easily (There are a number of ways around this. Some more clumsy than others, but in different ways) is to reference the form's ComboBox control directly from within your query :
    Code:
    ...
    WHERE [YourField] = Forms("YourForm").cmboActions

    Comment

    • TheSmileyCoder
      Recognized Expert Moderator Top Contributor
      • Dec 2009
      • 2322

      #3
      Have you tried using quotes around the query name? They seem to be missing in the code you have posted.

      Comment

      Working...