【问题标题】:Using Excel VBA to SQL delete in MS Access在 MS Access 中使用 Excel VBA 到 SQL 删除
【发布时间】:2015-11-10 13:59:52
【问题描述】:

我在 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

【问题讨论】:

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

标签: excel ms-access-2010 vba


【解决方案1】:

您正在删除,所以您没有记录集。

 '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

More notes on Execute.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-27
    • 2016-06-14
    • 2013-10-18
    • 1970-01-01
    • 2015-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多