我试图在关闭Excel工作簿时运行Access删除查询。我希望DELETE查询删除“ ResDate”字段中今天之前的任何记录。以下是我编写的代码。工作簿关闭,但记录仍保留在数据库(TR表)中。
我认为这可以解决问题,但到目前为止效果斐然。任何使这个工作的建议将不胜感激。感谢您的帮助...……。
Const ConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=H:\MyDatabase\TRC.mdb;Persist Security Info=False"
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Set Connection = New ADODB.Connection
Connection.ConnectionString = ConnectionString
Connection.Open
VSQL = "DELETE * FROM [TR] WHERE [TR].ResDate < " & Date
Set RecSet1 = Connection.Execute(VSQL, dbrows, adCmdText)
Connection.Close
Set RecSet1 = Nothing
End Sub
答案 0 :(得分:0)
始终使用参数!
当您进行VSQL = "DELETE * FROM [TR] WHERE [TR].ResDate < " & Date
时(取决于您的语言环境),可能会导致多个问题。
例如,DELETE * FROM [TR] WHERE [TR].ResDate < 2019-11-08
,并且2019减11减08等于2000,而CDate(2000)
是1905-06-22,因此这是一个有效的查询,但可能不会删除您的查询要删除。
在其他语言环境中,可能是11/08/2019,而11除以8除以2019大约是0,而CDATE(0)
是1899-12-30。
相反,请从How do I use parameters in VBA in the different contexts in Microsoft Access?中进行选择,例如:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Set Connection = New ADODB.Connection
Connection.ConnectionString = ConnectionString
Connection.Open
VSQL = "DELETE * FROM [TR] WHERE [TR].ResDate < " & Date
With CreateObject("ADODB.Command")
Set .ActiveConnection = Connection
.CommandText = "DELETE * FROM [TR] WHERE [TR].ResDate < ?"
Set RecSet1 = .Execute(, Array(Date))
End With
Connection.Close
Set RecSet1 = Nothing
End Sub
答案 1 :(得分:0)
在您的SQL语句中使用Access Date()
函数,而不是将日期作为文本插入到语句中。
在模块的声明部分包括Option Explicit
,然后从VB编辑器的主菜单运行Debug-> Compile。修复Access抱怨的第一个编译错误,然后再次调试->编译。重复直到没有更多错误为止。
基于DELETE
查询打开记录集没有用,因为DELETE
不会返回记录。只需执行查询即可。
Const ConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=H:\MyDatabase\TRC.mdb;Persist Security Info=False"
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Dim cn As ADODB.Connection
Dim VSQL As String
Dim dbrows As Long
Set cn = New ADODB.Connection
cn.ConnectionString = ConnectionString
cn.Open
VSQL = "DELETE * FROM [TR] WHERE [TR].ResDate < Date()"
cn.Execute VSQL, dbrows, adCmdText
cn.Close
End Sub