syntax error (missing operator) in query expression '2020-12-01' - vba

I wrote this code. When I try to activate this sub I always get this problem "syntax error (missing operator) in query expression '2020-12-01'". It's something wrong with Date (data in Polish means date).
Could u help me to fix this ?? I just want to take "Kolejka", "stadion", "Data" from form and add to my table Rozgrywki.
I also attached pictures of this error and picture of my form in access.
Runtime error "3075"
Dialog being composed
Public Sub Dodaj(Kolejka, stadion, Data, DA, DB, Optional wa = 0, Optional wb = 0)
If [wa] = "" Then wa = 0
If [wb] = "" Then wb = 0
DoCmd.SetWarnings False
dodaj_rozgrywka = "" & _
"INSERT INTO Rozgrywki ( IDStadionu, Data, Idkolejki)" & _
"SELECT " & stadion & " AS Wyr1, #" & Data & "# AS Wyr2;, " & Kolejka & " AS Wyr3;"
DoCmd.RunSQL (dodaj_rozgrywka)

Format your date value to a string expression:
"SELECT " & stadion & " AS Wyr1, #" & Format(Data, "yyyy\/mm\/dd") & "# AS Wyr2;, " & Kolejka & " AS Wyr3;"
Or use my CSql function. Even better, learn yourself to use queries with parameters.

Related

How can I resolve runtime error 3075 in VBA

I have problem running this code. It gives me Syntax error (missing operator) in query expression
Function SearchCriteria()
Dim class,StateProvince,strAcademicYear As As String
Dim task, strCriteria As String
If isNull(Forms!frmStudentList!cboClass) Then
Class = "[Class] LIKE '*' "
Else
Class = [Class] = " & Forms!frmStudentList!cboClass
End If
If isNull(Forms!frmStudentList!cboStateProvince) Then
StateProvince = "[StateProvince] LIKE '*' "
Else
StateProvince = [StateProvince] = " &
Forms!frmStudentList!cboStateProvince
End If
If isNull(Forms!frmStudentList!cboAcademicYear) Then
StrAcademicYear = "[AcademicYear] LIKE '*' "
Else
StrAcademicYear = [AcademicYear] = '" &
Forms!frmStudentList!cboAcademicYear & "'"
End If
strCriteria = Class & "AND" & StateProvince & "AND" & StrAcademicYear
task = "SELECT * FROM QryStudentSearch WHERE & Criteria
Forms!frmStudentList.RecordSource = task
Forms!frmStudentList.Requery
End Function
There are quite a few problems with this piece of code.
Firstly, most of your variables aren't explicitly declared as being of a type, so default to being Variant.
Next, Class is a reserved word in Access, and will probably cause you problems.
If a control has no choice made, you are using LIKE '*' to select data. There is no need to do this, as by applying no filter means that all records will be returned anyway.
As it doesn't return a value, you can create this as a Sub rather than a Function.
The main problem is with how you are concatenating the different parts together.
I would rewrite the code as:
Sub sSearch()
Dim strSearch As String
If Not IsNull(Forms!frmStudentList!cboClass) Then
strSearch = strSearch & " AND [Class]='" & Forms!frmStudentList!cboClass & "' "
End If
If Not IsNull(Forms!frmStudentList!cboStateProvince) Then
strSearch = strSearch & " AND [StateProvince]='" & Forms!frmStudentList!cboStateProvince & "' "
End If
If Not IsNull(Forms!frmStudentList!cboAcademicYear) Then
strSearch = strSearch & " AND [AcademicYear]='" & Forms!frmStudentList!cboAcademicYear & "' "
End If
If Left(strSearch, 4) = " AND" Then
strSearch = "WHERE " & Mid(strSearch, 6)
End If
strSearch = "SELECT * FROM qryStudentSearch " & strSearch
Forms!frmStudentList.RecordSource = strSearch
Forms!frmStudentList.Requery
End Sub
In each case, I am assuming that the bound column of each combo box is text, hence the need to use single quotes around the data. If the bound column is numeric, then the single quotes can be removed.
Regards,

How to handle 0 lines found after a DoCmd.RunSQL(INSERT INTO...)

For starters, I only started yesterday with the attempts of introducing SQL into my VBA code.
I'm trying to use VBA/SQL to Insert Data into a local table, made from a combination of a Database table and form input. I want to know how to trigger a "0 Lines retrieved".
I've already tried looking on several pages on how to handle "0 lines to Insert" when running a DoCmd.RunSQL("INSERT INTO ... SELECT ... FROM ... WHERE ...).
The code itself works when there is data present, so that's not the problem.
The problem itself is when I don't find data, I want to trigger a messagebox that gives instructions on how to handle the current situation.
Sadly, I have not found on how I can trigger this.
sqlTempInsert = "INSERT INTO tblScanInput (Support, EAN, Counted, Product, Description, Launched, Collected) " & _
"SELECT " & lblSupportData.Caption & ", " & txtEANInput.Value & ", "
If txtAmountInput.Visible = True Then
sqlTempInsert = sqlTempInsert & txtAmountInput.Value & ", "
ElseIf txtAmountInput.Visible = False Then
sqlTempInsert = sqlTempInsert & "1, "
End If
sqlTempInsert = sqlTempInsert & "GEPRO.CODPRO, GEPRO.DS1PRO, GESUPDC.UVCSRV, GESUPDC.UVCLIV " & _
"FROM [Database_Table] GESUPDC LEFT OUTER JOIN [Database_Table] GEPRO ON GESUPDC.CODPRO = GEPRO.CODPRO " & _
"WHERE GESUPDC.NUMSUP = " & lblSupportData.Caption & " AND GESUPDC.EDIPRO = '" & txtEANInput.Value & "';"
DoCmd.RunSQL(sqlTempInsert)
Use .Execute and .RecordsAffected.
Dim db As DAO.Database
Dim x As Long
Set db = CurrentDb
db.Execute sqlTempInsert, dbFailOnError
x = db.RecordsAffected
If x = 0 Then
' nothing was inserted
End If
Note: pay attention to Delete 5 Records but RecordsAffected Property is 0

VBA SQL Where IS NULL

Im trying to create a VBA sql string with the where clause using inputs from an access form. I need the code to still run properly even if one of the user inputs is null/unselected. The code below runs correctly when all user inputs have been selected but when one input is null/unselected the query ends up pulling back all the records in the table.
Dim SQL As String
SQL = "SELECT qry_1.field1, qry_1.field2, qry_1.field3 INTO recordset FROM qry_1" & _
" WHERE ((qry_1.Field1) IS NULL OR (qry_1.Field1) = '" & [Forms]![frm_Parameters]![cmbx_1] & "') " &_
" AND ((qry_1.Field2) IS NULL OR (qry_1.Field2) = '" & [Forms]![frm_Parameters]![cmbx_2] & "' ) " & _
" AND ((qry_1.Field3) IS NULL OR (qry_1.Field3) = '" & [Forms]![frm_Parameters]![cmbx_3] & "') ;"
DoCmd.RunSQL SQL
It is better to escape single apostrophes in the text for two reasons
You might get an invalid SQL statement if you don't.
A nasty user could can inject evil code (see: SQL injection).
Therefore I use this function
Public Function SqlStr(ByVal s As String) As String
'Input: s="" Returns: NULL
'Input: s="abc" Returns: 'abc'
'Input: s="x'y" Returns: 'x''y'
If s = "" Then
SqlStr = "NULL"
Else
SqlStr = "'" & Replace(s, "'", "''") & "'"
End If
End Function
To account for empty entries, create the condition like this:
Dim cond As String, sql As String
If Nz([Forms]![frm_Parameters]![cmbx_1]) <> "" Then
cond = "qry_1.field1 = " & SqlStr(Nz([Forms]![frm_Parameters]![cmbx_1]))
End If
If Nz([Forms]![frm_Parameters]![cmbx_2]) <> "" Then
If cond <> "" Then cond = cond & " AND "
cond = cond & "qry_1.field2 = " & SqlStr(Nz([Forms]![frm_Parameters]![cmbx_2]))
End If
If Nz([Forms]![frm_Parameters]![cmbx_3]) <> "" Then
If cond <> "" Then cond = cond & " AND "
cond = cond & "qry_1.field3 = " & SqlStr(Nz([Forms]![frm_Parameters]![cmbx_3]))
End If
sql = "SELECT qry_1.field1, qry_1.field2, qry_1.field3 INTO recordset FROM qry_1"
If cond <> "" Then
sql = sql & " WHERE " & cond
End If
This assumes that you want to test a condition only when the corresponding field is not empty.
If you have date constants, format them the Access-SQL way as #2018-08-21# with
Format$(date, "\#yyyy-MM-dd\#")
DoCmd.RunSQL is for action queries (UPDATE, INSERT, DELETE).
To answer the question, here is what I would do:
Nz(Field1,Nz([Forms]![frm_Parameters]![cmbx_1]))=Nz([Forms]![frm_Parameters]![cmbx_1])
That will create equality if either Field1 or [Forms]![frm_Parameters]![cmbx_1] is NULL without breaking the rest of the query.
To use that in VBA:
"Nz(Field1,'" & Nz([Forms]![frm_Parameters]![cmbx_1]) & "')='" & Nz([Forms]![frm_Parameters]![cmbx_1]) & "'"
Also see comment in Olivier Jacot-Descombes answer about taking single quotes in your strings into account.

MS Access: INSERT INTO statement returning a syntax error

I can't figure out the error. I already tried adding more parentheses but this didn't help. This code checks to see if there is already a query called "InsertFilmZip" and if there isn't one, it creates it with the given statement. For some reason, it's saying that there is a Run-time error 3139: Syntax error in PARAMETER clause but I can't find the error.
Private Sub Command8_Click()
Dim dbsCurrent As Database
Set dbsCurrent = CurrentDb
Dim query As QueryDef
Dim sql As String
Dim item_val As String
item_val = Me.Text314
For Each query In CurrentDb.QueryDefs
If query.Name = "InsertFilmZip" Then
Exit For
End If
Next query
If query Is Nothing Then
sql = "parameters " & "P1 Number" & _
"INSERT INTO [tbl_FilmZipInfo] " & _
"(qty_per_unit) " & _
" VALUES ([P1])" & _
"WHERE (((tbl_FilmZipInfo.qty_per_unit)='" & Me.Text314 & "'))"
Set query = CurrentDb.CreateQueryDef("InsertFilmZip", sql)
End If
query.Parameters("P1").Value = Me.Text317
query.Execute
End Sub
Your SQL doesn't make sense, so try this adjustment:
sql = "parameters P1 Long;" & _
"UPDATE [tbl_FilmZipInfo] " & _
"SET qty_per_unit = [P1] " & _
"WHERE qty_per_unit = " & Me.Text314 & ""

Using Cell reference in SQL query

I am using below VBA command to extract data using a SQL query by using a cell reference as filter.
Public Sub Run()
Dim SQL As String
Dim Connected As Boolean
Dim server_name As String
Dim database_name As String
Dim Allocation As String
Sheets("Perc").Select
Range("A6").Select
Selection.CurrentRegion.Select
Selection.ClearContents
' Our query
SQL = "SELECT Segmentation_ID,MPG,SUM(Segmentation_Percent) AS PERC " & _
"FROM dbo.HFM_ALLOCATION_RATIO " & _
"WHERE Segmentation_ID = " & Sheets("Perc").Range("A1").Value & " " & _
"GROUP BY Segmentation_ID,MPG ORDER BY MPG"
' Connect to the database
server_name = Sheets("General").Range("D1").Value
database_name = Sheets("General").Range("G1").Value
Connected = Connect(server_name, database_name)
If Connected Then
' If connected run query and disconnect
Call Query(SQL)
Call Disconnect
Else
' Couldn't connect
MsgBox "Could Not Connect!"
End If
End Sub
But when I run the macro, it's showing a runtime error
Invalid column name ALO0000274
Here ALO0000274 is the filter I set in A1.
Kindly help to fix this error.
Add quotes to your where clause (you're passing a text value, so you need to include quotes):
SQL = "SELECT Segmentation_ID,MPG,SUM(Segmentation_Percent) AS PERC " & _
"FROM dbo.HFM_ALLOCATION_RATIO " & _
"WHERE Segmentation_ID = '" & Sheets("Perc").Range("A1").Value & "' " & _
"GROUP BY Segmentation_ID,MPG ORDER BY MPG"
(Note the single quotes ' that enclose the value you want to filter)
I don't see where you are adding your single quotes around your string. Have you tried changing your WHERE clause portion of your SQL statement to "WHERE Segmentation_ID = '" & Sheets("Perc").Range("A1").Value & "' "