我使用RunCommand acCmdSaveRecord保存记录,并且尝试使用表单的BeforeUpdate事件来验证某些字段,在保存记录之前我不希望保留空白。
我对使用BeforeUpdate有点陌生,所以我不确定我是否正确地使用了它;下面是我的BeforeUpdate代码:
Private Sub Form_BeforeUpdate(Cancel As Integer)
If IsNull(Me.[First Name]) Or IsNull(Me.LastName) Or IsNull(Me.DateOfBirth) Or IsNull(Me.CourseStartDate) Then
MsgBox "Before the enrolment can be saved, you must provide:" & vbCrLf & vbCrLf _
& "- First Name" & vbCrLf _
& "- Last Name" & vbCrLf _
& "- Date of Birth" & vbCrLf _
& "- Start Date" & vbCrLf & vbCrLf _
& "You must also attach a course. This can be done by selecting " _
& "the appropriate course in the Prospectus Search and clicking " _
& "the Use Prospectus Code button." & vbCrLf & vbCrLf _
& "If your course is not currently in the prospectus, you can " _
& "add it first by clicking the Add Course button.", vbOKOnly Or vbInformation
Cancel = True
Else
Me!EnrolmentID = "Enr" & Format(Me!ID, String(12 - Len("Enr"), "0"))
End If
End Sub因此,这基本上是测试某些字段是否为空白,如果这些字段为空白,则显示一个消息框,显示哪些字段需要数据,然后更新被取消。否则,它将分配一个自定义主键,并允许更新记录。
当取消更新时,它会抛出一个错误,尽管它声明“没有当前记录”,并高亮显示RunCommand acCmdSaveRecord代码行。
我需要做些什么来避免这个错误?我也尝试过Me.Dirty = False,但仍然得到相同的错误。
@Johnny:
下面是一个简单的测试,我尝试了你给我的答案:
Public ShouldRun As BooleanPrivate Sub Command7_Click()
If ShouldRun = True Then
MsgBox ShouldRun
RunCommand acCmdSaveRecord
End If
End SubPrivate Sub Form_BeforeUpdate(Cancel As Integer)
If IsNull(Me.Field1) Or IsNull(Me.Field2) Then
MsgBox "This is the true"
ShouldRun = False
Else
MsgBox "This is the false"
ShouldRun = True
End If
End Sub基本上,无论字段是否为空白,MsgBox函数都不会触发,而且记录将被保存。我尝试将此作为测试,因为我的实际代码中的MsgBox也没有在BeforeUpdate事件中触发。但不明白为什么..。如果用户将其中一个字段留为空白,这将触发BeforeUpdate事件中if语句的真实部分,对吗?
我唯一能想到的是,BeforeUpdate事件不是由RunCommand acCmdSaveRecord触发的,尽管有MSDN俗语。
“如果然后移动到另一个记录或保存记录,表单的BeforeUpdate事件就会发生。”
不知道命令是什么..。VBA运行RunCommand acCmdSaveRecord,然后运行BeforeUpdate事件吗?如果是这样的话,那么ShouldRun变量在第一步(RunCommand acCmdSaveRecord)就不会有任何赋值,因为它只在第二步(BeforeUpdate)得到赋值。
发布于 2013-11-15 19:02:38
我会设置这样的全局变量:
Global ShouldRun as Bool您可以将其抛到代码页的最上面,在上面显式地声明选项。然后,在上面提供的If/ Then / the语句中,替换行:
Cancel = True使用
ShouldRun = False在其他部分中添加行
ShouldRun = True最后,命令按钮的OnClick事件应该更像这样:
If ShouldRun = True then
RunCommand acCmdSaveRecord
End If这样做,它甚至永远不会试图保存记录,如果它不应该。
发布于 2017-02-06 23:59:19
我知道很晚了,但是你试过用DoCmd.RunCommand acCmdSaveRecord代替吗?
因为对我来说,这是在触发Before Update事件,而RunCommand acCmdSaveRecord却不是!
但是在取消事件后,您可能会得到一个执行错误'2759',因为记录不能保存了。这样你就可以这样处理了:
Private Sub Command7_Click()
On Error GoTo Command7_Click_Error
DoCmd.RunCommand acCmdSaveRecord
Command7_Click_Exit:
Exit Sub
Command7_Click_Error:
If Err.Number=2759 Then
'ignore the error
Else
MsgBox Err.Description
End If
Resume Exit_Here
End Sub如果您使用的是Me.Dirty = False,则可以处理错误“2101”。
希望它能帮上忙
https://stackoverflow.com/questions/20006896
复制相似问题