Search code examples
ms-accessvbams-access-2010ms-access-2007ms-access-2016

Text box undo not working if there is a duplicate


I am having a form with a textbox and a list box. I want to enter a new record into the textbox to populate the table and listbox (listbox row source is the table). I have written a code to prevent duplicate entry into the table. When there is a duplicate entry I am getting a pop up to alert the user. What is not working is the undo option to clear the textbox. The code is pasted below with some required info. Any help with the code will be appreciated.

Table name: tblNewComponents

Field name: NewComponents

Textbox name: TextCOMPONENTS

Can someone help me? Thanks

Private Sub TextCOMPONENTS_AfterUpdate()
Dim NewComponent As String
Dim stLinkCriteria As String
Dim custNo As Integer
'Assign the entered customer name to a variable NewCustomer
NewComponent = Me.TextCOMPONENTS.Value
stLinkCriteria = "[NewComponents] = " & "'" & NewComponent & "'"
If Me.TextCOMPONENTS = DLookup("[NewComponents]", "tblNewComponents",     stLinkCriteria) Then
MsgBox "This Component, " & NewComponent & ", has already been entered in    database." _
& vbCr & vbCr & "Please check the component name again.", vbInformation, "Duplicate information"
Me.Undo
end if
exit sub

Solution

  • Just do this to clear the textbox (and set the focus into it)

    Me.TextCOMPONENTS.Value = Null
    Me.TextCOMPONENTS.SetFocus
    

    instead of Me.Undo.