Incorrect syntax near '' in vba code for sql - sql

I'm getting this error because try to put Itemnr2 variable as cell value. If I use plain value like in ItemNr1 all works. But I need to use value from cell because it will change time to time so don't want change code every time. How can I put value from cell to SQL code to get it correct?
It is working when I use it in other column where all values are numbers. In this column which I need there are values like b2b_pkl, and because of it I get those Conversion failed when converting the nvarchar value to data type int errors.
PA = get_market_setting(market, "PA")
POS = get_market_setting(market, "POS")
NetAmount = get_market_setting(market, "Net Amount")
CostAmount = get_market_setting(market, "Cost Amount")
qty = get_market_setting(market, "Quantity")
transNo = get_market_setting(market, "Transaction No.")
ItemNo = get_market_setting(market, "Item No.")
CustNo = "[Customer No_]"
ItemNr1 = "('80502842')"
Itemnr2 = ThisWorkbook.Sheets("Data").Range("C1").Value
ECPOS_arr = "(" & get_market_setting("LT", "ECPOS_Arr") & ")"
' SQL query string
myquery = "SELECT -SUM(" & NetAmount & ") AS [Result] FROM " & table_TSE & _
" WHERE " & ItemNo & " IN " & Itemnr2 & _
" AND [Date] BETWEEN '" & date_from & "' AND '" & date_to & "'"
' Set Recordset to query set database on SQL string
Set sourceRs = sourceDb.OpenRecordset(myquery)
'Assign Data to variable from RecordSet'
sourceRs.MoveFirst
NetAmount = sourceRs![Result]
sourceRs.Close
sourceDb.CloseRecordset
'Populate HFB Report file'
enter image description here

If ItemNo and Itemnr2 always have parentheses and no single quotes then should be treated as strings :
Itemnr2 = ThisWorkbook.Sheets("Data").Range("C1").Value
myquery = "SELECT -SUM(" & NetAmount & ") AS [Result] FROM " & table_TSE & _
" WHERE '" & ItemNo & "' = '" & Itemnr2 & _
"' AND [Date] BETWEEN '" & date_from & "' AND '" & date_to & "'"

Related

SQL in VBA erro: Each GROUP BY expression must contain at least one column that is not an outer reference

Trying to extract data with this query and group by Item number, but getting error:
Each GROUP BY expression must contain at least one column that is not
an outer reference
When try to use Order by getting error that need to use GROUP BY.
' Database source and connect
dbstr = "Provider=SQLOLEDB;Data Source=" & get_market_setting(market, "Data Source") & _
";Initial Catalog=" & get_market_setting(market, "Initial Catalog") & _
";Integrated Security=SSPI"
sourceDb.Connect (dbstr)
' Date from/to filter
date_from = ThisWorkbook.Sheets("Data").Range("H3").Value
date_to = ThisWorkbook.Sheets("Data").Range("H5").Value
' Set Header filter
table_TSE = "[" & get_market_setting(market, "Database") & "$Trans_Sales Entry]"
' SQL query string
myquery = "SELECT " & ItemNo & ", -SUM( " & NetAmount & " ) FROM " & table_TSE & _
" WHERE " & ItemNo & " IN " & Itemnr1 & _
" AND [Date] BETWEEN '" & date_from & "' AND '" & date_to & _
" GROUP BY '" & ItemNo & " '"
MsgBox myquery
' Set Recordset to query set database on SQL string
Set sourceRs = sourceDb.OpenRecordset(myquery)
'Assign Data to variable from RecordSet'
sourceRs.MoveFirst
sourceRs.Close
sourceDb.CloseRecordset

VBA code to read all the table and paste it in excel with SQL from Navision

with this code I can take specific value and paste it in specific cell.
PA = get_market_setting(market, "PA")
POS = get_market_setting(market, "POS")
NetAmount = get_market_setting(market, "Net Amount")
CostAmount = get_market_setting(market, "Cost Amount")
qty = get_market_setting(market, "Quantity")
transNo = get_market_setting(market, "Transaction No.")
ItemNo = get_market_setting(market, "Item No.")
CustNo = "[Customer No_]"
Itemnr1 = "('80502842')"
Itemnr2 = ThisWorkbook.Sheets("Data").Range("C1").Value
ECPOS_arr = "(" & get_market_setting("LT", "ECPOS_Arr") & ")"
' SQL query string
myquery = "SELECT -SUM(" & NetAmount & ") AS [Result] FROM " & table_TSE & _
" WHERE '" & ItemNo & "' = '" & Itemnr2 & _
"' AND [Date] BETWEEN '" & date_from & "' AND '" & date_to & "'"
' Set Recordset to query set database on SQL string
Set sourceRs = sourceDb.OpenRecordset(myquery)
'Assign Data to variable from RecordSet'
sourceRs.MoveFirst
NetAmount = sourceRs![Result]
MsgBox myquery
sourceRs.Close
sourceDb.CloseRecordset
'Populate HFB Report file'
ThisWorkbook.Sheets("Data").Range("A1") = NetAmount
But how I can take all table_TSE and save it in sheet?

Trying to update table in ms Access using VBA but getting failed , used multiple option but table not getting updated

Trying to update table in ms Access using VBA but getting failed , used multiple option but table not getting updated
Dim bod As Date
Dim assets As String
Dim emname As String
Dim ecode As String
Dim Astatus As String
Astatus = "SOLD"
msaved = True
DoCmd.SetWarnings False
bod = Me.datetime.Caption
price1k = Me.cmbox1_1AID.Value
emname = Me.empname.Value
ecod = Nz(Me.code.Value, 0)
//tried using this but not getting updated no error
DoCmd.RunSQL "UPDATE [Asset E7450 List] SET Code = '" & ecod & "',[Date & Time] ='" & bod & "' ,Status ='" & Astatus & "',[Sold To] ='" & empname & "', where Asset-ID ='" & price1k & "'"
// Tried using this no update no error
CurrentDb.Execute "UPDATE [Asset E7450 List] SET Code = '" & ecod & "',[Date & Time] ='" & bod & "' ,Status ='" & Astatus & "',[Sold To] ='" & empname & "', where Asset-ID ='" & price1k & "'"
// Tried this method no data update no error
Dim strSQL As String
strSQL = "UPDATE [Asset E7450 List] SET Code = '" & ecod & "',[Date & Time] ='" & bod & "' ,Status ='" & Astatus & "',[Sold To] ='" & empname & "', where Asset-ID ='" & price1k & "'"
DoCmd.RunSQL strSQL
MsgBox " Booking Request Accepted ", vbInformation
If [Date & Time] is a date/time type field, use # delimiter instead of '. If field is a number type, don't use any delimiter.
Remove the comma in front of WHERE clause.
Need [ ] around Asset-ID field name because of the hyphen.
Advise not to use spaces nor punctuation/special characters in naming convention.

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

SQL Query Date Related SELECT Statement

This is my query which runs perfectly
"SELECT RemBal FROM Sales WHERE CustomerName='" & CustomerName.Text & "'"
now i am trying to get the balance on two basis customer name & current date
"SELECT RemBal FROM Sales WHERE CustomerName='" & CustomerName.Text & "' AND SaleDate=#" & SaleDate.Value & "#"
now this query not giving me any error but not returning any value too
please help
Try this
SaleDate.Format = DateTimePickerFormat.Custom
SaleDate.CustomFormat = "yyyy-mm-dd"
"SELECT RemBal FROM Sales WHERE CustomerName='" & CustomerName.Text & "' AND SaleDate=#" & SaleDate.Text() &"# "
SELECT rembal
FROM sales
WHERE customername = '" & CustomerName.Text & "'
AND Format(saledate, 'dd/MM/yyyy') = '" & SaleDate.Value & "'