Access 2010 VBA Too few parameters: Expected 3 - sql

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

Related

ACCESS 365 and INSERT INTO not inserting data from FORM

I am updating a small medical database. So far all new products have been added manually / directly to a Products- table. I am creating a form to do that.
Even it is in a way very simple to do, I am facing up a problem that data is inserted correctly only if all fields have something typed in form, if any of the input boxes are left empty no new records are made.
Additionally a simple check for minimum fields is not working. It will step thru all controls correctly but does not stop even a field is left empty and its Tag has *-sign in it.
Insert into includes all fields which a defined in that table there is not any extra field in table except first field is autonumbered ID field. No need to type something in every field each time.
Pr
Private Function CheckAllFields() As Boolean
Dim Ctrl As Control
CheckAllFields = False
'Go through the controls in Form
'If control has tag (*) and it null (no value) then show alert
For Each Ctrl In Me.Controls
MsgBox Ctrl.Name
If Ctrl.Tag = "*" And IsNull(Ctrl) Then
Dim FieldName As String
FieldName = Ctrl.Name
'Show notification if field was not filled and move focus to that field
MsgBox "A required Field has not been filled."
Ctrl.SetFocus
CheckAllFields = True
Exit For
End If
Next Ctrl
MsgBox "Check fileds done"
End Function
Private Sub AddProduct_Click()
Dim strSQL As String
'SQL to insert Product
strSQL = "INSERT INTO Products([Product name],[Product description],[Finnish name],[Finnish description],[Matrix2012], " & _
"[Additional Info], [Unit], [Licence],[Remarks],Narcotic,[Asset], " & _
"[ATC], [Cathegory], [EIC code], [EIC name])" & _
" VALUES ('" & Me.txtProductName & "','" & Me.txtProductDesc & "','" & Me.txtFinnishName & "','" & Me.txtFinnishDesc & "','" & Me.ComboMatrix & "'," & _
"'" & Me.txtAdditionalInfo & "','" & Me.ComboUnit & "','" & Me.CheckLicense & "'," & _
"'" & Me.txtRemarks & "','" & Me.CheckNarcotic & "','" & Me.CheckAsset & "'," & _
"'" & Me.txtATC & "','" & Me.txtCathegory & "','" & Me.txtEICcode & "','" & Me.txtEICName & "')"
'' MsgBox strSQL
'Check the all fields have valid format
If CheckAllFields = False Then
'Execute SQL in database - insert new batch
' MsgBox "Step into Check all fields"
CurrentDb.Execute strSQL
MsgBox "A new product inserted !"
End If
Here is a debug output of my insert into command:
Debug output
Here is another output debug, now the new product is inserted correctly.
Correctly working version
Problem solved. As Craig pointed this way of incuding parameters is prone to fail.
Here is good way to solve this. Did not believe it but after I tried it worked ultimate.
MS access running SQL doesn't insert data, no error
strSQL = "INSERT INTO Products([Product name],[Product description],[Finnish name],[Finnish description],[Matrix2012], " & _
"[Additional Info], [Unit], [Licence],[Remarks],Narcotic,[Asset], " & _
"[ATC], [Cathegory], [EIC code], [EIC name])" & _
" VALUES (ptxtProductName, ptxtProductDesc,ptxtFinnishName,ptxtFinnishDesc,pComboMatrix, ptxtAdditionalInfo,pComboUnit, pCheckLicense, ptxtRemarks, pCheckNarcotic, pCheckAsset, ptxtATC, ptxtCathegory, ptxtEICCode, ptxtEICName);"
Set db = CurrentDb
Set qdf = db.CreateQueryDef(vbNullString, strSQL)
With qdf
.Parameters("ptxtProductName").Value = Me.txtProductName.Value
.Parameters("ptxtProductDesc").Value = Me.txtProductDesc.Value
.Parameters("ptxtFinnishName").Value = Me.txtFinnishName.Value
.Parameters("ptxtFinnishDesc").Value = Me.txtFinnishDesc.Value
.Parameters("pComboMatrix").Value = Me.ComboMatrix.Value
.Parameters("ptxtAdditionalInfo").Value = Me.txtAdditionalInfo.Value
.Parameters("pComboUnit").Value = Me.ComboUnit.Value
.Parameters("pCheckLicense").Value = Me.CheckLicense.Value
.Parameters("ptxtRemarks").Value = Me.txtRemarks.Value
.Parameters("pCheckNarcotic").Value = Me.CheckNarcotic.Value
.Parameters("pCheckAsset").Value = Me.CheckAsset.Value
.Parameters("ptxtATC").Value = Me.txtATC.Value
.Parameters("ptxtCathegory").Value = Me.txtCathegory.Value
.Parameters("ptxtEICCode").Value = Me.txtEICcode.Value
.Parameters("ptxtEICName").Value = Me.txtEICName.Value
.Execute dbFailOnError
End With
Debug.Print db.RecordsAffected
That check for empty fields is mystery, it works in another form so it has to be some sort of reference problem. Anyway to keep things simple this works perfectly:
If txtProductName.Value = "" Or ComboMatrix.Value = "" Or ComboUnit.Value = "" Then
'Show notification if field was not filled and move focus to that field
MsgBox "A required Field has not been filled."

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

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.

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, "'", "''") & "')"

ms access vba code for update records through form

I am new to MS Access 2007 & I know almost nothing about vba. ... I hv a table name F with fields F1, F2, F3, F4, F5 where 1st three are number fields & last two are text fields. In a form with textboxes: txtF1, txtF2, txtF3, txtF4, txtF5 and command button cmdUpdate, I want to update F5 in table F where F1=txtF1, F2=txtF2, F3=txtF3 and F4=txtF4 conditions staisfy. .. Kindly help with complete code.
In the cmdUpdate button's on click event, you need to place a procedure that will generate a sql command, then execute it.
Private Sub cmdUpdate_Click()
'Create a string variable to hold your sql command string
Dim strSQL As String
'Fill the variable with your sql command, plucking values out of your
'form as shown using the Me. operator. When using text values in your
'string, wrap them with the Chr(34)'s, which will insert quotation marks in
'your sql string when it's resolved.
strSQL = "UPDATE F SET F.F5 = " & Chr(34) & yourtextvaluehere & Chr(34) & _
" WHERE F1=" & Me.txtF1 & _
" AND F2=" & Me.txtF2 & _
" AND F3=" & Me.txtF3 & _
" AND F4=" & Chr(34) & Me.txtF4 & Chr(34)
'Execute the sql statement you've built against the database
CurrentDb.Execute strSQL, dbSeeChanges + dbFailOnError
End Sub

Access VBA - Identifying text

Im trying to create a button to delete certain records in a subform. However im getting "syntax error (missing operator) in query expression 'KEY_ID="1'.
I know what the problem is: The attribute is text therefore the value needs to be surrounded by single quotes. I just don't know how to write the VBA to accomplish this.
Private Sub cmdDelete_Click()
If Not (Me.subKey.Form.Recordset.EOF And Me.subKey.Form.Recordset.BOF) Then
If MsgBox("Confirm Deletion?", vbYesNo) = vbYes Then
Dim strSql As String
strSql = "DELETE FROM KEYS" & _
" WHERE KEY_ID='" & Me.subKey.Form.Recordset.Fields("KEY_ID")
Debug.Print strSql ' <- prints to Immediate window
CurrentDb.Execute strSql, dbFailOnError
End If
End If
strSql = "DELETE FROM KEYS" & _
" WHERE KEY_ID='" & Me.subKey.Form.Recordset.Fields("KEY_ID") & "'"
... though, mind you, using the quote as an ASCII character is safer, or at least more versatile or portable, when these kinds of things get more intensive.
strSql = "DELETE FROM KEYS" & _
" WHERE KEY_ID=" & _
Chr(32) & Me.subKey.Form.Recordset.Fields("KEY_ID") & Chr(32)
I'm not sure it's Chr(32) but I think that is correct.