Ms access 使用VBA在Access上创建登录表单

Ms access 使用VBA在Access上创建登录表单,ms-access,vba,ms-access-2010,Ms Access,Vba,Ms Access 2010,我正在尝试为Access db创建登录名,但无法使其正常工作。这是我的代码(请记住,“Preparer”是保存用户名和密码信息的表的名称: Private Sub Command1_Click() If IsNull(Me.txtLogin) Then MsgBox "Please Enter Login", vbInformation, "Need ID" Me.txtLogin.SetFocus ElseIf IsNull(Me.txtP

我正在尝试为Access db创建登录名,但无法使其正常工作。这是我的代码(请记住,“Preparer”是保存用户名和密码信息的表的名称:

Private Sub Command1_Click()

    If IsNull(Me.txtLogin) Then

        MsgBox "Please Enter Login", vbInformation, "Need ID"
        Me.txtLogin.SetFocus

    ElseIf IsNull(Me.txtPassword) Then

        MsgBox "Please Enter Password",vbInformation, "Need Password"    
        Me.txtPassword.SetFocus

    Else

        If ((IsNull(DLookup("Login","Preparer","Login='& Me.txtLogin.Value &'"))) or _
        (IsNull(DLookup("Password","Preparer","Password='& Me.txtPassword.Value &'")))) Then

            MsgBox "Incorrect Login or Password"

        Else

            DoCmd.Close    
            MsgBox "Success"

            DoCmd.OpenForm "Master"

        End If

    End If

End Sub
前两部分起作用,因此,如果登录名或密码为空,则会给出正确的错误消息,但每当我输入登录名和密码时,即使它们是正确的(即它们存在于preparer表中),也会给出“不正确的登录名或密码”

我假设问题在这里的代码中:

If ((IsNull(DLookup("Login","Preparer","Login='& Me.txtLogin.Value &'"))) or _
    (IsNull(DLookup("Password","Preparer","Password='& Me.txtPassword.Value &'")))) Then

    MsgBox "Incorrect Login or Password"

有人明白我为什么不能找到最下面的else语句吗?

您没有比较正确的信息。您应该检查为该
用户名输入的
密码是否存在于表中。因此,您的代码应该更改为仅一个DLookup,如下所示

Private Sub Command1_Click()
    If IsNull(Me.txtLogin) Then
        MsgBox "Please Enter Login", vbInformation, "Need ID"
        Me.txtLogin.SetFocus
    ElseIf IsNull(Me.txtPassword) Then
        MsgBox "Please Enter Password",vbInformation, "Need Password"    
        Me.txtPassword.SetFocus
    Else
        If Nz(DLookup("Password", "Preparer", "Login = '" & Me.txtLogin.Value & "'")), "GarbageEntry") = Me.txtPassword Then
            DoCmd.Close    
            MsgBox "Success"
            DoCmd.OpenForm "Master"
        Else
            MsgBox "Incorrect Login or Password"
        End If
    End If
End Sub
在上面的代码中,首先使用DLookup检索用户名的密码。如果用户名匹配,将返回密码,否则将返回默认值“GarbageEntry。因此正确的密码(或)GarbageEntry将与实际输入的密码进行比较。如果它们相同,则您授予它们访问权限。否则,将显示一条消息


希望这能有所帮助!

即使这样做有效,您也不会实际检查密码和登录值。您正在检查登录名是否存在以及密码是否存在,但它们不需要属于同一用户。请尝试调试。打印“DLookup”部分isnull语句,并找出返回的内容。我猜其中至少有一个语句始终返回Null。不客气。如果您觉得这很有用,请将其标记为已回答(绿色勾号)和/或投票赞成!谢谢。)