I made a SQL statement in the add/update button in the query wizard I changed it back to SQL view to see how the program made me the code and when I copy and paste the same error on the If statement of the btnAdd it throws me a syntax error, but how?
here is the entire code:
Private Sub cmdAdd_Click()
'In the button add we have two options
'1. Insert
'2. Update
If Me.txtID.Tag & "" = "" Then
CurrentDb.Execute "INSERT INTO tblClients ( ClientID, ClientName, Gender, " & _
"City, [Address (Fisical)], [Cellphone/Telephone] ) " & _
"SELECT " & Me.txtID & ",'" & Me.txtName & "','" & Me.cboGender & "', '" & Me.cboCity & "','" & Me.txtAddress & "','" & Me.txtCellphone & "'"
Else
'Otherwise the data will be updated
CurrentDb.Execute "UPDATE tblClients SET tblClients.ClientName = [me]. [txtName], tblClients.Gender = [me].[cboGender], tblClients.City = [me].[cboCity], tblClients.[Address (Fisical)] = [me].[txtAddress], tblClients.[Cellphone/Telephone] = [me].[txtCellphone] "
WHERE (([ClientID]=[Me].[txtID].[Tag]));
End If
cmdClear_Click
tblClients_subform.Form.Requery
End Sub
it highlights me this row in red:
WHERE (([ClientID]=[Me].[txtID].[Tag]));
It appears that the following code is not on the same line
CurrentDb.Execute "UPDATE tblClients SET tblClients.ClientName = [me]. [txtName], tblClients.Gender = [me].[cboGender], tblClients.City = [me].[cboCity], tblClients.[Address (Fisical)] = [me].[txtAddress], tblClients.[Cellphone/Telephone] = [me].[txtCellphone] "
WHERE (([ClientID]=[Me].[txtID].[Tag]))
So you may want to change it to
CurrentDb.Execute "UPDATE tblClients SET tblClients.ClientName = [me]. [txtName], tblClients.Gender = [me].[cboGender], tblClients.City = [me].[cboCity], tblClients.[Address (Fisical)] = [me].[txtAddress], tblClients.[Cellphone/Telephone] = [me].[txtCellphone] " & _
"WHERE (([ClientID]=[Me].[txtID].[Tag]))"
In addition to Cableload's correct answer where the WHERE statement that was on a new code line was not connected to the previous line by the use of an underscore at the end of the first one, there is still a referncing issue.
You are referencing values in a UserForm like that were columns in a table so it is not finding the value you are looking for. To get the value into the SQL statement you need to come out of the literal string, reference the value, and then continue writing the string (not forgetting to enclose the value with '): -
CurrentDb.Execute "UPDATE tblClients SET " & _
"[ClientName] = '" & Me.txtName & "', " & _
"[Gender] = '" & Me.cboGender & "', " & _
"[City] = '" & Me.cboCity & "', " & _
"[Address (Fisical)] = '" & Me.txtAddress & "', " & _
"[Cellphone/Telephone] = '" & Me.txtCellphone & "' " & _
"WHERE [ClientID]=" & Me.txtID.Tag
I have spread it across multiple lines for ease of reading but obviously you can adjust your actual code however needed.
I would also question [ClientID]=" & Me.txtID.Tag, is the ClientID in the in the txtID.value or the txtID.Tag, they are different places. The value property is the value in the text box, the Tag property is more like a area for metadata that you can populate if needed but is not automatically populated by default.
Finally I'd like to refer you back to an answer to a previous question you had, at the bottom of the answer there was a tip about placing the resultant query into a Access Query in SQL view to get better information on the error, that would have helped you here too. To give further assistance on the 'resultant query'.
In debug mode before the while the CurrentDb.Execute is highlighted but before it is run (using F8 to step through each line until you get there, or placing a breakpoint on that line
Open the the Immediate Window if it is not already open (either Ctrl+G to from the menu bar 'View' > 'Immediate Window')
Copy all related code from the line after the CurrentDb.Execute statement, in this case it would be UPDATE ... .Tag
In the immediate window type a question mark and then paste in the rleated code and press enter
The immediate window will return the resultant string for you to try in a Query in SQL view.
Change the SELECT keyword to VALUES in your INSERT statement.
CurrentDb.Execute "INSERT INTO tblClients ( ClientID, ClientName, Gender, " & _
"City, [Address (Fisical)], [Cellphone/Telephone] ) " & _
"VALUES (" & Me.txtID & ",'" & Me.txtName & "','" & Me.cboGender & "', '" & Me.cboCity & "','" & Me.txtAddress & "','" & Me.txtCellphone & "')"
And the UPDATE should be this. The issue here was that you were trying to use Form controls in the SQL, but you needed to evaluate the controls first then concatenate their values to your literal string.
I'm wondering if you really need Me.txtID instead of Me.txtID.Tag
So sway that out if it doesn't work.
CurrentDb.Execute "UPDATE tblClients SET tblClients.ClientName = '" & me.txtName & "', tblClients.Gender = '" & me.cboGender & "', tblClients.City = '" & me.cboCity & "', tblClients.[Address (Fisical)] = '" & me.txtAddress & "', tblClients.[Cellphone/Telephone] = '" & me.txtCellphone & "' WHERE (([ClientID]=" & Me.txtID.Tag & "));"
Related
I'm running an SQL query through VB in Microsoft Access for form to add records to a table. However, it keeps asking me to insert parameter value, when they are already present in the form.
Private Sub AddPart_Click()
Dim strSQL As String
strSQL = "INSERT INTO Part VALUES (" & Me.IdPartPrimary.Value & ", " & Me.NamePartPrimary.Value & ", " & Me.BrandPartPrimary.Value & ", " & Me.ModelPartPrimary.Value & ", " & Me.FunctionPartPrimary.Value & ", -1, " & Me.FatherPartPrimary.Value & ", " & Me.ProviderPartPrimary.Value & ", " & Me.AmountPartPrimary.Value & ");"
DoCmd.RunSQL strSQL
End Sub
I already checked for spelling mistakes and there were none. Also, this happens with every field. If I don't insert a parameter value and cancel instead, the record still gets added, only after I close and reopen the table lots of times.
If fields are text type, need text delimiters - apostrophe will serve. I assume comboboxes have a number value from a hidden foreign key column. Value property does not need to be specified as it is the default.
With Me
strSQL = "INSERT INTO Part " & _
" VALUES (" & .IdPartPrimary & ", '" & _
.NamePartPrimary & "', '" & .BrandPartPrimary & "', '" & _
.ModelPartPrimary & "', '" & .FunctionPartPrimary & "', -1, " & _
.FatherPartPrimary & ", " & .ProviderPartPrimary & ", " & .AmountPartPrimary & ")"
End With
AFAIK, Access cannot execute multi-action SQL statements but SQL injection is still possible. If you want to explore use of Parameters in VBA, review How do I use parameters in VBA in the different contexts in Microsoft Access?
Another alternative to avoid SQL injection is to open a recordset, use its AddNew method to create a new record, and set value of each field. DAO.Recordset AddNew
I have a textbox in a form. I use this textbox to write "Codes" and then I save it in the table in the database through the SQL insert statement, but the code doesn't accept to run and gives me an error message:
Run-Time error '3075'.
type of database: Access database
type of field data: LongText
What the problem and how to pass all same problems when I need to save codes inside the database field.
When I try to save the code without (') it's working!
I use this SQL Statement:
CurrentDb.Execute "Update Tbl_Codes Set [LP_ID]= " & Me.txtID & ",
[Code_Title]='" & Me.txtTitle & "'" _
& " ,[Code_Des]= '" & Me.txtDes & "',[Code_Key]= '" & Me.txtKey & "',
[Notes]= '" & Me.txtNotes & "'" _
& " Where [ID]= " & Me.txtID1 & ""
And I want to save this Code:
DSum("Field1";"Table";"Field2= '" & Value & "'")
Please change your code as follows. You need to escape single quotes by doubling them up. A simple replace will work for your.
CurrentDb.Execute "Update Tbl_Codes Set [LP_ID]= " & Replace(Me.txtID,"'","''") & ",
[Code_Title]='" & Replace(Me.txtTitle,"'","''") & "'" _
& " ,[Code_Des]= '" & Replace(Me.txtDes,"'","''") & "',[Code_Key]= '" & Replace(Me.txtKey,"'","''") & "',
[Notes]= '" & Replace(Me.txtNotes,"'","''") & "'" _
& " Where [ID]= " & Me.txtID1 & ""
DSum("Field1";"Table";"Field2= '" & Replace(Value,"'","''") & "'")
I have limited experience with Access. I followed some YouTube tutorials and made a functioning DB a couple of months ago.
I adapted the first DB, which essentially is changing the field names in the table in the Access file.
I can't get the new DB to function. I have a form with a subtable of the main table and it has a few text fields to fill in with the information to input. Then it has a few buttons to the side that either Add to the table, Delete from the table, Clear the text fields, Close the form, Edit a selected field, and then the Add button changes to Update after you Edit a field so that you can click Update to update the selected field after you've made changes to it.
All of this works in my first DB and in theory it should work exactly the same after changing the field names in the new DB and the corresponding txt field names and so on. I am having a tough time getting it to work for Add, Update, or Delete.
The error on the Add is Run time error "3134" Syntax error in INSERT INTO statement.
The Update and Delete error is run time error '3061' Too few parameters. expected 1.
The Clear works, as well as the Close and Edit.
Here is the code:
Option Compare Database
Private Sub cmdAdd_Click()
'when we click on button Add there are two options
'1. for insert
'2. for update
If Me.txtICN.Tag & "" = "" Then
'this is for insert new
'add data to table
CurrentDb.Execute "INSERT INTO tblInventory(ICN, manu, modelNum, serialNum, descr, dateRec, projectNum, dispo, flgDispo, dateRemoved, comments)" & _
" VALUES(" & Me.txtICN & ", '" & Me.txtManu & "', '" & Me.txtModel & "', '" & Me.txtSerial & "', '" & Me.txtDescrip & "', '" & Me.txtDateRec & "', '" & Me.txtProjectNum & "', '" & Me.txtDispo & "', '" & Me.chkFlag & "', '" & Me.txtDateRemoved & "', '" & Me.txtComments & "')"
Else
'otherwise (Tag of txtICN store the Lab Inventory Control Number to be modified)
CurrentDb.Execute "UPDATE tblInventory " & _
" SET ICN = " & Me.txtICN & _
", manu = '" & Me.txtManu & "'" & _
", modelNum = '" & Me.txtModel & "'" & _
", serialNum = '" & Me.txtSerial & "'" & _
", descr = '" & Me.txtDescrip & "'" & _
", dateRec = '" & Me.txtDateRec & "'" & _
", projectNum = '" & Me.txtProjectNum & "'" & _
", dispo = '" & Me.txtDispo & "'" & _
", flgDispo = '" & Me.chkFlag & "'" & _
", dateRemoved = '" & Me.txtDateRemoved & "'" & _
", comments = '" & Me.txtComments & "'" & _
" WHERE ICN = " & Me.txtICN.Tag
End If
'clear form
cmdClear_Click
'refresh data in list on form
tblInventorySub.Form.Requery
End Sub
Private Sub cmdClear_Click()
Me.txtICN = ""
Me.txtManu = ""
Me.txtModel = ""
Me.txtSerial = ""
Me.txtDescrip = ""
Me.txtDateRec = ""
Me.txtProjectNum = ""
Me.txtDispo = ""
Me.chkFlag = ""
Me.txtDateRemoved = ""
Me.txtComments = ""
'focus on ICN text box
Me.txtICN.SetFocus
'set button edit to enable
Me.cmdEdit.Enabled = True
'change caption of button add to Add
Me.cmdAdd.Caption = "Add"
'clear tag on txtICN for reset new
Me.txtICN.Tag = ""
End Sub
Private Sub cmdClose_Click()
DoCmd.Close
End Sub
Private Sub cmdDelete_Click()
'delete record
'check existing selected record
If Not (Me.tblInventorySub.Form.Recordset.EOF And Me.tblInventorySub.Form.Recordset.BOF) Then
'confirm delete
If MsgBox("Are you sure you want to delete this inventory entry?", vbYesNo) = vbYes Then
'delete now
CurrentDb.Execute "DELETE FROM tblInventory " & _
"WHERE ICN = " & Me.tblInventorySub.Form.Recordset.Fields("ICN")
'refresh data in list
Me.tblInventorySub.Form.Requery
End If
End If
End Sub
Private Sub cmdEdit_Click()
'check whether there exists data in list
If Not (Me.tblInventorySub.Form.Recordset.EOF And Me.tblInventorySub.Form.Recordset.BOF) Then
'get data to text box control
With Me.tblInventorySub.Form.Recordset
Me.txtICN = .Fields("ICN")
Me.txtManu = .Fields("manu")
Me.txtModel = .Fields("modelNum")
Me.txtSerial = .Fields("serialNum")
Me.txtDescrip = .Fields("descr")
Me.txtDateRec = .Fields("dateRec")
Me.txtProjectNum = .Fields("projectNum")
Me.txtDispo = .Fields("dispo")
Me.chkFlag = .Fields("flgDispo")
Me.txtDateRemoved = .Fields("dateRemoved")
Me.txtComments = .Fields("comments")
'store ICN in Tag of txtICN in case id is modified
Me.txtICN.Tag = .Fields("ICN")
'change caption of button add to Update
Me.cmdAdd.Caption = "Update"
'disable button edit
Me.cmdEdit.Enabled = False
End With
End If
End Sub
What data types are dateRec, flgDispo, dateRemoved? Values for DateTime fields must be delimited with # not '. Is flgDispo a Yes/No type? If so, this is numeric type field and number values do not have delimiters.
Why delete records? Do you really want to lose history? Why not just flag as 'Archived' or 'Inactive'? Deleting records should be a rare event.
I always give subform containers a name different from the object they hold, like ctrInventory:
CurrentDb.Execute "DELETE FROM tblInventory WHERE ICN = " & Me.ctrInventory!ICN
First, all your date expressions must be formatted like this:
", dateRec = #" & Format(Me.txtDateRec.Value, "yyyy\/mm\/dd") & "#" & _
or you could apply my CSql function to handle all this:
Convert a value of any type to its string representation
However, it appears that you could make life much easier for yourself by simply binding your form to the table - and then remove all of this code as the form will handle edit, insert, and delete automatically.
Having the weirdest problem ever. I do have an sql insert statement, that properly works in sql. When i put that sql into vba it works very good from my pc. However, it does not work and shows sql error: missing comma. Where can be the problem??? I use Access 2010 plus, others use same Access version and having same ODB connections (DSN servers) . Some code example:
sql = "Driver={Microsoft ODBC for Oracle}; " & _
"CONNECTSTRING=(DESCRIPTION=" & _
"(ADDRESS=(PROTOCOL=TCP)" & _
"(HOST= ODB)(PORT=1520))" & _
"(CONNECT_DATA=(SERVICE_NAME=ABTL))); uid=IN; pwd=XXX;"
Set con = New ADODB.Connection
Set rec = New ADODB.Recordset
Set cmd = New ADODB.Command
con.Open sql
Set db = CurrentDb()
Set rst = db.OpenRecordset(strSQL)
Do While Not rst.EOF
insetSQL = con.Execute(" INSERT INTO STOCK (PNM_AUTO_KEY, PN, DESCRIPTION, HISTORICAL_FLAG, qty_oh, qty_adj, qty_available, CTRL_NUMBER, CTRL_ID, receiver_number, rec_date, serial_number,pcc_auto_key, cnc_auto_key, loc_auto_key, whs_auto_key, unit_cost, adj_cost, stc_auto_key, visible_mkt, remarks, ifc_auto_key, exp_date, unit_price, tagged_by, tag_date, owner, PART_CERT_NUMBER,ORIGINAL_PO_NUMBER, SHELF_LIFE, CTS_AUTO_KEY, MFG_LOT_NUM, AIRWAY_BILL )" & _
" VALUES ( " & rst![minimumas] & ", '" & rst![pn] & "', '" & "FROM_SCRIPT" & "', '" & "F" & "'," & rst![qty_oh] & "," & rst![qty_oh] & "," & rst![qty_oh] & "," & "G_STM_CTRL_NUMBER.nextval" & "," & "1" & ", '" & rst![receiver_number] & "', " & " TO_DATE('" & rst![rec_date] & "','YYYY-MM-DD'), '" & rst![serial_number] & "'," & rst![pcc_auto_key] & "," & rst![cnc_auto_key] & "," & rst![loc_auto_key] & "," & rst![whs_auto_key] & "," & rst![unit_cost] & "," & rst![unit_cost] & "," & "1" & ",'" & "T" & "', '" & rst![remarks] & "'," & _
"1" & ", " & " TO_DATE('" & rst![exp_date] & "','YYYY-MM-DD'), " & "0" & ",'" & rst![TAGGED_BY] & "', " & " TO_DATE('" & rst![tag_date] & "','YYYY-MM-DD'), '" & "" & "', '" & rst![PART_CERT_NUMBER] & "', '" & rst![ORIGINAL_PO_NUMBER] & "', '" & rst![SHELF_LIFE] & "', " & rst![CERT_SOURCE] & ", '" & rst![MFG_LOT_NUM] & "', '" & rst![AIRWAY_BILL] & "'" & " )")
Loop
It might be that one of the rescordset fields that is a string data type, has a value that contains a comma but you have not treated it as string.
eg
VALUES ( " & rst![minimumas] & ",
For the above code to work minimumas CANNOT contain any commas.
Are you certain that all the string fields int he recordset have been appended to the SQL string with a ' around them.
We need to see the sql string is created which then causes the error. Please provide this as requested.
=========================================================
PART 2 Viewing the SQL causing the error
replace
insetSQL = con.Execute(
with
on error resume next
strMySQl = the string currently used in the execute statement
insetSQL = con.Execute(strMySQl)
if err.number <> 0 then
stop
debug.print err.number, err.description
debug.print strMySQl
end if
then post the sql string that is printed in the immediate window to this site.
I would also suggest that you compare the SQL string generated on your machine with the other machines - just in case something weird is happening.
I am trying to update a table using variables in VBA for Access. The statement is below.
DB.Execute "UPDATE tblSearchersList SET '" & vSearcherDay & "' = " & VHours & "
WHERE Member= '" & Me.cboMember.Column(1) & "'AND [Mission] = '" & Me.Mission & "'"
tblSearcherList is table to update
vSearcherDay is a variable that combines the letter "d" with a number, et(1,2,3,4,5) depending on other query
VHours is a decimal number (number of hours)
Member is a text value from Form Field Me.cboMember.Column(1)
Mission is a text value from form field Me.Mission
I get Runtime error 3061 - Too few parameters expected 2.
Hope I can get some help with this as I have been fighting it for awhile and am losing the battle.
Thanks
New code is this:
Sorry bout the comments thing. I am new and didn't quite know how to do this.
DB.Execute "UPDATE tblSearchersList SET " & vSearcherDay &_
" = " & VHours & " WHERE Member= '" & Me.cboMember.Column(1) & "' &_
" And [Mission] = '" & Me.Mission & "'"
I am quite embarrassed about this but I had the Member field name wrong. Should've been
MemberName instead. I really do appreciate all the quick help I got and will do better next time. It works perfectly. Thank you all.
Don't use apostrophes around field name. Instead
SET '" & vSearcherDay & "' = " &
do
SET " & vSearcherDay & " = " &