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

Car*_*arl 1 ms-access vba ms-access-2010

我正在尝试为我的 Access 数据库创建登录名,但无法让它工作。这是我的代码(请记住“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
Run Code Online (Sandbox Code Playgroud)

前两个部分有效,因此如果登录名或密码为空,它会给出正确的错误消息,但是每当我输入登录名和密码时,即使它们是正确的(即它们存在于准备器表中),它也会给我“错误的登录名或密码”密码”

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

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

    MsgBox "Incorrect Login or Password"
Run Code Online (Sandbox Code Playgroud)

有人明白为什么我无法深入了解 else 语句吗?

Pau*_*cis 5

您没有比较正确的信息。您应该检查表中是否存在Password输入的内容。Username因此,您的代码应该更改为只有一个 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
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,您首先使用 DLookup 检索用户名的密码。如果用户名匹配,将返回密码,否则返回默认值“ GarbageEntry ”。因此,将正确的密码(或)GarbageEntry 与输入的实际密码进行比较。如果它们相同,那么您就授予他们访问权限。还是留言吧

希望这可以帮助 !