Updating/adding entry to table only when question is answered? - vba

I'm setting up a database in MS Access 2013, and want to ask the user a yes/no if they want to save or discard their non-saved record or edit before navigating away from the current record in my Access form.
The user should not be met with the question if pressing either the "add record" or "save" buttons.
Can someone point to where my problematic code is / or what I need?
Also, I'm new to Access, so please be gentle.
I have tried a few different guides or other answers around the web, but haven't gotten exactly to where I want to be.
My code is as such (cbotxt_Change and Form_Load relate to other parts of the form)
Private blnGood As Boolean
Option Compare Database
Private Sub cbotxt_Change()
Me.txt1.Value = Me.test1.Column(2)
Me.txt2.Value = Me.test1.Column(3)
Me.txt3.Value = Me.test1.Column(4)
End Sub
Private Sub Form_Load()
DoCmd.GoToRecord , , acNewRec
End Sub
Private Sub button_addRecord_Click()
blnGood = True
DoCmd.GoToRecord , , acNewRec
blnGood = False
End Sub
Private Sub Form_BeforeUpdate(Cancel As Integer)
Dim strMsg As String
If Not blnGood Then
strMsg = "want to abort?"
If MsgBox(strMsg, vbYesNo + vbQuestion, "Yes") = vbYes Then
Me.Undo
Else
Yes = True
End If
End If
End Sub
Using the code above, "want to abort?" is asked whenever the user is attempting to navigate away from the current record + when "add record" or "save" buttons are pressed. If the user answers "No", then the entry will save and the action in question be performed, except the "add record" button, which only seems to save now, not add a new record.

Seems a little convoluted to me. Try with:
Private Sub button_addRecord_Click()
DoCmd.GoToRecord , , acNewRec
End Sub
Private Sub Form_BeforeUpdate(Cancel As Integer)
Dim strMsg As String
strMsg = "want to abort?"
If MsgBox(strMsg, vbYesNo + vbQuestion, "New Entry") = vbYes Then
Cancel = True
Me.Undo ' or let the user press Escape.
End If
End Sub

Related

How to execute code when user closes form?

I want a msg box to appear if certain fields are empty on close.
Private Sub Close_Click()
If IsNull(Me.startDate) Then
MsgBox “You are in Phase 1”
End If
End Sub
I want the pop up to appear when user clicks the exit x. I tried OnClose. Right now the code is attached to and works via a button.
I’d like the code to be executed when the user closes the form.
Edit New Code:
Private Sub Exit_Click ()
If IsNull(Me.startDate) Or IsNull(Me.stepOneA) Or IsNull(Me.stepOneB) Then
MsgBox “You are in Step I”
DoCmd.Close
ElseIf IsNull(Me.stepTwoA) or IsNull(Me.stepTwoB) or IsNull(stepTwoC)
MsgBox “You are in Step II”
DoCmd.Close
Else
DoCmd.Close
EndIf
End Sub
You can use the UnLoad event for this:
Private Sub Form_Unload(Cancel As Integer)
Cancel = IsNull(Me.startDate)
If Cancel = True Then
MsgBox "You are in Phase 1."
End If
End Sub

Access VBA Preventing form record entry on close

I am working with Access Database VBA.
I have noticed if a user has filled a few of the text boxes in and then clicks the windows close button, the form logs that into the records.
I am wondering what is the best way to prevent the form from entering the uncompleted record on close?
There were a few sites pointing to placing a code in the beforeupdate function.
This is what I have tried.
Private Sub frmRecLog_BeforeUpdate(Cancel As Integer)
DoCmd.SetWarnings False
Me.Undo
Cancel = True
Exit Sub
End Sub
This code does not work at all for me.. I tried my best, haha.
Anything helps.
So, what you need is to insert a command button Save. If user do not hit on Save then it will not save any records. They will get a warning that data is not saved. You need declare a private boolean variable and write codes to save and warning. So full code will be like below.
Option Compare Database
Option Explicit
Private blnSaveRecord As Boolean
Private Sub cmdSave_Click()
blnSaveRecord = True
DoCmd.RunCommand (acCmdSaveRecord)
blnSaveRecord = False
End Sub
Private Sub Form_BeforeUpdate(Cancel As Integer)
Dim strMsg As String
If Not blnSaveRecord Then
Cancel = True
strMsg = "Please save the record.," & _
vbNewLine & "or press ESC from keyboard to cancel the operation."
Call MsgBox(strMsg, vbInformation, "Save Record")
'Me.Undo 'You can set undo option here if you do not want to press ESC.
End If
End Sub

Access Required Fields Before Exiting Form

I have this BeforeUpdate code to check if certain fields are filled out. These fields are required and must be filled or the record shouldn't save. If other fields have been filled without the ID and Staff field, then the message box prompts pop up (These are required fields, etc.).
Private Sub Form_BeforeUpdate(Cancel As Integer)
If Nz([ID], "") = "" Then
MsgBox "The ID field is required.", vbExclamation, "Required Field"
Cancel = True
End If
If Nz([Staff], "") = "" Then
MsgBox "Staff field is required.", vbExclamation, "Required Field"
Cancel = True
Me.[Staff].SetFocus
End Sub
I have a 'Close Form' button as follows:
Private Sub CmdCloseForm_Click()
DoCmd.Close , ""
End Sub
When this button is clicked, I get the warning that the fields aren't filled, but then the form closes. I want a Yes/No message box asking the user to see if they would still like to close the form or not. I've made a Yes/No messagebox in the BeforeUpdate sub. However it doesn't stop the sub CmdCloseForm.
Is there a way to create a messagebox to confirm if the user wants to exit the form?
For example:
If MsgBox("Would you like to close the form still? Changes won't be saved.", vbYesNo + vbQuestion, "Warning") = vbNo Then
Exit Sub
End If
If I put the above Msgbox into the CmdCloseForm function, it prompts the user before letting them know that they're missing the ID/Staff fields.
I came about this solution by Mr. Craig Dolphin and it worked for me.
The way he approached is to have a generic validation function that is saved in a general purpose module (ie not in a form module).
Public Function validateform(myform As Form) As Boolean
'returns true if all required fields have data, or false if not.
'It will also create a popup message explaining which fields need data
Dim boolresponse As Boolean
Dim strError As Variant
Dim ctl As Control
boolresponse = True
strError = Null
With myform
For Each ctl In .Controls
With ctl
If .Tag = "required" Then
If .Value & "" = "" Then
boolresponse = False
strError = (strError + ", ") & .Name
End If
End If
End With
Next ctl
End With
If strError & "" <> "" Then MsgBox "The following information must be entered first: "
& strError, vbInformation
validateform = boolresponse
End Function
Then, for any fields that are absolutely required, you just set the Tag property of the control to 'required'
You can then, for example, call the function from the onclick event of the 'save' button or 'close' button.
Private Sub Command5_Click()
On Error GoTo Err_Command5_Click
If Me.PrimaryID & "" <> "" Then
If validateform(Me) Then DoCmd.Close
Else
DoCmd.Close
End If
Exit_Command5_Click:
Exit Sub
Err_Command5_Click:
MsgBox Err.Description
Resume Exit_Command5_Click
End Sub
this essentially checks to see if the auto pk field has a value indicating that the record has been created. If it has, then it validates the required fields. If not, it closes without checking. If the record has been created, it validates the form and only closes if all the required fields are filled in. If more data is required, then it pops up a message reminding the user which fields to fill in.
The nice part of this is that you can set conditional requirements using the vba to set the tag property of certain controls to required if another field is updated to a value that you want to trigger an additional requirement. Of course, if you do that then you also need to initialize those tag value in the on_current event for when you switch records.
Many thanks to Mr. Craig Dolphin
Since you want to show consecutive pop-ups, cancel the auto-update altogether and validate on Close.
If validation is successful save the record, if not notify the user.
Private Sub Form_BeforeUpdate(Cancel As Integer)
Cancel = True 'cancel auto-update
End Sub
'Validate and either Save or Close
Private Sub CmdCloseForm_Click()
If Me.Dirty Then
If IsFormValidated Then
DoCmd.RunCommand acCmdSaveRecord
Else
If MsgBox("Would you like to close the form still? Changes won't be saved.", vbYesNo + vbQuestion, "Warning") = vbNo Then Exit Sub
End If
End If
DoCmd.Close acForm, Me.Name, acSavePrompt
End Sub
'Validation
Private Function IsFormValidated() As Boolean
IsFormValidated = True 'assume all is in order
If Nz([ID], "") = "" Then
MsgBox "The ID field is required.", vbExclamation, "Required Field"
IsFormValidated = False
End If
If Nz([Staff], "") = "" Then
MsgBox "Staff field is required.", vbExclamation, "Required Field"
Me.[Staff].SetFocus
IsFormValidated = False
End If
End Function

Access/VBA: "Run-time error 2169. You can't save this record at this time"

Using: Access 2013 with ADO connection to SQL Server back-end database
A form in my Access database is dynamically bound at runtime to the results of a SELECT stored-procedure from SQL Server, and allows the user to make changes to the record.
It has 2 buttons: Save and Cancel.
It is shown as a pop-up, modal, dialog form, and it has a (Windows) Close button at the top right corner.
I've put VBA code to ask the user whether he wants to Save, Ignore or Cancel the close action.
But there are problems and it gives the aforementioned error if Cancel is clicked. There are also other problems, like, after the error occurs once, then any further commands (Save or Cancel or closing the form) don't work - I think this is because the VBA interpreter has halted due to the earlier error. Another complication is that arises - I now need to end the MS-Access process from Windows Task Manager, doing this and then restarting the database and then opening this form will give an error and the form won't load. When the form is then opened in Design mode, I can see the connection string for the form is saved in the Form's Record Source property (this happens only sometimes), and which looks something like this:
{ ? = call dbo.tbBeneficiary_S(?) }.
Here is my code:
Dim CancelCloseFlag As Boolean
Dim SavePrompt As Boolean
Private Sub Form_BeforeUpdate(Cancel As Integer)
Dim a As Integer
If SavePrompt Then
a = MsgBox("Do you want to save changes?", vbQuestion + vbYesNoCancel, "Changes made")
Select Case a
Case vbNo:
Me.Undo
CancelCloseFlag = False
Case vbYes:
'do nothing; it will save the changes
CancelCloseFlag = False
Case vbCancel:
Cancel = True
CancelCloseFlag = True
End Select
End If
End Sub
Private Sub Form_Dirty(Cancel As Integer)
SavePrompt = True
End Sub
Private Sub Form_Error(DataErr As Integer, Response As Integer)
If DataErr = 2169 Then
Response = acDataErrContinue
End If
End Sub
Private Sub Form_Load()
LoadBeneficiaryDetails
End Sub
Private Sub Form_Unload(Cancel As Integer)
If CancelCloseFlag Then
Cancel = True
End If
End Sub
Private Sub btCancel_Click()
If Me.Dirty Then
SavePrompt = True
End If
DoCmd.Close
End Sub
Private Sub btSave_Click()
SavePrompt = False
DoCmd.Close
End Sub
I'm stuck and would like to know how others go about this issue? Basically I want to offer the user the choice Save, Ignore, Cancel when the user attempts to close the form with either Cancel button or the (Windows) close button. If the user chooses Cancel, then it should just return to the form without changing or undoing any changes to the data. The solution may be simple but it escapes my overworked mind.
Thanks in advance!
Please try the following code - I tested against all six scenarios and the proper action is taken.
Option Compare Database
Option Explicit
Dim blnAction As Integer
Dim blnBeenThereDoneThat As Boolean
Private Sub Form_BeforeUpdate(Cancel As Integer)
If blnBeenThereDoneThat = True Then Exit Sub
blnBeenThereDoneThat = True
blnAction = MsgBox("Do you want to save changes?", vbQuestion + vbYesNoCancel, "Changes made")
Select Case blnAction
Case vbNo:
Me.Undo
Case vbYes:
'do nothing; it will save the changes
Case vbCancel:
Cancel = True
End Select
End Sub
Private Sub Form_Error(DataErr As Integer, Response As Integer)
If DataErr = 2169 Then
Response = acDataErrContinue
End If
End Sub
Private Sub Form_Load()
LoadBeneficiaryDetails
End Sub
Private Sub Form_Unload(Cancel As Integer)
If blnAction = vbCancel Then
blnBeenThereDoneThat = False
Cancel = True
End If
End Sub
Private Sub btCancel_Click()
If Me.Dirty Then
Form_BeforeUpdate (0)
End If
If blnAction = vbCancel Then
blnBeenThereDoneThat = False
Exit Sub
ElseIf blnAction = vbYes Then
DoCmd.Close
Else
DoCmd.Close
End If
End Sub
Private Sub btSave_Click()
If Me.Dirty Then
Form_BeforeUpdate (0)
End If
If blnAction = vbCancel Then
Exit Sub
Else
DoCmd.Close
End If
End Sub

Stop access from saving data, force user to click button to save edited data

I have a form that opens and takes data from a table; and puts it in text boxes. There is button on this form, named "CustomerInfoBackBtn".
The code I have inside of it that doesn't work (well, it might... just Access automatically saves the data anyways when I edit the text boxes) is this:
Private Sub CustomerInfoBackBtn_Click()
Dim LResponse As Integer
LResponse = MsgBox("Would you like to save?", vbYesNo, "Save?")
If LResponse = vbYes Then
DoCmd.RunCommand acCmdSaveRecord
DoCmd.Close
DoCmd.OpenForm "CustomerListF"
Else
DoCmd.Close
DoCmd.OpenForm "CustomerListF"
End If
End Sub
How do I make it pop up the msgbox asking them if they would like to save, and if they push yes it saves, then refreshes the subform and THEN opens the previous form (CustomerListF) and if they push no, it doesn't save, reverts information to what it was before, and opens up the previous form? I think all I really need is a way to stop access from automatically saving the data changes, but I am not sure.
Edit for answer:
Code in button that pulls up that error:
Dim TempSaveRecord As Boolean
Private Sub CustomerNotesBackBtn_Click()
If MsgBox("Do you want to save your changes?", vbInformation + vbYesNo, [Warning! Some data may be lost.]) = vbNo Then
TempSaveRecord = False
Else
TempSaveRecord = True
End If
DoCmd.Close
End Sub
Private Sub Form_BeforeUpdate(Cancel As Integer)
If (TempSaveRecord) Then
DoCmd.Save
Else
DoCmd.RunCommand acCmdUndo
End If
End Sub
Here is what I do to control whether a record is saved or not.
Make sure that the Close Button property of the form is set to No so that the user will have to click on the Back button, Then use the following code:
Dim TempSaveRecord as Boolean
Private Sub cmdBack_Click()
If MsgBox("Do you want to save your changes?", vbInformation + vbYesNo) = vbNo Then
TempSaveRecord = False
Else
TempSaveRecord = True
End If
DoCmd.Close
End Sub
Private Sub Form_BeforeUpdate(Cancel As Integer)
If (TempSaveRecord) Then
DoCmd.Save
Else
DoCmd.RunCommand acCmdUndo
End If
End Sub
Then when the Form closes you can force any other form to Refresh using the following:
Private Sub Form_Close()
[Forms]![MyFormName].Refresh
End Sub
Form bounded DAO.Recordset are saved automatically by DAO Engine without any user action. In your case Modifications can be saved any time without warning, or before clicking on [Back] or [Close] button.
You can work around like this with transaction here or ADO:
Option Compare Database
Option Explicit
Private boolFrmDirty As Boolean
Private boolFrmSaved As Boolean
Private Sub Form_AfterDelConfirm(Status As Integer)
If Me.Saved = False Then Me.Saved = (Status = acDeleteOK)
End Sub
Private Sub Form_AfterUpdate()
Me.Saved = True
End Sub
Private Sub Form_Delete(Cancel As Integer)
If Me.Dirtied = False Then DBEngine.BeginTrans
Me.Dirtied = True
End Sub
Private Sub Form_Dirty(Cancel As Integer)
If Me.Dirtied = False Then DBEngine.BeginTrans
Me.Dirtied = True
End Sub
Private Sub Form_Open(Cancel As Integer)
Dim db As DAO.Database
Dim rs As DAO.Recordset
Set db = CurrentDb
Set rs = db.OpenRecordset("SELECT * FROM Customers", dbOpenDynaset)
Set Me.Recordset = rs
End Sub
Private Sub Form_Unload(Cancel As Integer)
Dim msg As Integer
If Me.Saved Then
msg = MsgBox("Do you want to commit all changes?", vbYesNoCancel)
Select Case msg
Case vbYes
DBEngine.CommitTrans
Case vbNo
DBEngine.Rollback
Case vbCancel
Cancel = True
End Select
Else
If Me.Dirtied Then DBEngine.Rollback
End If
End Sub
Public Property Get Dirtied() As Boolean
Dirtied = boolFrmDirty
End Property
Public Property Let Dirtied(boolFrmDirtyIn As Boolean)
boolFrmDirty = boolFrmDirtyIn
End Property
Public Property Get Saved() As Boolean
Saved = boolFrmSaved
End Property
Public Property Let Saved(boolFrmSavedIn As Boolean)
boolFrmSaved = boolFrmSavedIn
End Property
If you use ADODB.Recordset as form.Recordset,
Dim rst As ADODB.Recordset
'
'... Create it by querying a remote db.
'
Set Me.Recordset = rst
You thus can control saving or abandon of user modifications, As ADO driver can not save to the Database itself... It's more complicated.
Code from Reference