Throwing an error message when entering a duplicate value in a form

  • Thread starter Thread starter MarkG
  • Start date Start date
M

MarkG

Does anyone know how to throw an error message when a
duplicate value is entered in a form?

Rgds
Mark
 
Duplicate value meaning --- duplicate value in a field that matches one
already in the table? duplicate value for the entire record?

More info please about how you define duplicate and what setup you're using
to enter the value and to handle it.
 
Open the table in design view, select the field, and in the lower pane set
the Indexed property to:
Yes (No Duplicates)
This will raise an error at the time the record is about to be saved.

If you wanted to allow the user to override the choice and save the record
anyway, you could use the BeforeUpdate event of the text box on your form to
DLookup() the table and see if the value exists in another record as well.
 
Allen, thanks for your reply but i probably didn't make
myself clear enough. I know how to prevent duplicate
data being added to a field in a table, but what I want
to do is throw a custom error message when a duplicate
value is entered in a field in a form. E.g. 'The User ID
you entered has already been used please choose another
one'

Any help would be greatly appreciated

Rgds
Mark
 
Ken, I replied to Allen's email, if you have any
suggestions it would be greatly appreciated.

Rgds
Mark
 
To capture and replace the existing message, use the Error event of the
form. Unfortunately, that event does not tell you which control caused the
problem, and does not fire until there is an attempt to save the record.

Your other option is the BeforeUpdate event of the control itself. Use
DLookup() to see if *another* record has the same value, and if so, cancel
the text box's BeforeUpdate event.
 
Private Sub txtBoxName_BeforeUpdate(Cancel As Integer)
If Len(DLookup("FieldName", "TableName", "[PrimaryFieldName]=" & _
Me.txtBoxName.Value) & "") > 0 Then
Cancel = True
MsgBox "You've entered a value that is already in the database."
End If
End Sub
 
Back
Top