How to validate data in a field?

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")
 
B

Brendan Reynolds

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.
 
M

Marshall Barton

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"
 
D

David Cox

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Access Daily Entry with multiple entries per field 0
Error 2001 1
Acoustics - 80Hz loss in car! 0
Error 2001 message 1
Error 2001 1
Parsing (Contencate?) 2 fields into 1 10
VBA error using Access 5
M:M/Multiple Keys 5

Top