Access数据库上存储密码的Excel VBA LogIn表单

时间:2016-06-12 16:01:29

标签: excel vba ms-access access userform

我想用Access数据库中存储的密码验证我的Userfrom密码,当我在下面运行我的代码时,我没有收到任何错误,但是,当我尝试输错密码时,它说“正确的密码。 ”。你能帮我解决这个问题吗?

Public cn As ADODB.Connection
Public rs As ADODB.Recordset

Sub LogIn()

Dim cn As Object
Dim rs As Object
Dim strSql As String
Dim DBPath As String
Dim userId As String

If Frm_UserPW.TxtBox_Password.Text = Empty Then
    MsgBox "Please type your password."
Else
    DBPath = Range("I2").Value
    Set cn = New ADODB.Connection

        cn.Provider = "Microsoft.ACE.OLEDB.12.0"
        cn.Properties("Data Source") = DBPath
        cn.Properties("Jet OLEDB:Database Password") = "db12345"
        cn.Open

        userId = Range("C3").Value

        'Open a recordset
        Set rs = New ADODB.Recordset
            'rs.Open "Inbox", cn, adOpenKeyset, adLockOptimistic, adCmdTable

            strSql = "SELECT * FROM ApplePassword WHERE AgentName=""" & userId & """ AND Passwords =""" & Frm_UserPW.TxtBox_Password.Text & """"
        Set rs = cn.Execute(strSql)

            MsgBox "Correct Passsword."
            Frm_UserPW.Hide
            Main.Show

            'clear memory
            rs.Close
        Set rs = Nothing
        cn.Close
    Set cn = Nothing

End If

End Sub

2 个答案:

答案 0 :(得分:0)

考虑在记录集recordCount上使用条件逻辑:

If rs.RecordCount > 0 Then
    MsgBox "Correct Passsword.", vbInformation
    Frm_UserPW.Hide 
    Main.Show
Else
    MsgBox "Incorrect Password.", vbCritical

    rs.Close: Set rs = Nothing 
    cn.Close: Set cn = Nothing
    Exit Sub
End If

答案 1 :(得分:0)

您的密码检查结果基于运行查询的能力是否成功,而不是查询结果。

您正在使用Set rs = cn.Execute(strSql)类似If语句,即如果它执行命令而没有错误则密码必须匹配。

你需要的是if语句然后根据查询结果工作,我建议: -

strSql = "SELECT count(*) FROM ApplePassword WHERE AgentName=""" & userId & """ AND Passwords =""" & Frm_UserPW.TxtBox_Password.Text & """"
Set rs = cn.Execute(strSql)
    if rs(0) > 0 then 'I.e. there was at least one match!
        MsgBox "Correct Password."
        Frm_UserPW.Hide
        Main.Show
    End If

    'clear memory
    rs.Close
Set rs = Nothing