The creation and customization of database applications using Microsoft Access
Use a fixed alias for the changing query column, bind the report text box to that alias, and update only the heading to show the selected laboratory field.
Recommended design: keep the report schema stable
Modify the SQL generated by the existing dynamic query so that whichever laboratory field is selected is always returned as the same alias—for example, ResultValue.
SELECT
PatientID,
TestDate,
[Glucose] AS ResultValue
FROM LabResults;
When another result is selected, generate:
SELECT
PatientID,
TestDate,
[Cholesterol] AS ResultValue
FROM LabResults;
The source field changes, but the output column remains ResultValue. Access SQL supports assigning a different result-column name with AS.^1^
Configure the report as follows:
- Open the report in Design View.
- Press F4 to open the Property Sheet.
- Select Report, then open the Data tab.
- Set Record Source to the saved dynamic query. A report’s
RecordSourcecan be a query name or SQL statement.^2^ - Select the result text box.
- Set Control Source to
ResultValue. The text box will now remain bound even when the underlying laboratory field changes.^3^ - Give its heading label a clear name, such as
lblResultHeading.
If the field selection is made on a form—for example, combo box cboResultField on frmLabSelector—set the report heading in its On Open event:
Private Sub Report_Open(Cancel As Integer)
Me.lblResultHeading.Caption = _
Forms!frmLabSelector!cboResultField.Column(1)
End Sub
Adjust the column number to the combo-box column containing the display name. The label’s Caption property controls its displayed text.^4^
Keep the selector form open while opening the report.
Alternative: rebind the report control at runtime
If changing the query to return a stable alias is not possible, change both the text box binding and its label when the report opens:
Private Sub Report_Open(Cancel As Integer)
Dim fieldName As String
fieldName = Forms!frmLabSelector!cboResultField.Value
Me.txtResult.ControlSource = "[" & fieldName & "]"
Me.lblResultHeading.Caption = fieldName
End Sub
This requires the selected field to exist in the report’s current RecordSource; otherwise Access reports that the field is not in the field list. Limit the combo box to the 25 known field names rather than accepting arbitrary user-entered names.
The alias approach is preferable because the report always sees the same structure: PatientID, TestDate, ResultValue, and any other fixed columns. Only the query decides which underlying result populates ResultValue.
References