Access 2013防止保存时重复记录

时间:2017-08-23 23:36:32

标签: access-vba concatenation ms-access-2013

所以我有一个像New Visitor Form

这样的参赛表格

如果访问者已经在表中,我试图阻止它保存记录。这是我尝试过的,但没有太多运气。它将匹配不同的记录。我对任何建议持开放态度。

Dim FName As String
Dim LName As String
Dim CName As String
Dim stLinkCriteriaFN As String
Dim stLinkCriteriaLN As String
Dim stLinkCriteriaCN As String

If IsNull(Me.tbFirstName.Value) Or IsNull(Me.tbLastName.Value) Or IsNull(Me.cbCompany.Value) Then
MsgBox "Not all information has been entered, visitor was not added.", vbOKOnly, "Data Entry Error"
Else

LName = Me.tbLastName.Value
FName = Me.tbFirstName.Value
CName = Me.cbCompany.Value



stLinkCriteriaLN = "[LastName] = " & "'" & LName & "'"
stLinkCriteriaFN = "[FirstName] = " & "'" & FName & "'"
stLinkCriteriaCN = "[Company] = " & "'" & CName & "'"


 If Me.tbLastName = DLookup("[LastName]", "VisitorInfo", stLinkCriteriaLN) And Me.tbFirstName = DLookup("[FirstName]", "VisitorInfo", stLinkCriteriaFN) And Me.cbCompany = DLookup("[Company]", "VisitorInfo", stLinkCriteriaCN) Then
    MsgBox "Visitor Already Added", vbOKOnly
 Else
    Dim f As Form
    DoCmd.RunCommand acCmdSaveRecord
    For Each f In Access.Forms
    f.Requery
    Next
    DoCmd.RunCommand acCmdClose
 End If
End If

1 个答案:

答案 0 :(得分:0)

假设您在VisitorInfo表中有某种主键,您可以组合这些条件并检查DLookup结果,如下所示:

If IsNull(DLookup("[VisitorID]", "VisitorInfo", "[LastName] = '" & LName & "' AND [FirstName] = '" & FName & "' AND [Company] = '" & CName & "'") Then
    Dim f As Form
    DoCmd.RunCommand acCmdSaveRecord
    For Each f In Access.Forms
        f.Requery
    Next
    DoCmd.RunCommand acCmdClose
Else
    MsgBox "Visitor Already Added", vbOKOnly
End If