使用Excel VBA在MS Access中进行SQL删除

3
我正在使用Excel中的VBA从MS Access数据库中删除行。我遇到了“错误3704-对象打开时不允许操作”的问题。尽管在使用类似的代码添加信息到数据库时没有出现问题,但现在尝试删除数据却出错了。请帮助解决!
Sub DeleteOldValues()

'--------------
'DIM STATEMENTS

Dim strMyPath As String, strDBName As String, strDB As String, strSQL As String, StrQuery As String

'instantiate an ADO object using Dim with the New keyword:
Dim adoRecSet As New ADODB.Recordset
Dim connDB As New ADODB.Connection

'--------------
'THE CONNECTION OBJECT

strDBName = "Test.accdb"
strMyPath = "Y:"
strDB = strMyPath & "\" & strDBName

 'Connect to a data source:
connDB.Open ConnectionString:="Provider = Microsoft.ACE.OLEDB.12.0; data source=" & strDB

StrQuery = "DELETE * FROM Table WHERE ProjectName Like '*Project 1*'"

'Performs the actual query
adoRecSet.Open StrQuery, connDB

'--------------
'close the objects
adoRecSet.Close
connDB.Close

'destroy the variables
Set adoRecSet = Nothing  <-error occurs at this point
Set connDB = Nothing

End Sub

2
清晰起见,错误实际上是在尝试清除变量声明时发生的吗?还是在删除查询操作期间?您在解释中写了一件事,在代码中又写了另一件事? - Scott Holtzman
1
还有另一个问题等着绊倒你。由于您正在使用ADO,因此必须使用不同的通配符-> Like'%Project 1%' - HansUp
谢谢你们两位。对于带有数据库的VBA,我是一个完全的新手,所以代码只是从网上复制和粘贴修改而来。Scott,即使SQL查询在Access中有效,该行也不会从数据库中删除。 - Recycle_Bin28
1个回答

2

你正在执行删除操作,因此没有记录集可用。

 'Connect to a data source:
connDB.Open ConnectionString:="Provider = Microsoft.ACE.OLEDB.12.0; data source=" & strDB
StrQuery = "DELETE * FROM Table WHERE ProjectName Like '*Project 1*'"

'Performs the actual query
connDB.Execute strQuery

大多数情况下,最好使用 DAO with MS Access

更多关于Execute的注意事项。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接