Run-time Error 3131 Syntax Error in FROM clause - sql

Tried scouring the forums for threads similar to mine but couldn't really find anything that would lead me in the right direction. Basically I have a table that has the QA scores for each of the 10 regions and I am trying to populate a text box with a specific region's score depending on the month. I was trying to do this in vba for this form but came across this Run-time error 3131 and I'm not entirely sure what's wrong with my code which seems simple enough to me. Thanks for any help or advice in advance.
Private Sub Form_Load()
Dim strSql As String
strSql = "SELECT tblScorecard.[QA_Overall]" & _
"FROM tblScorecard" & _
"WHERE tblScorecard.[Audit Month] = 'Jan'" & _
"AND tblScorecard.[Region] = '1'"
DoCmd.RunSQL strSql
txtReg1 = strSql
End Sub

Is it not possible you should just add spaces?
tblScorecard.[QA_Overall]FROM as one word?
Private Sub Form_Load()
Dim strSql As String
strSql = "SELECT tblScorecard.[QA_Overall] " & _
"FROM tblScorecard " & _
"WHERE tblScorecard.[Audit Month] = 'Jan'" & _
" AND tblScorecard.[Region] = '1'"
DoCmd.RunSQL strSql
txtReg1 = strSql
End Sub
In order to avoid Error: 2342 A RunSQL:
Private Sub Form_Load()
Dim qdf As QueryDef
strSql = "SELECT tblScorecard.[QA_Overall] " & _
"FROM tblScorecard " & _
"WHERE tblScorecard.[Audit Month] = 'Jan'" & _
" AND tblScorecard.[Region] = '1'"
On Error Resume Next
DoCmd.DeleteObject acQuery, "tempQry"
On Error GoTo 0
Set qdf = CurrentDb.CreateQueryDef("tempQry", strSQL)
DoCmd.OpenQuery ("tempQry")
End Sub
More information found here.

When you use & _, you are not adding a line beak INSIDE the string
Try adding a space at the end of the strings
strSql = "SELECT tblScorecard.[QA_Overall] " & _
"FROM tblScorecard " & _
"WHERE tblScorecard.[Audit Month] = 'Jan' " & _
"AND tblScorecard.[Region] = '1'"

Related

Update SQL MS Access 2010

This is wrecking my brains for 4 hours now,
I have a Table named BreakSked,
and I this button to update the table with the break end time with this sql:
strSQL1 = "UPDATE [BreakSked] SET [BreakSked].[EndTime] = " & _
Me.Text412.Value & " WHERE [BreakSked].AgentName = " & Me.List423.Value _
& " AND [BreakSked].ShiftStatus = '1'"
CurrentDB.Execute strSQL1
Text412 holds the current system time and List423 contains the name of the person.
I'm always getting this
"Run-time error 3075: Syntax Error (missing operator) in query
expression '03:00:00 am'
Any help please?
EDIT: Thanks, now my records are updating. But now its adding another record instead of updating the record at hand. I feel so silly since my program only has two buttons and I can't figure out why this is happening.
Private Sub Form_Load()
DoCmd.GoToRecord , , acNewRec
End Sub
Private Sub Command536_Click()
strSQL1 = "UPDATE BreakSked SET BreakSked.EndTime = '" & Me.Text412.Value & "',BreakSked.Duration = '" & durationz & "' " & vbCrLf & _
"WHERE (([BreakSked].[AgentID]='" & Me.List423.Value & "'));"
CurrentDb.Execute strSQL1
CurrentDb.Close
MsgBox "OK", vbOKOnly, "Added"
End Sub
Private Sub Command520_Click()
strSql = "INSERT INTO BreakSked (ShiftDate,AgentID,StartTime,Status) VALUES ('" & Me.Text373.Value & "', '" & Me.List423.Value & "', '" & Me.Text373.Value & "','" & Me.Page657.Caption & "')"
CurrentDb.Execute strSql
CurrentDb.Close
MsgBox "OK", vbOKOnly, "Added"
End Sub
You wouldn't need to delimit Date/Time and text values if you use a parameter query.
Dim strUpdate As String
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
strUpdate = "PARAMETERS pEndTime DateTime, pAgentName Text ( 255 );" & vbCrLf & _
"UPDATE BreakSked AS b SET b.EndTime = [pEndTime]" & vbCrLf & _
"WHERE b.AgentName = [pAgentName] AND b.ShiftStatus = '1';"
Debug.Print strUpdate ' <- inspect this in Immediate window ...
' Ctrl+g will take you there
Set db = CurrentDb
Set qdf = db.CreateQueryDef("", strUpdate)
qdf.Parameters("pEndTime").Value = Me.Text412.Value
qdf.Parameters("pAgentName").Value = Me.List423.Value
qdf.Execute dbFailOnError
And if you always want to put the current system time into EndTime, you can use the Time() function instead of pulling it from a text box.
'qdf.Parameters("pEndTime").Value = Me.Text412.Value
qdf.Parameters("pEndTime").Value = Time() ' or Now() if you want date and time
However, if that is the case, you could just hard-code the function name into the SQL and dispense with one parameter.
"UPDATE BreakSked AS b SET b.EndTime = Time()" & vbCrLf & _
As I said in my comment you need to wrap date fields in "#" and string fields in escaped double quotes
strSQL1 = "UPDATE [BreakSked] SET [BreakSked].[EndTime] = #" & _
Me.Text412.Value & "# WHERE [BreakSked].AgentName = """ & Me.List423.Value & _
""" AND [BreakSked].ShiftStatus = '1'"

CurrentDb.Execute delete query not deleting anything when its executed from VBA

I am trying to get my code to delete a newly created record if the user cancels. for some reason Access is not deleting the record even though the query is definitely filtering for unique IDs which exist within the table. Access is not throwing any errors.
PG_ID is the unique identifier in both tables, it is a Long Integer.
I've included a sample portion of my code below. Please help!
Dim var_PGID As String
Dim Delete_PG_Data, Delete_PG_Upld As String
Dim db As Database
Set db = CurrentDb
var_PGID = TempVars![var_PG_ID_NEW]
Delete_PG_Data = "DELETE * " & _
"FROM tbl_CapEx_Projects_Group " & _
"WHERE PG_ID=" & var_PGID
Delete_PG_Upld = "DELETE * " & _
"FROM tbl_CapEx_Projects_Group_Attachements " & _
"WHERE PG_ID=" & var_PGID
Debug.Print Delete_PG_Data
Debug.Print Delete_PG_Upld
db.Execute Delete_PG_Data, dbFailOnError
db.Execute Delete_PG_Upld, dbFailOnError
As requested I've switched msgbox to Debug.Print. Below is the debug.print output which runs correctly when placed in an access query.
It was a timing issue. I fixed it by committing the transaction then running the delete query. Thank you all for your input!
Private Sub cmd_Cancel_Click()
On Error Resume Next
DoCmd.SetWarnings False
If TempVars![var_NewRecord] = True Then
Do While Not Me.Recordset.EOF
Me.Recordset.Update
Me.Recordset.MoveNext
Loop
DBEngine.CommitTrans
Me.Recordset.Close
Dim var_PGID As String
Dim Delete_PG_Data, Delete_PG_Upld As String
Dim db As Database
Set db = CurrentDb
var_PGID = TempVars![var_PG_ID_NEW]
Delete_PG_Data = "DELETE * " & _
"FROM tbl_CapEx_Projects_Group " & _
"WHERE PG_ID=" & var_PGID
Delete_PG_Upld = "DELETE * " & _
"FROM tbl_CapEx_Projects_Group_Attachements " & _
"WHERE PG_ID=" & var_PGID
Debug.Print Delete_PG_Data
Debug.Print Delete_PG_Upld
db.Execute Delete_PG_Data, dbFailOnError
db.Execute Delete_PG_Upld, dbFailOnError
''Me.Recordset.Delete
''DBEngine.BeginTrans
''DBEngine.CommitTrans
Else
If Me.Saved Then
DBEngine.Rollback
Else
If Me.Dirtied Then DBEngine.Rollback
End If
End If
DoCmd.Close ObjectType:=acForm, ObjectName:=Me.Name
Form_frm_CapEx_Edit_Project_Groups_Cont.Requery
DoCmd.SetWarnings True
End Sub
.. delete a newly created record if the user cancels
Sounds like the record doesn't get saved. Even if not, it could be a timing issue as the run the query in another context than the form.
If it really has been created, the simplest and fastest method is to delete the record from the RecordsetClone of the form.
Use DoCmd.RunSQL
example :
Public Sub DoSQL()
Dim SQL As String
SQL = "UPDATE Employees " & _
"SET Employees.Title = 'Regional Sales Manager' " & _
"WHERE Employees.Title = 'Sales Manager'"
DoCmd.RunSQL SQL
End Sub
Hence your new code will be as below:
Dim var_PGID As String
Dim Delete_PG_Data, Delete_PG_Upld As String
var_PGID = TempVars![var_PG_ID_NEW]
Delete_PG_Data = "DELETE * " & _
"FROM tbl_CapEx_Projects_Group " & _
"WHERE PG_ID=" & var_PGID
Delete_PG_Upld = "DELETE * " & _
"FROM tbl_CapEx_Projects_Group_Attachements " & _
"WHERE PG_ID=" & var_PGID
MsgBox Delete_PG_Data
MsgBox Delete_PG_Upld
DoCmd.RunSQL Delete_PG_Data
DoCmd.RunSQL Delete_PG_Upld

Update another table when field is changed

I have a form contains "DateProduced" field. The table bound to it is called "Report".
I try to add after update event to this field and want this event to update "DateProduced" field in Quantity table if ID matches for both.
Me![Text0] displays the ID from Report field
Me![Text4] displays the DateProduced from Report field.
The event code is as below.
Private Sub Text4_AfterUpdate()
Dim strSQL As String
strSQL = "UPDATE Quantity " _
& "SET [DateProduced] = (#" & Me![Text4] & "#) " _
& "WHERE ID = (" & Me![Text0] & ")"
DoCmd.RunSQL strSQL
End Sub
But i can not succeed.
That date format will fail for values where dd/mm can be interchanged for a valid date. It should read:
Private Sub Text4_Exit(Cancel As Integer)
Dim strSQL As String
strSQL = "UPDATE Quantity " _
& "SET [DateProduced] = #" & Format(Me!Text4.Value, "yyyy\/mm\/dd") & "# " _
& "WHERE [ID] = " & Me![Text0].Value & ";"
DoCmd.RunSQL strSQL
End Sub
A note: You should change the names of Text0 etc. to meaningful names.
I made it work with the following code. Thx
Private Sub Text4_Exit(Cancel As Integer)
Dim strSQL As String
strSQL = "UPDATE Quantity " _
& "SET [DateProduced] = #" & Format(Me.Text4.Value, "dd-mm-yyyy") & "#" _
& "WHERE [ID] = (" & Me![Text0] & ");"
DoCmd.RunSQL strSQL
End Sub

Error SQL in VBA Access 2010

I'm trying to write a query in MS Access 2010 in order to use it to print a report, but it gives me "missing parameter" error in "set qd" line, hereunder is the code i wrote, can you please help me and tell me what is wrong with my code:
`Private Sub Command5_Click()
Dim qd As DAO.QueryDef
Dim rs As DAO.Recordset
Dim strSql As String
Dim strFrom, strTo As String
strFrom = [Forms]![FrmPrintSelection]![txtFrom]
strTo = [Forms]![FrmPrintSelection]![txtTo]
strSql = "SELECT tblInvoiceHead.CustomerNumber,
tblCustomers.AccountName,tblCustomers.Address,
tblCustomers.Phone1, tblCustomers.Phone2," _
& "tblCustomers.Mobile1, tblCustomers.Mobile2, tblInvoiceHead.InvoiceNumber,
tblInvoiceHead.InvoiceDate, tblInvoiceHead.TotalInvoice," _
& "tblInvoiceHead.CashDiscount, TblInvoiceDetails.Item, TblInvoiceDetails.Unit,
TblInvoiceDetails.Qtn, TblInvoiceDetails.Price," _
& "TblInvoiceDetails.[Discount%], TblInvoiceDetails.CashDiscount,
TblInvoiceDetails.NetUnitPrice, TblInvoiceDetails.TotalPrice, tblInvoiceHead.InvoiceType" _
& "FROM (tblCustomers INNER JOIN tblInvoiceHead ON tblCustomers.AccountNumber =
tblInvoiceHead.CustomerNumber) INNER JOIN TblInvoiceDetails" _
& "ON tblInvoiceHead.InvoiceNumber = TblInvoiceDetails.InvoiceNumber" _
& "WHERE (((tblInvoiceHead.InvoiceNumber) Between " & strFrom & " And " & strTo & "))"
Set qd = CurrentDb.CreateQueryDef("RepInv", strSql)
Set rs = qd.OpenRecordset
'DoCmd.OpenQuery "repinv", strSql
Reports!repinvoicetest.RecordSource = "repinv"
DoCmd.OpenReport "repinvoicetest", acViewPreview
End Sub
`
Usually the error "missing parameter" means that you spelled one of your columns wrong. If you take your sql and paste it into a new query (temp, don't save) and run it, the misspelled column will pop up a window asking you to provide a value for that "parameter" (because MSAccess is assuming that you never would misspell a column name).
In your query above, you might have copy/pasted it wrong, but if not, then you don't have enough spaces between your words as you continue them on the next line. For instance, your SQL string would end up having some stuff in it like "InvoiceTypeFROM", because you didn't have an extra (necessary) space in there.
Try this query instead:
strSql = "SELECT tblInvoiceHead.CustomerNumber, " _
& " tblCustomers.AccountName,tblCustomers.Address, " _
& " tblCustomers.Phone1, tblCustomers.Phone2, " _
& " tblCustomers.Mobile1, tblCustomers.Mobile2, tblInvoiceHead.InvoiceNumber, " _
& " tblInvoiceHead.InvoiceDate, tblInvoiceHead.TotalInvoice, " _
& " tblInvoiceHead.CashDiscount, TblInvoiceDetails.Item, TblInvoiceDetails.Unit, " _
& " TblInvoiceDetails.Qtn, TblInvoiceDetails.Price, " _
& " TblInvoiceDetails.[Discount%], TblInvoiceDetails.CashDiscount, " _
& " TblInvoiceDetails.NetUnitPrice, TblInvoiceDetails.TotalPrice, " _
& " tblInvoiceHead.InvoiceType " _
& " FROM (tblCustomers INNER JOIN tblInvoiceHead " _
& " ON tblCustomers.AccountNumber = tblInvoiceHead.CustomerNumber) " _
& " INNER JOIN TblInvoiceDetails " _
& " ON tblInvoiceHead.InvoiceNumber = TblInvoiceDetails.InvoiceNumber " _
& " WHERE (((tblInvoiceHead.InvoiceNumber) Between " & strFrom & " And " & strTo & "))"
Notice how I added a lot of unncessary spaces at the begining and end of each line. All of those extra spaces will be ignored. However, if there are too few, then you will get errors. It is a simple trick that I stick-with.

Using form combo boxes apply a filter to a query

I think I am close to this one, but can't work out the filtering process.
tblIndex(PrimaryCat,SubCat,UserID,Year)
tblResults(SubCat,UserID)
My Form has two combo boxes and a button. ComboBox1 has tblIndex.PrimaryCat values and ComboBox2 has tblIndexYear values.
What I want is when the command button in the form is pressed, tblResults opens showing the list of SubCat and UserID values when the combobox values are used as a filter on tblIndex.
Does this make sense?
I have the recordsource of the form set to tblResults. I'm using this, just need to add in filtering somehow:
Private Sub cmdGo_Click()
Dim strSQL As String
strSQL = "SELECT SubCat, UserID " & _
"FROM tblIndex " & _
"WHERE PrimaryCat = [strCat] AND Year = [strYear] " & _
"GROUP BY SubCat, UserID"
DoCmd.OpenQuery "strSQL"
End Sub
EDIT:
I'm not sure if I am allowed to answer my own question but I worked out a solution. I >used INTO to put the results into a temp table I can further manipulate using:
Private Sub cmdGo_Click()
Dim strSQL As String
strSQL = "SELECT SubCat, UserID INTO tblTemp " & _
"FROM tblIndex " & _
"WHERE PrimaryCat = '" & cboPrimaryCat.Value & "' AND Year = '" & >cboYear.Value & _
"' GROUP BY SubCat, UserID"
DoCmd.RunSQL strSQL
End Sub
Worked it out. Can't run SQL without first storing it in a query. Solution is:
Private Sub cmdGo_Click()
Dim qdfCurr As DAO.QueryDef
Dim strSQL As String
strSQL = "SELECT SubCat, UserID " & _
"FROM tblIndex " & _
"WHERE PrimaryCat = '" & strCat.Value & "' AND Year = '" & strYear.Value & _
"' GROUP BY SubCat, UserID"
On Error Resume Next
Set qdfCurr = CurrentDb.QueryDefs("TempQuery")
If Err.Number = 3265 Then
Set qdfCurr = CurrentDb.CreateQueryDef("TempQuery")
End If
qdfCurr.SQL = strSQL
DoCmd.OpenQuery "TempQuery"
End Sub
I think that this sould work. Working with temp tables is more complicated. Imagine that you have 50 queries with their corresponding temp table!
Private Sub cmdGo_Click()
Dim strSQL As String
strSQL = "SELECT SubCat, UserID " & _
"FROM tblIndex " & _
"WHERE PrimaryCat = " & Forms!FormName![strCat] & " AND Year = " & Forms!FormName![strYear] " " & _
"GROUP BY SubCat, UserID"
DoCmd.OpenQuery strSQL
End Sub