【发布时间】:2016-04-14 06:33:47
【问题描述】:
我试图通过在更新前检查条目来避免 Access 内置 msgbox 输入重复记录。代码有效,但有一个大问题——你不能再编辑这些记录了。任何方式来完成这两个 - 允许编辑并避免访问 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
【问题讨论】:
-
我明白了。您的
ID_Field是主键吗?通常,PK 应该对用户不可见,并且绝对不能由用户编辑。正如您所发现的,它会产生问题。如果是PK,有什么理由让用户可以编辑吗?如果没有,您可以使用 PK 来识别当前记录并将其从搜索中排除。 -
@Andre,不。 ID_Field 不是主键。并且 PK 对用户是不可见的。但是 ID 和 ID_Field(具有完全不同的名称 - 我搞砸了)都将索引设置为无重复项。但是,将 Id_Field 更改为 Indexed No 不会改变任何内容。
-
如何从搜索中排除记录,但如果输入具有相同 Id_Field 的新记录,则保持代码运行?