Search form in Access - ms-access

I want to implement a search form to operate on a table on access.
But when I choose the table then create a From, I get all the table data in the form instead of search field. And when I change any value, the table values change. I want to have a text field where user can enter search criteria and hit a search btn and the search result appears as a table in the form or as a message box.

You could add the data to the form after the search, but to keep things tidy, you might like to consider an unbound form with search box(es) and a subform for results. Let us say you have two boxes, txtName and txtDate and a search button, then a very rough idea would run:
strSQL = "SELECT aName, aDate FROM aTable WHERE 1=1 "
If Not IsNull(txtName) Then
strWHERE = " AND aName Like '*" & Replace(txtName,"'","''") & "*'"
End If
If Not IsNull(txtDate) Then
strWHERE = strWhere " AND aDate =#" & Format(txtdate,"yyyy/mm/dd") & "#"
End If
Me.SubformControlName.Form.RecordSource = strSQL & strWhere
You should, of course, make sure that the data in the controls in sensible and clean and that records are returned.

You can use something like this to put your form in Search mode when opened:
Private Sub Form_Open(Cancel As Integer)
'DoCmd.DoMenuItem acFormBar, acRecordsMenu, acFilterByForm, , acMenuVer70
DoCmd.RunCommand acCmdFilterByForm
End Sub

I have a search form created that I use that is very handy. In order to setup a form to search you need to create a search query. For example my form has the fields: Keywords and Source. So you need to link the query to the table that houses the data. The search query I have is
SELECT KWTable.KW AS Expr1, KWTable.Code, KWTable.Source
FROM KWTable
WHERE (((KWTable.KW) Like "*" & [Forms]![Search_Form]![KW_Text] & "*") AND ((KWTable.Source) Like "*" & [Forms]![Search_Form]![Source_Text] & "*"));
I type the words into the boxes and click a button to execute. The button code looks like
Private Sub Command8_Click()
On Error GoTo Err_Command8_Click
Dim stDocName As String
stDocName = "Search_Query"
DoCmd.OpenQuery stDocName, acNormal, acEdit
Exit_Command8_Click:
Exit Sub
Err_Command8_Click:
MsgBox Err.Description
Resume Exit_Command8_Click
End Sub
I hope this helps.

Related

Is it an access Bug? my problem with form filtering by txtBox entered value in a split DB

I have an Access 2016 DB 64bits contain related tables with a search split form that have an txtBox that filtered records accoring to its entered value.
Every thing is just fine with that for months and with thousands of records.
When I want to make it more proffesional to deploy it to other users by re-writing another similar DB but with 32bts Access 2016 and SPLIT it from the start into Tables Back-end and a Front end, the search form didn't show any record when I fire a searching parameter in the after update event!
the search form is linked to a query, I change it to a new one, also try to link the form directly to only one table for testing also not goes right, shows zero results.
when remove the filter, all records showing up again.
when I change the filter directly from the form properties it also fail for string search but when search for a primary key in a form control holding it its working just fine. ( search for Strings show no results, search for Numbers ( ex ID value, show correct results).
And Very strange, when I build another new DB (Same access application) just for testing for what is going on, with a form and joined to split back end tables and a textbox in the form to enter keywords to show the all related records in the that split form, it works fine, both for strings and for numbers?
Private Sub txtSearch_AfterUpdate()
Dim strFilter As String
On Error Resume Next
If Me.txtSearch.Text <> "" Then
strFilter = "[Complaints] Like '*" & Me.txtSearch.Text & "*'"
Me.Filter = strFilter
Me.FilterOn = True
Else
Me.Filter = ""
Me.FilterOn = False
End If
With Me.txtSearch
.SetFocus
.SelStart = Len(Me.txtSearch.Text)
End With
End Sub
when put a string into the txtsearch box , the code must search for any string with in [Complaints] similar to it and shows the records holding it.
with me it works in the old DB 64bits Not splitted, but its not working for the new DB 32bits split to back and front ends.
Be careful using .Text as it requires the control to have focus. So try:
Private Sub txtSearch_AfterUpdate()
Dim strFilter As String
' On Error Resume Next ' Don't use while debugging.
If Nz(Me!txtSearch.Value) <> "" Then
strFilter = "[Complaints] Like '*" & Me!txtSearch.Value & "*'"
Me.Filter = strFilter
Me.FilterOn = True
Else
Me.Filter = ""
Me.FilterOn = False
End If
With Me!txtSearch
.SetFocus
.SelStart = Len(.Value)
End With
End Sub

Custom navigation fails upon opening an individual record in Microsoft Access project

I'm having issues with my Microsoft Access project.
The project comprises of two forms called, InfoForm and SearchBox.
InfoForm form
The InfoForm form is the primary-form, and has the following:
Custom navigation buttons, which are; Next and Prev
A custom Search button, which opens up the SearchBox form.
SearchBox form
The SearchBox form is used to browse and open individual records, and has the following:
List of available individual records
Open button
Individual records
The individual records open into the InfoForm form.
I use this code on the Open' button of theSearchBox` form, as follows:
Private Sub Command1_Click()
Dim strLN As String
strLN = Me.SearchResults.Column(0)
Dim strGN As String
strGN = Me.SearchResults.Column(1)
Dim strMN As String
strMN = Me.SearchResults.Column(2)
DoCmd.OpenForm "InfoForm", acNormal, , _
"[Last Name] = '" & strLN & "' And " & _
"[Given Name] = '" & strGN & "' And " & _
"[Middle Name] = '" & strMN & "'"
DoCmd.Close acForm, "SearchBox"
End Sub
This code works perfectly when the InfoForm form is first opened, right up until an individual record is opened.
At this point, the navigation buttons "Next" and "Prev" on the 'InfoForm' form stop working.
Please help. Thank you.
As #Andre noted, if the form is filtered to a single record then there are no succeeding or previous records to navigate to. Does your filter criteria result in a single record dataset?
An alternative is to open the form unfiltered (or with a filter that returns a restricted dataset but will usually still have multiple records) and 'go to' the desired record, then there will be succeeding and preceding records to navigate. Example from my code:
To open form:
DoCmd.OpenForm "Samples", , , , , acDialog, strLabNum
Then code behind the opened form:
Private Sub Form_Open(Cancel As Integer)
Me.RecordsetClone.FindFirst "LabNum='" & Me.OpenArgs & "'"
Me.Bookmark = Me.RecordsetClone.Bookmark
End Sub

How to record unbound control to a database

I have a form control (address) that uses Dlookup to call info from a table "database" but the form is bound to table "Tracker". The dlookup is based on another control on the same form - "Name" I need the form to record this dlookup control, along with other controls that are bound to "tracker" as new recordto the table "tracker."
My failed attempts:
Using the default value property to assign the recalled data from the dlookup to another text box which would be bound to "tracker" This simply does not work for some reason. Perhaps I am missing something that tells this control "Address" to update upon selecting the correct "name?"
Code:
Private Sub SubmitReferral_Click()
On Error GoTo Err_SubmitReferral_Click
DoCmd.GoToRecord , , acNewRec
Exit_SubmitReferral_Click:
Exit Sub
Err_SubmitReferral_Click:
MsgBox Err.Description
Resume Exit_SubmitReferral_Click
End Sub
I also tried this - to assign the data - but the data from the dlookup in control "Address1" is not transferring/copying to control "Address2"
Private Sub Combo276_OnUpdate()
OnUpdate ([Address2].Value = [Address1].Value)
End Sub
Help or suggestions?
PS - I have tried to Edit per request to be as specific as possible, and to follow proper board etiquette.
Still unsure of your field names, etc., but the following is an example you can modify. Change 'tblEmployee' to 'database'.
I must state that if you are just starting out with developing in Access (or VBA) that you should never use names that are reserved words, or that can be misleading. Your table named 'database' is ok if named 'tblDatabase'.
Option Compare Database
option Explicit
Private Sub cmdInsert_Click()
Dim strSQL As String
Dim i As Integer
Debug.Print "cmdInsert; "
i = MsgBox("Do you want to add 1 row for Employee ID: " & Me.EmpID & " to table 'tracker'?", vbYesNo, "Confirm Add")
If i = vbNo Then
Exit Sub
End If
DoCmd.SetWarnings True
strSQL = "INSERT INTO tracker ( FirstName, LastName, Add1, City, St, Zip ) " & _
"SELECT tblEmployee.FirstName, tblEmployee.LastName, tblEmployee.Add1, tblEmployee.City, tblEmployee.St, tblEmployee.Zip " & _
"FROM tblEmployee " & _
"WHERE (((tblEmployee.EmpID)=" & Me.EmpID & "));"
DoCmd.RunSQL strSQL
End Sub
Thanks for the help - I solved my concern by hiding the fields that contain the dlookup, and putting code behind a button that copies the information to fields that are bound and therefore will record to the table "tracker"

Me.Requery appears to be doing no action on form

I have searched and have found a lot of information on using requery on a subform, but I can't seem to find anything that indicates attempting to requery the active form with a new recordset.
I have a form based on a query. I am using an unbound text box to capture the address which needs to be searched then changing the sql statement in the query to locate the records then attempting to use me.requery to load the new results.
The code is updating the sql statement, but the form is not requerying with the new record results. My code is below.
I am fairly new to access and VBA, and appreciate any wisdom you may have. Also, is there ANYTHING that I could be doing in other code which would cause this to fail?
Private Sub Command51_Click()
Dim d As DAO.Database
Dim q As DAO.QueryDef
Dim Addy As String
Dim Search As String
Set d = CurrentDb()
Set q = d.QueryDefs("SQL_Search")
If IsNull(Me!Addy) Then
MsgBox ("Please select a valid address from the list and try again.")
GoTo CleanUp
Else: End If
Addy = Me!Addy
Search = "select * from dbo_ECNumberVerify Where (((dbo_ECNumberVerify.invalidrecord)=False) AND ((dbo_ECNumberVerify.updated)=False) AND ((dbo_ECNumberVerify.Locations) Like '*" & Addy & "*'));"
'Send SQL SP execute command.
q.SQL = Search
Me.Requery
CleanUp:
Set q = Nothing
Set db = Nothing
End Sub
In your example you have a query, but the query is never set or attached to the forms record source in "any way". So the “query” acts independent from the form data source.
You can simply stuff the sql directly into the forms reocrdsouce like this:
Me.RecordSource = Search
(so you don’t need all of your existing code, nor do you need the queryDef.
And when you set the forms SQL directly as per above, then a requery is done automatic for you. So the code required will look like this:
Dim strSearch As String
If IsNull(Me.Addy) Then
MsgBox ("Please select a valid address fromthe list and try again.")
Exit Sub
End If
strSearch = "select * from dbo_ECNumberVerify WHERE " & _
"(invalidrecord = False) AND (updated = False) AND " _
"(Locations Like '*" & Addy & "*')"
Me.RecordSource = strSearch
So you don't need much code, and you really don't need to use + declare the querydef at all.

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