Search code examples
ms-accessonerror

Where to place my on error command in Access 365 vba code


I am using MS Access DB 365 on a windows 10 pc. I have a code I have put together. Now granted I am not an expert but this is working to a point. I am attaching some images and my code for this issue. I Have a Sign In sheet for employees to sign in. On that form I have two sub forms and two unbound textboxes. One text box (txt_EDPI) is were a user will input their Employee number. It then queries a the first sub-form (subUserList) which Source Object is (sfrm_User_Info), this sub-form is hidden. My second sub-form (subSignIn) which its source object is (sfrm_Sign_In_List) is visible it is a continuous form.

The goal is that when a user inputs their number in the (txt_EDPI) box and then clicks the Sign-In button it will locate (sfrm_User_Info) and that one record is taken to the next sub-form (sfrm_Sign_In_List). My only problem now is if that user does not exist in my Database I get an error. I need help on scripting it and where to place it with-in my current script. Now if there is a better way to do this please let me know. My Script is below.

Private Sub cmd_SignIn_Click()
Dim SQL As String
Dim db As Database
Dim rec As Recordset
SQL = "SELECT tbl_User_Info.EDPI, tbl_User_Info.[User Name]," _
        & "tbl_User_Info.[User Email]," _
        & "tbl_User_Info.Office FROM tbl_User_Info " _
        & "Where EDPI LIKE '*" & Me.txt_EDPI & "*'"                
    Me.subUserList.Form.RecordSource = SQL
    Me.subUserList.Form.Requery
    Set db = CurrentDb
    Set rec = db.OpenRecordset("Select * from tbl_Sign_In_List")
        rec.AddNew
        rec("EDPI") = Me.subUserList.Form.[EDPI]
        rec("User Name") = Me.subUserList.Form.[User Name]
        rec("User Email") = Me.subUserList.Form.[User Email]
        rec("Office") = Me.subUserList.Form.[Office]
        rec("Sign In Date") = Me.txt_MDate
        rec.Update
Set rec = Nothing
Set db = Nothing    
Me.subSignIn.Form.Requery
Me.txt_EDPI.Value = ""
DoCmd.GoToControl "cmd_SignIn"
DoCmd.GoToControl "txt_EDPI"
End Sub

Design View of the Form

Design View of the Form

Form View of the Form

Form View of the Form


Solution

  • As the first step, you could check if the user exists:

    If IsNull(DLookup("EDPI", "tbl_User_Info", "EDPI LIKE '*" & Me.txt_EDPI & "*'")) Then
        MsgBox "User not found."
        Exit Sub   ' or other action.
    Else
        SQL = "SELECT tbl_User_Info.EDPI, tbl_User_Info.[User Name]," _
                & "tbl_User_Info.[User Email]," _
                & "tbl_User_Info.Office FROM tbl_User_Info " _
                & "Where EDPI LIKE '*" & Me.txt_EDPI & "*'"
    <snip>