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'
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