一般而言,Access(和一般的关系数据库)首先是要防止输入重复数据。如果您只想“警告”,则需要一些自定义代码。因此,假设该表被调用Customers
并且它具有诸如CustomerID
(自动编号、主键)和LastName
(文本)之类的字段。然后表单有一个txtLastName
绑定到该LastName
字段的名为的文本框。在这种情况下,您可以像这样处理文本框的BeforeUpdate
事件:
Option Compare Database
Option Explicit
Const DuplicateWarningTitle = "Duplicate Record"
Const DuplicateValueWarning = "A record already exists with " + _
"the value you have entered. Are you sure you want to continue?"
Function GetSQLLiteral(Value As Variant) As String
Select Case VarType(Value)
Case vbNull
GetSQLLiteral = "Null"
Case vbString
GetSQLLiteral = "'" + Replace(Value, "'", "''") + "'"
Case Else
GetSQLLiteral = CStr(Value)
End Select
End Function
Sub HandleKeyFieldBeforeUpdate(Control As Access.TextBox, Cancel As Integer)
Dim RS As DAO.Recordset
Set RS = CurrentDb.OpenRecordset( _
"SELECT 1 FROM Customers " + _
"WHERE " + Control.ControlSource + " = " + GetSQLLiteral(txtLastName.Value) + _
" AND CustomerID <> " & Me.CustomerID)
If Not RS.EOF Then
Select Case MsgBox(DuplicateValueWarning, vbExclamation + vbYesNo, DuplicateWarningTitle)
Case vbYes
' just proceed
Case vbNo
Cancel = True
Control.Undo ' if desired!
End Select
End If
End Sub
Private Sub txtLastName_BeforeUpdate(Cancel As Integer)
HandleKeyFieldBeforeUpdate txtLastName, Cancel
End Sub
通过将重复检查代码推送到通用辅助例程中,可以轻松地以相同方式处理其他关键字段:
Private Sub txtAddress_BeforeUpdate(Cancel As Integer)
HandleKeyFieldBeforeUpdate txtAddress, Cancel
End Sub