使用组合框的 NotInList 事件。这是一个快速示例:
Private Sub PersonID_NotInList(NewData As String, Response As Integer)
Dim Result As VbMsgBoxResult, NewPersonID As Long, MaxPersonID As Long
On Error GoTo Err_PersonID_NotInList
Response = acDataErrDisplay
Result = MsgBox("'" & NewData & "' is not currently in the database. " & _
"Would you like to add '" & NewData & _
"' to the database?", vbYesNo + vbExclamation, _
"Person Not In List")
If Result = vbYes Then
MaxPersonID = DMax("PersonID", "People")
DoCmd.OpenForm "AddPerson", , , , acFormAdd, acDialog, NewData
NewPersonID = DMax("PersonID", "People")
If NewPersonID > MaxPersonID Then
Me.PersonID = NewPersonID
Me.PersonID.Requery
Response = acDataErrAdded
End If
End If
Exit_PersonID_NotInList:
Exit Sub
Err_PersonID_NotInList:
MsgBox Err.Description
Resume Exit_PersonID_NotInList
End Sub
笔记:
- 使用 DMax 不是获取新添加的 PersonID 的可靠方法,但它使示例更易于阅读。您应该
SELECT @@Identity
改用(谷歌了解更多信息)。
- 我将 NewData 作为 OpenArg 传递给“AddPerson”表单。这将允许您在打开 AddPerson 表单时预先填充此人的姓名。