Work around Ms Access continuous form? - sql

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

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

In Access form, is there a way to use a search box to populate the form using 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

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

Access Sign in Module

I'm trying to create a finance database that requires users to sign in and log out. I have that part working correctly. On the homepage of the database, I'm trying to get their last 25 (or X number) of transactions to display using a query. For some reason, I cannot get the code to pass as it shows a "Data type mismatch." Here is the various code - I'll explain each as I go:
Global Variables (My Global Module)
Option Compare Database
'global variables
Global C As Long
Global C2 As Long
Global HoldString As String
Global Flag As Boolean
Global Reply As String
Global mbReply As VbMsgBoxResult
Global User As String
Global GUser As Long
Global db As Database
The following are the Subs() to Log In (First Sub() is for Exit button, second sub() is for sign in button):
Option Compare Database
Private Sub B_Exit_Click()
mbReply = MsgBox(title:="Exit", _
prompt:="Are you sure you wish to exit the system?", _
Buttons:=vbYesNo)
If mbReply = vbNo Then
Exit Sub
Else
DoCmd.Quit acQuitSaveNone
End If
End Sub
Private Sub B_SignIn_Click()
'variables
Set db = CurrentDb()
Dim Employees As DAO.Recordset
Set Employees = db.OpenRecordset("Employees", dbOpenDynaset)
Dim isEmployeed As Boolean
Dim PassMatch As Boolean
Dim isTerm As Boolean
'check to see if the user is in the system
isEmployeed = False
PassMatch = False
isTerm = False
Do While Not Employees.EOF
If Employees![UserName] = T_Username.Value Then
isEmployeed = True
'make sure the employee is not terminated
If Employees![Terminated] = "Yes" Then
isTerm = True
End If
If isTerm = True Then
MsgBox ("This user has been terminated.")
Exit Sub
End If
'make sure password is correct
If Employees![Password] = T_Password.Value Then
PassMatch = True
End If
If PassMatch = False Then
MsgBox ("Incorrect Password.")
Exit Sub
End If
'mark signed in
Employees.Edit
Employees![SignedIn] = 1
Employees.Update
User = Employees![FirstName] & " " & Employees![LastName]
GUser = Employees![ID] 'Sets GUswer to equal record ID.
End If
Employees.MoveNext
Loop
If isEmployeed = False Then
MsgBox ("This username is not in the system.")
Exit Sub
End If
'close this form and open the main menu
Employees.Close
DoCmd.OpenForm FormName:="HomePage"
DoCmd.Close acForm, Me.Name, acSaveNo
End Sub
The next is my SQL code for the query:
SELECT TOP 25 Spend.ID, Spend.Vendor, Spend.MaterialGroup, Spend.GLCode, Spend.CostCenter, Spend.Department, Spend.InvoiceNumber, Spend.InvoiceDate, Spend.Amount, Spend.Tax, Spend.Total, Spend.DateEntered, Spend.DocNumber, Spend.Description, Spend.[Paid?], Spend.EnteredBy, Spend.EnteredBy
FROM Spend
WHERE (((Spend.[EnteredBy])="GUser"));
Spend.[EnteredBy] has a relationship with the Employees table. So EnteredBy is actually a number field because of this relationship.
If I hardcode the "WHERE" statement to be something like (((Spend.[EnteredBy])=2)); then the query will work fine.
Ultimately, what I want to happen is for the query to show the last 25 data entries that the logged on user completed.
Hope this makes sense. If there are questions, please let me know. I feel like I'm missing something small but I cannot figure it out.
Thanks,
Clark
Your query should read:
SELECT TOP 25 Spend.ID, Spend.Vendor, Spend.MaterialGroup, Spend.GLCode, Spend.CostCenter,
Spend.Department, Spend.InvoiceNumber, Spend.InvoiceDate, Spend.Amount, Spend.Tax, Spend.Total,
Spend.DateEntered, Spend.DocNumber, Spend.Description, Spend.[Paid?], Spend.EnteredBy, Spend.EnteredBy
FROM Spend WHERE (((Spend.[EnteredBy])=" & GUser & "));
Note the Ampersands ( & ) I placed before and after your GUser variable. This tells Access to evalute that expression and return the VALUE of it.
I'd also caution you against use the name "User" as a variable name. It's a Reserved Word in Access:
http://office.microsoft.com/en-us/access-help/access-2007-reserved-words-and-symbols-HA010030643.aspx

Read-Only and undo properties MS Access (VBA)

I have been surfing the wed looking for an answer to what I thought it was a pretty simple question, for a newbie like me.. But havent found any so here I am!. To keep things simple, i'll attach the two bits of my code that are giving me a bit of a headache. What I intend to do is to switch from a Read-Only mode to a Write Allowed state by clicking a button. In order to do so, I want the routine to check for changes on the record and, if there are any ask the user to decide whether to save the changes or discard them.. While testing this particular button, I found out something quite "funny".. It seems to work well when no changes are introduced. Switches perfectly from read-only to write-allow states. However, when in write-allow and changes have been made, if the "Save option" has been selected/clicked then it does not lock the content although all the other subroutines and changes are implemented.
My other problem, closely related to this, is that I cant find a way to set a "saving point" for the undo option. I would like to find a way to "save a record" so when the undo button is pressed doesnt undo all the changes that the record has suffered since the database has been firstly opened (as its currently happening), but since the button has been pressed. I tried the DoCmd Save function but is not behaving as I was expecting (Note: the last 'else' has been my last try to this problem but, again, its not working as expected)
Many thanks for all your future collaboration,
Alex
Private Sub Command28_Click()
If Form_AODNewRecord.AllowAdditions = True Then
Call isModified_Save
Form_AODNewRecord.AllowAdditions = False
Form_AODNewRecord.AllowEdits = False
Form_AODNewRecord.AllowDeletions = False
MsgBox "Read Only. Addition, Edits and Deletions are now locked"
Command28.Caption = "LOCKED"
Else
Form_AODNewRecord.AllowAdditions = True
Form_AODNewRecord.AllowEdits = True
Form_AODNewRecord.AllowDeletions = True
MsgBox "New records, edits and deletions are now allowed"
Command28.Caption = "Lock mode OFF"
End If
MsgBox Form_AODNewRecord.AllowAdditions
End Sub
Sub isModified_Save()
If Form_AODNewRecord.Dirty Then
Dim strMsg As String, strTitle As String
strMsg = "You have edited this record. Do you want to save the changes?"
strTitle = "Save Record?"
If MsgBox(strMsg, vbQuestion + vbYesNo, strTitle) = vbNo Then
Me.Undo
Else
DoCmd.OpenTable "AOD Type", acViewPreview, acReadOnly
DoCmd.Save acTable, "AOD Type"
DoCmd.Close acTable, "AOD Type", acSaveYes
End If
End If
End Sub
I think you want the following code. You cannot open a table that the form is bound to and affect the form, when you open the table, you have two different instances and they do not affect one another.
An odd side effect of running a macro in Office applications is that it clears the Undo list, so I created a small macro that just shows a message "Undo cleared" and that is exactly what it does!
As an aside, rename your control with meaningful names, such as cmdLock, rather than Command28, you will thank yourself later.
Private Sub Command28_Click()
If Me.AllowAdditions = True Then
Call isModified_Save
Me.AllowAdditions = False
Me.AllowEdits = False
Me.AllowDeletions = False
MsgBox "Read Only. Addition, Edits and Deletions are now locked"
Command28.Caption = "LOCKED"
Else
Me.AllowAdditions = True
Me.AllowEdits = True
Me.AllowDeletions = True
MsgBox "New records, edits and deletions are now allowed"
Command28.Caption = "Lock mode OFF"
End If
''MsgBox Me.AllowAdditions
End Sub
Sub isModified_Save()
If Me.Dirty Then
Dim strMsg As String, strTitle As String
strMsg = "You have edited this record. Do you want to save the changes?"
strTitle = "Save Record?"
If MsgBox(strMsg, vbQuestion + vbYesNo, strTitle) = vbNo Then
Me.Undo
Else
''Save record
Me.Dirty = False
''Clear undo list
DoCmd.RunMacro "ClearUndo"
End If
End If
End Sub