无效使用了无效的Microsoft Acess DLookup

时间:2019-06-02 03:40:11

标签: vba ms-access

我想在MS Access中设置用户登录访问权限,这意味着如果用户以管理员身份输入,它将显示不同的形式。

我尝试获取用户级别的字符串,该级别将显示“ Admin”或“ User”之类的内容,但它指示此行无效使用null UserLevel = DLookup("UserSecurity", "tblUser", "[UserLogin] = ' " & Me.txtLoginID.Value & "'")

Private Sub Command1_Click()
Dim UserLevel As String 'get the dlookup value
Dim TempPass As String

If IsNull(Me.txtLoginID) Then
   MsgBox "Please Enter Login ID", vbInformation, "Login Id Required"
   Me.txtLoginID.SetFocus

   ElseIf IsNull(Me.txtLoginPass) Then
       MsgBox "Please Enter Password", vbInformation, "Login password Required"
   Me.txtLoginPass.SetFocus
Else
'process the job
   If (IsNull(DLookup("UserLogin", "tblUser", "UserLogin ='" & Me.txtLoginID.Value & "'"))) Or _
   (IsNull(DLookup("password", "tblUser", "Password = '" & Me.txtLoginPass.Value & "'"))) Then
       MsgBox "Incorrect Password"
   Else
     TempPass = DLookup("password", "tblUser", "UserLogin = '" & Me.txtLoginID.Value & "'")

     UserLevel = DLookup("UserSecurity", "tblUser", "[UserLogin] = ' " & Me.txtLoginID.Value & "'")
     'get the usersecurity whcih indicate he is admin or user

   DoCmd.Close
        If UserLevel = "Admin" Then 'if admin then open employee form else open customer form
           'MsgBox "Login ID and password correct "
           DoCmd.OpenForm "Employee"
       Else
           DoCmd.OpenForm "CustomerForm"
       End If   
   End If
End If
End Sub

我尝试使用nz(),但是它给了我一个空值,该值将我带到客户表单。

2 个答案:

答案 0 :(得分:0)

删除您在条件中插入的空格,所以:

UserLevel = DLookup("UserSecurity", "tblUser", "[UserLogin] = '" & Me.txtLoginID.Value & "'")

答案 1 :(得分:0)

要解释您收到的错误:当您尝试为数据类型为 Null的变量分配Variant值时,会出现这种情况MS documentation

  

变量是一种特殊的数据类型,可以包含任何类型的数据。变量也可以包含特殊的值Empty,Error,Nothing和 Null

此错误出现在您的代码中,因为当域中没有记录满足提供的条件参数时,DLookup函数将返回Null,并且可以归结为以下两行:

Dim UserLevel As String
UserLevel = DLookup("UserSecurity", "tblUser", "[UserLogin] = ' " & Me.txtLoginID.Value & "'")

我怀疑这是由您的条件参数中的前导空格引起的:

"[UserLogin] = ' " & Me.txtLoginID.Value & "'"
                ^--------------------------------- HERE

可能应该是:

"[UserLogin] = '" & Me.txtLoginID.Value & "'"

但是,您可能仍希望解决没有记录符合条件的情况,这可以通过几种方法来实现。

您可以使用Nz函数,然后测试一个空字符串,例如:

UserLevel = Nz(DLookup("UserSecurity", "tblUser", "[UserLogin] = '" & Me.txtLoginID.Value & "'"), "")
Select Case UserLevel
    Case "Admin": DoCmd.OpenForm "Employee"
    Case "User" : DoCmd.OpenForm "CustomerForm"
    Case Else   : MsgBox "Invalid UserSecurity Value"
End Select

或者,您可以将UserLevel变量定义为Variant(因此允许使用Null值),然后使用{{1 }}函数:

Null
IsNull
相关问题