我试图通过检查更新事件之前的条目来避免Access内置的msgbox有关输入重复记录的信息。代码有效,但有一个大问题 - 您无法再编辑这些记录。任何两种方法都可以实现 - 允许编辑并避免使用Access msgbox?
Private Sub Form_BeforeUpdate(Cancel As Integer)
Dim rs As Recordset
Set rs = CurrentDb.OpenRecordset("MyTable", dbOpenDynaset)
If Data_Changed Then 'Variable of Boolean that is set to True in Dirty event
If Not IsNull(ID_Field) Then
If MsgBox("You have done changes. you wish to save? ?" & vbCrLf & vBCrLf & "Click Yes for saving changes or NO for Undoing changes ! " & _
, vbQuestion + vbOKCancel + vbDefaultButton1) = vbOK Then
rs.FindFirst "ID = " & Me.ID_Field
If Not rs.NoMatch Then
Cancel = True
MsgBox "Error. You cannot add another record with same ID!", vbCritical
DoCmd.RunCommand acCmdUndo
Exit Sub
End If
Else
DoCmd.RunCommand acCmdUndo
End If
Else
MsgBox "Error. you cannot save record with blank ID !", vbCritical
DoCmd.SetWarnings False
If Me.Dirty Then Me.Undo
DoCmd.SetWarnings True
Exit Sub
End If
Me.ID_Field.Locked = True
Me.Other_Field.Locked = True
End If
End Sub
答案 0 :(得分:0)
A"快照"获取当前状态的记录,例如检查。它们是只读的。
要打开记录集读/写,请使用dbOpenDynaset
答案 1 :(得分:0)
要阻止内置消息,最好使用Form.OnError
事件
请参阅:https://msdn.microsoft.com/en-us/library/office/ff836345.aspx
E.g。像这样:
Private Sub Form_Error(DataErr As Integer, Response As Integer)
' Error 3022 = "Cannot add a duplicate value because of a key constraint..."
If DataErr = 3022 Then
MsgBox "Your duplicate warning", vbExclamation
' Remove duplicate ID and set focus into ID control
Me!ID_Field = Null
Me!ID_Field.SetFocus
' Dont't show default error message
Response = acDataErrContinue
Else
' Other errors: show default error message
Response = acDataErrDisplay
End If
End Sub