5

I am new to Access and I am coming from C#, SQL Server & .Net. There is a project that has come my way and I have to complete some parts.

The scenario may be described as:

  1. An Access form with a subform
  2. An Access query that is the data source of the aforementioned subform, with two parameters, displayed as: Parametername1 String(255),Parametername2 String(255).
  3. VBA code module(s)

My plan is to set the values of the above mentioned query parameters within a procedure in my VBA code module. I believe this should refresh my subform as the query is the datasource for the subform.

The problem is I don't know how to implement this plan.

I want to use a query because I don't want to mess up my VBA Code with inline SQL.

I am using Access 2010.

StockB
  • 755
  • 1
  • 13
  • 33
Romi24
  • 271
  • 2
  • 7
  • 15
  • Inline SQL in a VBA module is a bad idea not only for readability purposes, but also because it could throw unexpected errors and pose a [security threat](http://xkcd.com/327/). – StockB Dec 12 '13 at 20:13

4 Answers4

6

I had exactly this question, I wanted to use the same 'stored' update query but execute it from two different forms so wanted to pass the parameter to the query at run-time. This is what I found (in another forum) that does exactly what I want:

With CurrentDb.QueryDefs("qry_YourQuery")
   .Parameters("yourParam") = yourVBAvar
   .Execute
End With
Ben
  • 84
  • 1
  • 2
  • What does "qry_YourQuery" look like? Do you just put `?` where the parameter value should go? – StockB Dec 12 '13 at 17:03
  • Do you have a link to the forum where you found this snippet? I searched, but all I could find were references to this post. – StockB Dec 13 '13 at 14:49
  • 1
    For those of you who are wondering. "qry_YourQyery" is the name of the saved query that you have in the list of queries in the access database, like qryUpdateSalary. "yourParam" is the name of the parameter that you have in your query, ie Update tblSalary set Salary = wage*workhrs where PersonId = [person]. In this case parameter is person so example above would look like `code With CurrentDb.QueryDefs("qryUpdateSalary") .Parameters("person") = personID 'this variable comes from another step in the VBA code .Execute End With ` – kuklei Jul 03 '14 at 16:27
2

The whole point of a subform is that it is controlled by the record source and the link child and master fields. Let us say the form is Company and the subform is Employees, the record source for the subform might be:

SELECT EmployeeID, CompanyID, Position, Etc FROM Employees

The link child and master fields would be CompanyID. As you moved through the master form, only those records relevant to the current company would be displayed. Let us say you then want to display only those employees who are in a technical position, you can change the record source at run time:

SELECT EmployeeID, CompanyID, Position, Etc FROM Employees
WHERE Position = "Technical"

Or if this is always to be a filter on the form, add a combobox, say, to the main form and use that as a second link master field, so you have:

Link Master Fields:  CompanyID; cboPosition
Link Child Fields :  CompanyID; Position

Finally, you can simply set the filter property from the main form :

Me.Employees_subform.Form.Filter = "Position=""Tecnical"""
Me.Employees_subform.Form.FilterOn = True

If this is not what you have in mind, please add some notes to your question.

EDIT

You can supply parameters to a query by referencing a control on a form:

SELECT EmployeeID, CompanyID, Position, Etc FROM Employees
WHERE Position = Forms!MyMainForm!cboPosition

You can completely change the SQL of a query and you can use ADO, however, changing the SQL is similar to setting the record source in that the SQL is changed in code and using ADO is usually not the best bet for forms.

What you cannot do is change a parameter and have it 'stick' with a form or subform.

For example:

DoCmd.SetParameter "@SomeID", "1"
' This works
DoCmd.OpenQuery ("Queryx")

' This will give a prompt for @SomeID and then run
Me.SomeSubform.Form.RecordSource = "Queryx"
Fionnuala
  • 90,370
  • 7
  • 114
  • 152
  • Remou thanks. This will help for sure. But I don't want to use a filter. I already have a query that is the record source for the sub form. I need to know if there is anyway by which I can change / set the parameters of the query within VBA code. I am looking for a solution on the lines of using a Stored Procedure in SQL server and using the SqlCommand (System.data.sqlclient) class in .net. I dont even know if it is possible. Otherwise I will just embed my sql in my VBA code and use the SQL stateemnt as my record / data source and get on with life. Access is different!! – Romi24 Aug 05 '12 at 05:06
  • Access is different and the main difference is that you can do a lot without any code at all, which is something people often forget. In this case, the parameters for your query should come from a form, and I was pointing out ways that this could happen. There are other options I missed and I will add them. – Fionnuala Aug 05 '12 at 07:36
  • thanks again Remou...i think we are close to a solution. the only thing is I dont want the application to prompt for the parameter defined in the query. I want to set the value of the parameter within my VBA code.... Taking up your example - where position = "Technical", I want to supply the value of "Technical" within my VBA code – Romi24 Aug 05 '12 at 08:33
  • Perhaps you would like to re-read my answer? I said you cannot do that within the limits you have set. If you want to supply "technical", write it to a control and reference the control in your query, it can be a hidden control. Where is "technical" coming from? If the user is supplying it, then you already have a control. – Fionnuala Aug 05 '12 at 09:06
  • Hi Remou I don't think I have been able to explain the problem properly. We have gone off at a tangent. My fault entirely. The value for the query is going to come froma control on the form. What I need is a way by which I prevent having to embed the SQL statements within the VBA code that I am writing. I wanted to use something on the lines of a stored procedure parameter with the stored procedure sql as follows Select where . I wanted to pass the value of the control to the query and reference it within the query as prmcontrol1value. Thanks – Romi24 Aug 06 '12 at 18:34
1

You could create a function and use that function (instead of a regular parameter) in your form's record source query.

Public Function PositionParam(Optional ByVal P1 As Variant) As Variant
    Static varP As Variant

    If Not IsMissing(P1) Then
        If IsNull(P1) Then
            varP = Null
        Else
            varP = CStr(P1)
        End If
    ElseIf VarType(varP) = vbEmpty Then
        varP = Null
    End If
    PositionParam = varP
End Function

The record source query:

SELECT y.id_fld, y.another_fld, y.position_fld
FROM YourTable AS y
WHERE
       y.position_fld = PositionParam()
    OR PositionParam() Is Null
ORDER BY y.id_fld, y.another_fld;

Later when you want to display a different set of rows in the subform, change the value assigned to PositionParam() and Requery the subform.

PositionParam "technician"
Forms("YourForm").Requery
HansUp
  • 95,961
  • 11
  • 77
  • 135
  • This could work. For me, think I would prefer to get the query parameters from a form as Remou suggested. However, since you don't seem to want to do it that way, this is another way. – HansUp Aug 06 '12 at 15:57
0

The sub form is bound to a query and that query should not have any parameters at all.

You can certainly store the SQL for the sub form in a query and that eliminates the in-line sql but then turning around and writing WHACKS of code to get around this issue makes no sense at all does it?

As noted the filtering and display of sub form recodes is automatic and occurs without code if you setup the master link and child settings of the sub from control. You likely do NOT need ANY code here.

However if for some real reason you need to write code or want more billable hours then you can use this code:

Dim strSql     As String

strSql = Split(CurrentDb.QueryDefs("name of query").SQL, ";")(0)

strSql = strSql & "where Field1 = " & "'your p1 value'" & _
                  " and Field2 = " & "' your p2 value'"

Me.custChild.Form.RecordSource = strSql

So you do not need any parameters in the sql but just use the CURRENT and SAME query the sub form is based on. Besides if you add parameters then you are hard coding the 2 values in the query and then the query cannot be used for other code and tasks unless you provide the 2 SAME hard coded parameters (so this give little if any flexibility in using that query elsewhere with differnt choices).

So leave the parameters out of the query and same money and time and billable hours.

It is a simple matter to pull the query SQL as per above and add criteria to the SQL. However, if you looking to insert data to the sub form, then you can use the subform data source and reocrdset directly. eg:

  Dim rst     As DAO.Recordset

  Set rst = Me.custChild.Form.RecordsetClone

  rst.AddNew
  rst!SomeField = "some valjue"
  rst!SomeField2 = "some value"
  rst.Update

  Me.custChild.Requery
Albert D. Kallal
  • 42,205
  • 3
  • 34
  • 51