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

时间:2022-09-27 16:14:00

I am using VBA in Excel to remove rows from a MS Access database. I am encountering

我在Excel中使用VBA从MS Access数据库中删除行。我遇到了

"Error 3704 - Operation is not allowed when the object is open"

“错误3704 - 对象打开时不允许操作”

although when using similar code I was able to add information to the DB. When trying to delete, its giving me errors. Please assist!

虽然使用类似的代码时我能够向DB添加信息。当试图删除时,它给我错误。请协助!

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

1 个解决方案

#1


1  

You are deleting, so you have not got a recordset.

您正在删除,因此您没有记录集。

 '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

For the most part, it is better to use DAO with MS Access

在大多数情况下,最好将DAO与MS Access一起使用

More notes on Execute.

关于执行的更多说明。

#1


1  

You are deleting, so you have not got a recordset.

您正在删除,因此您没有记录集。

 '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

For the most part, it is better to use DAO with MS Access

在大多数情况下,最好将DAO与MS Access一起使用

More notes on Execute.

关于执行的更多说明。