I am trying to create relational combo box filter in the MS Access forms. I have 2 columns one is GP and another column is Practice. If I select a GP from the combo box filter the 2nd filter related to practices need to display only the practices related to this particular GP but give the results of all GP’s related to the particular Practice. But I am not getting the results as expected. Any help is very much appreciated.
Below is the example of the data and output:
Raw Data:
Name Practice
------------------
John Practice_ABC
Sam Practice_ABC
Paul Practice_XYZ
Ana Practice_XYZ
Ani Practice_XYZ
Maria Practice_123
Output:
If I have selected John from GP (Name) combo box filter the 2nd filter (Practice) need to show the value “Practice_ABC” only and the results in the MS Access split form table need to display only the records below:
Name Practice
------------------
John Practice_ABC
Sam Practice_ABC
I have tried to develop this code in vba but it gives the error below:
Option Compare Database
Private Sub cmbGP_AfterUpdate()
' Filter the practices combo box based on the selected GP
Me.CmbPractice.RowSource = "SELECT DISTINCT [Practice] FROM kontakt_info WHERE [Name] = '" & Me.CmbGP & "';"
Me.CmbPractice.Requery
End Sub
Private Sub cmbPractice_AfterUpdate()
Dim selectedGP As String
Dim selectedPractice As String
' Get the selected GP and practice
selectedGP = Me.CmbGP.Value
selectedPractice = Me.CmbPractice.Value
' Check for null or empty values
If IsNull(selectedGP) Or IsNull(selectedPractice) Or selectedGP = "" Or selectedPractice = "" Then
' Handle the case where either GP or practice is not selected
MsgBox "Please select both a GP and a practice.", vbExclamation, "Selection Error"
Else
' Filter the split form based on the selected GP and practice
Me.Filter = "[Name] = '" & selectedGP & "' AND [Practice] = '" & selectedPractice & "';"
Me.FilterOn = True
End If
End Sub
Error:
Run-time error '3075':
Syntax error in query expression '[Name]' = 'John' AND [Practice] = 'Practice_ABC'';'.
Look correct to me. Did you check the column names?
There’s obviously an extra single quote in ‘[Name]’ = ‘John’ AND [Practice] = ‘Practice_ABC” .
NAME is a reserved word. Should not use reserved words as names. Better would be GPName. Also, better to filter on numeric keys instead of text. That would eliminate issue associated with apostrophe delimiters. Do you have lookup tables for GPs and Practices? Are you saving text instead of number keys into GP_Practices table?
Semicolon is not appropriate for Filter property expression as this is not a full SQL statement. Remove it.