I am running some EXCEL VBA code to update the contents of an ACCESS database table along the lines suggested here:
IF ##Rowcount = 0 -- SQL Syntax Error in Access
. When I execute the SELECT query, EXCEL VBA gives this error message:
Run-time error 424: Object required
I extracted the SQL string from the VBA Watch window and ran it as a Query in ACCESS. The first time I did this, there were no records becasue the table was empty, so I ran the INSERT query in ACCESS and then tried running the VBA code but got the same error message.
The code is here:
Public db As DAO.Database
' Open database
Public Sub OpenMdtDatabase()
Set db = DBEngine(0).OpenDatabase("SL_MDT_data_v1.accdb")
End Sub
' Update DB table
Sub UpdateDb()
' Initialise
Dim rs As DAO.Recordset
Set xlSht = Sheets("plot_data")
' Open database
Call OpenMdtDatabase
' Get the data to store
sname = xlSht.Cells(6, "R").Value
xfill = xlSht.Cells(6, "S").Value
xedge = xlSht.Cells(6, "T").Value
xstyl = xlSht.Cells(6, "U").Value
xsize = xlSht.Cells(6, "V").Value
' SQL stuff
sqlTxtSelect = "SELECT SeriesName FROM SeriesProperties WHERE SeriesName ='" & sname & "';"
sqlTxtUpdate = "UPDATE SeriesProperties " & _
sqlTxtUpdate = "SET SeriesFill = " & xfill & ", " & _
sqlTxtUpdate = "SeriesEdge = " & xedge & ", " & _
sqlTxtUpdate = "SeriesStyle = " & xstyl & ", " & _
sqlTxtUpdate = "SeriesSize = " & xsize & " " & _
sqlTxtUpdate = "WHERE SeriesName = '" & sname & "';"
sqlTxtInsert = "INSERT INTO SeriesProperties('" & sname & "') " & _
sqlTxtInsert = "VALUES(" & xfill & ", " & xedge & ", " & xstyl & ", " & xsize & ");"
Set rs = db.OpenRecordset(sqlTxtSelect)
If rs.RecordCount = 0 Then
DoCmd.RunSQL (sqlTxtInsert)
Else
DoCmd.RunSQL (sqlTxtUpdate)
End If
End Sub
I am guessing that there is something wrong with the SQL SELECT string. I tried setting this directly using
SELECT SeriesName FROM SeriesProperties WHERE SeriesName ='14/10-2:F2F_SLMC'
but still get the same error message. I have also tried removing the colon ...
The problem lies with the statement
DoCmd.RunSQL (sqlTxtInsert)
If I change this to
db.Execute (sqlTxtInsert)
then everything is fine. Should have scrolled to the end of the answer at the original link ....
Related
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'"
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
I am using a VBA query in Access database for creating a temp table for updating the values, however I am getting error message saying 'temp table0' already exists, how to navigate this?
I am getting error message in 'CurrentProject.Connection.Execute strSql'
rs2.Close 'Close the recordset
Set rs2 = Nothing 'Clean up
'Create temporary tables
Dim tableFlag As String
tableFlag = "Treaty"
For x = 1 To 2
If (rs1![Prems/Claims] = "Premium") Then
If (tableFlag = "Treaty") Then
strSql = "SELECT [Premiums " & tableFlag & "].ID, [Premiums " & tableFlag & "].[Pricing Segment]"
For i = 0 To columnsCount - 1 ' loop through all boolean atributes
strSql = strSql & ", [Premiums " & tableFlag & "].[" & boolAtrName(i) & "]"
Next
strSql = strSql & " INTO [tempTable " & tablesCount & "] FROM [Premiums " & tableFlag & "] WHERE [GDS Version] = " & rs1!ID & ";"
'Execute temporary table string
CurrentProject.Connection.Execute strSql
'Add column percentage to table
CurrentDb.Execute "ALTER TABLE [tempTable " & tablesCount & "] ADD COLUMN Percentage double, Identifier Text"
'Update values in column percentage
Set rs2 = CurrentDb.OpenRecordset("SELECT * FROM [tempTable " & tablesCount & "];")
I'm getting an Access Run-time error:
'3061': Too few parameters. Expected 1
when trying to run some VBA code from a form with sub-report.
I've tried with the variable (CurAssetID) as well as the direct link (Forms!Details!ID) in the SQL query but both result in the same error. I put in the MsgBox just to verify it was picking up the correct value which it is.
If I replace the last part of the SQL query with a value (HAVING (((Assignments.AssetID)=1));") it works fine. What's going on here and how can I fix it?
Private Sub LineSelect_Click()
CurAssetID = Forms!Details!ID
Status = MsgBox(CurAssetID, vbOKOnly)
Dim LastAssignment As DAO.Recordset
LastAssignmentSQL = "SELECT Assignments.AssetID, Last(Assignments.LocationID) AS LastLocationID FROM Assignments GROUP BY Assignments.AssetID HAVING (((Assignments.AssetID)=CurAssetID));"
Set LastAssignment = CurrentDb.OpenRecordset(LastAssignmentSQL, dbOpenDynaset, dbSeeChanges)
You can create a string variable with the parameter value concatenated inside it:
curAssetID = Forms!Details!ID
status = MsgBox(CurAssetID, vbOKOnly)
Dim lastAssignment As DAO.Recordset
lastAssignmentSQL = "SELECT Assignments.AssetID, " & _
"Last(Assignments.LocationID) AS LastLocationID " & _
"FROM Assignments " & _
"GROUP BY Assignments.AssetID " & _
"HAVING (((Assignments.AssetID)=" & CurAssetID & "));"
Set lastAssignment = CurrentDb.OpenRecordset(lastAssignmentSQL, dbOpenDynaset, dbSeeChanges)
' ...
As an additional precaution, if Forms!Details!ID is suposed to be a number (Integer or Long), I suggest you declare the variable CurAssetID explicitly:
Dim curAssetID as Integer ' Or Long
curAssetID = Forms!Details!ID
Dim lastAssignment As DAO.Recordset
lastAssignmentSQL = "SELECT Assignments.AssetID, " & _
"Last(Assignments.LocationID) AS LastLocationID " & _
"FROM Assignments " & _
"GROUP BY Assignments.AssetID " & _
"HAVING (((Assignments.AssetID)=" & CurAssetID & "));"
Set lastAssignment = CurrentDb.OpenRecordset(lastAssignmentSQL, dbOpenDynaset, dbSeeChanges)
' ...
If the value is a 'String', then you should enclose the value in quotes in your query:
Dim curAssetID as String
' ...
lastAssignmentSQL = "SELECT Assignments.AssetID, " & _
"Last(Assignments.LocationID) AS LastLocationID " & _
"FROM Assignments " & _
"GROUP BY Assignments.AssetID " & _
"HAVING (((Assignments.AssetID)= '" & CurAssetID & "'));"
' ...
I have problem with this UPDATE query , I have got message about syntax error query. I think that this query is correct and I can't find what is giving this error.
Link to error
Private Sub cmdModifyBook_Click() 'approves modifying books to the database
Dim str As String
Dim dbs As DAO.Database
Set dbs = CurrentDb()
'checks if the typed all the data of book
If (Me.txtModifyTitle.Value = "") Or (Me.txtModifyTitleWeb.Value = "") Or (Me.txtModifyVerkaufpreis.Value = "") _
Or (Me.txtModifyThemengruppe.Value = "") Then
MsgBox "Nicht alle von Ihnen eingegebenen Daten"
Exit Sub
End If
str = " UPDATE Katalog " _
& "(Bezeichnung, BezeichnungWeb, Verkaufspreis, Themengruppe) SET " _
& "('" & Me.txtModifyTitle.Value & "', '" & Me.txtModifyTitleWeb.Value & "', '" & Me.txtModifyVerkaufpreis.Value & "', '" & Me.txtModifyThemengruppe.Value & "') WHERE ID_Buch =" & Me.lblModifyID.Caption & ";"
dbs.Execute str, dbFailOnError
MsgBox "Das Buch wurde in der Datenbank geändert", vbInformation
dbs.Close
Set dbs = Nothing
End Sub
Your code should look like this instead:
Private Sub cmdModifyBook_Click() 'approves modifying books to the database
Dim str As String
Dim dbs As DAO.Database
Set dbs = CurrentDb()
'checks if the typed all the data of book
If (Me.txtModifyTitle.Value = "") Or (Me.txtModifyTitleWeb.Value = "") Or (Me.txtModifyVerkaufpreis.Value = "") _
Or (Me.txtModifyThemengruppe.Value = "") Then
MsgBox "Nicht alle von Ihnen eingegebenen Daten"
Exit Sub
End If
str = "UPDATE Katalog " & _
"SET Bezeichnung = '" & PQ(Me.txtModifyTitle.Value) & "', " & _
"BezeichnungWeb = '" & PQ(Me.txtModifyTitleWeb.Value) & "', " & _
"Verkaufspreis = '" & PQ(Me.txtModifyVerkaufpreis.Value) & "', " & _
"Themengruppe = '" & PQ(Me.txtModifyThemengruppe.Value) & "' " & _
"WHERE ID_Buch = " & Me.lblModifyID.Caption & ";"
Debug.Print str
MsgBox str
dbs.Execute str, dbFailOnError
MsgBox "Das Buch wurde in der Datenbank geändert", vbInformation
dbs.Close
Set dbs = Nothing
End Sub
Private Function PQ(s as string) as String
PQ = Replace(s, "'", "''")
End Function
Be aware that you need to replace any single quotes that might exist inside the values from the textboxes with two single quotes to prevent SQL errors. That's why I posted the PQ function.
The UPDATE command syntax is as follows
UPDATE Katalog
SET
Bezeichnung = Me.txtModifyTitle.Value ,
BezeichnungWeb = Me.txtModifyTitleWeb.Value ,
Verkaufspreis = Me.txtModifyVerkaufpreis.Value,
Themengruppe = Me.txtModifyThemengruppe.Value
WHERE ID_Buch = Me.lblModifyID.Caption
Of course the above will now work since you have to adopt it for str variable