VBA Access Getting Runtime Error 3144 on previously working event - ms-access

I have an issue that has developed while modifying an update event that previously had been working. I am now getting a Runtime Error 3144, "Syntax error in UPDATE statement." When I go to debug the following line of code is flagged.
Set qdf = db.CreateQueryDef(vbNullString, strUpdate)
This function previously was working as it it was meant to in creating a SQL string to run an Update command. However I needed to adapt this same function to a different but mostly similar form.
I have included the complete code below for review and could use some assistance in spotting whatever little detail I missed/messed up in the transfer.
Private Sub btnEntEdt_Click()
Dim strUpdate As String
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
strUpdate = "UPDATE EntList AS e" & vbCrLf & _
"SET e.BusinessUnit = pBusinessUnit, " & _
"e.EntityID = pEntityID, " & vbCrLf & _
"e.EntityName = pEntityName, " & vbCrLf & _
"e.Location = pLoc, " & vbCrLf & _
"e.Client = pCli, " & vbCrLf & _
"e.Dept = pDept, " & vbCrLf & _
"WHERE e.EntityID = pEntityID;"
Debug.Print strUpdate
Set db = CurrentDb
Set qdf = db.CreateQueryDef(vbNullString, strUpdate)
qdf.Parameters("pBusinessUnit") = Me.cboBUnit.Value
qdf.Parameters("pEntityName") = Me.txtEntName.Value
qdf.Parameters("pEntityID") = Me.txtEntID.Value
qdf.Parameters("pLoc") = Me.cboLoc.Value
qdf.Parameters("pCli") = Me.cboClient.Value
qdf.Parameters("pDept") = Me.cboDept.Value
qdf.Execute dbFailOnError
Set qdf = Nothing
Set db = Nothing
Me.lstEntName.Requery
End Sub

You were wise to include Debug.Print strUpdate. Examine its output ...
UPDATE EntList AS e
SET e.BusinessUnit = pBusinessUnit, e.EntityID = pEntityID,
e.EntityName = pEntityName,
e.Location = pLoc,
e.Client = pCli,
e.Dept = pDept,
WHERE e.EntityID = pEntityID;
That statement triggers an error because of the comma at the end of the SET clause.
e.Dept = pDept,
^ here
Eliminate that comma, test the revised UPDATE statement in the query designer, and once you have it working correctly, modify your VBA code to produce the same statement text.
Or you could save the working version as a named query, qryUpdateEntList, and then reference the named query from your VBA code instead of re-creating the statement text at run time.
Set qdf = db.QueryDefs("qryUpdateEntList")
Apart from the syntax error, this combination looks wrong to me ...
SET e.EntityID = pEntityID
WHERE e.EntityID = pEntityID
Because of the WHERE clause, the UPDATE will only affect rows where EntityID = pEntityID. So there is no need to SET EntityID = pEntityID; they are already equal.

Related

Access VBA: Recordset should be NOT nothing

I have a Front-End database setup for users to extract data regarding a list of information that they upload. The export function worked fine except they want the results to go to the open workbook add a sheet with the data without saving. The problem is that the created query has data when I run the query before or after the macro is not running. However as the macro is running the query returns nothing. The latest VBA I'm using is below. Please review and advise what I'm missing.
Thank you,
MS Office - Access: 2010
Active Reference Library:
Visual Basic for applications
Microsoft Access 14.0 Object Library
OLE Automation
Microsoft Excel 14.0 Object Library
Microsoft Office
14.0 Access database engine Object Library
Macro:
Private Sub ExpFile_Click()
Dim sql2export, s As String, blnExcel, blnWhere As Boolean, qdf As QueryDef, xlApp As Object, ws As Excel.Worksheet
Dim MyDatabase As DAO.Database, MyQueryDef As DAO.QueryDef, MyRecordset As DAO.Recordset
blnWhere = False
If Me. QueryASubform.Visible = True Then 'exceptions
sql2export = "QueryA"
blnWhere = True
ElseIf Me. QueryBSubform.Visible.Visible = True Then 'no Program Group for Build ID
sql2export = " QueryB"
ElseIf Me. QueryCSubform.Visible = True Then 'Bill to and Type report.
sql2export = " QueryC"
Else: Exit Sub
End If
If blnWhere = False Then
s = "select * from " & sql2export & " Where (((" & sql2export & ". GPID)=[Forms]![frmFEFindQA]![GPID]));"
Else: s = "select * from " & sql2export
End If
On Error Resume Next
CurrentDb.QueryDefs.Delete "xlsExport"
Set qdf = CurrentDb.CreateQueryDef("xlsExport", s)
Set xlApp = GetObject(, "excel.application")
If (Err.Number = 0) Then
Set xlApp = GetObject("Excel.Application")
xlApp.Visible = True
Set ws = xlApp.Sheets.Add
Set MyDatabase = CurrentDb
MyDatabase.QueryDefs.Delete ("xlsExport")
Set MyQueryDef = MyDatabase.CreateQueryDef("xlsExport", s)
Set MyRecordset = MyDatabase.OpenRecordset("xlsExport") ‘<------ empty
With xlApp
.ws.Select
.ActiveSheet.Range("a2").CopyFromRecordset MyRecordset
For i = 1 To MyRecordset.Fields.Count
xlApp.ActiveSheet.Cells(1, i).Value = MyRecordset.Fields(i - 1).Name
Next i
xlApp.Cells.EntireColumn.AutoFit
End With
Else:
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "xlsExport", "C:\Users\" & Environ("USERNAME") & "\Documents\VehInfoExp", True
xlApp.Workbooks.Open "C:\Users\" & Environ("USERNAME") & "\Documents\InfoExp.xls", True, False
End If
Err.Clear
On Error GoTo 0
Set xlApp = Nothing
End Sub
Arg, I found the answer. After a week of trying I decided to post the question and then I figured it out an hour later.
The issue is in the "Where" clause of the SQL. I needed to capture the value of the form as a variable and put it into the equation. For some reason while the macro is running the referenced part of the form was valued as nothing. So nothing was returned.
Therefore, the following line of SQL:
s = "select * from " & sql2export & " Where (((" & sql2export & ".GPID)=[Forms]![frmFEFindQA]![GPID]));"
Became:
s = "select * from " & sql2export & " Where (((" & sql2export & ".GPID)=""" & strWhere & """));"
Thank you for letting me post.

Combining Access Tables

I have a central database that is kept on a network that stores part numbers & descriptions for various components for machines. Often times individuals will need to use an offline copy during design and will add new entries to it. Is there a script to find the differences and update the master file that is on the network? I played around with union queries but I'm struggling to be able to update the original file and original table. My sql/microsoft access knowledge is limited.
For sake of clarity let's call the files as such:
Network Database: Network_DB.mdb
Offline Database: Offline_DB.mdb
Table: MISC_CAT
In my experience a generic solution is pretty difficult. I tend to store the field names I want in a table then run the relevant update:
Public Function UpdateData()
Dim db As Database
Dim qd As QueryDef
Dim rs As Recordset
Dim strSQL As String
On Error GoTo Err_UpdateData
Set db = CodeDb
strSQL = "SELECT fldName FROM MyTables WHERE tblName = 'MISC_CAT'"
Set rs = db.OpenRecordset(strSQL, dbOpenSnapshot)
Do Until rs.EOF
strSQL = "UPDATE MISC_CAT_Network INNER JOIN MISC_CAT_Offline ON MISC_CAT_Network.KeyID = MISC_CAT_Offline.KeyID " & _
"SET MISC_CAT_Network.[" & rs!fldName & "] = [MISC_CAT_Offline].[" & rs!fldName & "] " & _
"WHERE (((Nz([MISC_CAT_Network].[" & rs!fldName & "],''))<>Nz([MISC_CAT_Offline].[" & rs!fldName & "],'')))"
db.Execute strSQL, dbFailOnError
rs.MoveNext
Loop
db.Execute strSQL, dbFailOnError
rs.Close
db.Close
Exit_UpdateData:
Set rs = Nothing
Set qd = Nothing
Set db = Nothing
Exit Function
Err_UpdateData:
Debug.Print "Error - " & Err.Number & " - " & Err.Description
Resume Exit_UpdateData
End Function

Invalid use of Me keyword

This code is a function and not a private subroutine. I'm suddenly getting this error with the Me.[field name here]. I'm not getting that error in my other code, just in this one. Here's my full code without the boring end part, but I'm getting the error starting from the line:
Me.assignedby.Column(1)
Public Function AssignNullProjects() As Long
Dim db As dao.Database
Dim rs As dao.Recordset
Dim strSQL As String
assignedby = TempVars("user").Value
Set db = CurrentDb
strSQL = "SELECT CFRRRID FROM CFRRR WHERE assignedto Is Null"
Set rs = db.OpenRecordset(strSQL, dbOpenDynaset)
If Not rs.BOF And Not rs.EOF Then
While Not rs.EOF
strSQL = "UPDATE CFRRR SET assignedto = " & GetNextAssignee & ", assignedby = " & Me.assignedby.Column(1) & ", Me.Dateassigned = #" & Now & "#, Me.actiondate = #" & Now & "#, Me.Workername = " & _
Me.assignedto.Column(0) & ", Me.WorkerID = " & Me.assignedto.Column(0) & " WHERE CFRRRID = " & rs!CFRRRID
db.Execute strSQL, dbFailOnError
rs.MoveNext
Wend
End If
rs.Close
db.Close
Set rs = Nothing
Set db = Nothing
What could be the possible reason for the above-stated error, and how it could be removed?
Put that code in the form's code module. When you try to use Me in a standard module, you will always get that "Invalid use of Me keyword" complaint.
Check out the "Invalid use of Me keyword" and "Me <keyword>" topics in Access' help system for further details.

Access VBA to update Access table from SQL Server table source

I have created the code below to test whether I can run a query and retrieve a data from an SQL server table. And so far I can return the result using a MessageBox, but somehow I just don't know how to use this connection to update the table inside this Access file. Basically I want to use this as a front end file. Then, when the form is open it will automatically update the table inside this access file and load the data to the combo box as a list. I tried searching it here and read many discussions here and in Google but currently I can't find the right solution.
Option Compare Database
Sub LocalServerConn_Test()
Set conn = New adodb.Connection
Set rst = New adodb.Recordset
strDBName = "DataSet"
strConnectString = "Provider = SQLOLEDB.1; Integrated Security = SSPI; " & _
"Initial Catalog = " & strDBName & "; Persist Security Info = True; " & _
"Worksation ID = abc123;"
conn.ConnectionString = strConnectString
conn.Open
strSQL = "SELECT DISTINCT dbo.abc.abc123 FROM dbo.abc"
rst.Open Source:=strSQL, ActiveConnection:=strConnectString, _
CursorType:=adOpenDynamic, LockType:=adLockOptimistic
If rst.RecordCount = 0 Then
MsgBox "No records returned"
Else
rst.MoveFirst
Do While Not rst.EOF
MsgBox rst.Fields("abc123").Value
rst.MoveNext
Loop
End If
conn.Close
rst.Close
End Sub
You should be able to use code very similar to this:
Dim cdb As DAO.Database
Set cdb = CurrentDb
cdb.Execute _
"DELETE FROM LocalTable", _
dbFailOnError
cdb.Execute _
"INSERT INTO LocalTable (abc123) " & _
"SELECT DISTINCT abc123 " & _
"FROM " & _
"[" & _
"ODBC;" & _
"Driver={SQL Server};" & _
"Server=.\SQLEXPRESS;" & _
"Database=DataSet;" & _
"Trusted_Connection=yes;" & _
"].[dbo.abc]", _
dbFailOnError
Set cdb = Nothing
You can just keep the combo box bound to [LocalTable] and the updated values from the SQL Server table should appear.

Access pass-through query giving error

I'm using the following code to run a passthrough query. I'm trying to run the passthrough query, then check how many records are returned to figure out if it worked. But I get an error saying
"Invalid Operation"
Why is it doing this and how can I correct?
Dim Item As String
Item = InputBox("Enter Item needing a surrogate UPC.", "Enter Item")
Set db = CurrentDb
Set qdf = db.QueryDefs("spAL_AssignSurrogateUPC")
qdf.ReturnsRecords = True
qdf.SQL = "spAL_AssignSurrogateUPC '" & Item & "'"
With qdf.OpenRecordset(dbOpenSnapshot) '<--- Error triggered here.
If qdf.RecordCount = 1 Then
MsgBox "Surrogate UPC assigned."
Else
MsgBox "ERROR. Could not assign surrogate UPC."
End If
End With
Use the EXEC syntax
qdf.SQL = "EXEC spAL_AssignSurrogateUPC '" & Replace(Item, "'", "''") & "';"
(I assume it's SQL Server.)
I also added a replace function in order to cope with single quotes in the Item string. This also helps prevent SQL injections.
EDIT:
Try to do this, instead of using the With-statement
Dim rs as DAO.Recordset
...
Set rs = qdf.OpenRecordset(dbOpenSnapshot)
If rs.EOF Then
MsgBox "ERROR. Could not assign surrogate UPC."
Else
MsgBox "Surrogate UPC assigned."
End If