【发布时间】:2021-10-05 09:09:38
【问题描述】:
我创建了一个表单,我可以在其中输入教师信息,如果缺少某些字段,我会显示错误消息。
然而,只要我点击保存,表单就会像我想要的那样保存条目,但也会立即生成我创建的错误消息,即使我没有机会在字段中输入任何新内容。我的代码是这样的……
' Click event for Save button
Private Sub cmdSave_Click()
' ToDo fix the labels in this function so they match the function name. Just cosmetic.
On Error GoTo Add_Faculty_Click_Err
On Error Resume Next
DoCmd.GoToRecord , "", acNewRec
' Error handling for FirstName
Dim OKToSave As Boolean
OKToSave = True
If Not SomethingIn(Me.FirstName) Then ' Null
Beep
MsgBox "A first name is required", vbOKOnly, "Missing Information"
OKToSave = False
End If
If Not SomethingIn(Me.Combo17) Then
Beep
MsgBox "A department is required", vbOKOnly, "Missing Information"
OKToSave = False
End If
If Not SomethingIn(Me.LastName) Then
Beep
MsgBox "A last name is required", vbOKOnly, "Missing Information"
OKToSave = False
End If
If Not SomethingIn(Me.Text19) Then
Beep
MsgBox "A user name is required", vbOKOnly, "Missing Information"
OKToSave = False
Else
Dim myUserName As String
myUserName = "UserName = " + Chr(34) + Me.Text19 + Chr(34)
If DLookup("UserName", "tFaculty", myUserName) <> Null Then
MsgBox "User name already on file", vbOKOnly, "User name already on file."
OKToSave = False
End If
End If
If OKToSave Then
' If we get this far, all data is valid and it's time to save
DoCmd.RunCommand acCmdSaveRecord
' ToDo refresh and synch combo box
Me.cbFacultyID = Me.FacultyID
' ToDo hide save and cancel buttons
Me.cmdSave.Visible = False
Me.cmdCancel.Visible = False
' ToDo show Add and delete buttons
Me.[Add Faculty].Visible = True
Me.Delete.Visible = True
End If
Add_Faculty_Click_Exit:
Exit Sub
Add_Faculty_Click_Err:
Resume Add_Faculty_Click_Exit
End Sub
我以为我用 OKToSave 部分解决了问题,但它不起作用。这是什么原因造成的?
【问题讨论】:
-
为避免出现多个弹出窗口,您可以使用
ElseIf。这样,它只会返回它找到的第一个缺失的信息。 -
@HackSlash 我会用 ElseIf 替换什么?
-
对于所有互斥的条件,请将
End If, If替换为ElseIf。这告诉编译器,如果一个条件为真,则无需查看链中的任何其他条件。见这里:tutorialspoint.com/vba/vba_if_elseif_else_statement.htm
标签: sql vba ms-access debugging