In Access form, is there a way to use a search box to populate the form using VBA? - vba

I have two solutions I've been working to solve this problem...
Attempt #1
I have a combo box in an Access form with two options, "All," and "All Sample." The Sample is a selection of records from my table that are flagged for review with a sample_record_id (text field) for identification with a non-zero positive number. "All" and "All Sample" are in my Row Source. My combo box is named myFilters.
Afterupdate, this VBA runs:
Private Sub myFilters_AfterUpdate()
Debug.Print myFilters.Value
If myFilters.Value = "All Sample" Then
Me.FilterOn = True
DoCmd.ApplyFilter , "sample_record_id <> '0'"
Else
Me.FilterOn = False
End If
End Sub
All records have an entry for sample_record_id.
I was expecting my sample records to populate when "All Sample" is selected, and all records to populate otherwise. In fact, all records do populate when "All" is selected, but when "All Sample" is selected, a "Enter Paramaters Value" dialog box appears with the text "sample_record_id" with a space for entering text.
Interestingly, when I switch the IF and ELSE:
If myFilters.Value = "All" Then
Me.FilterOn = False
Else
Me.FilterOn = True
DoCmd.ApplyFilter , "sample_record_id <> '0'"
...neither selection works as expected.
Attempt #2
I also tried the following VBA:
Private Sub myFilters_AfterUpdate()
DoCmd.SetWarnings False
strSQL = "SELECT * FROM invoice_summary WHERE sample_record_id <> '0';"
Debug.Print strSQL
DoCmd.RunSQL strSQL
DoCmd.SetWarnings True
End Sub
I was expecting this to do the same thing as previous code, but no matter which selection I pick, a debug error pops up saying "A RunSQL action requires an argument consisting of a SQL statement."
Debug of strSQL returns: SELECT * FROM invoice_summary WHERE sample_record_id <> '0';
I've tried it with and without the ;
The sql statement works in a standard query.
Is there a way to make either of these work?

Been working on this for two days, and 30 minutes after I post I figure it out. Sigh.
Using my first attempt, I just had to put brackets around my field name:
Private Sub myFilters_AfterUpdate()
If myFilters.Value = "All Sample" Then
Me.FilterOn = True
DoCmd.ApplyFilter , "[sample_record_id] <> '0'"
Else
Me.FilterOn = False
End If
End Sub

Related

The blank column of the particular List Box based on query is not recognized as either empty or null

The Listbox: SearchList get data from the query: Machine_Search.So how it works is i input my Serial Number into the Search textbox and press the button search then select the record displayed on the SearchList. When the record is selected, i then press edit. The condition is that if the record that i search using Serial Number have empty field in the End_Date it will go on smoothly. However if the record that is search using Serial Number have a date in the End_Date it will prompt a msgbox and, close and open the form again. The issue lies at where it cannot detect if End_Date is null or empty and will prompt the msgbox regardless of the condition.
Table: Machine
Query: Machine_Search - It query the table:Machine where there is a form called: Machine_Load which fills half the field in the table and the other will be filled by Machine_Unload/
Form:Machine_Unload
Is there a way to solve this issue?
Private Sub cmdSearch_Click()
Dim check As String
DoCmd.OpenQuery "Machine_Search"
DoCmd.Close acQuery, "Machine_Search"
SearchList.Requery
If SearchList.ListCount = 0 Then
MsgBox ("No records found.")
DoCmd.Close
DoCmd.OpenForm "Machine_Unload"
Exit Sub
End If
Me.cmdEdit.Enabled = True
Me.cmdSearch.Enabled = False
Me.txtSN.Enabled = True
Me.txtDate.Enabled = True
Me.txtTime.Enabled = True
Me.CheckTime.Enabled = True
Me.ListSuccess.Enabled = True
Me.txtOperator.Enabled = True
Me.txtRemarks.Enabled = True
Me.txtSearch.Enabled = False
Me.txtSN.SetFocus
End Sub
Private Sub cmdEdit_Click()
On Error GoTo Err_cmdEdit_Click
Dim SN_Value As String
Dim Date_Value As String
If Me.SearchList.ListIndex > -1 Then
SN_Value = Me.SearchList.Value
Date_Value = Me.SearchList.Column(5)
If Not IsEmpty(Date_Value) Then
MsgBox ("The Unload data for this Serial Number have been filled, Please confirm with cell leader.")
DoCmd.Close
DoCmd.OpenForm "Esagon_Unload"
Exit Sub
End If
End If
'check whether there exists data in list
If Not (Me.SearchList.Recordset.EOF And Me.SearchList.Recordset.BOF) Then
'get data to text box control
With Me.SearchList.Recordset
Me.txtSN = .Fields("Serial_Number")
'store id of serial number in tag of txtSN in case id is modified
Me.txtSN.Tag = .Fields("Serial_Number")
'Disable button edit
Me.cmdEdit.Enabled = False
Me.cmdUpdate.Enabled = True
End With
End If
End_Err:
Exit Sub
Err_cmdEdit_Click:
MsgBox ("Select the Serial Number." & vbCrLf & "Please try again and click on the Serial Number below.")
DoCmd.Close
DoCmd.OpenForm "Machine_Unload"
Resume End_Err
End Sub
SELECT Machine.Serial_Number, Machine.End_Date, Machine.End_Time, Machine.End_System_Time, Machine.End_Operator, Machine.Success, Machine.End_Remarks
FROM Machine
WHERE (((Machine.Serial_Number)=[Forms]![Machine_Unload]![txtSearch]));
IsEmpty is not for this usage. Try:
If Not IsNull(Date_Value) Then
or:
If Nz(Date_Value) <> "" Then

Executing Append Query not doing anything

Executing Append Query not doing anything
I'm having an odd problem that just reared its ugly head for some reason. I have a form that is used to add/edit/delete records in tblWorkOrder. When the record is saved, a check is made to see if the companion record in tblServiceRecord exists, and if not (like if it were the first time the record in tblWorkOrder is being saved/input) it will execute a query (qryCreateSR).
Several weeks ago it worked just fine. I had no problems with it, but then I updated tblServiceRecord to add several new columns and now it's not working at all. However, the SQL for the query doesn't delineate any of these new columns, let alone any specific information from tblWorkOrder. So I'm not entirely sure how this bug came up.
Here is the SQL:
INSERT INTO tblServiceRecord ( WorkOrderID )
SELECT Forms![frmWorkOrders].Form![txtID];
And here is the code behind the command button:
Private Sub cmdSave_Click()
If DCount("*", "[tblServiceRecord]", "[WorkOrderID] = " & [Forms]![frmWorkOrders].[Form]![txtID]) > 0 Then
Else
DoCmd.SetWarnings False
DoCmd.OpenQuery "qryCreateSR"
End If
DoCmd.RunCommand acCmdSaveRecord
DoCmd.GoToRecord , "", acNewRec
Me.lstWorkOrders.Requery
Me.lstWorkOrders.Value = ""
Me.txtComments.Value = ""
cmdSave_Click_Exit:
Exit Sub
cmdSave_Click_Err:
MsgBox Error$
Resume cmdSave_Click_Exit
End Sub
After removing the warnings suppression I get a key violation issue.
No clue what is causing the key violations. I checked my tables, and the two tables in question are tblWorkOrder and tblServiceRecord. Both have no records in them, I compacted the database, the linked fields (in tblServiceRecord, there is a reference to tblWorkOrder with the field WorkOrderID) are set to the same data type (number), and the child-tables are set to Indexed (No).
Just in case anyone wants to look at the database itself, here is a link:
https://drive.google.com/open?id=1_T-G9fyYQYjH3-YBe4PXhbBDTKNmY3ce
Try saving the current record in the form (by setting Me.Dirty = False), before inserting the record to the other table. Since you try to insert into a child table with a relation to a parent table, you must have a corresponding (saved) record in the parent table. When you create a new entry in the form, it first doesn't exist in the table until it is saved for the first time.
Private Sub cmdSave_Click()
Me.Dirty = False ' Or DoCmd.RunCommand acCmdSaveRecord <==== Save here
If DCount("*", "[tblServiceRecord]", "[WorkOrderID] = " & [Forms]![frmWorkOrders].[Form]![txtID]) = 0 Then
DoCmd.SetWarnings False
DoCmd.OpenQuery "qryCreateSR"
End If
'Removed: DoCmd.RunCommand acCmdSaveRecord <==== instead of here
DoCmd.GoToRecord , "", acNewRec
Me.lstWorkOrders.Requery
Me.lstWorkOrders.Value = ""
Me.txtComments.Value = ""
cmdSave_Click_Exit:
DoCmd.SetWarnings True
Exit Sub
cmdSave_Click_Err: // This code will never run, since a "On Error Goto cmdSave_Click_Err" is missing
MsgBox Error$
Resume cmdSave_Click_Exit
End Sub

Updating a record by using a selection box control

I would like to know what the preferred function to put in a code string immediately after a user selects a selection box control of a record so that his selection is acknowleged and included as "true". In short, I have a form where the user uses a selection box to indicate which records to select and then executes a command where I have code that should copy and paste the records he selected. Unfortunately, the last record selected, upon running executing the copy/paste command is not recognised. I understand that I probably need to add a function such as ' go-to the next record' however I am not sure if this is the best way or if there is a more standard way that programmers use to not lose the last record selected. Below is the code I am currently using which currently does not pick up the last record selected by the user.
Private Sub Comando99_Click()
If CurrentRecord = Recordset.RecordCount And CurrentRecord <> 1 Then
DoCmd.GoToRecord , "", acFirst
Else
DoCmd.GoToRecord , "", acNext
End If
Dim intAnswer As Integer
On Error GoTo HandleError
intAnswer = _
MsgBox("Are you sure you want to add these dependencies to your dependency project tracker?", _
vbQuestion + vbYesNo, "Add Dependencies")
If intAnswer = vbYes Then
st_sql = "INSERT INTO [tblDependencies] ( [Description] )SELECT [tblDependencyTypeListing].[Dependency (General)] FROM [tblDependencyTypeListing] WHERE ((([tblDependencyTypeListing].[ToIncludeInProject])=True))"
Application.DoCmd.RunSQL (st_sql)
st_sql = "UPDATE[tblDependencies],[tblHoldingProjectid]SET[tblDependencies].[ID Project]=[tblholdingprojectid].[ID_Project]where([tbldependencies].[ID Project])=0 and ([tblholdingprojectid].[ID_Project])is not null"
Application.DoCmd.RunSQL (st_sql)
st_sql = "UPDATE[tblDependencies]SET[tblDependencies].[Automatic date of entry]=now() where([tblDependencies].[Automatic date of entry])is null"
Application.DoCmd.RunSQL (st_sql)
st_sql = "UPDATE[tblContacts],[tblDependencies]SET[tblDependencies].[Automatic user entry]=[tblContacts].[Complete name]where([tblContacts].[In use])is not null and([tblDependencies].[Automatic user entry])is null"
Application.DoCmd.RunSQL (st_sql)
st_sql = "UPDATE[tblDependencytypelisting]SET[tblDependencytypelisting].[toincludeinproject]=null"
Application.DoCmd.RunSQL (st_sql)
Me.Refresh
End If
ExitHere:
Exit Sub
HandleError:
MsgBox "Error is " & Err.Description
Resume ExitHere
End Sub
Problem is resolved by entering the following IF statement at the beginning of the routine to ensure that prior to running the code, ACCESS moves to the next record to ensure that it acknowledges the last modification made
If CurrentRecord = Recordset.RecordCount And CurrentRecord <> 1 Then
DoCmd.GoToRecord , "", acFirst
Else
DoCmd.GoToRecord , "", acNext
End If

VBA - Check multiple comboboxes

I have the below code where I'm trying to check comboboxes to make sure they are not null
I have a core combobox - cmbHierarchy - with Store, Retailer, Territory, District and secondary comboboxes to select stores, retailers, territories, districts (one for each)
I want the VBA to check cmbHierarchy to make sure it's populated, then depending on what it is populated with, make sure it's corresponding combobox has a value selected.
The current code is checking to make sure all 5 are populated. Where what I need is if cmbHierarchy = store then check cmbStore, if cmbHierarchy = retailer then check retailer, and so on.
Private Sub btnQryTermCount_Click()
Dim strQueryName As String
If Me.cmbHierarchy.Value = Store Or IsNull(Me.cmbStore.Value) Then
MsgBox "Please choose a Store"
Me.cmbStore.SetFocus
ElseIf Me.cmbHierarchy.Value = Retailer Or IsNull(Me.cmbRetailer.Value) Then
MsgBox "Please choose a Retailer"
Me.cmbRetailer.SetFocus
Else: strQueryName = "TERM_Count_" & Me.cmbHierarchy
MsgBox "Query Ready: " & strQueryName
DoCmd.OpenQuery strQueryName
End If
End Sub
Any help would be greatly appreciated.
Thanks!
Since your controls are named conveniently, you can do something like this:
If Nz(Me.cmbHierarchy.Value, "") <> "" Then
If Nz(Me.Controls("cmb" & Me.cmbHierarchy.Value).Value) = "" Then
MsgBox "Please choose a " & Me.cmbHierarchy.Value & "."
Else
strQueryName = "TERM_Count_" & Me.cmbHierarchy.Value
MsgBox "Query Ready: " & strQueryName
DoCmd.OpenQuery strQueryName
End If
Else
'cmbHierarchy validation failed logic here.
End if
IsNull instead of Nz maybe fine, but I am always in the habit of casting the value to be safe.

Work around Ms Access continuous form?

The problem
In the following form i want to accomplish two things
When Post check box is ticked i.e. when post= true a query should run targeting the current record only and subtracting the amount with balance field in the customer table.
UPDATE Customer INNER JOIN [Loan Payment] ON Customer.CUSID = [Loan Payment].CUSID SET Customer.CUSBalance = [Customer]![CUSBalance]-[Forms]![Loan Payment]![Amount]
WHERE (((Customer.CUSID)=[Forms]![Loan Payment]![CUSID]));
BUT INSTEAD THE WHEN THE QUERY IS EXECUTED FOR EXAMPLE ON LP6 INSTEAD OF [BALANCE]-20 IT DOES BALANCE-110 i.e. THE QUERY IS RUNNING ON ALL FIELDS
When the query have ran and post has been changed to true the post check box of the current record should become disabled so that the query may not ran twice or more times
AND I FOUND THAT CONDITIONAL FORMATTING CANNOT BE APPLIED TO TEXT BOXES
Requirement
I would like to know if i can achieve what i want and how?
Any workaround or alternative solution to what i am currently trying to achiee.
Firstly, I was using the wrong SQL.
UPDATE Customer SET Customer.CUSBalance = [Customer]![CUSBalance]-[Forms]![Loan Payment]![Amount]
WHERE (((Customer.CUSID)=[Forms]![Loan Payment]![CUSID]));
Secondly I found that conditional formatting can not be applied to check boxes so I had to find a workaround and I found three.
work around 1
I locked the Post check box and introduced a button which if Post = false would run the query and make Post = True
MY FORM NOW
The Code I used on the post button [on click procedure]
Private Sub Command19_Click()
If Me.Post = False Then
DoCmd.SetWarnings False
DoCmd.OpenQuery "updateCustomerLoan"
DoCmd.SetWarnings True
Me.Post = True
MsgBox ("Record has been Posted")
ElseIf Me.Post = True Then
MsgBox ("Record has already been posted")
End If
End Sub
Work around 2
I applied the following code on post_update() where I wrote two queries one do query (update) and one undo query (update)
Private Sub Post_AfterUpdate()
If Me.Post = True Then
DoCmd.SetWarnings False
DoCmd.OpenQuery "payLoanONpost"
DoCmd.SetWarnings True
MsgBox ("The record has been posted")
ElseIf Me.Post = False Then
DoCmd.SetWarnings False
DoCmd.OpenQuery "unpayLoanONunpost"
DoCmd.SetWarnings True
MsgBox ("Record has been unposted")
End If
End Sub
Work around 3 (by far the best and does what I initially set out to do
Here I only used one update query
Private Sub Post_AfterUpdate()
If Me.Post = True Then
DoCmd.SetWarnings False
DoCmd.OpenQuery "payLoanONpost"
DoCmd.SetWarnings True
MsgBox ("The record has been posted")
ElseIf Me.Post = False Then
MsgBox ("The record cannot unposted")
Me.Post = True
End If
End Sub