Error handling user input - ms-access

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

Related

code ot check if data entry already exist

I have a form where the user enters data "last name"
I am trying to put a code together that checks if the data entered for "last name" already exists in a database, and if it does, for a message box to appear advising the user that the last name already exists, and then giving them the option on whether they would like to continue in adding that "last name" into the database.
ive written the code several different ways, with if statements and dlookup, but it doesn't seem to be working
Check this out
Private Sub btn_Click()
'variable declaration
Dim lastName As String
Dim cnt As Long
Dim retVal As Variant
'get textbox value into variable. Nz function checks for null and replaces it with empty string in case its nulll
lastName = Nz(Me.txtLastName, "")
'dcount function checks the count of lastname in tblUser
If DCount("*", "tblUser", "LastName='" & lastName & "'") > 0 Then
retVal = MsgBox("Name already exist. Do you want to continue?", vbYesNo)
If retVal = vbYes Then
'your insert statement
Else
'
End If
End If
End Sub

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

Access Input Form with Custom Error Messages

The Solution
The solution was to not try and capture the errors but do the error handling myself as part of the Add New Record command button:
Private Sub buttonNewRecord_Click()
Dim ErrorInt As Integer
Dim TeleCheck As Variant
Name.SetFocus
If Name.Text = "" Then
MsgBox "Name is missing!"
ErrorInt = ErrorInt + 1
End If
TeleCheck = DLookup("[Telephone]", "tblColdCallLog", "[Telephone] = '" & Me.Telephone & "'")
If Not IsNull(TeleCheck) Then
MsgBox "Telephone number already exists in the table!"
ErrorInt = ErrorInt + 1
End If
If ErrorInt < 1 Then
DoCmd.GoToRecord , , acNewRec
MsgBox "Record Added!"
End If
End Sub
Original Post:
What I Have:
I have created a simple Access 2013 Form used to input data into a table. On the Form, the user enters data into the fields and clicks on a button made using the Command Button Wizard to Add New Record.
The form has one required field, [Name], and one field set to 'Index: Yes (No Duplicates)', [Telephone Number]. In the Form, this correctly produces error messages if the [Name] field is empty or there is a duplicate number detected in the [Telephone] field that is also in the table.
What I Am Trying To Do:
The error messages that appear are not user friendly. I would like to replace them with custom error messages and if there are no errors, maybe a message that says all went well.
What I Have Tried:
On the Form properties, Events tab, in 'On Error', [Event Procedure]:
Private Sub Error_Sub(DataErr As Integer, Response As Integer)
If DataErr = 3022 Then
MsgBox "Duplicate telephone number found in table!"
Response = acDataErrContinue
End If
If DataErr = 3314 Then
MsgBox "Name is missing!"
Response = acDataErrContinue
End If
End Sub
This works but only when you close the Form... When you click the 'Add New Record' Command Button, it simply shows the default error messages when appropriate.
Maybe I should use the Event 'Before Update'? I can't seem to use the same VBA script. I'm not allowed to define DataErr or Response. So, I'll use an Expression instead:
=IIf(Error(3022),MsgBox("Duplicate telephone number found in table"))
=IIf(Error(3314),MsgBox("Name is missing"))
This works... but when there is no error. Even if there is a name in the [Name] field, the error shows but at least it replaces the default error message.
Let's put it in the button itself? I'll have to use the Macro Builder to edit it. It's a bit hard to copy and paste this one so I'll simplify:
OnError GoTo Error_Handling
GoToRecord New
If [MacroError]<>0 Then
MsgBox = "[MacroError].[Description]"
End If
Error_Handling:
If Error(3022) Then
MsgBox = "Duplicate telephone number found in table!"
End If
If Error(3314) Then
MsgBox = "Name is missing!"
End If
This does the same as the 'Before Update' event; replaces the default error message but regardless of whether or not the error message should be triggered in the first place.
What am I doing wrong? I get the feeling it's something really simple. I've tried a variety of other combinations and endless Googling but I feel stumped.
Private Sub buttonNewRecord_Click()
Dim ErrorInt As Integer
Dim TeleCheck As Variant
Name.SetFocus
If Name.Text = "" Then
MsgBox "Name is missing!"
ErrorInt = ErrorInt + 1
End If
TeleCheck = DLookup("[Telephone]", "tblColdCallLog", "[Telephone] = '" & Me.Telephone & "'")
If Not IsNull(TeleCheck) Then
MsgBox "Telephone number already exists in the table!"
ErrorInt = ErrorInt + 1
End If
If ErrorInt < 1 Then
DoCmd.GoToRecord , , acNewRec
MsgBox "Record Added!"
End If
End Sub

DLookup Function - returning wrong value

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.

MS Access: An error in vba of my form

I have a simple MS Access form that has 3 objects: a text box, a list box, and a button. The intended use of the form is as follows: the user enters a name in the text box, selects an item from the list box, then clicks the button to add the data to a table.
However, when I click on the button, I keep getting the error message, "You can't reference property or a method for a control unless the control has the focus."
Below is my code. Thanks!
Private Sub addRecord_button_Click()
Dim CustomerName As String
Dim CustomerType As String
On Error GoTo Errhandler
CustomerName = "[name not selected]"
CustomerType = "[type not selected]"
CustomerName = Customer_TextBox.Text
Select Case Type_ListBox.ListIndex
Case 0
CustomerType = "Type 1"
Case 1
CustomerType = "Type 2"
Case 2
CustomerType = "Type 3"
End Select
'MsgBox ("Name: " & CustomerName & " and Type: " & CustomerType)
DoCmd.RunSQL "INSERT INTO Customer VALUES (CustomerName, CustomerType);"
Errhandler:
MsgBox ("The following error has occured: " & Err & " - " & Error(Err))
End Sub
The .Text property can only be used when the TextBox has focus. Try using the .Value property instead.
Try replacing the below line
CustomerName = Customer_TextBox.Text
with
CustomerName = Customer_TextBox.Value