1

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

我试图获取userlevelwhich 是一个字符串,并会显示类似"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(),但它给了我一个空值,将我带到客户表单。

4

2 回答 2

0

解释您收到的错误:根据MS 文档Null,当您尝试将值分配给数据类型不是a的变量时会出现这种情况:Variant

Variant 是一种特殊的数据类型,可以包含任何类型的数据 [...] Variant 还可以包含特殊值 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变量定义为 a Variant(因此允许一个Null值),并测试此类变量是否正在Null使用该IsNull函数:

Dim UserLevel As Variant ' Or just "Dim UserLevel" since Variant is the default type
UserLevel = DLookup("UserSecurity", "tblUser", "[UserLogin] = '" & Me.txtLoginID.Value & "'")
If IsNull(UserLevel) Then
    MsgBox "Invalid UserSecurity Value"
ElseIf UserLevel = "Admin" Then
    DoCmd.OpenForm "Employee"
Else 
    DoCmd.OpenForm "CustomerForm"
End If
于 2019-06-02T12:10:58.867 回答
0

删除您在条件中插入的空间,因此:

UserLevel = DLookup("UserSecurity", "tblUser", "[UserLogin] = '" & Me.txtLoginID.Value & "'")
于 2019-06-02T08:26:58.450 回答