Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Validating data 3

Status
Not open for further replies.
Jun 20, 2003
40
GB
I have a form that inputs data into a single table, one of the fields needs to be unique. I need to check after the field has been updated on the form that it is unique and produce an error message if it is not. Is this possible at all?
 
The simplest thing is to index the field in the table as unique. Access will then prevent any further entries.
 
I've already done that and Access produces and error only when the form is either closed or attempts to save the data to the table. Which is not what I'm after, I need to perform a check before the form is either saved or closed as the field is the first of many that need to be updated and the users will get a little pissed if they have to re-type the entry.

I may have to change my direction on this if it's not possible, but I'm sure it is.

 
Yes it is possible and there must be lots of ways of doing this, here is how I tend to approach this. You need to use the Before Update event in VBA on the field concerned. In the example below the Table is called 'A' and the field you are concerned about is 'ID'
Obviously you can change the message after msgbox . The use will need to press Escape to clear the field before continuing. POst again if you need any more help
Simon Rouse

Private Sub ID_BeforeUpdate(Cancel As Integer)

Dim dbs As DAO.Database
Dim rst As DAO.Recordset
Dim SQLStr As String
Set dbs = CurrentDb
SQLStr = "SELECT A.ID FROM A WHERE ((A.ID)=""" & [ID] & """);"
Set rst = dbs.OpenRecordset(SQLStr)
If rst.RecordCount > 0 Then
MsgBox "It's already there!"
DoCmd.CancelEvent
End If
rst.Close
dbs.Close

End Sub
 
Thanks Simon, that's what I've been looking for. I just coun't get it work how I wanted it.

Thanks again

Garry
 
I could not get this solution to work on my Db until I removed the data type lines Dim dbs As DAO.Database
Dim rst As DAO.Recordset. Once they were removed, it worked. Thanks for the post Dr. Simon.
 
Pappalito, you had to reference Microsoft DAO 3.x library.
Anyway, what about something like this ?
Private Sub ID_BeforeUpdate(Cancel As Integer)
If DCount("[Unique field]", "[Table name]", "[Unique field]='" & [Control name] & "'") > 0 Then
MsgBox "Duplicate !"
DoCmd.CancelEvent
End If
End Sub

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ222-2244
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top