Access VBA: repeatedly change form filter with Me.Filter - ms-access

Filters in Access seem to be 'sticky' - when you set one with VBA you can remove it but you can't set a different one.
I have a Access database for tracking student scores. It has tables subjects, teachers, students, tests and test_results. Each results record refers to a student and a test.
I have a form displaying tests with a subform displaying results. I want to search for tests using various criteria so I added some unbound fields to the (outer) form header and labelled them 'name', 'subject', 'start date', 'end date' and 'teacher'. I added a 'filter' button and a 'reset' button. Each search field is optional so any combination can be used: any left blank will be ignored.
This is the code for the filter button:
Me.Filter =
"([Forms]![testWithResults]![Text102] IS NULL OR test_name Like '*' & [Forms]![testWithResults]![Text102] & '*')
AND ([Forms]![testWithResults]![Combo89] IS NULL OR teacher = [Forms]![testWithResults]![Combo89])
AND ([Forms]![testWithResults]![Combo52] IS NULL OR subject = [Forms]![testWithResults]![Combo52])
AND ([Forms]![testWithResults]![Text83] IS NULL OR [Forms]![testWithResults]![Text85] IS NULL OR test_date BETWEEN [Forms]![testWithResults]![Text83] AND [Forms]![testWithResults]![Text85])"
Me.FilterOn = True
This is the code for the reset button:
Me.FilterOn = False
Me.Combo89 = Me.Combo89.DefaultValue
Me.Combo52 = Me.Combo52.DefaultValue
Me.Text83 = Me.Text83.DefaultValue
Me.Text85 = Me.Text85.DefaultValue
Me.Text102 = Me.Text102.DefaultValue
When I first load the form, the first time I search it all works perfectly. The filter button works just as expected and the reset button empties all fields and displays all records. But when I try to search again with new criteria I just get my old results again. To make it work I have to close and reopen the form.
When I replaced Me.Filter with DoCmd.ApplyFilter it still worked perfectly the first time but the second time I would get an error 'the expression is too complex to be evaluated'.

Since Access complains the Filter string is too complex, simplify it.
You want to base a Filter condition on a text box. At the time you create the Filter string, your code can check whether that text box is Null. If it is not Null, add a condition based on the text box's value. If it is Null, the Filter can simply ignore that text box.
Dim strFilter As String
With [Forms]![testWithResults]
If Not IsNull(![Text102]) Then
strFilter = strFilter & " AND test_name Like '*" & ![Text102] & "*'"
End If
If Not IsNull(![Combo89]) Then
strFilter = strFilter & " AND teacher = " & ![Combo89]
End If
If Not IsNull(![Combo52]) Then
strFilter = strFilter & " AND subject = " & ![Combo52]
End If
If Not (IsNull(![Text83]) Or IsNull(![Text85])) Then
strFilter = strFilter & " AND test_date BETWEEN " & Format(![Text83], "\#yyyy-m-d\#") _
& " AND " & Format(![Text85], "\#yyyy-m-d\#")
End If
End With
If Len(strFilter) > 0 Then
' use Mid() to discard leading " AND "
Debug.Print Mid(strFilter, 6) '<- view this in Immediate window; Ctrl+g will take you there
Me.Filter = Mid(strFilter, 6)
Me.FilterOn = True
Else
MsgBox "no conditions for Filter"
End If

Related

Parameter Value on Combo Box

I am trying to filter a subform with a combobox. What I have works, but it keeps bringing up an "Enter Parameter Value" textbox. When I enter the value I want to filter with, it searches the subform no problem. I would prefer to not have to enter the value though as it defeats the purpose of the combobox.
Here is my code for the ComboBox,
Private Sub ComboFE_AfterUpdate()
On Error GoTo Proc_Error
If IsNull(Me.ComboFE) Then
Me.SubFormPF.Form.Filter = ""
Me.SubFormPF.Form.FilterOn = False
Else
Me.SubFormPF.Form.Filter = "Lead_FE = " & Me.ComboFE
Me.SubFormPF.Form.FilterOn = True
End If
Proc_Exit:
Exit Sub
Proc_Error:
MsgBox "Error " & Err.Number & " in setting subform filter:" & vbCrLf & Err.Description
Resume Proc_Exit
End Sub
I have checked and made sure all the names are correct and match the corresponding items on my form.
Any Ideas?
Many Thanks
When applying a filter on a text column, the value needs quotes.
Me.SubFormPF.Form.Filter = "Lead_FE = '" & Me.ComboFE & "'"
To avoid problems if the value itself contains quotes, use Gustav's CSql() function from here: https://stackoverflow.com/a/36494189/3820271
Me.SubFormPF.Form.Filter = "Lead_FE = " & CSql(Me.ComboFE.Value)
This works for all data types.

Warning for Dynamic Combobox list

I have a combobox that builds it's list upon first usage. I know that the way I want "NotInList" to behave isn't conventional - I don't want to waste adding the item to a table separate from the needed entry, but I'd like to still warn about an item that hasn't been used yet, so that the user has to think twice before accepting the entry.
Once the user adds the item, it will automatically appear in the list next time because the data source for the combo box is as follows:
SELECT tbl_SP.PROGRAM
FROM tbl_SP
GROUP BY tbl_SP.PROGRAM
HAVING (((tbl_SP.PROGRAM) Is Not Null And (tbl_SP.PROGRAM)<>""));
I tried this:
Private Sub cmbPROGRAM_NotInList(NewData As String, Response As Integer)
If MsgBox("'" & Chr(34) & NewData & Chr(34) & " hasn't been used yet. Add to list? ", vbQuestion + vbYesNo, "Add - " & NewData & "?") = vbYes Then
Response = acDataErrAdded
End If
End Sub
but of course, Access wants the item to actually exist before it will release the error. And...if I set LimitToList to "No" then the user doesn't get a warning.
How can I achieve this behavior?
Ok, I tried this which works fine if the user selects YES, but becomes more complicated when the user selects "NO"
Public Function ReturnsRecords(strSQL As String) As Boolean
Dim d As DAO.Database
Dim arr(1 To 3) As DAO.Recordset
'Dim rs As DAO.Recordset
'assume 3 items in array above
Set d = CurrentDb
Set arr(1) = d.OpenRecordset(strSQL)
' MsgBox "Record Count is " & arr(1).RecordCount
If arr(1).RecordCount > 0 Then
ReturnsRecords = True
Else
ReturnsRecords = False
End If
Set d = Nothing
End Function
Private Sub cmbPROGRAM_BeforeUpdate(Cancel As Integer)
Dim strSQL As String
strSQL = "Select * from LU_PROGRAM where PROGRAM ='" & Me.cmbPROGRAM & "'"
If ReturnsRecords(strSQL) = False Then
If MsgBox("'" & Chr(34) & Me.cmbPROGRAM & Chr(34) & " hasn't been used yet. Add to list? ", vbQuestion + vbYesNo, "Add - " & Me.cmbPROGRAM & "?") = vbNo Then
Cancel = True
' how do I reset this? Me.cmbPROGRAM.Text = Null
End If
End If
End Sub
How do I clear the combobox if the user selects NO? If I select me.undo, that will undo all of the entries, but I just want to clear the combobox.
Incidentally, the form is totally unbound and doesn't accept an entry until the user selects "Save"
First, I'm not quite sure what you wish to achieve ...
Then, educate the users to press Escape to cancel. This is mandatory wisdom when operating an Access application.
For your code to work, you can't change the content of a control in the BeforeUpdate event. So try the AfterUpdate event with either:
Me!cmbPROGRAM.Text = ""
or:
Me!cmbPROGRAM.Value = Null

filter continuous form using textbox

I need to let users filter a continuous form using values the user enters into a textbox. And the continuous form is also nested within a couple levels of navigation subforms. This sounds easy enough, but all the examples I find on the web use macros instead of vba.
I set up the structure and wrote an AfterUpdate procedure for a textbox txtFilter as follows:
Private Sub txtFilter_AfterUpdate()
Dim filterval As String
filterval = txtFilter.Value
With Forms!Main!NavigationSubform.Form!NavigationSubform.Form
.Filter = "LastName Like " & filterval
.FilterOn = True
End With
End Sub
I have played with different syntax, but none of it seems to work properly. Here is a link to download the relevant parts of the database from a file sharing site: http://jmp.sh/v/HGctZ4Ru74vDAjzN43Wq
Can anyone show me how to alter this so that users can use the textbox to filter the continuous form?
I got it to work using this: .Filter = "LastName Like """ & filterval & """"
Need those annoying String Identifiers even for strings sometimes.
Okay, To get the form to open with no records and then pull up just the records you (or the user) specifies is easiest with a bit of re-work.
(I'd recommend you working with a copy and not your original)
1:On your Continuous Form, remove the Recordsource; we're going to use Late Binding (Kinda)
2:Then delete the code under the txtFilter box, then delete the box itself.
3:Add a comboBox with something like this as the recordsource:
SELECT DISTINCT myTable.LastName FROM myTable ORDER BY myTable.LastName; (This will get you a unique list of last names so knowing how to spell the name will not be necessary, plus it assures at least one match)
4:In the After Update event of that combobox, add code like this:
Dim strSource As String
strSource = "SELECT mt.IntakeNumber, mt.ClientNumber, " & _
"mt.LastName, mt.FirstName, mt.ConsultationDate " & _
" FROM myTable mt " & _
"WHERE (mt.LastName)= '" & Me.cboFilter.Value & "'"
Me.RecordSource = strSource
Me.Requery
Obviously you'll need to change the table and field names as necessary, but hopefully you get the idea.
Option Compare Database
Option Explicit '<- always include this!!!!!
Private Sub txtFilter_AfterUpdate()
Dim strFilter As String
' only set Filter when text box contains something
' to search for ==> don't filter Null, empty string,
' or spaces
If Len(Trim(Me.txtFilter.Value & vbNullString)) > 0 Then
strFilter = "LastName Like '*" & _
Replace(Me.txtFilter.Value, "'", "''") & _
"*'"
' that Replace() prevents the procedure from breaking
' when the user enters a name with an apostrophe
' into the text box (O'Malley)
Debug.Print strFilter ' see what we built, Ctrl+g
Me.Filter = strFilter
Me.FilterOn = True
Else
' what should happen here?
' maybe just switch off the filter ...
Me.FilterOn = False
End If
End Sub

Getting Records from Table in Access

I have this requirement where I have to check the data based on data given in other fields. I have table with 'N' fields. I should allow user to select 4 fields which are from the table. And then I should get all other fields of that particular record and display it to the user so that he can verify that the data he entered into table is correct. Please help.
Thanks
I have a clearer understanding now of what you require - hopefully this is what you need:
Assume you have a table called 'Phones'
The phones table has three primary fields: Manufacturer, Operating System, and Carrier
In addition to these primary fields there are secondary "spec" fields. For now we have three: ScreenSize, Frequencies, and Price.
I create a form with three combo boxes: ManufacturerFilter, OperatingSystemFilter, and CarrierFilter.
Each combo box's row source is similar to:
SELECT Carrier FROM Phones GROUP BY Carrier ORDER BY Carrier;
Where Carrier is replaced by Manufacturer and [Operating System] respectively.
I then add in all of the secondary fields, each bound to their own respective field.
You can also add in a button called "Retrieve" for now leave the click code blank.
At this point you have a few options. I'll highlight two, but both options will require the following procedure:
Private Function FilterStr() As String
Dim myFilterStr As String
' Include each filter if they are entered
If Nz(Me.ManufacturerFilter, "") <> "" Then myFilterStr = myFilterStr & "[Manufacturer]='" & Me.ManufacturerFilter.Value & "' AND"
If Nz(Me.OperatingSystemFilter, "") <> "" Then myFilterStr = myFilterStr & "[Operating System]='" & Me.OperatingSystemFilter.Value & "' AND"
If Nz(Me.CarrierFilter, "") <> "" Then myFilterStr = myFilterStr & "[Carrier]='" & Me.CarrierFilter.Value & "' AND"
' Remove the last AND statement
If myFilterStr <> "" Then myFilterStr = Mid(myFilterStr, 1, Len(myFilterStr) - 4)
FilterStr = myFilterStr
End Function
This function returns a filter string, based on the combo box options selected.
Option #1: Filter the Recordset
What we want to occur, is when a primary field value is selected, the records are filtered to display only those matching the criteria. Add the following code to the OnClick event of your Retrieve button:
Private Sub RetreiveButton_Click()
Dim myFilterStr As String
myFilterStr = FilterStr
If myFilterStr <> "" Then
Me.Filter = myFilterStr
Me.FilterOn = True
Else
Me.Filter = ""
Me.FilterOn = False
End If
End Sub
So what happens when the button is clicked, is that a filter string is created based on the values selected, and then a filter is applied to the form. If no values are selected in the combo boxes, the filter is cleared and turned off.
Option #2: Find a Record based on the Value
What we want is to select the values in the comboboxes, and then move to the record that matches the criteria.
Add the following code to the onClick event of the retrieve button.
Private Sub RetreiveButton_Click()
Dim rst As DAO.Recordset
Dim myFilterStr As String
myFilterStr = FilterStr()
If myFilterStr = "" Then
MsgBox "No Filter Selected", vbOKOnly, "Error"
Exit Sub
End If
Set rst = Me.RecordsetClone
rst.FindFirst myFilterStr
If rst.NoMatch Then
MsgBox "No Matching Records were found", vbOKOnly, "No Data"
Else
Me.Bookmark = rst.Bookmark
End If
Set rst = Nothing
End Sub
This uses the the same FilterStr() function to return a search string, but uses the recordset's FindFirst method to locate a record. If found, it will move to the record.
Hope that answers your question. As I indicated, the exact behaviour will vary but the underlying principle remains the same.

MS Access: outer join in a search form

I have an access database with a search form.
I have an "Object" table with amongst other things, a "name" field, and an "owner" table with a "name" field as well.
Between the two, I have a join table so I have a many-to-many relationship
An object does not necessarily have an owner.
In my search form, I have two unbound fields: "object name" and "owner name".
What I want to do:
When the user leaves both fields blank, he gets a list of all the objects (including those with no owner), and if that object has an owner it is also displayed in the list.
When the user fills something in the "object name" field, he gets a list of all the objects containing the entered substring (including those with no owner).
When the user fills something in the "owner name" field, he gets a list of all the objects where the owner name contains the entered substring (ignoring NULL owners).
What I did thus far:
I made a query with a left outer join, and a criteria on Object.name using the value of the "object name" textfield
That works fine for use case 1 and 2, but there's no owner filtering in case 3
However if I add a criteria on Owner.name based on the "owner name" textfield, case 3 works fine, but case 1 and 2 don't work anymore (making the left outer join obsolete)
How could I solve this problem?
It seems to me that you could use a Continuous Forms form with the following Record Source...
SELECT Objects.ObjectName, ObjectOwners.OwnerName
FROM (ObjectOwnership INNER JOIN ObjectOwners ON ObjectOwnership.OwnerID = ObjectOwners.OwnerID) INNER JOIN Objects ON Objects.ObjectID = ObjectOwnership.ObjectID
UNION ALL
SELECT Objects.ObjectName, NULL AS OwnerName
FROM ObjectOwnership RIGHT JOIN Objects ON Objects.ObjectID = ObjectOwnership.ObjectID
WHERE ObjectOwnership.ObjectID IS NULL
ORDER BY 1, 2;
...and then put a couple of text boxes and a "Filter" command button in the form header to update the forms .Filter property to filter the records as desired, like this:
Private Sub cmdFilter_Click()
Dim sFilter As String
If IsNull(Me.txtObjectFilter.Value) And IsNull(Me.txtOwnerFilter.Value) Then
Me.FilterOn = False
Else
If IsNull(Me.txtObjectFilter.Value) Then
sFilter = ""
Else
sFilter = "ObjectName LIKE ""*" & Me.txtObjectFilter.Value & "*"""
End If
If Not IsNull(Me.txtOwnerFilter.Value) Then
If Len(sFilter) > 0 Then
sFilter = sFilter & " AND "
End If
sFilter = sFilter & "Ownername LIKE ""*" & Me.txtOwnerFilter.Value & "*"""
End If
Me.Filter = sFilter
Me.FilterOn = True
End If
End Sub
When the form opens it shows all records...
...and then we can filter by object...
...or by owner...
...or both, for that matter.
Edit
A similar technique for Subforms would be to save the query above as [ObjectOwner_base_query] and specify that as the Record Source of the Subform, then change the VBA code very slightly, to
Private Sub cmdFilter_Click()
Dim sFilter As String, sSQL As String
sFilter = ""
If Not IsNull(Me.txtObjectFilter.Value) Then
sFilter = "ObjectName LIKE ""*" & Me.txtObjectFilter.Value & "*"""
End If
If Not IsNull(Me.txtOwnerFilter.Value) Then
If Len(sFilter) > 0 Then
sFilter = sFilter & " AND "
End If
sFilter = sFilter & "Ownername LIKE ""*" & Me.txtOwnerFilter.Value & "*"""
End If
sSQL = "SELECT * FROM ObjectOwner_base_query"
If Len(sFilter) > 0 Then
sSQL = sSQL & " WHERE " & sFilter
End If
Me.RecordSource = sSQL
End Sub
(It appears that modifying the .Filter property of a subform can cause Access to act strangely; updating the .RecordSource property seems to produce better results.)