MS Access: An error in vba of my form - ms-access

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

Related

Access 2016 How can I use the value of a variable not the variable?

Access 2016 VBA Code -
Lead in:
fullname is the table field name, tag is the property
msgbox fullname.tag
will show the value of tag
Problem:
Using the field name in a variable then trying to use the value of the variable
Example:
x = "fullname"
msgbox x.tag
does not show the contents of tag, error is: 424 object required
even if I Dim x as field or fields or variant I still can not get it to work.
How do I use the value of x, not x ?
Thank you in advance
You can't use a variable to reference a variable.
HOWEVER, you can most certainly use a string variable to referance a control on a form.
So,
dim strMyCtrl as string
strMyCtrl = "LastName"
Now,
msgbox "value of LastName = " & me!LastName
msgbox "Value of LastName = " & me("LastName")
msgbox "Value of LastName = " & me("LastName").Value
or
msgbox "Value of LastName = " & me(strMyCtrl)
msgbox "Value of LastName = " & me(strMyCtrl).Value
And since you can referance the control with a string, then you can also grab the tag value also
eg:
msgbox "Value of LastName control tag value = " & me(strMyCtrl).tag.
So, if you have controls 1 to 5 named:
TextBox1
TextBox2
TextBox3
TextBox4
TextBox5
You can grab the values like this:
dim i as integer
dim strCtrl as string
For i = 1 to 5
strCtrl = "TextBox" & i
msgbox "Value of " & strCtrl & " is = " & me(strCtrl)
Next i
So, no variable against a variable is allowed. However for controls, or even field names in a recordset, you can use a "string" variable with the name of the column, or as per above the name of the control.

Text box undo not working if there is a duplicate

I am having a form with a textbox and a list box. I want to enter a new record into the textbox to populate the table and listbox (listbox row source is the table). I have written a code to prevent duplicate entry into the table. When there is a duplicate entry I am getting a pop up to alert the user. What is not working is the undo option to clear the textbox. The code is pasted below with some required info. Any help with the code will be appreciated.
Table name: tblNewComponents
Field name: NewComponents
Textbox name: TextCOMPONENTS
Can someone help me? Thanks
Private Sub TextCOMPONENTS_AfterUpdate()
Dim NewComponent As String
Dim stLinkCriteria As String
Dim custNo As Integer
'Assign the entered customer name to a variable NewCustomer
NewComponent = Me.TextCOMPONENTS.Value
stLinkCriteria = "[NewComponents] = " & "'" & NewComponent & "'"
If Me.TextCOMPONENTS = DLookup("[NewComponents]", "tblNewComponents", stLinkCriteria) Then
MsgBox "This Component, " & NewComponent & ", has already been entered in database." _
& vbCr & vbCr & "Please check the component name again.", vbInformation, "Duplicate information"
Me.Undo
end if
exit sub
Just do this to clear the textbox (and set the focus into it)
Me.TextCOMPONENTS.Value = Null
Me.TextCOMPONENTS.SetFocus
instead of Me.Undo.
your error is in your event act, u should keep it on next textbox gotfocus event ,and not in current textbox afterupdate ,
in next text box gotfocus event,and will work perfectly.
many thanks SOF club

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

Getting Records from Table in Access

I have this requirement where I have to check the data based on data given in other fields. I have table with 'N' fields. I should allow user to select 4 fields which are from the table. And then I should get all other fields of that particular record and display it to the user so that he can verify that the data he entered into table is correct. Please help.
Thanks
I have a clearer understanding now of what you require - hopefully this is what you need:
Assume you have a table called 'Phones'
The phones table has three primary fields: Manufacturer, Operating System, and Carrier
In addition to these primary fields there are secondary "spec" fields. For now we have three: ScreenSize, Frequencies, and Price.
I create a form with three combo boxes: ManufacturerFilter, OperatingSystemFilter, and CarrierFilter.
Each combo box's row source is similar to:
SELECT Carrier FROM Phones GROUP BY Carrier ORDER BY Carrier;
Where Carrier is replaced by Manufacturer and [Operating System] respectively.
I then add in all of the secondary fields, each bound to their own respective field.
You can also add in a button called "Retrieve" for now leave the click code blank.
At this point you have a few options. I'll highlight two, but both options will require the following procedure:
Private Function FilterStr() As String
Dim myFilterStr As String
' Include each filter if they are entered
If Nz(Me.ManufacturerFilter, "") <> "" Then myFilterStr = myFilterStr & "[Manufacturer]='" & Me.ManufacturerFilter.Value & "' AND"
If Nz(Me.OperatingSystemFilter, "") <> "" Then myFilterStr = myFilterStr & "[Operating System]='" & Me.OperatingSystemFilter.Value & "' AND"
If Nz(Me.CarrierFilter, "") <> "" Then myFilterStr = myFilterStr & "[Carrier]='" & Me.CarrierFilter.Value & "' AND"
' Remove the last AND statement
If myFilterStr <> "" Then myFilterStr = Mid(myFilterStr, 1, Len(myFilterStr) - 4)
FilterStr = myFilterStr
End Function
This function returns a filter string, based on the combo box options selected.
Option #1: Filter the Recordset
What we want to occur, is when a primary field value is selected, the records are filtered to display only those matching the criteria. Add the following code to the OnClick event of your Retrieve button:
Private Sub RetreiveButton_Click()
Dim myFilterStr As String
myFilterStr = FilterStr
If myFilterStr <> "" Then
Me.Filter = myFilterStr
Me.FilterOn = True
Else
Me.Filter = ""
Me.FilterOn = False
End If
End Sub
So what happens when the button is clicked, is that a filter string is created based on the values selected, and then a filter is applied to the form. If no values are selected in the combo boxes, the filter is cleared and turned off.
Option #2: Find a Record based on the Value
What we want is to select the values in the comboboxes, and then move to the record that matches the criteria.
Add the following code to the onClick event of the retrieve button.
Private Sub RetreiveButton_Click()
Dim rst As DAO.Recordset
Dim myFilterStr As String
myFilterStr = FilterStr()
If myFilterStr = "" Then
MsgBox "No Filter Selected", vbOKOnly, "Error"
Exit Sub
End If
Set rst = Me.RecordsetClone
rst.FindFirst myFilterStr
If rst.NoMatch Then
MsgBox "No Matching Records were found", vbOKOnly, "No Data"
Else
Me.Bookmark = rst.Bookmark
End If
Set rst = Nothing
End Sub
This uses the the same FilterStr() function to return a search string, but uses the recordset's FindFirst method to locate a record. If found, it will move to the record.
Hope that answers your question. As I indicated, the exact behaviour will vary but the underlying principle remains the same.

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