Error 2465 in MS Access when running a VBA code - vba

Read through a few of the previously asked posts about this error but still cannot understand it.
The error text is "Run-time error '2465' CASREP reporting tool can't find the field '|1' referred to in your expression
I have a form to assign parts to certain supply reports. We have a form where users can manually hyperlink the parts to the request if they fall in the cracks. There is a check box feature, followed by the use of an "Assign" button to achieve this.
Every time a box is checked and a user selects "Assign" the error pops up. The string of code that pops up with the bug is as follows:
strSQL_del = "DELETE FROM [tbl_Temp_Assign] " & _
"WHERE [jcn_cd]= '" & Forms![Parts: Assign Unit].[tblTemp_Assign subform1].Form.[jcn.cd] & "'
AND [CASREP #] = '" & strCASREP & "' AND [doc_num_cd] = '" & Forms![Parts: Assign Unit].[tblTemp_Assign subform1].Form.[doc_num_cd] & "'
AND [last_updated_dte] = #" & Forms![Parts: Assign Unit].[tblTemp_Assign subform1].Form.[last_updated_dte] & "#
AND [PMOMsgDte] = #" & Forms![Parts: Assign Unit].[tblTemp_Assign Unit].Form.[PMOMsgDte] & "#" 'Intentionally left off AssignDte
Any help is greatly appreciated. I'm lost on what is wrong.

The error is related to the SQL string concatenation, but that string is quite long, it's hard to say if you have a space between ' and the first AND condition. Also, after the first continuation character _, is all that a single line?
Anyway, I would strongly advise to setup a delete query where you pass the form values as parameters and in VBA you just execute the query. It will be easier to update later on if needed.
The query:
PARAMETERS [prmTextField] Text (50), [prmDateField] DateTime, [prmNumberField] Long;
DELETE *
FROM T
WHERE T.TextField = [prmTextField]
AND T.DateField = [prmDateField]
AND T.NumberField = [prmNumberField];
Then, in VBA just execute the query.
With CurrentDb().QueryDefs("QueryName")
.Parameters("[prmTextField]").Value = '[Value from Form (text)]
.Parameters("[prmDateField]").Value = '[Value from Form (date)]
.Parameters("[prmNumberField]").Value = '[Value from Form (number)]
.Execute dbFailOnError
End With
By the way, do you really need to pass all those parameters to delete a record? Usually, just the record id is needed.

Related

Why does MS Access prompt to enter parameter in update query which already has values?

I am making a database where the user can change the name of a company in a table. However , whenever I use the update query, it asks for a parameter which is already supplied. The old company name is in the variable new_comp and then the new one is in the Me.comp1_box.Value.
Funny enough the query runs excellently whenever I hit ok and enter nothing inside the "Enter Parameter" setting
Dim record_changer As String
record_changer = "UPDATE " & "[" & new_comp & "]" & " SET " & "[" & new_comp & "]" & ".Company_Name =" & """" & Me.comp1_box.Value & """" & ";"
MsgBox (record_changer)
DoCmd.RunSQL (record_changer)
This is the final value of the record_changer.
UPDATE [EREDEON TECHNOLOGIES] SET [EREDEON TECHNOLOGIES].Company_Name="EREDEON TECH";
This is how it is when the code runs.
This is the query that it is supposed to run
It gives this prompt meaning it's supposed to run perfectly, meaning there is nothing wrong with the Query
This what pops up
Can anyone please help me out?
I am genuinely lost.The name of the Old Company name is EREDEON TECHNOLOGIES and the new name is EREDEON TECH
But funny enough when I just hit Okay without entering a value into the parameter dialogue box, it actually makes the changes.-_- weird
This happens, then I press "OK"
THEN THIS HAPPENS, Then I hit Okay
This is the table before.
It updates the table the new value which is EREDEON TECH. When I just hit OK, without typing anything into Parameter Dialogue.
Try changing your SQL string to the following. Note the single quotes change around Me.comp1_box.Value.
record_changer = "UPDATE " & "[" & new_comp & "]" & " SET " & "[" & new_comp & "]" & ".Company_Name ='" & Me.comp1_box.Value & "';"
Misused quote marks is the most common cause for the Parameter Value prompt. If that doesn't work, use this article to perform step-by-step trouble shooting on all of the other usual causes, Why does Access want me to enter a parameter value?
You can also reference the following articles:
MS Docs, Quotation marks in string expressions
Bytes, (') and (") - Where and When to use them
Fundamentally, the issue is due to the use of double quotes in VBA which works in Access SQL by itself but not via VBA using DoCmd.RunSQL. You could have used single quotes to enclose company name value.
However, avoid concatenating VBA literals to SQL queries with quotes in the first place. Instead, use the industry best practice of parameterization which is available in MS Access using QueryDefs in VBA and PARAMETERS clause in SQL:
Dim record_changer As String
Dim qdef As QueryDef
sql = "PARAMETERS new_name_param TEXT; " _
& "UPDATE [" & new_comp & "] " _
& "SET Company_Name = new_name_param;"
' SET UP QUERYDEF
Set qdef = CurrentDb.CreateQueryDef("", sql)
' BIND PARAMS
qdef!new_name_param = Me.comp1_box.Value
' RUN ACTION
qdef.Execute
' RELEASE RESOURCE
Set qdef = Nothing
Nonetheless, the need to concatenate table name, new_comp, in query is questionable database design. Proper names (EREDEON TECHNOLOGIES, GAME DISCOUNT STORE, SHOPRITE, etc.) should never be names of tables. Avoid maintaining a separate table for every company. Instead, normalize data for a single table of all companies, then run UPDATE with WHERE adding a second parameter.
' PREPARED STATEMENT, NO VARIABLE CONCATENATION
sql = "PARAMETERS new_name_param TEXT, old_name_param TEXT; " _
& " UPDATE Companies " _
& " SET Company_Name = new_name_param" _
& " WHERE Company_Name = old_name_param;"
Set qdef = CurrentDb.CreateQueryDef("", sql)
qdef!new_name_param = Me.comp1_box.Value
qdef!old_name_param = new_comp
qdef.Execute
In fact, since above SQL is now separated from VBA, save the query without VBA punctuation (&, ", or _) as a separate object and call it in QueryDefs by name:
Set qdef = CurrentDb.QueryDefs("mySavedQuery")
qdef!new_name_param = Me.comp1_box.Value
qdef!old_name_param = new_comp
qdef.Execute
Even better, if your parameters derive from controls on open forms, include them directly in query for a single line VBA call. Below runs the normalized version of single Companies table:
SQL (save as query object, adjust names to actuals)
UPDATE Companies
SET Company_Name = Forms!myForm!comp1_box
WHERE Company_Name = Forms!myForm!new_comp
VBA (no need to close action queries)
DoCmd.OpenQuery "mySavedQuery"

Referencing Variable for Functions

Every two weeks there will be a new table with new data coming in to me, I need to update that onto a master table. I want to automate this process.
I would like to declare a variable that a user can input the date the data is from, and based on that date update to the appropriate field on the master table. I have no clue how to make SQL functions use variables to locate tables with the syntax, not even sure if this can be done. Any help would be appreciated.
As I am inexperienced, I am making a VBA Macro and embedding the SQL code from the access query I made.
Sub UpdateFieldX()
Dim SQL As String
SQL = "UPDATE [15-Jun-16] " & _
"RIGHT JOIN MasterSPI " & _
"ON [15-Jun-16].[SR#] = MasterSPI.[SR#] " & _
"SET MasterSPI.[30-Jun-16] = [15-Jun-16].[SPI]; " _
DoCmd.RunSQL SQL
End Sub
I've done something similar to this and used an Update Query and Insert Query.
It sounds like you're trying to just update any existing records that may need updating and then adding new records into the table.
For an update, I'd try creating a query in SQL view and type something like:
UPDATE MasterSPI SET MasterSPI.SRnumber = [newtablename]![SRnumber] etc.
and do that for each field in your table.
For inserting you could do something like:
INSERT INTO MasterSPI SELECT * FROM newtablename
That may help you get started.
I know many of you are advanced users but I found an answer that fit my quick needs. As a notice and disclaimer for other people, it will be in no way secure, it is more for personal use such that I do not need to spend an hour doing append and updates to several master tables repetitively.
To do this, I made a global string variable called name, then I made another variable called strung that translated it into a readable string for referencing. I then made an SQL string that references that strung variable. This allows the user to submit an input for the global variable, which translates into a readable string for the RunSQL method.
Here's a snippet of the parts that were most relevant, I hope it helps whoever comes next with the same scenario.
**
Public name As String 'global variable declared so that the new field to be created can be used elsewhere
name = InputBox("Name of Month", "InputBox") 'variable that takes user input and it will be name for new fields to be added
Dim SQLa As String 'creates a string variable such that it will be read as an SQL line by the RunSQL method
strung = "[" & name & "]" 'sets strung as global varible name, which is user input on the specific table being used to update
'the following lines runs a query such that it updates the master table with new data and does the grouping by SR number
SQLa = "UPDATE " & strung & " " & _
"RIGHT JOIN MasterSPI " & _
"ON " & strung & "." & "[SR#] = MasterSPI.[SR#] " & _
"SET MasterSPI." & strung & " = " & strung & "." & "[SPI]; " _
DoCmd.RunSQL SQLa 'executes the SQL code in VBA **

How to do a MS Access Update query for a table in external database

Im trying to perform an update query on a table that its on a separate database, so far i have this SQL:
UPDATE [;database=C:\QA_Daily_YTD_Report_Export.accdb].[YTD-Daily_Report] AS EXT_DB
SET EXT_DB.Category1 = "1"
WHERE (EXT_DB.Category1 = "status1");
When i run this it returns an "invalid operation" error. Any idea what im doing wrong?
I would recommend linking the table [YTD-Daily_Report] into your database because you can easily put the update query into your code without having your code execute the connection to the other database.
You can link a table in Access by clicking on the External Data. Then click on the Access symbol.
You should then get a dialog box like this:
Be sure you choose the second radio button because you don't want to import the data from the database, just link it.
Navigate to the location of the Database and click on it. Then make sure your database is shown in the dialog box above and click okay.
You should then get a dialog box like this one that will show the table you won't. Highlight it and click okay. Now you can rename the linked table with any name you want and this will be a much less of a stumbling block for your work.
Try to omit ;database=
UPDATE [C:\QA_Daily_YTD_Report_Export.accdb].[YTD-Daily_Report] AS EXT_DB SET EXT_DB.Category1 = "1" WHERE (EXT_DB.Category1 = "status1");
I ended up using VBA in a form, just in case someone is wondering how here it is:
Dim SQL As String
Dim db_external As Database
Set db_external = OpenDatabase(CurrentProject.Path & "\QA_Daily_YTD_Report_Export.accdb")
SQL = "UPDATE [YTD-Daily_Report]" & Chr(13) & _
"SET [YTD-Daily_Report].Category1 = '" & New_value & "'" & Chr(13) & _
"WHERE ([YTD-Daily_Report].Category1= '" & Look_up_value & "');"
db_external.Execute SQL

How to stop Access from thinking my table.field in VBA is a form component?

So I'm writing a SQL query in VBA in Access 2010, and when this code is ran, it thinks that SupplierConnect.MailboxID is a component on a form, where it is in fact a database table (SupplierConnect) and field (MailboxID). Every time that code is ran it pops up a box asking me for input from that form component, which actually isn't one. Is there any way to get around this or code this differently?
Thanks!
' Mailbox ID
If IsNull(MailboxIDComboBox.Value) Then
Else
If firstWhere = True Then
MailboxID = "WHERE SupplierConnect.MailboxID = '" & [Forms]![SupplierQuery]!MailboxIDComboBox.Value & "'"
firstWhere = False
Else
MailboxID = " AND SupplierConnect.MailboxID = '" & [Forms]![SupplierQuery]!MailboxIDComboBox.Value & "'"
End If
End If
This is not popping up asking you for this value because it thinks it is a form control, it is because it is undefined to the query. It cannot find the field within query definition. This usually happens because you do not have the proper case sensitive table or field id or the incorrect table is linked. If you provided more code for the SQL statement you are using from beginning to end and your Exact table structure we can narrow down the mistake.

Access VBA set variable to string "Yes" not -1

I am using Access to import information from Excel and then cycle through the data. I do not have control of the information that is in the Excel document. The Excel document is used for performing audits and I am doing reporting on the results. Recently a change was made so that some of the answers are no longer Yes/No. Answer may be "No - Document missing". I created a table that stores Yes/No/NA responses to be able to capture these changes however I now have stumbled upon an issue.
yText = Nz(Dlookup("yText","tblQuestions","Group = '" & group & "' AND Question = " & qID), "Yes")
The yText is used in a dynamic SQL string so because that value stored in the field will be 'Yes' as a string I need yText to equal 'Yes' but instead VBA changes yText = -1. The same issue occurs with nText = 'No'. Is there any way to prevent this behavior?
You can use Format within DlookUp:
Format(yText,"Yes/No")
Dlookup("Format(yText,'Yes/No')","tblQuestions","Group = '" _
& group & "' AND Question = " & qID)