How to validate data in a field?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I created a form where the user has to enter data. For one of the fields, I
would like to validate their data entry. I want to create an error message,
if the user does not enter "PK" or "TR" into this field. However, with the
below code, when I type "TR" or "PK" into the field it gives me the error
message("You must enter PK or TR"). Can you tell me what is wrong with my
code?

If (Me.Division<>"TR" Or Me.Division <> "PK") Then
Docmd.CancelEvent
returnvalue=Msgbox("You must enter PK or TR", vbCritical, "Required")
 
Your rule tells VBA to display the message if the value is not equal to "PK"
*OR* if the value is not equal to "TR". In other words, the only way you
could not trigger the message would be to enter *both* "PK" *and* "TR",
which of course is not possible. Your test should be ...

If (Me.Division<>"TR" And Me.Division <> "PK") Then

Note 'And', not 'Or'.

Better still, though, if the user must enter one of a small list of fixed
values, use a combo box or an option group instead of a text box.
 
Lavatress said:
I created a form where the user has to enter data. For one of the fields, I
would like to validate their data entry. I want to create an error message,
if the user does not enter "PK" or "TR" into this field. However, with the
below code, when I type "TR" or "PK" into the field it gives me the error
message("You must enter PK or TR"). Can you tell me what is wrong with my
code?

If (Me.Division<>"TR" Or Me.Division <> "PK") Then
Docmd.CancelEvent
returnvalue=Msgbox("You must enter PK or TR", vbCritical, "Required")


Change the OR to AND.

This is best done in the form's BeforeUpdate event, ehich
also has a Cancel argument. Setting Cancel = True
is more direct than using the CancelEvent method.

When you have no use for a function's return value. call it
as if it were a Sub procedure. The MsgBox line can be
written:

Msgbox "You must enter PK or TR", vbCritical, "Required"
 
You have commanded it to display the error if the field is not "PK" or "not
"TR".

If it is "PK" then it is not "TR" so you get the message
if it is "TR" then it is not "PK" so you get the message

you want the message if it is not "PK" and not "TR",

try again. You know you can do it.
 
Back
Top