Cancel a New Record Entry With ESCAPE Key

crhodus

Registered User.
Local time
Today, 08:11
Joined
Mar 16, 2001
Messages
257
On my Form I have created code that will launch a message box telling the user they must enter a project name and project manager before they can close the form.

If the user decides not to enter a new record and want to discard the changes they have made, they can press the escape key and any changes they made will go away. My problem is that after they press the excape key and then click on the Close button, they still receive my message saying that a project manager and project name are required. How can I modify my code so that the message box is not executed when this occurs? Is there a way to programatically tell my code that the Escape button was pressed?

Thanks!
Crhodus

Private Sub Close_Project_Click()

On Error GoTo Err_Close_Project_Click

If Me!project_name = "" Or IsNull(Me!project_name) Or IsNull(Me.project_mgr) Then
RecordOK = False
Else
RecordOK = True
End If

If RecordOK = True Then
DoCmd.Close
Else
MsgBox "Project Name and Project Manager is required before saving or changing a record! If you wish to cancel all changes you have made to this record, press the ESCAPE key on your keyboard."
End If

Exit_Close_Project_Click:
Exit Sub

Err_Close_Project_Click:
MsgBox Err.Description
Resume Exit_Close_Project_Click

End Sub
 
You can use the form's .NewRecord method to test whether or not the record in question is or is not new. If the user has hit ESC, then the record would be new.
 
Your code does not belong in the close event. It belongs in the BeforeUpdate event of the Form. The code is ineffective where it is since the record has already been saved by the time the close event executes. So if you don't have any required fields so that Jet will prevent the record save, a bad record will have already been added to the table before your code ever runs.

Move the code to the BeforeUpdate event of the form. Don't forget to cancel the update if an error is found.

Code:
If RecordOK = True Then
Else
    Cancel = True
    If MsgBox("There is data missing from the record.  Press Yes to continue, editing.  Press No to discard all changes.",vbYesNo) = vbYes
        Me.Project_Name.SetFocus
    Else
        Me.Undo
    End If
End If
End If
 

Users who are viewing this thread

Back
Top Bottom