2017-10-13 135 views
0

我有一個表單,我不希望用戶能夠輸入具有相同名稱的聯繫人。在將記錄插入Access之前檢查重複

窗體上有一個保存按鈕。要檢查重複的那個按鈕的代碼部分是: -

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 

如果計數<> 0,則顯示的消息。但是,如果我然後單擊我的取消按鈕,仍然爲重複添加一條記錄。

的取消按鈕的代碼是: -

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

我怎樣才能防止被寫入重複記錄?

回答

2

我會將所有代碼遷移到表單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

+0

這樣做的工作,因爲它不寫入記錄。但是(對於在問題中沒有指定這個,但是保存按鈕實際上是保存並關閉),所以,根據您的建議,顯示該消息,然後表單關閉,我可以阻止這種情況發生嗎? – user1936588

+0

那麼,在關閉它之前你可以檢查'Me.Dirty'(如果記錄已經保存,它應該是'True',否則'False')。但是很難說不知道完整的代碼 –

+0

對不起,意思是說反向(如果記錄已保存,則'Me.Dirty'應該爲'False') –

相關問題