在ACCESS VBA中,当进行表格操作时,可能会出现重复输入数据的问题。为避免这种情况的发生,可以通过以下代码示例进行处理:
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim strSQL As String
Set db = CurrentDb
strSQL = "SELECT [FieldName] FROM [TableName] WHERE [FieldName]='" & Me.FieldName & "'"
Set rs = db.OpenRecordset(strSQL)
If rs.RecordCount > 0 Then
MsgBox "该条记录已经存在.", vbExclamation, "重复数据"
Me.Undo
Exit Sub
End If
Dim qd As DAO.QueryDef
Dim db As DAO.Database
Dim strSQL As String
Dim prm As DAO.Parameter
Set db = CurrentDb
Set qd = db.CreateQueryDef("")
strSQL = "SELECT [FieldName] FROM [TableName] WHERE [FieldName]='" & Me.FieldName & "'"
With qd
.SQL = strSQL
For Each prm In .Parameters
prm.Visible = False
Next prm
Set rs = .OpenRecordset(dbOpenSnapshot)
End With
If Not rs.EOF Then
MsgBox "该条记录已经存在.", vbExclamation, "重复数据"
Me.Undo
Exit Sub
End If
rs.Close
Set rs = Nothing
Set qd = Nothing
Set db = Nothing
以上两种方法都可以避免在表格中出现重复数据的情况,并且可以按需选择适用于自己的代码。