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
Related
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,"'","''") & "'")
In MS Access 2010, I have the following query which randomly orders the data and puts it in a new sheet. Before I added in the WHERE, it was working, but now I get an error telling me:
Too few parameters: Expected 2.
Does anybody know how I could fix this?
sqlQuery = "SELECT [My_Sheet].* " & _
" INTO My_New_Sheet" & _
" FROM [My_Sheet] " & _
" WHERE [Some_Field] = [Some_Possible_Value_For_The_Field] " & _
" ORDER BY Rnd(-(100000*[Some_Other_Field])*Time())"
Debug.Print sqlQuery
CurrentDb.Execute sqlQuery
Where [Some_Possible_Value_For_The_Field] is comes from [My_Sheet]
Note that this is Access SQL
sqlQuery = "SELECT [My_Sheet].* " & _
" INTO My_New_Sheet" & _
" FROM [My_Sheet] " & _
" WHERE [Some_Field] = '" & [Some_Possible_Value_For_The_Field] & "'" & _
" ORDER BY Rnd(-(100000*" & [Some_Other_Field] & ")*Time())"
Debug.Print sqlQuery
CurrentDb.Execute sqlQuery
When you use a form variable, the value has to be read from outside of the SQL statement. Hence why we close the statement with double quote, add the field value, and then continue by opening the with a double quotes again.
Notice that you need to keep the field qualifiers. In this case I assumed your first field was a string which requires the single quote qualifiers and the second variable as an integer which doesn't require qualifiers.
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 & "));"
I have a macro that opens a MS Project file and copies the content itself in an Access table. I make it through Excel because afterwards I need to make some queries and copy the results into some cells.
This code below creates or drops the table:
Dim dbX As DAO.Database
If Err.Number = 0 Then
dbX.Execute ("DROP TABLE " & dbName & ";")
End If
dbX.Execute ("CREATE TABLE " & dbName & " ([ID] INTEGER, [TaskID] INTEGER, [Milestone] TEXT(3), [TaskName] TEXT(255), " & _
"[pComplete] TEXT(10), [Start] DATE, [Finish] DATE, [BaselineStart] DATE, [BaselineFinish] DATE, " & _
"[ActualStart] DATE, [ActualFinish] DATE);")
Err.Clear
This fills the table using the project fields:
dBquery = "INSERT INTO " & tName & "(ID, TaskID, Milestone, TaskName, pComplete, Start, Finish, BaselineStart, BaselineFinish, " & _
"ActualStart, ActualFinish)" & _
" VALUES (" & t.ID & ", " & t.UniqueID & ", '" & t.GetField(pjTaskMilestone) & "', '" & t.Name & "', '" & t.GetField(pjTaskPercentComplete) & _
"', " & RetrieveDate(t.Start) & ", " & RetrieveDate(t.Finish) & ", " & RetrieveDate(t.BaselineStart) & ", " & _
RetrieveDate(t.BaselineFinish) & ", " & RetrieveDate(t.ActualStart) & ", " & RetrieveDate(t.ActualFinish) & ");"
dB.Execute dBquery
RefreshDatabaseWindow
This is the function used to retrieve the date fields:
Function RetrieveDate(D As Variant) As Variant
If D = "NA" Then
RetrieveDate = "NULL"
Else
RetrieveDate = "#" & D & "#"
End If
End Function
The problem that I have is that when the code finds an ambiguous date, uses the American format, so when I try to run queries, the results are not correct.
For example, here I have a task with its dates and everything:
Whatever the date format I use it spins the date or it just doesn't insert the dates into the DB.
For example, in this table, the dates are inserted in decimal format. The same task in the database is:
In this image above we can see fewer fields because I've just taken the ones that I need.
So, if for example I make a query to retrieve the date in 'dd/mm/yyyy' format this same task, I get:
SELECT FORMAT(Start, "dd/mm/yyyy"), FORMAT(Finish, "dd/mm/yyyy")
FROM ow18_072014
WHERE TaskID = 202;
I have tried to convert the format to yyyy/mm/dd but the dates are not pasted into the table.
Another conversion I have tried is to change date format from Project but now Access changes some dates without any sense: a date equal to 20 Jun 2014 in MS Project becomes 15/11/2013 in MS Access.
You do not give us much information, and in the future, if you want people to actually have a chance of helping you, you have to put more effort in your question: give us some code you tried, some data example, etc.
Anyway, the issue is that by default, Access interprets literal dates as #mm/dd/yyyy#, except when it's unambiguous, like #25/12/2014#.
There are 2 ways to solve this issue: if you pass a litteral date to Access, use the #yyyy/mm/dd# ISO format instead because it's unambiguous and it will work in every locale.
Alternatively, convert your date to a decimal value and pass that to your Access date field instead, like CDec(myDate), will pass something like 41851.3465625 to Access and it will work.
The GetField method of the Task object returns a string value. For date fields, it returns the value in the format selected by the user (or set by the DefaultDateFormat property of the application object).
The simplest solution is to use the explicit properties of the Task object instead of the GetField method.
Modify your SQL statement to something like this:
dBquery = "INSERT INTO " & t.Name & "(ID, TaskID, Milestone, TaskName, pComplete, Start, Finish, BaselineStart, BaselineFinish, " & _
"ActualStart, ActualFinish)" & _
" VALUES (" & t.ID & ", " & t.UniqueID & ", '" & t.Milestone & "', '" & t.Name & "', '" & t.PercentComplete & _
"', " & RetrieveDate(t.Start) & ", " & RetrieveDate(t.Finish) & ", " & RetrieveDate(t.BaselineStart) & ", " & _
RetrieveDate(t.BaselineFinish) & ", " & RetrieveDate(t.ActualStart) & ", " & RetrieveDate(t.ActualFinish) & ");"
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 & " = " &