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

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

Related

MS Access recordcount is always 1 even with no record

I am using MS Access 2010. I am trying to search a table and determine if the record exists based on First and Last name, If the record exists then update the record, and if it does not exist, then insert the new record. I am not getting any errors but I always get a recordcount of 1 even if I enter a name that I know does not exist in the table.
Private Sub txtSearchFirstName_Exit(Cancel As Integer)
Dim strSQL As String
Dim db As Database
Dim rs As DAO.Recordset
Dim recordCount As Long
Set db = CurrentDb
Set rs = Nothing
Stop
''Check if a keyword entered or not
If IsNull(Me.txtSearchlastName) = "" Then
MsgBox "Please type in your search keyword.", vbOKOnly, "Keyword Needed"
Else
strSQL = "SELECT COUNT(*) " & _
"FROM tblBobbettesMarketBulletin_CustNum " & _
"WHERE tblBobbettesMarketBulletin_CustNum.Last = " & Chr(34) & txtSearchlastName & Chr(34) & _
" AND tblBobbettesMarketBulletin_CustNum.First = " & Chr(34) & txtSearchFirstName & Chr(34)
Debug.Print strSQL
Set rs = db.OpenRecordset(strSQL, dbOpenDynaset)
If (rs.BOF And rs.EOF) Then
recordCount = 0
Else
rs.MoveLast
recordCount = rs.recordCount
End If
If recordCount > 0 Then MsgBox ("Record exists")
If recordCount = 0 Then MsgBox ("Record does not exist")
rs.Close
Set rs = Nothing
End If
End Sub
#HansUp describes your problem perfectly.
If you want to simplify the code and use this feature, assign a field name to your Count(*) and then query and use its value in one step
strSQL = "SELECT COUNT(*) AS NumFound " & _
"FROM tblBobbettesMarketBulletin_CustNum " & _
"WHERE tblBobbettesMarketBulletin_CustNum.Last = " & Chr(34) & txtSearchlastName & Chr(34) & _
" AND tblBobbettesMarketBulletin_CustNum.First = " & Chr(34) & txtSearchFirstName & Chr(34)
Debug.Print strSQL
Set rs = db.OpenRecordset(strSQL, dbOpenDynaset)
MsgBox ("Found " & rs!NumFound & " Record(s)")

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'"

VBA/SQL issue access

I keep recieving compiling errors saying that txtlln in the where line cannot be found. I am fairly new to SQL/VBA so I am not sure I am using the correct expressions to have this work.
Private Sub btnlledit_Click()
Dim strSQL As String
SQL = "UPDATE tblll " & _
"SET [Component/Product] = '" & Forms!frmaddll!txtllcomponent & "',[HN] = '" & Forms!frmaddll!txtllhn & "' " & _
"WHERE [LLN] = '" & Forms!frmaddll!txtlln.value & "';"
debug.print sql
DoCmd.RunSQL strSQL
DoCmd.SetWarnings True
DoCmd.Requery
Me.Refresh
End Sub
You seem to have a few issues swith your string concatenation.
Private Sub btnlledit_Click()
Dim strSQL As String
SQL = "UPDATE tblll " & _
"SET [Component/Product] = '" & Forms!frmaddll!txtllcomponent & "' " & _
"WHERE [LLN] = '" & Forms!frmaddll!txtlln.value & "';"
debug.print sql
DoCmd.RunSQL strSQL
DoCmd.SetWarnings True
DoCmd.Requery
Me.Refresh
End Sub

Run-time Error 3131 Syntax Error in FROM clause

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'"

MS.Access VBA - Error 3061: Too Few Parameters.Expected 2

I'm new to VBA. Right now, I want to create editable crosstab table using temp table. I have problem when I want to update the normalize table based on edited data. When I run my codes, I get this error, Error 3061: Too Few Parameters.Expected 2.Can somebody help me to check my codes? Thanks in advance
Public Sub Normalize()
Dim rs As DAO.Recordset
On Error GoTo EH
'delete existing data from temp table
CurrentDb.Execute "DELETE * FROM tblNormalize;", dbFailOnError + dbSeeChanges
'get a recordset of the column headers
Set rs = CurrentDb.OpenRecordset("SELECT DISTINCT newvalue FROM Table1;")
Debug.Print
rs.MoveFirst
Do While rs.EOF = False
' "un" crosstab the data from crosstab table into Normalize table
CurrentDb.Execute "INSERT INTO tblNormalize (product, spec, descr,newvalue, Rate )" & Chr(10) & _
"SELECT product,spec,descr, " & rs.Fields("newvalue") & ", [" & rs.Fields("newvalue") & "]" & Chr(10) & _
"FROM tblCrosstab;", dbFailOnError + dbSeeChanges
Debug.Print rs.Fields("newvalue")
rs.MoveNext
Loop
rs.Close
Set rs = Nothing
'update the original normalized dataset
CurrentDb.Execute "UPDATE tblNormalize INNER JOIN Table1 t1 ON (tblNormalize.newvalue = t1.newvalue) " & _
" AND (tblNormalize.product = t1.product) AND (tblNormalize.spec = t1.spec) " & _
" AND (tblNormalize.descr = t1.descr)" & _
" SET Table1.Rate = tblNormalize.Rate;", dbFailOnError + dbSeeChanges
Exit Sub
EH:
MsgBox "Error " & Err.Number & ": " & Err.Description, vbOKOnly, "Error"
End Sub
You are creating a world of hurt for yourself. Apart from that, this:
"INSERT INTO tblNormalize (product, spec, descr,newvalue, Rate )" & Chr(10) & _
"SELECT product,spec,descr, " & rs.Fields("newvalue") & ", [" & rs.Fields("newvalue") & "]" & Chr(10) & _
"FROM tblCrosstab;"
Is going to come out all wrong.
Try:
"INSERT INTO tblNormalize (product, spec, descr,newvalue, Rate )" & _
" SELECT product,spec,descr, " & rs.Fields("newvalue") & ", [" _
& rs.Fields("newvalue") & "] FROM tblCrosstab;"
Also, use Debug.Print to write the string to the immediate window (Ctrl+G) and check if it works in the query design window. That error is usually due to misspelling of missing fields (columns).