By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,761 Members | 1,879 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,761 IT Pros & Developers. It's quick & easy.

VB Code check please

P: 67
Hi All

I am having a little problem with the following code. I can't seem to get it to go back to focus on the Contact field. Please Advise.

Private Sub Contact_LostFocus()
If IsNull(Contact) Then
MsgBox "This field must be filled in!"
End If
End Sub


Jan 15 '09 #1
Share this Question
Share on Google+
4 Replies

Expert 100+
P: 634

I think perhaps you should use the BeforeUpdate Event something like this.

Expand|Select|Wrap|Line Numbers
  1. Private Sub Contact_BeforeUpdate(Cancel As Integer)
  2.     If IsNull(Contact) Then
  3.         MsgBox "This field must be filled in!"
  4.         Cancel = True
  5.     End If
  6. End Sub
This will prevent focus from leaving the control if it is null.

Hope that helps.

Jan 15 '09 #2

Expert 2.5K+
P: 3,532
As to the
I can't seem to get it to go back to focus on the Contact field
this is one of those quirks of Access. The focus both has and hasn't actually left the field in question when the LostFocus event fires. The way to beat this, as Mike TheBike has suggested, is to use the BeforeUpdate event and use the line

Cancel = True

The problem with using the BeforeUpdate event of the textbox for this kind of validation is that the user can simply not enter the textbox at all, in which case the validation won't take place at all! You need to place the code in the form's BeforeUpdate. This will insure that the user has to fill in the data.

Expand|Select|Wrap|Line Numbers
  1. Private Sub Form_BeforeUpdate(Cancel As Integer)
  2.      If IsNull(Me.Contact) Then
  3.          MsgBox "This field must be filled in!"
  4.          Cancel = True
  5.          Me.Contact.SetFocus
  6.      End If
  7.  End Sub
This is true for data validation that is intended to insure that a given field is populated before saving the record . Validation that is intended to insure that data entered into a field complies with some criteria, such as an ID number containing only numeric characters or a description field only containing alpha characters, can be placed in either the BeforeUpdate event of the textbox or the form.

Linq ;0)>
Jan 15 '09 #3

P: 67
Ok, the code works fine. The problem i now have is that the contact field is the first field on the form. When the sales form loads and if i tab away from the contact field the code doesn't work. How do i activate the form so that the code works.


Jan 15 '09 #4

P: 67
sorry guys my mistake. i put the code in the contact fields beforeupdate instead of the forms. works fine now. thanks
Jan 16 '09 #5

Post your reply

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