我正在为癌症研究目的建立一个数据库。我创建了一个名为" inputPI_form"的表单。 PI代表"首席研究员"又名研究员。 tblPI只是一个包含名字和姓氏的表。
这是我的表格:
点击"保存"按钮,你运行底部代码。
我使用两个名称在tblPI中创建了一个复合键,以防止任何重复记录。此代码可防止重复记录,但没有显示MsgBox:
'Add new PI's name and verify uniqueness with composite key'
Private Sub newPI_Button_Click()
'Declare duplication error number'
Const ERR_DUPLICATE_VALUE = 3022
On Error GoTo Err_Handler
'Declare database object and string variables'
Dim dbs As Database
Dim firstName As String
Dim lastName As String
'Capture firstName and lastName from inputPI_form as strings'
firstName = Forms("inputPI_form")!firstName.Value
lastName = Forms("inputPI_form")!lastName.Value
'Set the dbs object'
Set dbs = CurrentDb
'Excute SQL code to create new record in tblPI by passing firstName and lastName values'
dbs.Execute "INSERT INTO tblPI (lastName, FirstName) VALUES " & _
"('" & lastName & "','" & firstName & "');"
'Update the PI selection combobox on inputProtocolForm'
Forms("inputProtocolForm")!selectionPI.Requery
dbs.Close
DoCmd.Close acForm, "inputPI_form"
Err_Handler:
If Err.Number = ERR_DUPLICATE_VALUE Then
MsgBox ("This PI's name is already taken. Please select another one.")
End If
End Sub
我不熟悉在VBA中捕获错误。我犯了一个明显的错误吗?我非常感谢社区的反馈。谢谢!
答案 0 :(得分:1)
尝试简化错误处理程序。取出If语句并替换它是一个简单的Msgbox Err.number& Err.description。你得到了预期的结果吗?