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
MsgBox
byDebug.Print
and add the output from the Immediate window to your question (Ctrl+G takes you there). -- See also: How to debug dynamic SQL in VBA – AndredbFailOnError
parameter to db.Execute. Try to copy the value of Delete_PG_Data and Delete_PG_Upld variables to query builder and execute there. – Sergey S.On Error Resume Next
is dangerous, it's masking all sorts of errors - you are updating records you didn't edit, committing or rolling back transactions you didn't start, etc. -- I have the feeling that a simpleMe.Dirty = False
to save the new & edited record would solve your issues. – Andre