我需要确保我的用户不会输入比他们可用的更多的停机时间。为此,我计算了他们可用的时间,并在表单中创建了一个运行总计列,以显示他们当前的停机时间分钟数(他们每次输入一个停机原因和“停机分钟数”)。
现在我正在尝试编写一个 VBA 代码来检查可用时间与运行总停机时间。除了第一个条目之外,它都有效。如果用户输入的数字高于第一次输入时的可用时间,则允许。我认为这是因为我使用了“更新后”,但我尝试了其他事件,但它并没有改变结果。
这是我当前的 VBA 代码:
Private Sub Form_AfterUpdate()
If Me.RunTime.Value < Me.DTSum Then
MsgBox ("You have too much downtime")
DoCmd.RunCommand acCmdDeleteRecord
DoCmd.RunCommand acCmdRecordsGoToPrevious
Else
MsgBox ("Okay")
End If
End Sub
最佳答案
考虑使用BeforeUpdate触发事件(通常是数据验证事件),您在输入后和保存之前警告用户,然后相应地取消该事件。对于新事件,请使用 BeforeInsert触发事件。
通过这种方法,您可以避免删除操作并采取主动立场而不是被动立场。
Private Sub Form_BeforeUpdate(Cancel As Integer)
If Me.RunTime.Value < Me.DTSum Then
MsgBox ("You have too much downtime")
Cancel = True
Me!RunTime.Undo
Else
MsgBox ("Okay")
End If
End Sub
Private Sub Form_BeforeInsert(Cancel As Integer)
If Me.RunTime.Value < Me.DTSum Then
MsgBox ("You have too much downtime")
Cancel = True
Me!RunTime.Undo
Else
MsgBox ("Okay")
End If
End Sub
或者使用函数来实现 DRY-er 解决方案:
Private Sub Form_BeforeUpdate(Cancel As Integer)
Cancel = CheckRunTime
Me!RunTime.Undo
End Sub
Private Sub Form_BeforeInsert(Cancel As Integer)
Cancel = CheckRunTime
Me!RunTime.Undo
End Sub
Function CheckRunTime As Integer
Dim Cancel As Integer
If Me.RunTime.Value < Me.DTSum Then
MsgBox ("You have too much downtime")
Cancel = True
Else
MsgBox ("Okay")
Cancel = False
End If
CheckRunTime = Cancel
End Sub
关于ms-access - 使用先前的条目计算 MS Access vba,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50357023/