Add a simple search box to a Microsoft Access form
A step-by-step guide to adding a simple search box to a Microsoft Access form.
I have recently been developing a database in Microsoft Access; a really powerful tool for searching and querying data.
I created a Form (called
Project_Metadata which is based on a Table of the same name, but needed to add a search box so that I could identify specific projects in my database by their project code. The project codes are contained in a column within the
Project_Metadata Table called
Here’s how I created the search box:
Open the Form that you want to add the search box to and select “Design View” from the menu via the “Design” ribbon.
Insert a text box into the header section of the form by dragging it from the “Controls” pane.
Rename the text box caption to “Search Project ID” (or other meaningful text).
Right-click on the text box and select “Properties” to reveal the “Property Sheet”.
After Update and select “[Event Procedure]”:
Go to the “Other” tab in the “Property Sheet” and rename the text box to something meaningful (eg “search_project_ID”).
Go back to the “Event” tab and click on
After Update. This will bring up a Visual Basic window in Access.
Replace all of the text with the following:
Option Compare Database Private Sub Search_Exp_AfterUpdate() If search_project_ID <> "" Then query = "SELECT * FROM Project_Metadata WHERE project_code='" & search_project_ID & "'" & "" Me.RecordSource = query Me.Refresh Else Me.RecordSource = "SELECT * FROM Project_Metadata" Me.Refresh End If End Sub
You will need to customise the above code for your own database. In the example above:
search_project_IDis the name of the text box that we renamed in Step 6.
Project_Metadatais the name of the Table that contains the data that we need to search.
project_codeis the column in our table that we need to search.
Me commands stand for the Form that is currently in focus and whose code is now running, which is why it is used here.
Check that your search box works in your Form. You should now be able to enter a term and return all records that contain the string that you enter.