用于登录用户名和密码的DLookup代码

时间:2013-05-19 15:44:39

标签: database vba ms-access ms-access-2007 access-vba

我想创建一个登录表单,但我不知道如何在我的登录按钮中使用DLookup获取或确认我在用户名和密码文本框中输入的内容是在我的表中。

这是我目前的代码:

Dim u As Variant
Dim p As Variant
Dim inu As String
Dim inp As String

u = DLookup("cusername", "tbl_users", "inuser.Value")
p = DLookup("cpassword", "tbl_users", "inpass.Value")

inu = inuser.Value
inp = inpass.Value

If inu = u And inp = p Then
DoCmd.OpenForm "frm_userlog"
MsgBox "Welcome " & tuser & "!"

ElseIf IsNull(Me.inuser.Value) And inpass.Value = 1 Then
MsgBox "You must input a username"

ElseIf IsNull(Me.inpass.Value) And inuser.Value = 1 Then
MsgBox "you must input a password"

ElseIf IsNull(Me.inuser.Value) And IsNull(Me.inpass.Value) Then
MsgBox "you must input a username and password"

Else
MsgBox "The username or password you entered is invalid"
    End If
End Sub

2 个答案:

答案 0 :(得分:3)

第三个DLookup参数标准是一个可选的字符串表达式,类似于SQL表达式中的“WHERE子句,没有单词WHERE”

在你看来,你似乎试图给它一个名为inuser的控件的值。但是,您实际上是在传递包含文本“inuser.Value”的字符串。

DLookup("cusername", "tbl_users", "inuser.Value")

但即使你删除引号,这也不会给你你想要的东西。

如果您想从cusername查找某个字段(可能tbl_users)与user_id匹配的inuser.Value ...

DLookup("cusername", "tbl_users", "user_id = " & inuser.Value)

如果该字段user_id是文本而非数字数据类型,请在条件字符串中构建引号...

DLookup("cusername", "tbl_users", "user_id = '" & inuser.Value & "'")

我认为你和DLookup("cpassword", ...)有同样类型的问题,所以如果我得到第一个问题,请在那里进行类似的更改。

您可以在Description of DLookup() usage, examples, and troubleshooting in Access 2000找到有关DLookup的更多信息。虽然这是一篇旧文章,但一切仍然适用于最近的Access版本AFAICT。

答案 1 :(得分:0)

根据我的评论,我用这个:

Private Sub cmdlogin_Click()
    If IsNull(Me.cb_user) Then
        MsgBox "You didn't select a user", vbCritical, "Error"
        Me.cb_user.SetFocus
        Exit Sub
    Else
        If IsNull(Me.txtpass) Then
            MsgBox "You didn't enter a password", vbCritical, "Error"
            Me.txtpass.SetFocus
            Exit Sub
        Else
            If encrypt(Me.txtpass.Value) = DLookup("password", "users", "user_id = " & Me.cb_user.Value) Then
                DoCmd.OpenForm ("home")
                Me.Visible = False
            Else
                MsgBox "Incorrect password. Please try again", vbCritical, "Incorrect password"
                Me.txtpass = Null
                Me.txtpass.SetFocus
            End If
        End If
    End If
End Sub

其中cb_user是用户名的组合框。

Encrypt是我放在模块中的基本ROT 13加密:

Public Function encrypt(strInput As String)
    Dim n As Integer, i As Integer
    n = 13
    For i = 1 To Len(strInput)
        Mid(strInput, i, 1) = Chr(Asc(Mid(strInput, i, 1)) + n)
    Next i
    encrypt = strInput
End Function

如果没有必要,请省略密码查找的encrpyt换行,以便:

If encrypt(Me.txtpass.Value) = DLookup("password", "users", "user_id = " & Me.cb_user.Value) Then

变为

If Me.txtpass.Value = DLookup("password", "users", "user_id = " & Me.cb_user.Value) Then