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

Creating Login form on Access using VBA

我正在尝试为我的 Access 数据库创建一个登录名,但我无法让它工作。这是我的代码(请记住 "Preparer" 是 table 保存用户名和密码信息的名称:

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

前两部分有效,所以如果登录名或密码为空,它会给出正确的错误消息,但每当我输入登录名和密码时,即使它们是正确的(即它们存在于准备程序中 table ) 它给了我 "Incorrect Login or Password"

我假设问题出在此处的代码中:

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 语句吗?

您没有比较正确的信息。您应该检查为 Username 输入的 Password 是否存在于 table 中。所以你的代码应该改为只有一个 DLookup,as.

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 与实际输入的密码进行比较。如果它们相同,则您授予他们访问权限。否则一条消息。

希望对您有所帮助!