使用ADO从Excel错误3704连接到Access数据库

时间:2013-12-19 09:28:24

标签: excel vba ms-access ado

当我使用下面的代码从Excel连接到访问数据库时,出现错误3704“关闭对象时不允许操作。”在线

Call .Offset(1, 0).CopyFromRecordset(rstRecordSet)

我可以通过注释掉

来解决这个问题
adoConnection.Close

但我真的不喜欢这样,或者理解它解决问题的原因。

任何人都可以解释什么是错的以及如何解决它?

由于

Private Const constStrDBPath As String = "H:\Projects\DP.mdb"
Private Const constStrConnection As String = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
                             "Data Source=" & constStrDBPath & ";" & _
                             "Jet OLEDB:Engine Type=5;" & _
                             "Persist Security Info=False;"


Public Function SelectStatement(strCommandText As String) As Object

    Dim adoConnection As New ADODB.Connection
    Dim adoCommand As New ADODB.Command
    Dim rstRecordSet As New ADODB.Recordset

    adoCommand.CommandText = strCommandText

    adoConnection.Open constStrConnection
    adoCommand.ActiveConnection = adoConnection

    'create the recordset by executing command string
    Set rstRecordSet = adoCommand.Execute(, , adadoCommandText)

    Set SelectStatement = rstRecordSet

    ' clean up
    adoConnection.Close
    Set rstRecordSet = Nothing
    Set adoConnection = Nothing
    Set adoCommand = Nothing

End Function

Sub TestSelect()

    Dim rstRecordSet As Object
    Dim lngField As Long

    Set rstRecordSet = SelectStatement("SELECT * FROM tblSystem")

    If Not rstRecordSet Is Nothing Then
        With Sheet1.Range("A1")
            For lngField = 1 To rstRecordSet.Fields.Count
                .Cells(1, lngField).Value = rstRecordSet.Fields(lngField - 1).Name
            Next lngField
            Call .Offset(1, 0).CopyFromRecordset(rstRecordSet)
        End With
    End If

End Sub

1 个答案:

答案 0 :(得分:2)

您的函数SelectStatement不从数据库中提取(读取)任何内容。

简单来说,你的实际SelectStatement()打开一个带有Access的通道,准备查询,设置一个光标然后扔掉所有。

在阅读完最后一个记录集后,必须推迟清理阶段。