Suppress standard error message with predefined choice - ms-access

I have built a form in MS Access that creates datasets for a database.
I have then implemented some code to check if all required fields have been filled before permitting the form to be closed and the dataset to be saved to the database.
All is working well, but I can't seem to suppress the standard error message created by Access telling me that I cannot save the dataset at the moment (if a required field is not filled and Cancel is set to true) and aksing me if I wanted to exit the form without saving.
The structure of my code is as follows:
Private Sub Form_BeforeUpdate(Cancel As Integer)
If requiredFieldsNotFilled Then
Cancel = True
Else
Cancel = False
End If
End Sub
When Cancel is set to true (i.e. the required fields haven't all been filled) a standard error message is thrown by Access (Error Code 2169) which I am trying to suppress as such:
Private Sub Form_Error(DataErr As Integer, Response As Integer)
If DataErr = 2169 Then
Response = acDataErrContinue
Else
Response = acDataErrDisplay
End If
End Sub
However, the generated error message provides a yes/no choice. 'Yes' being close the dataset without saving, 'No' being not close the dataset.
If I use the error handler as described above the default choice is taken which in this case is 'Yes' and the dataset is closed without being saved!
This is not what I want! I want 'No' to be chosen so that the user stays on the form and can correct his inputs... Any ideas on how to do that?
Any help is much appreciated! Thanks in advance!

I don't think such functionality is available, but you can manually stop the next close action by using the Form_Unload event:
Dim DontClose As Boolean
Private Sub Form_Error(DataErr As Integer, Response As Integer)
If DataErr = 2169 Then
Response = acDataErrContinue
DontClose = True
Else
Response = acDataErrDisplay
End If
End Sub
Private Sub Form_Unload(Cancel As Integer)
Cancel = DontClose
DontClose = False
End Sub

Related

How to ignore MS Access error 2113 totally?

I have a textBox formatted as "Short Date". When I put invalid data in field, for example random "dfsdf", and try to change focus, form throws validation Error 2113.
My goal is to give an opportunity to user to close form by click on "Cancel" button without any problem, because no matter what he entered in Date textbox while form is canceled.
I can handle this error and disable message with Form_Error event, but focus stays set to date textBox anyway, when i try to click Cancel button, and button is never clicked.
I use a setup, probably similar to yours:
Private Sub Form_Error(DataErr As Integer, Response As Integer)
Const InvalidDate As Long = 2113
Select Case DataErr
Case InvalidDate
MsgBox "Invalid date!"
Response = acDataErrContinue
' Cancel invalid entry.
Me.Undo
' DoCmd.Close
Case Else
Response = acDataErrDisplay
End Select
End Sub
Problem is, that this will fire before your button gets focus. This means, that the form doesn't even know what you clicked, only that it was somewhere outside the date textbox.
Thus, the DoCmd.Close would close the form for whatever was clicked.
You may turn it into an advantage, that the user is able to watch the removal of the faulty input ...
You should use the after update event to check if the user entered a valid date,
if not then clear or undo. Without knowing the controls of your form i can't tell if you allow users to change table values or if you are using transactions.
pseudo code:
Private Sub Text1_AfterUpdate()
If Check_If_Date Then
Execute_Code
Else
End If
End Sub
Private Function Check_If_Date() as Boolean
If IsDate(Text1) then
Check_If_Date = True
Else
Check_If_Date = False
Select Case msgbox("Not a valid date", vbOKCancel)
case vbOK
reset_value
case vbCancel
Close_Form
case else
End Select
End If
End Sub
Private Sub Reset_Value()
'need to clear value or undo
End Sub
Public Sub Execute_Code()
'Code to save values or allow Update to complete
End Sub
Private Sub Close_Form()
'Code For Closing Form and logging errors
End Sub
I split up repeatable actions for reuse in case the same thing can be repeated in another text box for example a second date or to get the same behavior for the other controls.

Use a button to Enable/Disable a text box in VBA

I have a form with a text box named Contract_Applying_for which is disabled on form load, but I want to have a button which allows me to edit the contents of the text box.
When I add a button I get presented with the Command Button Wizard, so I have created a Macro called ToggleEnableButton which has the instruction to
RunCode Function Name "=ToggleEnableButton()"
Then I have written the function
Function ToggleEnableButton()
If Me.Contract_Applying_for.Enabled = True Then
Me.Contract_Applying_for.Enabled = False
Else
Me.Contract_Applying_for.Enabled = True
End If
End Function
This seems to produce the error "Member already exists in an object module from which this object module derives."
The code for the ToggleEnableButton_Click is automatically created by the Command Button Wizard and is
Private Sub ToggleEnableButton_Click()
On Error GoTo Err_ToggleEnableButton_Click
Dim stDocName As String
stDocName = "ToggleEnableMacro"
DoCmd.RunMacro stDocName
Exit_ToggleEnableButton_Click:
Exit Sub
Err_ToggleEnableButton_Click:
MsgBox Err.Description
Resume Exit_ToggleEnableButton_Click
End Sub
Any suggestion of what I am doing wrong or a better way to approach this.
Seems like a very simple thing that I am trying to do, but quite a long winded approach.
As suggested by Peekay in the comments I have tried to use a checkbox instead, I wrote
Private Sub chbToggleEdit_Click()
If Me.chbToggleEdit.Value = False Then
Me.Contract_Applying_for.Enabled = False
Else
Me.Contract_Applying_for.Enabled = True
End If
End Sub
This gives the error: "A problem occurred while Microsoft Access was communication with the OLE server or ActiveX Control."
Can you not simply have:
Private Sub ToggleEnableButton_Click()
On Error GoTo Err_ToggleEnableButton_Click
ToggleEnableButton()
Exit_ToggleEnableButton_Click:
Exit Sub
Err_ToggleEnableButton_Click:
MsgBox Err.Description
Resume Exit_ToggleEnableButton_Click
End Sub
You can declare your function with the code behind your form.
Let me know if that works,
Ash

Access : how do i cancel an action if the data entered in the fields on the main matches data from a table displayed in a subform?

I have a Main Form with 3 fields, where the rep would enter the Property, Room Type, and the requested Check-in Date - however on the same form i have a subform displaying Property, Room Type and Check-in Dates NOT AVAILABLE. If a rep enters data in those 3 fields and ALL 3 match what is in the NOT AVAILABLE subform - what code (either VBA or On Lost Focus etc) can i use to look up those values in the subform (so that if it matches what's in the subform it will not allow for submission) and also popup an ERROR message that the "Property, Room Type and Check-In Date you selected are not available" ?
(Main Form data entered will go into a table let's say RoomRequestTable and Not Available subform displays data from another table RoomNotAvailableTable)
Below is some sample code utilizing the BeforeUpdate event. I'm assuming you want to trigger this from any of the fields, so I wrote a sample function that returns false if all of the fields match. We access the subform by calling Me.[SubFromName].Form.
Private function validate() As Boolean
Dim sbfrm As Form
Set sbfrm = Me.SubFormName.Form
If Me.FieldName = sbfrm.FieldName And Me.FieldName2 = sbfrm.FieldName2 And Me.FieldName3 = sbfrm.FieldName3 Then
MsgBox "you can't do that", vbExclamation, "Sorry kid"
'return false
validate = false
Else
'return true
validate = true
End If
End Function
Private Sub ControlName1_BeforeUpdate(Cancel As Integer)
Cancel = Not validate
If Cancel then
Me.ControlName1.Undo
End If
End Sub
Private Sub ControlName2_BeforeUpdate(Cancel As Integer)
Cancel = Not validate
If Cancel then
Me.ControlName2.Undo
End If
End Sub
Private Sub ControlName3_BeforeUpdate(Cancel As Integer)
Cancel = Not validate
If Cancel then
Me.ControlName3.Undo
End If
End Sub

How to cancel a form close in Close Event?

I'm sure this is very simple, but I can't find it. In the close event of an Access Form, how can I cancel closing the form? I have a test that counts the records in a table. If that table has records, I want to ask the user if they want to close or go back and work with them. So how do I cancel the close event?
You can use the Unload event:
GlobalVar ButtonClicked
Private Sub Form_Open(Cancel As Integer)
ButtonClicked = False
End Sub
Private ClickMe_Click(Cancel As Integer)
ButtonClicked = True
End Sub
Private Sub Form_Unload(Cancel As Integer)
If Not ButtonClicked Then
Cancel = True
End if
End Sub
Order of events for database objects
Study and try this code, it worked for me. Replace necessary variable names with your chosen names. Paste the code in the form_unload Event of your form.
WARNING!!!: After you perform this operation you will find it difficult to access your form in design and layout view
Private Sub Form_Unload(Cancel As Integer)
userresponse = MsgBox("Are you sure you want close? All your work wouldn't be saved", vbYesNo, "Database Information")
Select Case userresponse
Case 6
Cancel = False
'this line opens another form in my own case
DoCmd.OpenForm "EngMenu"
Case 7
Cancel = True
'this line keeps my own form open in my own case
DoCmd.OpenForm "UpdateForm"
Case Else:
MsgBox "You are not allowed to perform this operation", vbInformation, "Database Information"
End Select
End Subenter code here
Use the "Form_BeforeUpdate(cancel as integer)" event and set cancel to True.
Notice that you simply will not be able to close at all unless you add some logic to actually allow updating the database.

VBA isnumber istext function problem

im trying to check if a number is a text or number in a banking system. If the value is incorrect it should erase and send an error message, but my code isnt working at all... can someone help me? here is the code:
Private Sub TextBox1_Change()
name = TextBox1
If Application.IsText(name) = True Then
IsText = True
Else
MsgBox "Insert only words"
Selection.name.Delete
End If
End Sub
I think you should be using name = TextBox1.Text instead. It's probably giving you an error on that line.
Also, you may want to wait until the user is finished typing the response, I believe the changed event will run each time a character is pressed. The AfterUpdate will run after you tab or click away from the textbox.
And really, instead of deleting the response (which I don't think will work), you should simply set the textbox blank back to an empty string.
Private Sub TextBox1_AfterUpdate()
If Not MyIsANumber(TextBox1.Text) Then
MsgBox ("It's Text")
Else
TextBox1.Text = ""
End If
End Sub
Function MyIsANumber(str As String) As Boolean
For i = 1 To Len(str)
If IsNumeric(Mid(str, i, 1)) Then
MyIsANumber = True
Exit Function
End If
Next
MyIsANumber = False
End Function
I'm sure the code could be structured better, but there's something along the lines of what you need. In this case, it just wipes the textbox if there is a number entered. Obviously, things will need to be the opposite for your textbox that you want to contain a number.
Have you considered the vartype() function? https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/vartype-function