Microsoft Access VBA:MsgBox弹出两次。知道为什么吗?

时间:2018-05-01 23:43:59

标签: database vba access programmers-notepad

我正在为培训师和成员设计一个登录表单。如果会员登录,则会将其重定向到“frm2_Member Class Registration”表单,如果培训师登录,则会将其重定向到“frm3_Main Menu”表单。但是,当单击表单上的登录按钮(Command9_Click)时,错误会正确弹出,但它们会显示两次。一旦教练登录msg框,说明登录成功。然后另一个msgbox立刻弹出“登录失败”,但是所有数据都正确显示,它只是msgbox,它们似乎无法正常工作。

有人可以帮帮我,真的很感激,谢谢。 VBA代码如下。

Private Sub Command9_Click()

If (DCount("MemberFirstName", "tbl1_Members", "MemberEmail = [txtEmail] And MemberPassword = [txtPassword] ")) > 0 Then
    MsgBox ("Welcome")
    DoCmd.Close acForm, "frm1_Member & Trainer Login"
    DoCmd.OpenForm "frm2_Member Class Registration"
Else
    MsgBox ("Login Failed")
    End If

If (DCount("TrainerFirstName", "tbl4_Trainers", "TrainerEmail = [txtEmail] And TrainerPassword = [txtPassword] ")) > 0 Then
    MsgBox ("Welcome")
    DoCmd.Close acForm, "frm1_Member & Trainer Login"
    DoCmd.OpenForm "frm3_Main Menu"
Else
    MsgBox ("Login Failed")

    End If
End Sub

2 个答案:

答案 0 :(得分:0)

Private Sub Command9_Click()

    Dim isTrainer As Boolean, isMember As Boolean

    isTrainer = DCount("TrainerFirstName", "tbl4_Trainers", _
                 "TrainerEmail = [txtEmail] And TrainerPassword = [txtPassword] ") > 0
    isMember = DCount("MemberFirstName", "tbl1_Members", _
                 "MemberEmail = [txtEmail] And MemberPassword = [txtPassword] ") > 0

    If isTrainer Or isMember Then
        MsgBox ("Welcome")
        DoCmd.Close acForm, "frm1_Member & Trainer Login"
        If isTrainer Then
            DoCmd.OpenForm "frm3_Main Menu"
        Else
            DoCmd.OpenForm "frm2_Member Class Registration"
        End If

    Else
        MsgBox ("Login Failed")
    End If

End Sub

答案 1 :(得分:0)

您的代码在第一个结束后继续运行。最好使用ElseIf将这两个单独的If语句组合在一起,从而只在两个If语句都不真实时生成失败的消息。

Private Sub Command9_Click()

If (DCount("MemberFirstName", "tbl1_Members", "MemberEmail = [txtEmail] And MemberPassword = [txtPassword] ")) > 0 Then
    MsgBox ("Welcome")
    DoCmd.Close acForm, "frm1_Member & Trainer Login"
    DoCmd.OpenForm "frm2_Member Class Registration"
ElseIf (DCount("TrainerFirstName", "tbl4_Trainers", "TrainerEmail = [txtEmail] And TrainerPassword = [txtPassword] ")) > 0 Then
    MsgBox ("Welcome")
    DoCmd.Close acForm, "frm1_Member & Trainer Login"
    DoCmd.OpenForm "frm3_Main Menu"
Else
    MsgBox ("Login Failed")
End If

End Sub