MS-ACCESS Write Conflict Issue - vba

I am having a write conflict issue. Not sure what the cause could be. The issue occurs when multiple users are using the Access database.
Below is a schematic of whats happening. The (Main) Form displays a Subform (with some data displayed from the Table). The user can double click a name to pull up that individuals details, via the (Details) Form that pops up. If changes are made, the user can save the details (actually, a prompt pops up asking if you would like to save when closing the window).
When saving, then going to open up another individuals details, the write conflict pops up.
The code when closing the (Details) Form:
Private Sub Form_BeforeUpdate(Cancel As Integer)
' This procedure checks to see if the data on the form has
' changed. If the data has changed, the procedure prompts the
' user to continue with the save operation or to cancel it. Then
' the action that triggered the BeforeUpdate event is completed.
Dim ctl As Control
On Error GoTo Err_BeforeUpdate
' The Dirty property is True if the record has been changed.
If Me.Dirty Then
' Prompt to confirm the save operation.
If MsgBox("Do you want to save?", vbYesNo + vbQuestion, _
"Save Record") = vbNo Then
Me.Undo
End If
End If
Exit_BeforeUpdate:
Exit Sub
Err_BeforeUpdate:
MsgBox Err.Number & " " & Err.Description
Resume Exit_BeforeUpdate
End Sub
Which was taken from the Microsoft website (I think).
Is there something wrong with my data structure that is causing this?
If more information is needed, I can edit the post to include more code etc.
EDIT 1: Reversed Subform arrow. The Subform simply displays data from the Table.
EDIT 2: Backend is Access. To open the (Details) Form from the Subform:
Private Sub First_Name_DblClick(Cancel As Integer)
DoCmd.OpenForm "Details", , , "[First Name] = '" & Me![First Name] & "' and [Last Name] = '" & Me![Last Name] & "'"
End Sub
EDIT 3:
While looking at the (Main) Form, the Subform has a Source Object set to the name of the Subform, which I call QuerySF. The QuerySF Form has a Record Source set to the Table. The pop-up (Details) Form has a Record Source set to the Table. I can instead set the Record Source for the (Details) Form to my Query, but I tried this and it did not help.
Would inserting a Requery somewhere help?
I have noticed the pop-up occurs every third time the (Details) Form is opened via the Subform.

If you don't want to save, use Cancel = True. BeforeUpdate would not trigger if form is not dirty so don't bother with If Me.Dirty.
' Prompt to confirm the save operation.
If MsgBox("Do you want to save?", vbYesNo + vbQuestion, "Save Record") = vbNo Then
Cancel = True
Me.Undo
End If

Related

Dealing with edited fields left in blank on subform

I am having a problem when an user decides to "clear/delete" a line entered on the form during the first update.
I have a form with a subform to give the user the possibility of multiple entries, however, after the user has first edited any field on the subform the respective record gets dirty and recorded, so if the user decides to not use anymore that record and deletes all the info for that line, that line which now is all blank still being recorded, and this is giving me blank lines in my data (The TransactionID and ID are not shown to the user on the form, I added it for the sake of this post).
This can also accidentally happen if on the "new" line, which is not dirty, the user hits any key by mistake, and even deleting it straight away, the record gets dirty for good, so it ends being recorded completely in blank.
I couldn't find a way to avoid recording this blank lines.
I would like to know if it is possible to have buttons to "add a new line" and "delete a line", just like, on the last line it would have a "+" to add new line (so the "new not dirty" line wouldn't appear automatically), and on the precedent lines would have a "-" to remove that specific record (this is just an idea, it can be in any kind of way).
Is that achievable? If it is not, is there a way to simply avoid blank lines to be saved? Like, saving jumping those blank lines, just like in a loop?
More information added for the sake of better explanation.
I didn't include the code before as there is no code behind this, this is just access natural recording set. I am not using DAO Record Set nor SQL to "save" the records (just to delete from table in a discard event), I am using normal bounded controls.
The modifications I did were on Parent form to always stay on the Current Record (Cycle) and On Load event it always goes to new record. Thus, the buttons Save and Cancel, are used to confirm or discard the new record created on the Parent form, because, as I have previously said, the subform is used to enter multiple records under the same record on the Parent Table, in other words, Relationship One-To-Many, therefore the button "Close" holds a simple code for deleting the last entry on the Parent Table (as it still on the current record) and as the tables have "Delete Cascade Relationship" all the information entered into the subform/Child Table get automatically deleted, so I just had to handle the data inserted into the Parent Table, whereas, the save button is used to get the confirmation of saving from the user, and make sure that the user will fill all the fields prior to save.
That is pretty much the code on this form, which is below.
But before the code, I would like to reinforce that, I have made use of the "BeforeUpdate" event, which works fine, it makes the user to add all the fields before opening a new record on the subform, but let's suppose that the user enters 10 records on the subform, then the user decides to "Delete" one of the records (which in this case is not the last one, so he cannot just press "ESC" and I cannot just run "Me.Undo"), so if the user clears the fields (just like in the images I have provided, as I don't know how to delete a record in this scenario yet), the before update event gets triggered and doesn't allow the user to do anything while he/she fills in the blank fields, not even to click in "Cancel". Therefore, in my "Save" button I check all the fields and if one of them is "dirty" them the user must fill all the subsequent fields, however, if all the fields are "empty", the user is still able to save.
In the beginning I thought that those "blank lines" wouldn't happen so often and I would have to clean them sporadically, but it is unbelievable, the amount of blank lines that have been created by the users. I have to clean them almost every week.
I really would like a way to create "+ add line" and "- delete line" buttons, because if the user wants to delete a line he just click on "-" button, the same for add new line.
Again, I appreciate the help. I am really struggling on this. Thanks all.
Private Sub btnSave_Click()
If IsNull(Me.TransactionDate) _
And IsNull(Me.SupplierPayee) _
And IsNull(Me.TotalReceipt) Then
MsgBox "Form in blank!", vbInformation + vbOKOnly, "Saving..."
Exit Sub
End If
If IsNull(Me.TransactionDate) _
Or IsNull(Me.SupplierPayee) _
Or IsNull(Me.TotalReceipt) Then
MsgBox "Please fill in all the fields", vbCritical + vbOKOnly, "Transaction not Saved"
Exit Sub
End If
Me![subfrmPCHeaderDetail].SetFocus
DoCmd.GoToRecord , , acFirst
If IsNull(Me.TransactionDate) _
Or IsNull(Me.SupplierPayee) _
Or IsNull(Me.TotalReceipt) _
Or IsNull(Form_frmPCHeaderDetail.Item) _
Or IsNull(Form_frmPCHeaderDetail.ItemAmount) _
Or IsNull(Form_frmPCHeaderDetail.VATRate) _
Or IsNull(Form_frmPCHeaderDetail.DescriptionPurpose) Then
MsgBox "Please fill in all the fields", vbCritical + vbOKOnly, "Transaction not Saved"
Exit Sub
ElseIf Form_frmPCHeaderDetail.ItemAmount = "0" Then
MsgBox "Amount cannot be €0.00", vbCritical + vbOKOnly, "Transaction not Saved"
Form_frmPCHeaderDetail.ItemAmount.SetFocus
Exit Sub
End If
If Not Me.TotalReceipt.Value = Form_frmPCHeaderDetail.GrossTotal _
Or IsNull(Me.TotalReceipt) Then
MsgBox "Please check the Receipt Amount Details as ""Gross Total"" and ""Receipt Total"" are not matching"
Exit Sub
End If
If Me.ReceiptScanned.AttachmentCount = 0 Then
MsgBox "Please scan the receipt and add it to this transaction", vbInformation + vbOKOnly, "Add the Receipt"
Me.AddReceiptScanned.SetFocus
Exit Sub
End If
If Me.TransactionDate > Date Then
MsgBox "Future Transaction Date not allowed", vbCritical + vbOKOnly, "Transaction not Saved"
Me.TransactionDate.SetFocus
Exit Sub
Else
Dim Result As Long
Result = MsgBox("Saving Transaction!" & vbNewLine & vbNewLine & _
"Attention!" & vbNewLine & vbNewLine & _
"You will not be able to delete nor modify any detail of this transaction!" & vbNewLine & vbNewLine & _
"Are you sure you would like to save this transaction?" & vbNewLine & vbNewLine & _
"Click ""YES"" to save, or click ""NO"" to return.", vbExclamation + vbYesNo, "Save Transaction?")
If Result = 6 Then
DoCmd.Save
DoCmd.Requery
Form_frmPCHeader.TransactionDate.SetFocus
DoCmd.GoToRecord , , acNewRec
MsgBox "Transaction added successfully to the Petty Cash Register", _
vbInformation + vbOKOnly, "Petty Cash transaction added"
End If
End If
End Sub
Private Sub btnClose_Click()
Dim LastID As Long
Dim Result As Long
If IsNull(TransactionID) Then
DoCmd.Close
Exit Sub
End If
LastID = TransactionID
MsgBox("Closing without saving!" & vbNewLine & vbNewLine & _
"If you want to discard the entries, click ""YES"", or click ""NO"" to return.", vbCritical + vbYesNo, "Discard Entries?")
If Result = 6 Then
Application.Echo False
Me.Painting = False
DoCmd.SetWarnings False
Me.TransactionDate = "31/12/2099"
Me.SupplierPayee = "Discarded"
Me.TotalReceipt = 0
DoCmd.Save
DoCmd.Requery
DoCmd.RunSQL "DELETE * FROM tblPCHeader WHERE TransactionID = " & LastID & ""
DoCmd.Close
Application.Echo True
DoCmd.SetWarnings True
End If
End Sub
Private Sub Form_Load()
DoCmd.GoToRecord , , acNewRec
End Sub
For a Delete (-) button, consider code:
DoCmd.SetWarnings False
DoCmd.RunCommand acCmdDeleteRecord
DoCmd.SetWarnings True
For Add (+) button, just move to new record row with code you already know.
Docmd.GoToRecord , , acNewRec

Can I filter an Access form based on a match criteria using VBA?

I have created a form that acts like a more advanced find dialog box. The user clicks on a button within a form, which opens my search form. This search form filters the original form to only display records that match certain fields from the original record within a certain tolerance.
Is there a way to sort the filtered form to display the closest matches first? I have considered using a couple of helper fields within the form. These helper fields would be equivalent to the absolute value of the difference between my criteria and the data within the record's fields. However, I was unsure of whether there was a better way to approach the problem.
Thank you.
Yes, you can certainly set the forms sort order quite much as easy to set the filter.
You might have say this:
Dim f As String
Dim strWhere As String ' our filter
Dim strSortBy As String ' our sort by
f = "frmFilter" ' name of our filter form.
DoCmd.OpenForm f, , , , , acDialog
If CurrentProject.AllForms(f).IsLoaded = False Then
' user closed the dialog form, so lets cancel
Exit Sub
End If
' setup our form filter.
If IsNull(Forms(f)!CompanyName) = False Then
' user entered company name - filter by that
' match by starting
strWhere = "CompanyName LIKE '" & Forms(f)!Company & "%'"
strSortBy = "CompanyName"
End If
If IsNull(Forms(f)!City) = False Then
' user entered Persons name - filter by that
strWhere = "LastName = '" & Forms(f)!LastName & "'"
strSortBy = "City, LastName"
End If
' ok, done with that form, close it
DoCmd.Close acForm, f
Me.Filter = strWhere
Me.FilterOn = True
Me.OrderBy = strSortBy
Me.OrderByOn = True
For the dialog form to work (allow the code to continue?). The ok button on the dialog form will cause the code above to wait. So, to get "back" to this calling code, the ok button on the dialog form (the filter form) will have:
me.Visible = False
And the cancel button on the filter form will have:
docmd.Close acForm, me.Name
So, we assume that
If user hits ok on filter form - it is a "ok", and the form is STILL open. This allows our above code to use/look at/grab values from that dialog form.
If the user hits cancel in that dialog form, it is closed and once again our above code will run after the user closes that dialog form. So, closing the form means cancel, and setting visible = False means ok. (both actions (close, or visible = False) will flip the dialog form OUT of dialog mode and allow our above code to run after the open dialog form command we have above.
It is then a simple matter to get/grab values from the dialog form , setup our filter, and also setup our "order by"

Message Box on Record Change

I have a form that queries records that the user may want to edit. I want the user to only be able to save the record if they've clicked the 'Save' button. Hitting the 'Close' button will prompt the user if they haven't saved yet, and may ask if they want to save.
I'm encountering a problem when the user changes through the records: I want to have a Y/N message box prompt the user for saving the changes they made to the previous record, otherwise their changes will be discarded. I have the following code set up:
Private Sub CmdCloseForm_Click()
If Me.Dirty Then
'checks that needed fields are completed
If IsFormValidated = False Then
If MsgBox("Required fields aren't filled." & vbCrLf & "Would you like to close this form without saving?", vbYesNo + vbQuestion + vbDefaultButton2, "Warning") = vbNo Then
Exit Sub
End If
Else
'checks if form has been saved already
If mSaved = False Then
Select Case MsgBox("Form hasn't been saved. Do you want to save and close?" & vbCrLf & "If you click 'No' the form will close without saving.", vbQuestion + vbYesNoCancel, "Save As")
'selecting yes will save and close form
Case vbYes:
mSaved = True
'selecting no will close the form w/o saving
Case vbNo:
mSaved = False
'selecting cancel will cancel out of the prompt
Case vbCancel:
Exit Sub
End Select
ElseIf mSaved = True Then
'if form has been previously saved, will finally close the form
If MsgBox("Would you like to close this form?", vbYesNo + vbQuestion + vbDefaultButton2, "Close Form") = vbNo Then
Exit Sub
End If
End If
End If
End If
DoCmd.Close acForm, Me.Name, acSaveNo
End Sub
'won't save automatically unless mSaved is true
Private Sub Form_BeforeUpdate(Cancel As Integer)
'if mSaved = False then the record won't save
If mSaved = False Then
Cancel = True
Me.Undo
Cancel = False
End If
End Sub
I pretty much want the 'CmdCloseForm' Message Boxes to run when the user moves on to the next record. Is there any way to do this?
If you really want to ask user about saving changes for each row, ask in Form_BeforeUpdate and in Form_BeforeDelConfirm. Those events will be fired each time when user changes edited record, or when subform with edited records loses focus, or user closes form with data. But this is not good solution because messageboxes will be too annoying. The better way is to copy edited data to temporary table, allow user edit the data and copy back to source table changed data when user clicks "Save". It's quite simple if you don't need multi-user data editing, in this case you will need some additional code for avoiding collisions.

Using query yes/no field for checkbox record source?

First of all, you start with a form named LoginF. Once you choose your login ID, and password; and log in it takes data from the table LoginIntoT for the login ID you chose, and creates a query with said data using this code:
On Error Resume Next
DoCmd.DeleteObject acQuery, "IsAdminQ"
On Error GoTo Err_LoginBtn_Click
Dim qdef As DAO.QueryDef
Set qdef = CurrentDb.CreateQueryDef("IsAdminQ", _
"SELECT IsAdmin " & _
"FROM LoginInfoT " & _
"WHERE EmployeeID = " & LoginCmBx.Value)
Exit_LoginBtn_Click:
DoCmd.Close acForm, "LoginF", acSaveNo
DoCmd.OpenForm "MenuF"
Exit Sub
Err_LoginBtn_Click:
MsgBox Err.Description
Resume Exit_LoginBtn_Click
From there in that query after you log in is only 1 column and 1 row; meaning one piece of data. This data is a yes/no field which is either Yes or No depending on who you logged in as.
On the form it opens after you click the login button it has a logout button. The logout button brings you to the previous login form, and deletes the query (IsAdminQ).
What I am trying to do is attach a yes/no button on a form to take that data, and output if it's yes or no on the query.
I've tried putting this in it's control source:
=[IsAdminQ].[IsAdmin]
Though what that does is output it as a filled in square instead of a checkmark or empty. I have triple state set as no.
How would I attach the checkbox to the query so if the data says yes, then it's a check mark and if it says no it is an empty box?
I understand you.
"On the form it opens after you click the login button it has a logout button", we call it frmLogout. You shall do this:
Solution I:
frmLogout.RecordSource = "IsAdminQ"
Then for your checkbox named MyCheckbox, we set it this:
Me.MyCheckbox.ControlSource = "IsAdmin"
You cannot use this:
Me.MyCheckbox.ControlSource = "[IsAdminQ].[IsAdmin]" ' <= here it's impossible.
Solution II:
On the form frmLogout without setting IsAdminQ as .RecordSource,
In a Public Module, insert this:
Function GetLoginStateIsAdmin()
'
Dim rst As DAO.Recordset
Set rst = CurrentDb.OpenRecordSet("IsAdminQ")
GetLoginStateIsAdmin = Nz(rst(0), False)
Set rst = Nothing
'
End Function
Then in the private module of any form, as frmLogout:
Private Sub Form_Open(Cancel As Integer)
'
Me.MyCheckbox.Value = GetLoginStateIsAdmin()
'
End Sub
Set it in addition in design mode:
Me.MyCheckbox.TripleState = false
And check also if the query IsAdminQ has been successfully created in the login step. And open it in Access Navigation Pane by double-clicking on it. And see the value of the query.

More info when you click a field in a subform table in pop up form

I am trying to get a window to popup when you click that small box beside a field in my subform table, and then click the button "more info". This form would pop up with all the extra information about that record; in text boxes so you can edit it. On this form it pops out, it only has a button that has back and when you click back, it saves all the changes made in the text boxes in the record you were viewing more information about... and updates it. It then brings back up the previous form, and updates the subform on that form so it shows all changes made to the table. I am not looking for the More Info button to show more info for all records. I am looking for it to bring up more info for that one record you selected only, and to get more info on another, you must click back and select a new one. How would I go about setting up the More Info button so it pops up the new form with the information?
For an example of what I mean by pressing the more info button, here is a picture:
In the picture, it is a table. Clicking that small space highlights the whole record, and you are able to push DEL on your keyboard to delete the record (though that doesn't matter in the case, just pointing out it's a table.)
Code I have in my More Info button:
Private Sub CustomerMoreInfoBtn_Click()
On Error Resume Next
DoCmd.Close acForm, "CustomerInfoF"
DoCmd.DeleteObject acQuery, "CustomerMoreInfoQ"
On Error GoTo Err_CustomerMoreInfoBtn_Click
Dim qdef As DAO.QueryDef
Set qdef = CurrentDb.CreateQueryDef("CustomerMoreInfoQ", _
"SELECT * " & _
"FROM CustomersT " & _
"WHERE CustomerID = " & txtCustID.Value)
DoCmd.OpenForm "CustomerInfoF"
Exit_CustomerMoreInfoBtn_Click:
Exit Sub
Err_CustomerMoreInfoBtn_Click:
MsgBox Err.Description
Resume Exit_CustomerMoreInfoBtn_Click
End Sub
Code in the form it self:
Private Sub Form_Close()
On Error Resume Next
DoCmd.DeleteObject acQuery, "CustomerMoreInfoQ"
End Sub
In the below example your button is named cmdMoreInfo. When you click on the button it creates the MyCustDetail query based on the value of the customer id. Then it opens the frm_CustDetailEdit form. Set the forms Record Source to MyCustDetail.
In order to be able to create the query it must not already exist. Therefore, I check beforehand and delete it if it exists. Also, when closing the main form it also will delete the query since it would no longer be needed anyway.
Private Sub cmdMoreInfo_Click()
On Error Resume Next
DoCmd.Close acForm, "frm_CustDetailEdit"
DoCmd.DeleteObject acQuery, "MyCustDetail"
On Error GoTo Err_cmdMoreInfo_Click
Dim qdef As DAO.QueryDef
Set qdef = CurrentDb.CreateQueryDef("MyCustDetail", _
"SELECT * " & _
"FROM tbl_Customer " & _
"WHERE CustomerID = " & txtCustID.value)
DoCmd.OpenForm "frm_CustDetailEdit"
Exit_cmdMoreInfo_Click:
Exit Sub
Err_cmdMoreInfo_Click:
MsgBox Err.Description
Resume Exit_cmdMoreInfo_Click
End Sub
Private Sub Form_Close()
On Error Resume Next
DoCmd.DeleteObject acQuery, "MyCustDetail"
End Sub