在将记录插入Access之前检查重复

时间:2017-10-13 10:05:15

标签: vba ms-access access-vba

我有一个表单,我不希望用户能够输入同名的联系人。

表单有一个保存按钮。要检查重复项,该按钮代码的一部分是: -

If Me.DataEntry = False Then
Else
    'Check for duplicate contact
    If DCount("[ContactID]", "tblContactsNew", "[first_name] = " & "'" & Me.FIRST_NAME & "'" & "And [Surname] = " & "'" & Me.SURNAME & "'") <> 0 Then
        MsgBox "A contact with these details already exists:-" & vbCrLf, vbOKOnly + vbExclamation
        End
    End If
End If

之前: -

DoCmd.RunCommand acCmdSaveRecord

如果计数&lt;&gt; 0,显示消息。但是,如果我单击“取消”按钮,则仍会为复制添加一条记录。

取消按钮的代码是: -

If Me.Dirty Then
Me.Undo
End If
DoCmd.Close acForm, Me.Name

如何防止写入重复记录?

1 个答案:

答案 0 :(得分:3)

我将所有代码迁移到表单Form_BeforeUpdate事件。

在保存按钮代码中,您唯一需要的是DoCmd.RunCommand acCmdSaveRecord

然后,在Form_BeforeUpdate事件中:

If Me.DataEntry = False Then
    Cancel = True 'Don't save the form I guess
Else
    'Check for duplicate contact
    If DCount("[ContactID]", "tblContactsNew", "[first_name] = " & "'" & Me.FIRST_NAME & "'" & "And [Surname] = " & "'" & Me.SURNAME & "'") <> 0 Then
        MsgBox "A contact with these details already exists:-" & vbCrLf, vbOKOnly + vbExclamation
        Cancel = True 'Cancel the update
        End Sub
    End If
End If

您可以在表单中添加全局,在取消按钮中将其设置为True,如果是True则不保存

相关问题