3

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

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

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

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
3
  • 2
    for clarity's sake the error actually occurs when you try to clear the variable declaration? Or during the delete query operation? You wrote one thing in your explanation and another in your code? Commented Nov 10, 2015 at 14:08
  • 1
    There is another issue waiting to trip you up. Since you're using ADO, you must use different wild cards -> Like '%Project 1%' Commented Nov 10, 2015 at 15:33
  • Thank you both. I am a total newbie when it comes to VBA with a DB, so the code was just modified copy and paste from the net. Scott, the line doesnt delete from the DB either, even though the SQL query works in Access. Commented Nov 10, 2015 at 17:12

1 Answer 1

2

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

More notes on Execute.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.