Correctly assigned parameter valuecan not be used - variables

I want to get a cmb-value before the entry is changed, by using ".oldValue". The value is correctly assigned (according to debugger), but running the SQL Access is asking for a manual entry. Doing the entry manually works fine, so the remaining code should be fine.
My Code:
Dim CategoryNameBeforeChange As String
CategoryNameBeforeChange = Forms!frmCategory!txtCategoryName.OldValue
SQL = "UPDATE CategoryTbl " & _
"SET CategoryTbl.CategoryName = Forms!frmCategory!txtCategoryName " & _
"WHERE (CategoryTbl.CategoryName = CategoryNameBeforeChange);"
Any idea what went wrong here?
Any help is greatly appreciated!

Try this:
SQL = "UPDATE CategoryTbl " & _
"SET CategoryTbl.CategoryName = Forms!frmCategory!txtCategoryName " & _
"WHERE (CategoryTbl.CategoryName = " & CategoryNameBeforeChange & ");"
I suspect that CategoryName is text, in this case it should be
SQL = "UPDATE CategoryTbl " & _
"SET CategoryTbl.CategoryName = Forms!frmCategory!txtCategoryName " & _
"WHERE (CategoryTbl.CategoryName = '" & CategoryNameBeforeChange & "');"

Related

Use Dlookup inside SQL in VBA for Microsoft Access causes Unknown Error

I am trying to update a field based on a lookup field in VBA. This is the code that I have:
SQL = "UPDATE tblDispatch td " & _
"SET td.NumOfStops = Dlookup(""NumOfStops"", ""qryStops"", ""PK = td.PK"")" & _
"WHERE td.DispatchDate = #" & Me.tbDate.Value & "#;"
DoCmd.RunSQL SQL
The syntax and everything looks correct but it keeps giving me a weird error. "Run-time error '2741' Unknown" What is this error and how can I fix it?
Just a guess based on the limited information available, but try:
SQL = "UPDATE tblDispatch td " & _
"SET td.NumOfStops = Dlookup(""NumOfStops"", ""qryStops"", ""PK = '"" & td.PK & ""'"") " & _
"WHERE td.DispatchDate = #" & Me.tbDate.Value & "#;"
DoCmd.RunSQL SQL
Or if PK isn't a string, then:
SQL = "UPDATE tblDispatch td " & _
"SET td.NumOfStops = Dlookup(""NumOfStops"", ""qryStops"", ""PK = "" & td.PK) " & _
"WHERE td.DispatchDate = #" & Me.tbDate.Value & "#;"
DoCmd.RunSQL SQL

MS-Access Update SQL Not Null But is Blank (! Date & Number Fields !)

I have a few controls that are number and short date format in my tables also the date controls are masked to mm/dd/yyyy. Some of the fields that are loaded into the form are blank from the original table and so when executing the sql I am essentially evaluating the wrong thing whether Im checking for '' or Null. as '' fails as text for date number and the fields are not actually blank.
strSQL4 = "UPDATE [tblDetails] SET " & _
"[Proposed] = IIF(IsNull(" & Forms!frmEdit.txtProposed.Value & "),0," & Forms!frmEdit.txtProposed.Value & "), " & _
"[Multi] = IIF(IsNull(" & Forms!frmEdit.txtMulitplier.Value & "),0," & Forms!frmEdit.txtMulitplier.Value & "), " & _
"[Rational] = '" & Forms!frmEdit.txtRational.Value & "' " & _
" WHERE [RNumber] = '" & Forms!frmEdit.cmbUpdate.Value & "'"
Debug.Print strSQL4
dbs.Execute strSQL4
ERROR 3075 Wrong number of arguments used with function in query expression
'IIF(IsNull(),0,'
I also tried entering the field itself suggested from another site
strSQL4 = "UPDATE [tblDetails] SET " & _
"[Proposed] = IIF(" & Forms!frmEdit.txtProposed.Value & "='',[Proposed]," & Forms!frmEdit.txtProposed.Value & "), " & _
" WHERE [RNumber] = '" & Forms!frmEdit.cmbUpdate.Value & "'"
Debug.Print strSQL4
dbs.Execute strSQL4
Same Error 3075 'IIF(IsNull(),0,[ProposedHrs]'
***also fails if I use the IIF(IsNull method as opposed to the =''
I did not paste an example of the dates failing, but is the same idea, not null but is blank, but cant seem to update back to blank again or even skip maybe?
Thanks to anyone in advance.
Update-1 from attempting Erik Von Asmuth code <--Thanks btw!
Set qdf = db.CreateQueryDef("", & _
"UPDATE [tblDetails] SET " & _
"[Proposed] = #Proposed, " & _
"[Multi] = #Multi, " & _
"[Rational] = #Rational " & _
"WHERE [RNumber] = #RNumber")
This portion is all red and the first "&" is highlighted after closing the notification window
Compile error:
Expected: expression
Update-2: I moved the update to the first line and it seems to be working. Set qdf = db.CreateQueryDef("", "UPDATE [tblDetails] SET " & _
I am going to try this method with the dates fields next.
Update-3: when attempting the same parameterization with textbox's masked with 99/99/0000;0;_ I am receiving item not found in collection? I have checked the spelling several times and everything seems ok. I tried the following three formats so set parameter DateRcvd, can anyone comment if this is correct for a text box with dates?
qdf.Parameters("#DateRcvd") = IIf(Nz(Forms!frmEdit.txtDateRcvd.Value) = "", 0, Forms!frmEdit.txtDateRcvd.Value)
qdf.Parameters("#DateRcvd") = IIf(IsNull(Forms!frmEdit.txtDateRcvd.Value), 0, Forms!frmEdit.txtDateRcvd.Value)
qdf.Parameters("#DateRcvd") = IIf(Forms!frmEdit.txtDateRcvd.Value = "", 0, Forms!frmEdit.txtDateRcvd.Value)
Update-4:
Dim qdf2 As DAO.QueryDef
Set db = CurrentDb
Set qdf2 = db.CreateQueryDef("", "UPDATE [tblDetails] SET " & _
"[DateReceived] = #DateRcvd " & _
"WHERE [RNumber] = #RNumber")
qdf.Parameters("#DateRcvd") = IIf(Nz(Forms!frmEdit.txtDateRcvd.Value) = "", 0, Forms!frmEdit.txtDateRcvd.Value)
qdf.Parameters("#RNumber") = Forms!frmEdit.cmbUpdate.Value
qdf2.Execute
Please Note text box txtDateRcvd has an Input Mask 99/99/0000;0;_ set within the properties of the textbox.
You should account for empty strings, and do that IIF statement in VBA instead of SQL:
strSQL4 = "UPDATE [tblDetails] SET " & _
"[Proposed] = " & IIF(Nz(Forms!frmEdit.txtProposed.Value) = "",0, Forms!frmEdit.txtProposed.Value) & ", " & _
"[Multi] = " & IIF(Nz(Forms!frmEdit.txtMulitplier.Value) = "",0, Forms!frmEdit.txtMulitplier.Value) & ", " & _
"[Rational] = '" & Forms!frmEdit.txtRational.Value & "' " & _
" WHERE [RNumber] = '" & Forms!frmEdit.cmbUpdate.Value & "'"
Or better yet, do it properly and parameterize the whole update so you can't get these kind of errors or SQL injection.
Example of how to do it properly:
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Set db = CurrentDb
Set qdf = db.CreateQueryDef("", _
"UPDATE [tblDetails] SET " & _
"[Proposed] = #Proposed, " & _
"[Multi] = #Multi, " & _
"[Rational] = #Rational " & _
"WHERE [RNumber] = #RNumber"
)
qdf.Parameters("#Proposed") = IIF(Nz(Forms!frmEdit.txtProposed.Value) = "",0, Forms!frmEdit.txtProposed.Value)
qdf.Parameters("#Multi") = IIF(Nz(Forms!frmEdit.txtMulitplier.Value) = "",0, Forms!frmEdit.txtMulitplier.Value)
qdf.Parameters("#Rational") = Forms!frmEdit.txtRational.Value
qdf.Parameters("#RNumber") = Forms!frmEdit.cmbUpdate.Value
qdf.Execute

SQL syntax error on vba

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 & "));"

Requery using a variable within string

I am having trouble to requery my subform using a SQL string, here is my code:
Dim Day As Integer
Day = txt_Days.Value
SQL = "SELECT [qry_Records].[Tool_ID], [qry_Records].[Cal_Date]," _
& "[qry_Records].[Cal_By], [qry_Records].[As_Received], " _
& "[qry_Records].[Result], [qry_Records].[Next_Due], " _
& "[qry_Records].[Due] FROM [qry_Records]" _
& " WHERE [qry_Records].[Due] < Day;"
subform_View_Search_Records.Form.RecordSource = SQL
I tried to use different variations to quote the Day variable at the end of the SQL String such as below but nothing works:
& " WHERE [qry_Records].[Due] < ""Day"";"
& " WHERE [qry_Records].[Due] < '"Day"';"
Your help is much appreciated!
You just need to add a couple of ampersands
& " WHERE [qry_Records].[Due] < " & Day & ";"
I would try this:
SQL = "SELECT [Tool_ID], [Cal_Date]," _
& "[Cal_By], [As_Received], " _
& "[Result], [Next_Due], " _
& "[Due] FROM [qry_Records]" _
& " WHERE [Due] < " & format$(txtDays, "\#dd\/mm\/yyyy\#")
subform_View_Search_Records.Form.RecordSource = SQL
The final ";" is useless.

access 2013 increasing quantity in a table field

Good day. I'm a little stumped about what is happening in my code. I have a userform which collects txtQntyRecd and cboSupplySource. I calculate the lookupValue. And it works just fine. It successfully places the txtQntyRecd in the correct tblWarehouseLocations.WQuantity location. The code is:
updateQnty = "UPDATE tblSupplySources INNER JOIN ((tblWarehouseLocations " & _
"INNER JOIN tblSupplySource_WarehouseLocation ON tblWarehouseLocations.WLocation_ID = tblSupplySource_WarehouseLocation.SWLocation_ID)) " & _
"ON tblSupplySources.SupplySourceID = tblSupplySource_WarehouseLocation.Supply_Source_ID " & _
"SET tblWarehouseLocations.WQuantity = '" & Me.txtQntyRecd & "'" & _
"WHERE (((tblSupplySource_WarehouseLocation.Supply_Source_ID)= " & Me.cboSupplySource & ") " & _
" AND ((tblWarehouseLocations.WLocation_ID)=" & lookupValue & "))"
CurrentDb.Execute updateQnty, dbFailOnError
What I want to do is add the next quantity to the same location. I get weird results if I change the SET statement to the following:
SET tblWarehouseLocations.WQuantity = tblWarehouseLocations.WQuantity + '" & Me.txtQntyRecd & "'"
If I put 200 in the first statement, I get 200 in my WQuantity field. When I change to the second statement and I try to add 1 to the 200 I get a result of 211. If I add 1 again, the result is 223. Add 1 again, the result is 236.
Could someone explain what is happening and why the results aren't 201, 202 and 203? In the future I will need to subtract quantities from WQuantity as well.
Thanks
You're adding quotes around an integer and appending it as a string. Change it to:
".....
SET tblWarehouseLocations.WQuantity = tblWarehouseLocations.WQuantity + " & val(Me!txtQntyRecd) & "....
...."
I've changed the . to a ! as I think it's still a nice distinction between objects properties and controls, and used the val function as it converts the string number value to the integer value.
This is your query in full:
' When I use values from controls, I like to store them in vars
Dim quantityReceived As integer
quantityReceived = val(Me!txtQntyRecd)
updateQnty = "UPDATE tblSupplySources INNER JOIN ((tblWarehouseLocations " & _
"INNER JOIN tblSupplySource_WarehouseLocation ON tblWarehouseLocations.WLocation_ID = tblSupplySource_WarehouseLocation.SWLocation_ID)) " & _
"ON tblSupplySources.SupplySourceID = tblSupplySource_WarehouseLocation.Supply_Source_ID " & _
"SET tblWarehouseLocations.WQuantity = tblWarehouseLocations.WQuantity + " & quantityReceived & _
" WHERE (((tblSupplySource_WarehouseLocation.Supply_Source_ID)= " & Me.cboSupplySource & ") " & _
" AND ((tblWarehouseLocations.WLocation_ID)=" & lookupValue & "))"
I solved the problem. I created a SELECT query to get the present amount in WQuantity. Now quantityReceived = Me!txtQntyRecd + the present amount. With SET tblWarehouseLocations.WQuantity = " & quantityReceived it works fine. However, if just seems so cumbersome.
' lookupValue gives the index into the tblWarehouseLocations where WQuantity resides
Dim lookupValue As Integer
lookupValue = DLookup("[WLocation_ID]", "[tblWarehouseLocations]", "[Location_Name] = '" & Me.cboWLocation & "'")
'Define SQL Query
strSQL = "select tblWarehouseLocations.WQuantity FROM tblWarehouseLocations WHERE (((tblWarehouseLocations.WLocation_ID)= " & lookupValue & "))"
Set rs = db.OpenRecordset(strSQL)
If IsNull(rs!WQuantity) Then
dbvalue = 0
Else
dbvalue = rs!WQuantity
End If
Dim quantityReceived As Integer
quantityReceived = Val(Me!txtQntyRecd) + dbvalue
updateQnty = "UPDATE tblSupplySources INNER JOIN ((tblWarehouseLocations " & _
"INNER JOIN tblSupplySource_WarehouseLocation ON tblWarehouseLocations.WLocation_ID = tblSupplySource_WarehouseLocation.SWLocation_ID)) " & _
"ON tblSupplySources.SupplySourceID = tblSupplySource_WarehouseLocation.Supply_Source_ID " & _
"SET tblWarehouseLocations.WQuantity = " & quantityReceived & _
" WHERE (((tblSupplySource_WarehouseLocation.Supply_Source_ID)= " & Me.cboSupplySource & ") " & _
" AND ((tblWarehouseLocations.WLocation_ID)=" & lookupValue & "))"
CurrentDb.Execute updateQnty, dbFailOnError