首页 > 解决方案 > 区分 MS Access Form.AfterUpdate 中的更新和插入

问题描述

我在 MS Access 中有一个绑定表单。我希望能够告诉:

  1. 插入新记录时
  2. 更新现有记录时

我认为这些事件非常适合这个,但我刚刚测试Form.AfterUpdate并发现它在更新和插入后触发。Form.AfterInsertForm.AfterUpdate

有什么方法可以从内部分辨更新和插入之间的区别Form_AfterUpdate()吗?或者我应该考虑在 Access 中检测这些事件的另一种方法吗?

Private Sub Form_AfterInsert()
    Debug.Print "after insert"
End Sub

Private Sub Form_AfterUpdate()
    Debug.Print "after update"
End Sub

当我插入一条新记录时,会打印:

after update
after insert

当我更新现有记录时,将打印:

after update

标签: ms-accessvba

解决方案


如果您真的只需要知道这是新的还是现有的记录承诺,请使用BeforeUpdate事件设置一个模块级变量,然后可以在AfterUpdate事件中读取该变量。

Option Compare Database
Option Explicit

Dim booNew As Boolean

Private Sub Form_BeforeUpdate(Cancel As Integer)
    booNew = Me.NewRecord
End Sub

Private Sub Form_AfterUpdate()
    Debug.Print IIf(booNew, "New", "Existing")
End Sub

推荐阅读