Question: In Microsoft Access 2003/XP/2000/97, I'd like to have a button on a form that when clicked will open a popup form. On the popup form, the user can select (from a combo box) one of the field names contained on the original form and text to search on.
Once the search has been performed, the original form will then display only those records that match the search criteria. I'd also like to have another button on the original form that when clicked will display a report with the search results.
Answer: We've provided a download to demonstrate how you can set up search functionality.
First, we've set up the form which displays the Customer records. The user can click on the Search button to perform a search on any text field in the Customers table.
When the Search button is pressed, the following form will appear:
The user can select the field to search on and the search criteria. In this example, we've selected the "CompanyName" field and "store" as the value to search for in the "CompanyName" field.
When the Search button is pressed, the following message box will appear:
Your form will then display the search results as follows:
Pay close attention to how the RecordSource is set on the form called frmCustomers. The RecordSource on this form is updated using VBA code and not in the Properties window.
We've also included a "Show all customers" button in case you wish to view all customer records, and a "Generate Report" button to display a report of the search results.
Question: I've tried the example on this webpage and I've encountered a problem while searching. The problem seems to occur when searching for anything with a single quote in it. Is there a workaround?
Answer: Single quotes can sometimes cause problems when writing queries in VBA as this example does. To workaround the error that you are receiving, try stripping out the single quotes when performing the search.
To do this, in the cmdSearch_Click event, try replacing the following code:
GCriteria = cboSearchField.Value & " LIKE '*" & txtSearchString & "*'"
with the following:
GCriteria = "Replace(" & cboSearchField.Value & ", chr(39), '')" & " LIKE '*" & Replace(txtSearchString, "'", "") & "*'"
This code strips out the single quotes for the purposes of searching, but still displays the search results with the single quotes intact.