DLookup Function - returning wrong value - ms-access

I am trying to run the following code, but I'm getting a Run-time error '2471' on DLookUp. "The expression you entered as a query parameter produced this error: 'dkim'".
DLookUp returns a value, but it's returning the wrong value. This code is supposed to compare Text7 to a dlookup 'Password' value. Am I missing something?
Private Sub btn_enter_Click()
If Me.Text7.Value = DLookup("Password", "tbl_ref_users", _
"[ID]=" & Me.Text5.Value) Then
ID = Me.Text5.Value
'Close logon form and open splash screen
DoCmd.Close acForm, "form_Login", acSaveNo
DoCmd.OpenForm "form_Menu"
Else
MsgBox "Password Invalid. Please Try Again", vbOKOnly, _
"Invalid Entry!"
Me.Text7.SetFocus
End If
'If User Enters incorrect password 3 times database will shutdown
intLogonAttempts = intLogonAttempts + 1
If intLogonAttempts > 3 Then
MsgBox "You do not have access to this database.Please contact admin.", _
vbCritical, "Restricted Access!"
Application.Quit
End If
End Sub

I'm getting a Run-time error '2471' on DLookUp. "The expression you
entered as a query parameter produced this error: 'dkim'".
Since the DLookup expression is DLookup("Password", "tbl_ref_users", "[ID]=" & Me.Text5.Value), perhaps the .Value of Me.Text5 is dkim.
In that case, quote the text box value in the DLookup criteria:
DLookup("[Password]", "tbl_ref_users", "[ID]='" & Me.Text5.Value & "'")
However the datatype of tbl_ref_users.ID must be text in order for that to work. If it's numeric, you need to compare it to a number instead of a text string such as "dkim".
Also note I bracketed the field name Password because it's a reserved word.

Related

How does the DLookup work in this instance?

New user here :)
I got a question about DLookup in the below code. The code is suppose to only allow a selected user to open a form. The user is in the tbl and with the On Error Resume Next the code is working, allowing the user to access the application, however when I comment out the On Error I get the Run-time error '13': Type Mismatch. I was hoping for someone to explain why does it fail with On Error commented out. I understand that If statement requires a condition to evaluate, so how does getting the username allow the application to open the form?
Private Sub Form_Open(Cancel As Integer)
On Error Resume Next
If DLookup("[CitrixID]", "tbl_UserAccess", "[CitrixID] = " & "'" & Environ("username") & "'") Then
Else
MsgBox "You do not have permission to access the application"
DoCmd.Close
End If
End Sub
That's really not the way to do this, but I'll explain what it does.
DLookUp looks up a value from a table. In your case, it's looking up CitrixID from the table CitrixID where CitrixID is equal to the username. It then returns that username as the condition for that If statement.
An If statement, however, expects the condition to be either True, False, Null, or a numeric value (0 = falsy, all other numerals are truthy) which counts as false, not a Windows username, that's why the error occurs.
If you use On Error Resume Next, you're actually jumping into that If statement if the DLookup returns a string, because that's the next thing. However, if it returns Null, because it can't find that username, that doesn't trigger an error, because Null is a valid value which is cast to false.
Some sample code to help you understand this:
Public Sub TestIfResumeNext()
If Null Then
Debug.Print Null
End If
On Error Resume Next
If "A" Then
Debug.Print "A"
End If
If 1 Then
Debug.Print 1
End If
If 0 Then
Debug.Print 0
End If
If -1 Then
Debug.Print -1
End If
End Sub
This will return "A" because of error capturing, 1 and -1 because they're truthy, but not Null because that's a valid falsy value, and not 0 for that same reason.
If you don't want to rely on this error trapping behavior, but want to keep the rest of the logic, you could simply replace DLookUp with DCount. Since 0 is falsy, you don't even need to check if it's 0 (but doing so is a good practice imho).
If DCount("[CitrixID]", "tbl_UserAccess", "[CitrixID] = " & "'" & Environ("username") & "'") Then
Or, with the comparison
If DCount("[CitrixID]", "tbl_UserAccess", "[CitrixID] = " & "'" & Environ("username") & "'") <> 0 Then
Note that you can now shorten it using If Not or If DCount = 0 and remove the Else
DLookup returns Null for "not found" so all you need is to check for this:
Private Sub Form_Open(Cancel As Integer)
If IsNull(DLookup("[CitrixID]", "tbl_UserAccess", "[CitrixID] = '" & Environ("username") & "'")) Then
MsgBox "You do not have permission to access the application."
DoCmd.Close
End If
End Sub

How to use Dlookup in Microsoft access

I am trying to use DLookup to check a text field against a database value except it returns an error when I try to do so. MemberID is the username and is being found using txtUsername field and the password is obviously password which are both retrieved from the Member table.
Here is the code:
Private Sub btnLogin_Click()
If Me.txtPassword.Value = DLookup("[Password]", "Member", "MemberID =
Me.txtUsername.Value") Then
MsgBox "Access Granted", vbInformation, "CD Shop"
MsgBox "Welcome", vbInformation, "CD Shop"
DoCmd.Close
DoCmd.OpenForm "frmGymActivity"
Else
MsgBox "Please re-enter your Username and Password."
End If
End Sub
You need to use proper quoting and string concatenation, to make sure you're passing a string with the value you want.
If Me.txtPassword.Value = DLookup("[Password]", "Member", "MemberID = " & Me.txtUsername.Value) Then
I am assuming MemberID is a number.

DCount with 2 criteria

I am using DCount to help display an error message if the data signals an error. I have it working with one criteria where a number is equal to another number. Now I wanted to add another criteria in there where another field, ReturnDate (this field is Text not Date/Time) is equal to a hyphen (-).
I'm just not really sure how to format it. I have this:
If DCount("*", "CrewTable", "KitNumber=" & _
Me.AssignKit.Value And "ReturnDate=" & _
"-") > 0 Then
Cancel = True
MsgBox "Kit is already assigned!"
AssignKit = ""
AssignKit.SetFocus
Else
...
The error pops up with a 'Type Mistmatch' and the debugger highlights the whole statment from 'If -> Then' and has an error pointing to the line with the hyphen in the quotes.
If DCount("*", "CrewTable", "ReturnDate='-' AND KitNumber=" & _
Me.AssignKit.Value) > 0 Then
It's easier to troubleshoot DCount errors when you store its Criteria option in a string variable.
Dim strCriteria As String
strCriteria = "ReturnDate='-' AND KitNumber=" & Me.AssignKit.Value
Debug.Print strCriteria
If DCount("*", "CrewTable", strCriteria) > 0 Then
If you had used this approach, Access would have alerted you to the fact that the original code which built the Criteria string was invalid. That should make it clearer that the problem wasn't due to the If condition, and it wasn't exactly a DCount problem either ... it was a problem with string concatenation.
Me.AssignKit.Value & " And ReturnDate=" & _

Error handling user input

Hi i am using an access form which asks the user to enter a number. I am trying to handle errors which include; 1. If value entered = null, 2. If the value entered is not an integer. i have tried with my code below but still get an "type mismatch error"
Dim refNum As Integer
refNum = InputBox("Please enter the Reference Number")
If IsNumeric(refNum) Then
MsgBox ("ok")
ElseIf refNum = Null Then
MsgBox (" Field is empty , enter a number")
Else
MsgBox (" Please enter a number")
End If
With these 2 lines ...
Dim refNum As Integer
refNum = InputBox("Please enter the Reference Number")
If the user types any of the following into the InputBox, the code will throw a type mismatch error.
letters, eg "abc"
a number larger than 32767
nothing
The reason for that is because it attempts to store the InputBox value to a variable, refNum, which was declared as Integer. The user could however enter a floating point number, and the assignment to refNum will discard the decimal places. For example, if the user enters 1.2, the value of refNum will be 1.
An InputBox offers limited direct control of the users' inputs. Since you're doing this from a form, consider an unbound textbox, txtRefNum, to collect the value from the user. Check the value In the text box's before update event, display your message for unacceptable values and Cancel the update.
In a comment, you indicated you want "an error handler to trap the mismatch error when assigning to refNum, notify the user, and throw up the InputBox again." In that case, this code does what you want.
Dim refNum As Integer
Dim strMsg As String
On Error GoTo ErrorHandler
refNum = InputBox("Please enter the Reference Number")
MsgBox "ok"
ExitHere:
Exit Sub
ErrorHandler:
Select Case Err.Number
Case 13 ' type mismatch
MsgBox "Reference NUMBER!"
Resume ' present InputBox again
Case Else
strMsg = "Error " & Err.Number & " (" & Err.Description & ")"
MsgBox strMsg
GoTo ExitHere
End Select
Your refNum variable needs to be a variant or a string. When you assign your InputBox to refNum as an integer your InputBox expects only integer values and so breaks before getting to your if statement.
If you use a string you would also need to change your elseif.
ElseIf refNum = Null Or refNum = "" Then

Microsoft Access 2003 VBA - Login Form

This is my first attempt to create a login form. I've read up a few forums about it and tried them myself. However, I've encountered the error when trying out the form.
"Run time error '2001': You canceled the previous operation."
Here's my code! The error highlighted is the DLOOKUP statement. When I move my cursor to LanID, it appears to be 0. (I guess it got something to do with it?)
Option Compare Database
Option Explicit
Private intLoginAttempts As Integer
Private Sub cmdLogin_Click()
'Check mandatory fields
If IsNull(Me.txtLanID) Or Me.txtLanID = "" Then
MsgBox "Lan ID is required.", vbOKOnly, "Required Data"
Me.txtLanID.SetFocus
Exit Sub
End If
If IsNull(Me.txtPassword) Or Me.txtPassword = "" Then
MsgBox "Password is required.", vbOKOnly, "Required Data"
Me.txtPassword.SetFocus
Exit Sub
End If
'Compare input password and database password
If Me.txtLanID <> "" Then
If Me.txtPassword = DLookup("Password", "tblUser", "[LanID]=" & Me.txtLanID) Then
LanID = Me.txtLanID
'Close Login Page
DoCmd.Close acForm, "frmUserLogin", acSaveNo
'Check whether user is an admin
If Me.txtAdmin = DLookup("Administrator", "tblUser", "[LanID]=" & Me.txtLanID) Then
If Me.txtAdmin = -1 Then
DoCmd.OpenForm "frmMenu"
Else
DoCmd.OpenForm "frmBack"
End If
End If
Else
MsgBox "Invalid Password. Try again.", vbOKOnly, "Invalid Entry!"
Me.txtPassword.SetFocus
End If
End If
'If user enters incorrect password 3 times
intLoginAttempts = intLoginAttempts + 1
If intLoginAttempts = 3 Then
MsgBox "You do not have access to the database. Please contact system administrator.", vbCritical, "Restricted Access!"
Application.Quit
End If
End Sub
If tblUser.LanID is text data type, enclose Me.txtLanID in quotes to avoid an error with your DLookup() expression. (You don't need .Value there because it's the default property.)
DLookup("Password", "tblUser", "[LanID]='" & Me.txtLanID & "'")
If that was not the explanation, test your DLookup() expression in the Immediate window (go there with Ctrl+g) to see whether it throws an error or what value it does return.
Note, when you test DLookup() in the Immediate window, use the current value of Me.txtLanID. For example, if Me.txtLanID contains the text "foo", test it like this ...
? DLookup("Password", "tblUser", "[LanID]='foo'")