Access Run-Time error 2465. Can't find the field '1' referred to in your expression - sql

I need help with this code.
Option Compare Database
Option Explicit
Private Sub BTNSEARCHOnetoOne_Click()
Dim SQL As String
SQL = "SELECT [00_SheetList-Revit-UNION].PACKAGE, [00_SheetList-Revit-UNION].DRAWING, [00_SheetList-Revit-UNION].DISCIPLINE, Hillsboro_OR_xlsx.FileName_Hillsboro_OR, Hillsboro_OR_xlsx.FilePath_Hillsboro_OR FROM Hillsboro_OR_xlsx, WHERE(([00_SheetList-Revit-UNION].PACKAGE) Like '" & Me.TXTKeywordsPackage & "') AND ((Hillsboro_OR_xlsx.FileName_Hillsboro_OR) Like ('*" & ([00_SheetList-Revit-UNION].DRAWING) & "*')"
Me.SubONEtoONEInsideJoin.Form.RecordSource = SQL
Me.SubONEtoONEInsideJoin.Form.Requery
Me.SubONEtoONENullJoin.Form.Requery
End Sub
Private Sub Detail_Click()
End Sub
I narrowed it down to this part of the code.
"...((Hillsboro_OR_xlsx.FileName_Hillsboro_OR) Like ('*" & ([00_SheetList-Revit-UNION].DRAWING) & "*')"
As I can take this part out and it works. Is this just syntax?

Currently, your SQL has a number of syntax issues:
Comma before WHERE clause;
Unclosed parentheses in last WHERE condition;
Unknown alias ([00_SheetList-Revit-UNION]) not referenced in FROM or JOIN clauses. Possibly you meant to cross join this source with Hillsboro_OR_xlsx.
See issues with current code with line breaks for illustration:
SQL = "SELECT [00_SheetList-Revit-UNION].PACKAGE," _
& " [00_SheetList-Revit-UNION].DRAWING," _
& " [00_SheetList-Revit-UNION].DISCIPLINE," _
& " Hillsboro_OR_xlsx.FileName_Hillsboro_OR, " _
& " Hillsboro_OR_xlsx.FilePath_Hillsboro_OR " _
& " FROM Hillsboro_OR_xlsx, " _
& " WHERE(([00_SheetList-Revit-UNION].PACKAGE) " _
& " Like '" & Me.TXTKeywordsPackage & "') " _
& " AND " _
& " ((Hillsboro_OR_xlsx.FileName_Hillsboro_OR) " _
& " Like ('*" & ([00_SheetList-Revit-UNION].DRAWING) & "*')"
These issues can be mitigated with parameterized queries (an industry best practice when writing SQL in application code) which is supported in MS Access using QueryDef Parameters. Below are a few advantages and further below adjustment to your setup.
Saving a stored query instead of a VBA string query allows it is to be optimized by engine and the Access GUI will not allow query to be saved with syntax issues;
Abstract data from code, specifically VBA variables from SQL statement;
Readability and maintainability is enhanced.
SQL (with no VBA)
Save below as a stored Access query, using parameters and table aliases. Also, [00_SheetList-Revit-UNION] is cross joined (comma-separated in FROM clause) as assumed above.
PARAMETERS [PackageParam] Text;
SELECT o.PACKAGE, o.DRAWING, o.DISCIPLINE,
h.FileName_Hillsboro_OR, h.FilePath_Hillsboro_OR
FROM Hillsboro_OR_xlsx h, [00_SheetList-Revit-UNION] o
WHERE ((o.PACKAGE) Like [PackageParam])
AND ((h.FileName_Hillsboro_OR) Like '*' & o.DRAWING & '*');
VBA
Private Sub BTNSEARCHOnetoOne_Click()
Dim qDef As QueryDef
Dim rst As Recordset
' OPEN SAVED QUERY
Set qDef = CurrentDb.QueryDefs("mySavedQuery")
' BIND PARAMETERS
qDef![PackageParam] = "*" & Me.TXTKeywordsPackage & "*"
' BUILD RECORDSET FROM QUERYDEF AND SET TO SUBFORM
Set rst = qDef.OpenRecordset()
Me.SubONEtoONEInsideJoin.Form.Recordset = rst
Me.SubONEtoONENullJoin.Form.Requery
Set qDef = Nothing
End Sub

It looks like that you had something wrong here
you have written
Like '" & Me.TXTKeywordsPackage & "'
but it has to be like this
Like '*" & Me.TXTKeywordsPackage & "*'
you had this part wrong
check this below part
Like ('*" & ([00_SheetList-Revit-UNION].DRAWING) & "*')
Make sure that you are getting the value from textbox. It looks like you are calling table column.

Carefully count your parenthesis.
There should be an additional ) at the very end.

Related

Access Compile error: Type mismatch on SQL Recordset Query

I've been chasing my tail on this SQL query for a record set. If I comment the query out, I do not receive the type mismatch error, so I'm relatively confident it is in this query. The query also works just fine in the Query window in Access (sans the quotes for getting it into VBA). I cannot, for the life of me, figure out why I'm getting a Compile error: Type mismatch on this. It always goes to the last '&'. I think I posted all the relevant code below. Please help? I do intend to move this to a string variable in the end, but I want to get it working first.
edit: I can address the type mismatch by making the change noted below. However, now I get a 424 error. If I output this to a debug window and paste the output into an SQL query window in access, I get the result I expect, but VBA doesn't like it for some reason.
Dim rs As DAO.Recordset
Dim FileNumber As String
FileNumber = Me.txtFileNumber
Set rs = "SELECT tblParentRecord.FileNumber, tblChildRecord.CombinedName " _
& " FROM tblParentRecord INNER JOIN tblChildRecord ON tblParentRecord.FileNumber = tblChildRecord.FileNumber " _
Added: & " WHERE (((tblParentRecord.FileNumber)= " & """" & Me.FileNumber & """" & ")) "
Removed:& " WHERE (((tblParentRecord.FileNumber) LIKE'" & FileNumber & "*" & "'))')
Try,
Dim rs As Recordset
Dim db As Database
Dim FileNumber As String
Set db = CurrentDb
FileNumber = Me.txtFileNumber
strSql = "SELECT tblParentRecord.FileNumber, tblChildRecord.CombinedName " _
& " FROM tblParentRecord INNER JOIN tblChildRecord ON tblParentRecord.FileNumber = tblChildRecord.FileNumber " _
& " WHERE tblParentRecord.FileNumber Like '" & FileNumber & "' "
Set rs = db.OpenRecordset(strSql)

Microsoft Access passing variables to VB from Form

I built a form with 2 combo boxes, one for Event and one for People. The two queries for the boxes include the Event_id and People_id but are not shown. The idea is to select the event from a drop down then add a person to attend the event. My problem is passing these two ID to the SQL update script.
Below is the VB; I receive a 424 error and calls the SQL as the area.
What's wrong?
Private Sub Command15_Click()
Dim dbs As DAO.Database, sql As String, rCount As Integer
Set dbs = CurrentDb
sql = "INSERT INTO Whos_Going (Event_ID, Who_is_invited) " _
& "VALUES(" & Event_id.Text & ", " & People_id.Text & ")"
dbs.Execute sql, dbFailOnError
rCount = dbs.RecordsAffected
If rCount > 0 Then
MsgBox "Person Added to Event"
'update listbox
conInfo.Requery
End If
End Sub
With VBA you need to construct the valid sql statement. All string literals must be enclosed into ', all dates must be enclosed into #. In addition to that, if your string variable contains an apostrophe it needs to be replaced with ''. The correct syntax will be:
sql = "INSERT INTO Whos_Going (Event_ID, Who_is_invited) " _
& "VALUES('" & Replace(Event_id.Text, "'", "''") & "', '" _
& Replace(People_id.Text, "'", "''") & "')"

Using an ADODB record set to perform a joined update query

In the following code, I would like to join ADODB record set 'rs3' to table 'tblValueChain10' and update 3 different columns based on the values extracted in the ADODB record set 'rs3'. Currently, the update query is not returning anything.
Dim st_Sql3 As String
Dim rs3 As ADODB.Recordset
Set rs3 = New ADODB.Recordset
Dim Max3 As Integer
rs3.Open "SELECT tblRisk05Holding.IDMacroProcesso01, tblRisk05Holding.Level01Risk, Max(tblRisk05Holding.ManualityStatus) AS MaxDiManualityStatus, Max(tblRisk05Holding.RiskProbabilityStatus) AS MaxDiRiskProbabilityStatus, Max(tblRisk05Holding.RiskExposureStatus) AS MaxDiRiskExposureStatus FROM tblRisk05Holding GROUP BY tblRisk05Holding.IDMacroProcesso01, tblRisk05Holding.Level01Risk", CurrentProject.Connection
st_Sql3 = "UPDATE tblValueChain10 INNER JOIN rs3 ON (tblValueChain10.IDMacroProcesso01 = tblRisk05Holding.IDMacroProcesso01) SET L1RiskManuality = " & rs3.Fields(2) & ", L1RiskProbability = " & rs3.Fields(3) & ", L1RiskGravity = " & rs3.Fields(4) & ""
Application.DoCmd.RunSQL (st_Sql2)
rs3.Close
Set rs3 = Nothing
Access never allows you to use a recordset object as a data source in another query. It doesn't matter whether you have an ADO or DAO recordset; you can't do it. And the query type (SELECT, UPDATE, INSERT, etc.) also doesn't matter; you can't use a recordset object as a data source in any query type.
You might get a workable UPDATE by first saving your SELECT statement as a named query, qryRS3. Then revise the UPDATE to INNER JOIN tblValueChain10 to qryRS3. But I'm uncertain whether Access would consider that query to be updatable; the GROUP BY might cause Access to treat it as not updatable. You'll have to test to see.
Although the goal you try to achieve using ADO Recordset in the way presented can't be done (as user #HansUp wrote), you could try the approach with updating your table tblValueChain10 using subquery taken from the rs3 recordset open call.
I hope that the following query :
UPDATE
tblValueChain10
INNER JOIN
(
SELECT
tblRisk05Holding.IDMacroProcesso01,
tblRisk05Holding.Level01Risk,
Max(tblRisk05Holding.ManualityStatus) AS MaxDiManualityStatus,
Max(tblRisk05Holding.RiskProbabilityStatus) AS MaxDiRiskProbabilityStatus,
Max(tblRisk05Holding.RiskExposureStatus) AS MaxDiRiskExposureStatus
FROM
tblRisk05Holding
GROUP BY
tblRisk05Holding.IDMacroProcesso01,
tblRisk05Holding.Level01Risk
) AS qry_Risk05Holding
ON (tblValueChain10.IDMacroProcesso01 = qry_Risk05Holding.IDMacroProcesso01)
SET
tblValueChain10.L1RiskManuality = qry_Risk05Holding.MaxDiManualityStatus,
tblValueChain10.L1RiskProbability = qry_Risk05Holding.MaxDiRiskProbabilityStatus,
tblValueChain10.L1RiskGravity = qry_Risk05Holding.MaxDiRiskExposureStatus
could help you solve your problem.
You should be able to run the above SQL with the following code:
Dim st_Sql3 As String
st_Sql3 = " UPDATE tblValueChain10 INNER JOIN ( "
st_Sql3 = st_Sql3 & " SELECT " _
& " tblRisk05Holding.IDMacroProcesso01, " _
& " tblRisk05Holding.Level01Risk, " _
& " Max(tblRisk05Holding.ManualityStatus) AS MaxDiManualityStatus, " _
& " Max(tblRisk05Holding.RiskProbabilityStatus) AS MaxDiRiskProbabilityStatus, " _
& " Max(tblRisk05Holding.RiskExposureStatus) AS MaxDiRiskExposureStatus "
st_Sql3 = st_Sql3 & " FROM " _
& " tblRisk05Holding " _
& " GROUP BY " _
& " tblRisk05Holding.IDMacroProcesso01, " _
& " tblRisk05Holding.Level01Risk "
st_Sql3 = st_Sql3 & " ) AS qry_Risk05Holding " _
& " ON (tblValueChain10.IDMacroProcesso01 = qry_Risk05Holding.IDMacroProcesso01) " _
& " SET " _
& " tblValueChain10.L1RiskManuality = qry_Risk05Holding.MaxDiManualityStatus, " _
& " tblValueChain10.L1RiskProbability = qry_Risk05Holding.MaxDiRiskProbabilityStatus, " _
& " tblValueChain10.L1RiskGravity = qry_Risk05Holding.MaxDiRiskExposureStatus "
Application.DoCmd.RunSQL (st_Sql3)
The query is being built-up in four stages because as far as I remember there is a restriction in VBA that there can't be too many line breaks _.
Please notice also that the JOIN used in the update query assumes that connecting two tables by IDMacroProcesso01 would ensure that the records are updated in the right way.
I can't check the solution in Acces right now but maybe it could somehow help you, at least a concept. If there were any errors, please write.
You need to loop through the recordset to iteratively update by each record:
Do While NOT rs3.EOF
st_Sql3 = "UPDATE tblValueChain10"_
& " INNER JOIN rs3 ON (tblValueChain10.IDMacroProcesso01 = tblRisk05Holding.IDMacroProcesso01)" _
& " SET L1RiskManuality = " & rs3.Fields(2) & ", L1RiskProbability = " & rs3.Fields(3) & "," _
& " L1RiskGravity = " & rs3.Fields(4) & ""
DoCmd.RunSQL (st_Sql3)
rs3.MoveNext
Loop
Also please note, your RunSQL () command is calling the incorrect SQL string.
If no err appears, then try to place this code:
Set rs3 = New ADODB.Recordset
in form_load, as in,
private sub Form_load()
Set rs3 = New ADODB.Recordset
End Sub
note: this sample is in vb6.0. that's what I can do. Besides, check the version in references

Using Cell reference in SQL query

I am using below VBA command to extract data using a SQL query by using a cell reference as filter.
Public Sub Run()
Dim SQL As String
Dim Connected As Boolean
Dim server_name As String
Dim database_name As String
Dim Allocation As String
Sheets("Perc").Select
Range("A6").Select
Selection.CurrentRegion.Select
Selection.ClearContents
' Our query
SQL = "SELECT Segmentation_ID,MPG,SUM(Segmentation_Percent) AS PERC " & _
"FROM dbo.HFM_ALLOCATION_RATIO " & _
"WHERE Segmentation_ID = " & Sheets("Perc").Range("A1").Value & " " & _
"GROUP BY Segmentation_ID,MPG ORDER BY MPG"
' Connect to the database
server_name = Sheets("General").Range("D1").Value
database_name = Sheets("General").Range("G1").Value
Connected = Connect(server_name, database_name)
If Connected Then
' If connected run query and disconnect
Call Query(SQL)
Call Disconnect
Else
' Couldn't connect
MsgBox "Could Not Connect!"
End If
End Sub
But when I run the macro, it's showing a runtime error
Invalid column name ALO0000274
Here ALO0000274 is the filter I set in A1.
Kindly help to fix this error.
Add quotes to your where clause (you're passing a text value, so you need to include quotes):
SQL = "SELECT Segmentation_ID,MPG,SUM(Segmentation_Percent) AS PERC " & _
"FROM dbo.HFM_ALLOCATION_RATIO " & _
"WHERE Segmentation_ID = '" & Sheets("Perc").Range("A1").Value & "' " & _
"GROUP BY Segmentation_ID,MPG ORDER BY MPG"
(Note the single quotes ' that enclose the value you want to filter)
I don't see where you are adding your single quotes around your string. Have you tried changing your WHERE clause portion of your SQL statement to "WHERE Segmentation_ID = '" & Sheets("Perc").Range("A1").Value & "' "

Access 2010 VBA Too few parameters: Expected 3

In VBA for Access 2010 and I am just trying to insert some data into a subform. I have a form, with 3 subforms on it. I have 3 unbound text boxes that the user will enter data, hit a command button, and then that data will instert into the subform I have on the layout. Here is my code:
Private Sub cmdAssign_Click()
CurrentDb.Execute " INSERT INTO Crew " _
& "(txtCrewName,txtKitNumber,txtActionDate) VALUES " _
& "(txtAssignCrew, txtAssignKit, txtAssignDate);"
End Sub
I know it has got to be something simple but I'm not really familiar with this. The txtCrewName, txtKitNumber, and txtActionDate are the empty values in the subform where I want data to go. And the txtAssignCrew, txtAssignKit, and txtAssignDate are the unbounds on the form, but outside of the subform 'Crew'. Any ideas? Thanks
EDIT: Figured it out. Thank you all for the help
So txtAssignCrew, txtAssignKit, and txtAssignDate are the names of controls on the form. The db engine doesn't know what they are, so assumes they must be parameters.
You could build those controls' values (instead of the controls' names) into your INSERT statement. But consider an actual parameter query instead, and execute it from a QueryDef object.
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim strInsert As String
strInsert = "PARAMETERS crew_name Text(255), kit_num Long, action_date DateTime;" & vbCrLf & _
"INSERT INTO Crew (txtCrewName,txtKitNumber,txtActionDate)" & vbCrLf & _
"VALUES (crew_name, kit_num, action_date);"
Debug.Print "strInsert:" & vbCrLf & strInsert
Set db = CurrentDb
Set qdf = db.CreateQueryDef("", strInsert)
qdf.Parameters("crew_name") = Me.txtAssignCrew
qdf.Parameters("kit_num") = Me.txtAssignKit
qdf.Parameters("action_date") = Me.txtAssignDate
qdf.Execute dbFailOnError
Set qdf = Nothing
Set db = Nothing
Note, in the PARAMETERS clause I assumed text as the data type for txtCrewName, long integer for txtKitNumber, and Date/Time for txtActionDate. If all are text, adjust the PARAMETERS clause.
This should work, assuming txtAssignCrew, Kit, and Date are your unbound controls you want to insert. Realize that if there are single quotes or anything in those fields, it would cause the statement to fail, so you would need to escape them.
Private Sub cmdAssign_Click()
CurrentDb.Execute " INSERT INTO Crew " _
& "(txtCrewName,txtKitNumber,txtActionDate) VALUES " _
& "('" & me.txtAssignCrew & "', '" & me.txtAssignKit & "','" & me.txtAssignDate & ");"
End Sub
I may have botched a quote.
Corrected code:
CurrentDb.Execute " INSERT INTO Crew " _
& "(txtCrewName,txtKitNumber,txtActionDate) VALUES " _
& "('" & txtAssignCrew & "','" & txtAssignKit & "','" & txtAssignDate & ");"
Notes:
- You might need to change the format for the AssignDate parameter
- Column names in the database are usually not prefixed with txt
- You would be better off using parametized queries to avoid SQL injection attacks