Ms access 访问时登录的代码有问题
我不熟悉VB脚本和任何类型的脚本,但我学习速度很快 在各种辅助工具的帮助下,我一直在开发一个使用脚本的Access数据库 我开发了以下脚本作为登录屏幕的一部分Ms access 访问时登录的代码有问题,ms-access,vba,ms-access-2010,dao,Ms Access,Vba,Ms Access 2010,Dao,我不熟悉VB脚本和任何类型的脚本,但我学习速度很快 在各种辅助工具的帮助下,我一直在开发一个使用脚本的Access数据库 我开发了以下脚本作为登录屏幕的一部分 Private Sub cmdLogin_Click() Dim dbs As Database Dim rstUserPwd As Recordset Dim bFoundMatch As Boolean Set dbs = CurrentDb Set rstUserPwd = dbs.Ope
Private Sub cmdLogin_Click()
Dim dbs As Database
Dim rstUserPwd As Recordset
Dim bFoundMatch As Boolean
Set dbs = CurrentDb
Set rstUserPwd = dbs.OpenRecordset("qryUserPwd")
bFoundMatch = False
If rstUserPwd.RecordCount > 0 Then
rstUserPwd.MoveFirst
' check for matching records
Do While rstUserPwd.EOF = True
If rstUserPwd![UserName] = frmLogin.txtUsername.Value And rstUserPwd![Password] = frmLogin.txtPassword.Value Then
bFoundMatch = True
Exit Do
End If
rstUserPwd.MoveNext
Loop
End If
If bFoundMatch = True Then
'Open the next form here and close this one
DoCmd.Close acForm, Me.Name
DoCmd.OpenForm "frmNavigation"
Else
'
MsgBox "Incorrect Username or Password"
End If
rstUserPwd.Close
End Sub
<> P>即使输入正确的用户名和密码,我也会收到“用户名或密码不正确的消息”。有人能告诉我我做错了什么吗?如果需要的话,我可以添加一个数据库的副本。
仔细考虑这行中的逻辑……/P> rstUserPwd.EOF=True时执行 这对VBA说,“在条件为真时运行此块中的代码”。但是,当您第一次遇到该行时,记录集的当前行是第一行(由于
MoveFirst
)。因此,EOF
为False,并且由于False不等于True,因此Do While
循环中的代码不会运行
我的第一个猜测是你想要这样的东西来控制循环
Do While Not rstUserPwd.EOF
该更改可能会使您的代码按预期工作。但是,该方法比必要的方法复杂得多。您可以使用表达式,而不是打开记录集并遍历行以检查用户名和密码是否匹配。我估计用户名和密码都是字符串值,建议将您的代码更改为以下:
Dim sSql As String
Dim rstUserPwd As DAO.Recordset
Dim bFoundMatch As Boolean
sSql = "Select * from qryUserPwd Where UserName='" & Nz(frmLogin.txtUsername, "") & "' And Password = '" & Nz(frmLogin.txtPassword, "") & "'"
Set rstUserPwd = CurrentDb.OpenRecordset(sSql, dbOpenSnapshot)
If Not (rstUserPwd.BOF And rstUserPwd.EOF) Then
bFoundMatch = True
End If
rstUserPwd.Close: Set rstUserPwd = Nothing
If bFoundMatch = True Then
'Open the next form here and close this one
DoCmd.Close acForm, Me.Name
DoCmd.OpenForm "frmNavigation"
Else
'
MsgBox "Incorrect Username or Password"
End If
您也可以使用此1衬板:
bFoundMatch = DCount("*", "qryUserPwd", "UserName = '" & frmLogin.txtUsername & "' And Password = '" & frmLogin.txtPassword & "'") > 0
@PankajJaju是MS Access中用于表示中当前打开的数据库的方法。有关更多信息,请参阅。