473,400 Members | 2,163 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,400 software developers and data experts.

How do I stop a form from closing from the BeforeUpdate Event?

Seth Schrock
2,965 Expert 2GB
I have some code in the forms BeforeUpdate event that checks if a certain checkbox is checked. If it is not, I have a message appear that says "Do you wish to cancel this transaction?" with VbYesNo buttons. I want to be able to have it so that if I click no, the BeforeUpdate event is canceled and the form's close event stops so that the form remains open. If they click yes, then I want the BeforeUpdate's Cancel = True to run and then the form can close. The reason for this is that I don't want the record saving if that field is not checked. I'm not sure if setting the checkbox to be required will work and besides, I don't know how to customize the messages so that they are more understandable for average users.
Nov 28 '12 #1

✓ answered by NeoPa

When I'm doing such things Seth, I add a Private blnAllowClose As Boolean line at the top of the form and set it to True when, and only when, you want to allow the form to close. The Form_Unload(Cancel As Integer) procedure would then look something very like :
Expand|Select|Wrap|Line Numbers
  1. Private Sub Form_Unload(Cancel As Integer)
  2.     If blnAllowClose Then Exit Sub
  3.     Cancel = True
  4.     Call MsgBox(Prompt:="Please use the 'Close' button to close this form", _
  5.                 Buttons:=vbOKOnly Or vbExclamation, _
  6.                 Title:=Me.Name)
  7. End Sub

16 9854
Rabbit
12,516 Expert Mod 8TB
In the BeforeUpdate event, set a global variable that is checked in the BeforeClose event of the form.
Nov 28 '12 #2
NeoPa
32,556 Expert Mod 16PB
When I'm doing such things Seth, I add a Private blnAllowClose As Boolean line at the top of the form and set it to True when, and only when, you want to allow the form to close. The Form_Unload(Cancel As Integer) procedure would then look something very like :
Expand|Select|Wrap|Line Numbers
  1. Private Sub Form_Unload(Cancel As Integer)
  2.     If blnAllowClose Then Exit Sub
  3.     Cancel = True
  4.     Call MsgBox(Prompt:="Please use the 'Close' button to close this form", _
  5.                 Buttons:=vbOKOnly Or vbExclamation, _
  6.                 Title:=Me.Name)
  7. End Sub
Nov 28 '12 #3
Seth Schrock
2,965 Expert 2GB
@Rabbit, I had thought of that method, but I was hoping that there was an easier way. Oh well.

@NeoPa, How would a Private variable work? Wouldn't it have to be a public variable? Do I just declare the variable at the top of the form's VBA code right under the Option Explicit instead of inside a private sub?
Nov 29 '12 #4
NeoPa
32,556 Expert Mod 16PB
As you say Seth (and how I thought I'd explained it in my earlier post). What you would expect to see is something like the following :

Expand|Select|Wrap|Line Numbers
  1. Option Compare Database
  2. Option Explicit
  3.  
  4. Private blnAllowClose As Boolean
  5.  
  6. ...
Remember to set it to True somewhere though, or the code in post #3 will never allow the form to close ;-)

Seth:
@Rabbit, I had thought of that method, but I was hoping that there was an easier way. Oh well.
NB. What I'm suggesting, and giving details on, is essentially the same as Rabbit was. The difference seems to be in that the BeforeClose() event doesn't actually exist, but the concept is the same and I'm sure the Form_Unload() event was what he was thinking of.
Nov 29 '12 #5
Seth Schrock
2,965 Expert 2GB
I have never done a private variable that way before so I wasn't sure if that was what you were meaning.

I plan on setting the blnAllowClose with yes/no buttons of the message box that the BeforeUpdate event will trigger. I will have to have the variable sit on True so that it doesn't run unless the BeforeUpdate variable is triggered before that (unsaved data is in the form). I have done other things like this so I think that I can figure that part out.

Thanks to both of you for your help.
Nov 29 '12 #6
NeoPa
32,556 Expert Mod 16PB
You were quite right to check if you were unsure Seth. My bad for bringing that up.

Your explanation of the logic though, seems flawed. blnAllowClose should be left as False until some code is triggered that determines, for you, when the form should be allowed to close. Your logic is unknown to me, so I offer the following code as an example and illustration only. It does what I needed in my form :

Expand|Select|Wrap|Line Numbers
  1. Option Compare Database
  2. Option Explicit
  3.  
  4. Private blnAllowClose As Boolean
  5.  
  6. ...
  7.  
  8. Private Sub cmdClose_Click()
  9.     blnAllowClose = True
  10.     Call DoCmd.Close
  11. End Sub
  12.  
  13. Private Sub Form_Unload(Cancel As Integer)
  14.     If blnAllowClose Then Exit Sub
  15.     Cancel = True
  16.     Call MsgBox(Prompt:="Please use the 'Close' button to close this form", _
  17.                 Buttons:=vbOKOnly Or vbExclamation, _
  18.                 Title:=Me.Name)
  19. End Sub
Note that until this point in the code is reached blnAllowClose is left as False.
Nov 29 '12 #7
Seth Schrock
2,965 Expert 2GB
For me, the form should be allowed to close if there isn't any unsaved data on the form. My plan was based on tests that clicking the close button will trigger the BeforeUpdate event if there is unsaved data. That is when I planned on setting blnAllowClose to false, stop the closing of the form, and then set blnAllowClose to true as the last step of the On_Unload event of the form. Then, the next time the form is closed without any changes made to the data, blnAllowClose would already be set to True, BeforeUpdate wouldn't run, and the form would close.

I believe that this would work. However, it might not be the best way.
Nov 29 '12 #8
NeoPa
32,556 Expert Mod 16PB
That sounds a bit convoluted for something that should probably be a lot simpler. Why don't you explain what it is you're trying to achieve. What should be allowed and what shouldn't. When it isn't allowed what should happen instead.

That way we can match the requirement better, as we would have a better idea what you're really asking.
Nov 29 '12 #9
Seth Schrock
2,965 Expert 2GB
My goal is to make it so that there are no records where any of the fields are blank. For some reason, if there are, it messes up my queries that I do for billing purposes. What I have noticed is that occasionally, people start to create a record and realize someone else has already created it, so they just get out. This saves the record only partially filled out and then my billing gets messed up (reports won't open because of errors). I have put a cancel button on the form to undo the record, but I also want to make it so that it will undo the record if they try to exit without having canceled the record and the record isn't complete. I'm currently testing the last field in the recordset to see if it has been populated to know whether or not the record is complete. So if the record has been changed and the last field hasn't been checked, then I want to prevent the record from being saved, hence the BeforeUpdate event. That message will ask if you want to cancel the record changes. If yes, the the form can close. If no, then the form won't close and will remain on that record.
Nov 29 '12 #10
zmbd
5,501 Expert Mod 4TB
Seth,
Normally I set the field property at the table level to not allow null values and set the required to yes in cases like this... The user either has to [ESC] the record or enter a non-null. Is there any reason you have not done these same things at the table level?
Nov 29 '12 #11
NeoPa
32,556 Expert Mod 16PB
Zmbd:
Normally I set the field property at the table level to not allow null values and set the required to yes in cases like this...
I believe Z is referring to zero length strings rather than Null values in his comment, as the Required property does the latter and zero length strings are most definitely not Null values. That small anomaly cleared up, Z has expressed my thinking exactly. You should find that handles everything you need.

However, in case you are still interested in the logic, I will outline it for you :

Expand|Select|Wrap|Line Numbers
  1. Option Compare Database
  2. Option Explicit
  3.  
  4. ...
  5.  
  6. Private Sub Form_BeforeUpdate(Cancel As Integer)
  7.     If Not IsNull([X]) _
  8.     And Not IsNull([Y]) _
  9.     And Not IsNull([Z]) Then Exit Sub
  10.     Cancel = True
  11.     If MsgBox(Prompt:="Invalid Data.  Continue editing", _
  12.               Buttons:=vbOKCancel Or vbExclamation, _
  13.               Title:=Me.Name) = vbOK Then Exit Sub
  14.     Call Me.Undo
  15. End Sub
Seth:
For some reason, if there are, it messes up my queries that I do for billing purposes.
That would indicate to me that Null values are not being handled in your queries. It is not valid to design queries based on the assumption that all records will always have every field populated. Certainly not for any field where the [Required] property is not set to Yes (See Z's point).
Nov 29 '12 #12
Seth Schrock
2,965 Expert 2GB
As I described in previous post, I don't know how to create my own custom error messages if the fields aren't all populated. To me, the error messages are self explanatory, however my users don't see them that way. Hence, I always try to create my own messages so that they are worded more clearly and don't panic when they get it. I also have a question about a checkbox field being required. Does that make it be required to be true?

I will check my queries to see if I can figure that part out. That would certainly be the easier to fix. However, I seem to remember that the first WHERE clause in the query is to pull a certain CustomerID and partially empty records that have a different CustomerID seem to cause the problem as well. I would think that those wouldn't matter, but deleting those records makes the queries work.
Nov 30 '12 #13
NeoPa
32,556 Expert Mod 16PB
If a field is Required then the user cannot even leave the related control until it's either populated or the record buffer is undirtied (All changes cancelled). If you really feel that your users will find that too confusing then you'll need to take the other approach. I've dealt with users for many years and would find very little that they do and struggle with would still surprise me, but if they can use a mouse and keyboard they should be able to recognise a simple message telling them they need to enter a value before leaving a control. We are talking human life-forms here I assume. Ultimately your decision of course - but you'll certainly be creating vast amounts of work for yourself going forward.

The Required property means that the field must contain a value (IE. Not Null). Boolean values of True and False are both values (-1 and 0 respectively) so either would be allowed in a field that will not accept Nulls.
Nov 30 '12 #14
zmbd
5,501 Expert Mod 4TB
NeoPa... well... not exactly in that it's both-and not either-or: That will clear up in a minute, I think :)

Seth,
In the table design itself.
Open the table in design view.
Select a field... well, any text/numeric field
IN the properties section of the table creator for the field there are two properties..."Allow Zero Length" and "Required"
IF they are set as follows:
(this may get a tad weird:

By setting the properties as indicated when the user presses [Enter], [Space Bar], or attempts "" (zero length string either via VBA or directe entry) you get the following results stored, or not, in the field:
Expand|Select|Wrap|Line Numbers
  1. [Required]    [AllowZeroLength]    (Stored Values)
  2. (NO)      (NO)
  3.    [Enter]=Null; [SpaceBar]=Null; ""=NotAllowed
  4.  
  5. (NO)      (Yes)
  6.    [Enter]=Null; [SpaceBar]=Null; ""=""
  7.  
  8. (Yes)      (NO)
  9.    [Enter]=NotAllowed; [SpaceBar]=NotAllowed; ""=NotAllowed
  10.  
  11. (Yes)      (Yes)
  12.    [Enter]=NotAllowed; [SpaceBar]=""; ""=""
So by setting AllowZeroLength to No and Required to Yes, you prevent the record from having either a null or zerolength entry in the field and you force the user to enter something... AND/OR you can then use the validation rules on the field to help prevent out of bound entries; however, there are some limitations on the field level and table level validation rules.
Nov 30 '12 #15
NeoPa
32,556 Expert Mod 16PB
I appreciate it's both Z, but your post specified the same property twice. Setting Required to Yes is the same as not allowing Null values.

I agree that both the properties should be set correctly, but I'm a little confused as to your table. How is a user supposed to specify from the interface that they are entering an empty string rather than not entering anything (a Null)? They certainly wouldn't use quote characters. Empty strings, as far as I understand it, will be entered into the field in only two was :
  1. If (Required = Yes) and (Allow Zero Length = Yes) then when a user clears the contents of the control it is treated as a string value of zero length.
  2. The control or field is assigned a zero length string in VBA code explicitly.

Otherwise, the control will return a Null result and that will either be allowed or not depending on Required.

All-in-all though, I believe our advice is fundamentally the same, even if we don't necessarily see eye-to-eye on all the finer details.
Nov 30 '12 #16
zmbd
5,501 Expert Mod 4TB
Table was taken directly from the MS explaination for how the settings are effective once set as indicated.

Personally, I've not tried to enter a zero-length into a field via the keyboard; however, I have via VBA ;) and in which case the property settings if done right will cause a field level error.

I'd agree with that... the Devil is in the details which in this case doesn't matter - just the final result. :)
Nov 30 '12 #17

Sign in to post your reply or Sign up for a free account.

Similar topics

0
by: Steve V | last post by:
I'm using Access 2000 to build a budgeting/tracking database. Can I make a validation rule (using VBA) that checks the data as if the record has already been added? I've got 5 tables (only the...
0
by: Deano | last post by:
My beforeupdate event on the main form fires when a change has been made and the record has not been saved (2 variables are used to track this). Works great but if they make a change in my...
10
by: MLH | last post by:
Would like to examine the value entered into a textbox on an A97 form during the BeforeUpdate event. The textbox may or may not have had an earlier entry in it prior to the latest value that is...
6
by: John S | last post by:
When the user clicks the "X" in the upper right-hand corner of a form, how can I stop the form from closing?
6
by: lorirobn | last post by:
Hi, I have a form with a continuous subform. I am working on putting validations in for the subform's required fields. Being somewhat new to Access (or rather, an antiquated mainframe...
6
by: MLH | last post by:
Using A97. Want to examine 17-char VIN entered by user. VIN codes are alphanumeric and do not contain Oh's to prevent the confusion that could result if zeros were misread as O's or o's. So, if...
4
by: PW | last post by:
Hi, I want to add code to check if the user wants to save the record (fields are unbound) when they press the form's close (X) button. Is it possible to return the user to the form if there...
8
by: evn678 | last post by:
Hello all, I am trying to handle a scenario where a user clicks the 'X' close control on a form window border. I want to force the user to use the form's 'save' button to write the updated...
19
by: zacks | last post by:
I have a .NET 2.0 MDI application where the child form has a Tab Control. Each of the Tab in the Tab Control has a Validating event to handle what it should do when the user changes tabs. But...
7
by: liam sheerin | last post by:
Hi i am fairly new to vba and have a taxi booking database. every time you book a job the cust_name field must be filled out and same if account job for account_ref and account_password fields but...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.