Run-time error: The value you entered isn't valid for this field - vba

I am trying to update a record using Subform. When I update the first time it updates properly but when I try to update the same record again I am getting the error:
Run-time error '-2147352567 (80020009)': The value you entered isn't valid for this field
The following is the form.
When I click edit, the information from the selected record is populated into the respective text-boxes. Once I update the information and click update, the record gets successfully updated for the first time.
When I try to update the same record again I get the mentioned error.
Here is the VB script that runs on clicking edit.
Private Sub cmdEdit_Click()
'Check if data exists in the list
If Not (Me.frmschoolsub.Form.Recordset.EOF And Me.frmschoolsub.Form.Recordset.BOF) Then
'get data to text box control
With Me.frmschoolsub.Form.Recordset
Me.Schooltxt = .Fields("School_Name")
Me.Desctxt = .Fields("Description")
Me.Deantxt = .Fields("Dean")
Me.Adeantxt = .Fields("Associate_Dean")
'store id of student in tag
Me.Schooltxt.Tag = .Fields("School_ID")
'change caption of button to update
Me.cmdAdd.Caption = "Update"
Me.cmdEdit.Enabled = False
End With
End If
End Sub
When I click on Debug it highlights the following line.
Me.Schooltxt = .Fields("School_Name")
Can you help me in identifying what is the issue here.

I figured that after the each update, I am losing the position of record. I added the following statement after update and Requery
Me.frmschoolsub.Form.Recordset.MoveFirst
Following is the code snippet.
Else
CurrentDb.Execute "Update School " & _
" SET School_Name ='" & Me.Schooltxt & "'" & _
", Description ='" & Me.Desctxt & "'" & _
", Dean ='" & Me.Deantxt & "'" & _
", Associate_Dean='" & Me.Adeantxt & "'" & _
"where School_ID=" & Me.Schooltxt.Tag
End If
'Clear the Fields
cmdClr_Click
'Refresh the table
frmschoolsub.Form.Requery
Me.frmschoolsub.Form.Recordset.MoveFirst
This fixed the issue.

This error is happening that a form field cannot be referenced to a textbox like you did.
You can do it as below.
With Me.frmschoolsub.Form.Recordset
Me.Schooltxt = Forms![<<if you have main form >>]![frmschoolsub].form![School_Name]

Related

dynamic search box filters using LIKE

I have a dynamic search box filtering a subform based on user input. I also have a few filter buttons that filter the same subform. I set up the search box to incorporate preexisting filters applied by those buttons.
All that works fine. The problem I have is:
The dynamic filter using the LIKE statement only seems to work correctly when the length of the filter text is >= 3. Go below that and it applies some wonky filtering. Maybe I am using the statement wrong. I thought it would look if the field's value contains the search string somewhere in it. But it seemingly accepts values like "Natronlauge 50% techn. EN 896" for a search string of "Hä", which seems weird to me. It works once I add a third character though. Lines 11 and 13:
Me.Form.Filter = "[bezeichnung] LIKE '*" & SearchBoxStoffe & "*' AND [kategorie] = '" & Forms![HUB]![FilterAlleLink] & "'"
Would be nice if someone has some ideas how to go about these issues.
Here the full code for my searchbox:
Private Sub SearchBoxStoffe_KeyUp(KeyCode As Integer, Shift As Integer)
On Error GoTo errHandler
Dim filterText As String
'Apply dynamic filter for current filter category.
If Len(SearchBoxStoffe.Text) > 0 Then
filterText = SearchBoxStoffe.Text
If Forms![HUB]![FilterAlleLink] = "" Then
Me.Form.Filter = "[bezeichnung] LIKE '*" & SearchBoxStoffe & "*'"
Else
Me.Form.Filter = "[bezeichnung] LIKE '*" & SearchBoxStoffe & "*' AND [kategorie] = '" & Forms![HUB]![FilterAlleLink] & "'"
End If
Me.FilterOn = True
'Retain filter text in search box after refreshing.
SearchBoxStoffe.Text = filterText
SearchBoxStoffe.SelStart = Len(SearchBoxStoffe.Text)
Else
'Revert to current main filter category.
If Forms![HUB]![FilterAlleLink] <> "" Then
Call FilterStoffe("[kategorie] = '" & Forms![HUB]![FilterAlleLink] & "'")
Else
If Forms![HUB]![FilterAlleLink] = "" Then
Me.Filter = ""
Me.FilterOn = False
End If
End If
End If
'Set focus back to search box
SearchBoxStoffe.SetFocus
Exit Sub
errHandler:
MsgBox Err.Number & " - " & Err.Description, vbOKOnly, "Error ..."
End Sub
The dynamic filter using the LIKE statement only seems to work
correctly when the length of the filter text is >= 3. Go below that
and it applies some wonky filtering.
I don't really know why this is happening, but try the below. It makes use of the Change() event and covers 4 scenarios:
Both filters applicable.
Search Box only.
Main category only.
Nothing (clear the filter).
Also, I don't know what the FilterStoffe() method does, but I assume it just applies the main filter only.
Private Sub SearchBoxStoffe_Change()
On Error GoTo Trap
Select Case True
'both filters
Case Len(SearchBoxStoffe.Text) > 0 And Not IsNull(Forms.HUB.FilterAlleLink.Value):
Form.Filter = "[bezeichnung] LIKE '*" & SearchBoxStoffe.Text & "*' AND [kategorie] = '" & Forms.HUB.FilterAlleLink.Value & "'"
FilterOn = True
'SearchBox only
Case Len(SearchBoxStoffe.Text) > 0:
Form.Filter = "[bezeichnung] LIKE '*" & SearchBoxStoffe.Text & "*'"
FilterOn = True
'FilterAlleLink only
Case Not IsNull(Forms.HUB.FilterAlleLink.Value):
Form.Filter = "[kategorie] = '" & Forms.HUB.FilterAlleLink.Value & "'"
FilterOn = True
'Nothing
Case Else:
FilterOn = False
Filter = vbNullString
End Select
Leave:
On Error Resume Next
SearchBoxStoffe.SetFocus
Exit Sub
Trap:
MsgBox Err.Number & " - " & Err.Description, vbOKOnly, "Error ..."
Resume Leave
End Sub
Keep in mind, within the Change() event, the Text property gets updated with every keystroke and when the control loses the focus, it gets copied to the Value property.
However, the Value is the default property when you just reference the control.
So this
Me.SearchBoxStoffe
is the same as this:
Me.SearchBoxStoffe.Value
There were 2 issues that prevented the searchbox from running as intended:
Object references in the project were created with 2 different language versions of access. Objects would call other objects using the formulation of one language, which in turn called objects using referencing in another language etc. In cases where fields and/or queries would return empty, this would cause some of the references to no longer function as intended. The result was the program running out of stack space, empty controls on subforms that returned empty queries, objects not being found and more.
The searchbox filter was lagging behind the text in the searchbox by one event. If entering a new search string, the applied filter would always be missing the last character when using SearchBoxStoffe in the filter statement. Entering "Wood" would cause the filter to apply "Woo" etc.
The solutions are the following:
Fix all the references in the file manually to either language version and do not mix them up going forward.
The Value of the search box SearchBoxStoffe is not yet updated on either the KeyUp or the Change event when entering a new character. This can be fixed by substituting the Text value instead, which is updated already. Simply change line 11 to Me.Form.Filter = "[bezeichnung] LIKE '*" & SearchBoxStoffe.Text & "*'" and line 13 to Me.Form.Filter = "[bezeichnung] LIKE '*" & SearchBoxStoffe.Text & "*' AND [kategorie] = '" & Forms![HUB]![FilterAlleLink] & "'". The info originally came from #KostasK in his solution:
Keep in mind, within the Change() event, the Text property gets updated with every keystroke and when the control loses the focus, it gets copied to the Value property.
Which works too btw, just wasn't able to be verified since issue 1 prevented the code from running correctly. Answer by Kostas K.

Access VBA - Input Form Detect Duplicate and then Display Duplicate Record

What I Have:
I have an Access input form, the user fills in data in the form, pushes a button which triggers a VBA script which checks if the input telephone number in the [Telephone] control matches an entry in the table. If there's a duplicate it triggers a MsgBox, if not it commits the data to the table. This works and it's great. Here is the script:
Option Compare Database
Private Sub buttonNewRecord_Click()
Dim ErrorInt As Integer
Dim TeleCheck As Variant
TeleCheck = DLookup("[Telephone]", "tblLog", "[Telephone] = '" & Me.Telephone & "'")
If Not IsNull(TeleCheck) Then
MsgBox "Telephone number already exists in the database!"
ErrorInt = ErrorInt + 1
End If
If ErrorInt < 1 Then
DoCmd.GoToRecord , , acNewRec
MsgBox "Record Added!"
End If
End Sub
What I Am Trying To Do:
In the table, along with [Telephone], there is a [Date] and [Customer_Name] field. When a duplicate telephone number is detected, I would like the triggered MsgBox to display the [Date] and [Customer_Name] of the record where the duplicate was found. Like:
MsgBox "Telephone number already exists for [Customer_Name] added on [Date]!"
What I Have Tried:
Not a lot because I'm not sure what to try. Googling provides a lot of different ways to detect a duplicate but I have found no one trying to return any data from the record of the duplicate found.
Dim cstmerName as String
Dim dateAdded as String
Let cstmerName = DLookup("[Customer_Name]", "tblLog", "[Telephone] = '" & Me.Telephone & "'")
Let dateAdded = CStr(DLookup("[Date]", "tblLog", "[Telephone] = '" & Me.Telephone & "'"))
MsgBox "Telephone number already exists for " & cstmerName & " added on " & dateAdded & "!"

How to add a comment using comment boxes in Access?

I am building an Access database for work. I have set up a report to open upon click for a certain record. So only the information of that record is to appear on the report. However, I would like to add a comment box in the report where you can add comments. The new comments are stamped and added to the previous comments already showing in the report. I was able to program the commenting function in a separate report. However, for the reports that show only specific records it won't work. I know it is because I have to somehow add each comment to my database, but I just can not figure out how to do it. I used the following code that I found online in another article. It works fine when your comments are not tied to a certain record.
Private Sub cmdAppendComment_Click()
If (IsNull(txtNewComment.Value)) Then
MsgBox ("Please enter a comment before clicking" & _
"on the Append Comment button.")
Exit Sub
End If
' These commented lines will never be reached:
' If (IsNull(txtComment.Value)) Then
' Table.tblmain.User_comment.Value = txtNewComment.Value & " ~ " & _
' VBA.DateTime.Date & " ~ " & VBA.DateTime.Time
' Else
Table.tblmain.User_comment.Value = txtComment.Value & _
vbNewLine & vbNewLine & _
txtNewComment.Value & " ~ " & _
VBA.DateTime.Date & " ~ " & VBA.DateTime.Time
' End If
' txtNewComment.Value = ""
' Use Null:
txtNewComment.Value = Null
End Sub
You would use a form, not report, for this.
Bind this to the table, add the new comment to the existing comment bound to texbox, and save the record.

Trying to use VBA to write query in Access

I am getting a type mismatch with the following syntax in my Access VBA. I am trying to update my table named "Billing" by seeing if any records have a date that looks at a string value in my "Certs" table like "2012-07-01" corresponding to my form's billYear textbox e.g. 2012 and my billMonth textbox e.g. 07. Is there a better way to write the VBA or see an error - many thanks:
Dim sRecert As String
Dim byear As Integer
Dim bmonth As Integer
byear = Me.billYear
bmonth = Me.billMonth
sRecert = "Update Billing set recertifying = -1 where (select certificationExpireDate from certs where Left((certificationExpireDate),4) = " & byear
& " and Mid((certificationExpireDate),6,2) = " & bmonth & ")"
DoCmd.RunSQL sRecert
I may not have explained it well. I created a real Query called from my form:
DoCmd.OpenQuery "updateRecert"
I set up my SQL below as a test on a real date I’m working with. It is in SQL Server (ODBC linked)
My dbo_certs table and my dbo_billing table share only one joinable field peopleID:
UPDATE dbo_Billing AS a INNER JOIN dbo_certs AS b ON a.peopleid = b.peopleid
SET a.recertifying = -1
WHERE b.certificationExpireDate = '2015-08-31 00:00:00.000';
The above gave a data mismatch error.
My bottom line is I have two text boxes on my form to pass in data preferably into my VBA code:
billMonth which in this case is 8 because it is an integer so that is
a problem
billYear is 2015
so I need to update my dbo_billing table’s ‘recertifying’ field with -1 if the dbo_cert’s field ‘certificationExpireDate’ is '2015-08-31 00:00:00.000' but only if that can be gotten from the form.
Is there a better way to write the VBA or see an Error?
Yes. You need Error Handling
I don't think the issue is in the code, I think it's in the SQL.
To troubleshoot your code, wrap it in an good error handler.
Public Sub MyRoutine()
On Error GoTo EH
'put your code here
GoTo FINISH
EH:
With Err
MsgBox "Error" & vbTab & .Number & vbCrLf _
& "Source" & vbTab & .Source & vbCrLf & vbCrLf _
& .Description
End With
'for use during debugging
Debug.Assert 0
GoTo FINISH
Resume
FINISH:
'any cleanup code here
End Sub
When the msgbox shows the error, make note of the Source. This should help you determine where the error comes from.
The lines following 'for use during debugging are helpful. Here's how to use them:
execution will stop on the Debug.Assert 0 line
drag the yellow arrow (which determines which line to run next) to the Resume line
hit {F8} on the keyboard (or use the menu Debug > Step Into)
This will go to the line where the error occurred. In your case, it will probably be the last line of your code.
Error in SQL... but!! Are you sure that certificationExpireDate is string and all the time equal to yyyy-mm-dd pattern?? It's dangerouse to have relation with "not certain" key like you have. I think this is not a good db design.
But, after all, for your case:
VBA:
sRecert = "UPDATE Billing a inner join certs b " & _
"on format(a.imaginary_date_field, """yyyy-mm-dd""") = b.certificationExpireDate " & _
"set a.recertifying = -1 " & _
"where CInt(Left((b.certificationExpireDate),4)) = " & byear & " and CInt(Mid((b.certificationExpireDate),6,2)) = " & bmonth
QueryDef:
PARAMETERS Forms!your_form!byear Short, Forms!your_form!bmonth Short;
UPDATE Billing a inner join certs b
on format(a.imaginary_date_field, "yyyy-mm-dd") = b.certificationExpireDate
set a.recertifying = -1
where CInt(Left((b.certificationExpireDate),4)) = Forms!your_form!byear and CInt(Mid((b.certificationExpireDate),6,2)) = Forms!your_form!bmonth
UPDATED
mismatch error
You get error probable because you have date/time field, not a string. Date in MS Access queries write with # symbol. WHERE b.certificationExpireDate = #2015-08-31 00:00:00.000#;
In your case:
PARAMETERS Forms!your_form!byear Short, Forms!your_form!bmonth Short;
UPDATE dbo_Billing AS a INNER JOIN dbo_certs AS b ON a.peopleid = b.peopleid
SET a.recertifying = -1
WHERE year(b.certificationExpireDate) = Forms!your_form!byear and Month(b.certificationExpireDate) = Forms!your_form!bmonth;
For more info follow this link

MS access sum results between two dates as text box in form

I issue following query in SQL and works fine
SELECT SUM(goudOpkoop.winst)
FROM goudOpkoop
WHERE goudOpkoop.date
BETWEEN '2015-1-10' AND '2015-1-22'
I would like to have the results in a Form in Textbox 3 (name Text183) when last of two dates, one in Textbox 1 (name Text179) and other in textbox 2 (name Text181) have been picked.
I think I would need to use AfterUpdate code builder for Textbox 2 and issue there the query to eventually show results in Textbox 3.
I have already linked with SQL server.
Information: ODBC;DSN=Essence Test;;TABLE=goudOpkoop
In me not being a professional in VBA I have no clue how to get this working.
Not tested, but should do the trick slightly, unless I made a typo.
Change the format of your 2 dates textboxes in "Short Date", that way you will have a calendar picker and you will ensure that your date have a correct format
Create this sub in your form module :
Private Sub CheckSUM()
Dim RST As Recordset
Dim SQL As String
' Reset the result textbox
Text183.value = ""
' If your 2 date textboxes are not populated, cancel
If Text179.Value = "" or Text181.Value = "" Then Exit Sub
' Prepare the query, with proper formating of the dates
SQL = " SELECT SUM(goudOpkoop.winst) AS mySum " & _
" FROM goudOpkoop " & _
" WHERE goudOpkoop.Date " & _
" BETWEEN '" & Format(Text179.Value, "YYYY-MM-DD") & "' " & _
" AND '" & Format(text181.Value, "YYYY-MM-DD") & "'"
' Execute the query
Set RST = CurrentDb.OpenRecordset(SQL)
' If the query is valid and returned something, we recuperate the value
If Not RST.BOF Then
Text183.Value = RST!mySum
End If
' Cleaning
RST.Close
Set RST = Nothing
End Sub
Then, for your 2 dates textboxes, create an afterupdate event and call the previous sub in them:
Private Sub Text179_AfterUpdate()
CheckSUM
End Sub
Private Sub Text181_AfterUpdate()
CheckSUM
End Sub