Access 2007,VBA:检查重复项,具有空字段

时间:2013-09-04 14:25:34

标签: vba ms-access-2007

我想检查一个字段是否与我的 EMP 表中有重复项。一切都有效,除非我需要在字段中没有又名 null 例外时创建例外。

Private Sub cmdDuplicates2_Click() 
Dim Name As String
Dim dbs As DAO.Database
Dim rst As DAO.Recordset

Set dbs = CurrentDb
Set rst = dbs.OpenRecordset("EMP", dbOpenDynaset)
Name = Me.Personnel
rst.FindFirst "[Personnel] = '" & Name & "'"
If rst.NoMatch Then
        MsgBox "No duplicates found"
  Else
        MsgBox "Name is already in Database"
End If

End Sub

编辑:现在就这样做。如果它为null则表示“请输入名称”。但它也说“没有重复发现。”我希望它只是说“请输入一个名字。” 如果字段为空

Private Sub cmdDuplicates2_Click()
Dim Name As String
Dim dbs As DAO.Database
Dim rst As DAO.Recordset

Set dbs = CurrentDb
Set rst = dbs.OpenRecordset("EMP", dbOpenDynaset)

If IsNull(Me.Personnel) Then MsgBox "Please enter a name." Else: Name = Me.Personnel

rst.FindFirst "[Personnel] = '" & Name & "'"
If rst.NoMatch Then
        MsgBox "No duplicates found"
  Else
        MsgBox "Name is already in Database"
End If

End Sub

2 个答案:

答案 0 :(得分:1)

做这样的事情:

If IsNull(Me.Personnel) Then Name = "Empty" Else Name = Me.Personnel

答案 1 :(得分:0)

试试这个。在这个版本中,我实际上是在计算每个Personnel值的记录数:

Private Sub cmdDuplicates2_Click() 
Dim rst As DAO.Recordset
Dim Qry as string
Qry="Select count(*) from EMP where [Personnel]='" & Me.Personnel & "'"

Set rst = Currentdb.OpenRecordset(Qry, dbOpenDynaset)

If rst.fields(0)>1 then
        MsgBox "Name is already in Database"
  Else
        MsgBox "No duplicates found"
End If

End Sub

修改

抱歉,我的第一直觉是按照我的方式重构您的代码。尝试将此添加到您的过程的开头:

If Me.Personnel="" then 
    msgbox "Please enter a name."
    exit sub
end if