Design an Access Form with Dynamic SQL as Recordso

2019-05-22 09:04发布

问题:

I am pretty new to Access VBA programming. Here is one problem I have when creating a form in Access. I need to link the form's recordsource to a query object which I have already defined. Let's say I have field1, field2, field3, etc. in my query. The end product I would like to present is

  1. on top of the form, there are several text boxes for user to input filtering criteria of field1, field2, field3 ... and
  2. on a click of a button, a datasheet displays at the bottom of the form with the filtering criteria applied
  3. besides the existing fields in my query, I need to include at the end of the datasheet a customized column based on certain calculation result from field1 and field2. Some text could be displayed, for example "Late", "Early" or "On Time"

I have come up with two design approaches, but due to the lack of experience in VBA programming I am not able to accomplish either one of them right now...

Design 1:

I have a main form with the criteria input text boxes. This main form is not linked to any data source. Then I have a subform at bottom whose data source is dynamically set by reading the text boxes' values in the main form.

Design 2:

I have a single form, but I shift all the criteria boxes to the Form Header section. This form has a record source from my query object. The detail section is used for displaying the data sheet with the form's filter property set to user criteria.

I am not able to do design 1 because I don't know how to set the data source for my sub form dynamically. I am also not able to do design 2 because my form's header section does not appear even I have checked in the design view the form header/footer is enabled.

What can I do to realize my form design? Any alternative design suggestions?

I am using Access 2003 for this development, but I hope my code can be upgradable to Access 2010 in future.

Thanks in advance for your advice.

回答1:

With both designs you should build the datasource dynamically, something like this:

sql = "SELECT * FROM MyTableOrQuery WHERE 1=1"
If Not IsNull(textBox1) Then
  sql = sql & " And Field1 = '" & textBox1 & "'"
End If
If Not IsNull(textBox2) Then
  sql = sql & " And Field2 = '" & textBox2 & "'"
End If

And, finally, assign the sql to the form datasource.

Design1

The below code goes in the main form, just next to the above:

SubFormControlName.Form.RecordSource = sql

Design2

To show the controls in the header section you need to set the property DefaultView to running forms (I don't know the extact translation, I work with Access in spanish) In this case, the datasource is assigned to the main form

Me.recourdsource = sql

For your third point: You can build calculated field using

Iif(fieldA<5,"Early",Iif(fieldA>10,"Late","OnTime"))

or you can use conditional formatting. I think this option is most clear