Access数据库中的唯一成员编号

时间:2016-07-25 12:37:24

标签: ms-access access-vba ms-access-2010

我在Access 2010中有一个数据库,其中第一个字段是唯一的成员编号。该字段设置为索引,没有重复。如果在输入表单上输入了重复项,则不会显示任何错误消息,并且在输入唯一编号之前不会执行任何其他操作。我需要的代码可以捕获数字字段失去焦点的错误,以便消息框告诉用户问题,然后将焦点设置回数字字段或让用户取消所有输入。 这就是我所拥有的,它会导致数据类型错误

Private Sub Grumpy_No_BeforeUpdate(Cancel As Integer)  
    If DLookup(Str("[Grumpy_No]"), "Grumpy", Str("[Grumpy_No]") = Me!Str(Grumpy_No)) Then   
    MsgBox "Number has already been entered in the database."   
    Cancel = True  
    Me!Grumpy_No.Undo   
    End If   
End Sub

非常感谢任何关于我出错的线索

1 个答案:

答案 0 :(得分:2)

在我看来,您正朝着正确的方向前进,但是您需要修复DLookup表达式。它的第三个参数必须是单个字符串。我不明白为什么Str()有用 - 只需构建一个字符串。实际上我会使用DCount而不是DLookup,但是同样的问题仍然适用。

Private Sub Grumpy_No_BeforeUpdate(Cancel As Integer)  
    If DCount("[Grumpy_No]", "Grumpy", "[Grumpy_No] = " & Me!Grumpy_No.Value) > 0 Then   
        MsgBox "Number has already been entered in the database."   
        Cancel = True  
        'Me!Grumpy_No.Undo '<- consider allowing the user to see the value which failed
    End If   
End Sub

注意,如果您可以使Grumpy_No成为自动编号主键,Access将自动提供唯一值,因此您不需要自己的代码来检查这些值。