如果用户取消,我试图让我的代码删除新创建的记录。由于某种原因,即使查询肯定是对表中存在的唯一ID进行过滤,Access也不会删除该记录。访问不会造成任何错误。
PG_ID是两个表中的唯一标识符,它是一个长整数。
我在下面列出了我的代码的示例部分。请帮忙!
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
根据要求,我已将msgbox切换到Debug.Print。下面是debug.print输出,当放入访问查询时,它会正确运行。
这是一个时间问题。我通过提交事务然后运行删除查询来修复它。谢谢大家的投入!
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
答案 0 :(得分:1)
..如果用户取消
,删除新创建的记录
听起来没有保存记录。即使不是,也可能是一个时间问题,因为在另一个上下文中运行查询而不是表单。
如果确实已创建,最简单,最快捷的方法是从表单的RecordsetClone
中删除记录。
答案 1 :(得分:0)
使用DoCmd.RunSQL
示例:
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
因此,您的新代码如下:
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