【问题标题】:Excel VBA - How to force close an ADO connection?Excel VBA - 如何强制关闭 ADO 连接?
【发布时间】:2014-07-01 07:06:20
【问题描述】:

我正在尝试通过 VBA 将 Excel 工作表连接到本地 Access 数据库,我遇到了 Access 数据库在之前的调试中被锁定的问题,并且正在抛出错误 3704 或 3709(见下文)尝试调试时。

现在我是 VBA 的新手,所以我很有可能无法正确地将它连接到数据库。有没有办法强制关闭数据库?

以下是连接代码:

    Dim objAccess As Object
    Dim strFile, strConnection As String
    strFile = "Address of SampleDB.accdb"

    Set objAccess = CreateObject("Access.Application")
    Call objAccess.OpenCurrentDatabase(strFile)

    'get the connection string
    strConnection = objAccess.CurrentProject.Connection.ConnectionString
    objAccess.Quit

    Set cn = CreateObject("ADODB.Connection")
    cn.ConnectionString = strConnection

所以为了检查状态是否打开,我写了一个 if 块来检查,但这是当我在 cn.CloseConnection 行上得到“运行时错误 3074:对象关闭时不允许操作”时:

    If cn.State = adStateOpen Then
        cn.Close
        Else
            MsgBox "The connection is already open."
    End If

所以我将上面的代码注释掉并替换为以下代码,但我得到“运行时错误 3079:连接不能用于执行此操作。它在此上下文中已关闭或无效。”在 Set rs.ActiveConnection = cn 行上。它首先进入 (cn.State And adStateOpen) = adStateOpen is true 部分。

    If (cn.State And adStateOpen) = adStateOpen Then
        MsgBox "cn Connection is already open."
        Else
        cn.Open strConnection
        MsgBox "Connection is now open"
    End If
    Set rs = Nothing
    Set rs = CreateObject("ADODB.Recordset")
    Set rs.ActiveConnection = cn

我在最后使用 cn.Close 和 Set cn = Nothing 来清理连接。但是,代码在到达该点之前就停止了,现在将我锁定在 Access 数据库之外。至于我运行的查询,它只是一个带有变量的基本选择语句:

    Dim iArea As String
    Dim strSQL As String
    Dim dId As Integer
    iArea = "Sales"
    strSQL = "SELECT [deptID] FROM [tblDept] WHERE [deptArea]='" & iArea & "'"

    rs.Open
    Set rs = cn.Execute(strSQL)
    dId = rs.Fields(0)
    MsgBox dId 
    rs.Close
    Set rs = Nothing

代码最初停止是因为我在 SQL 中放置变量的语法错误。 我能够再次调试的唯一方法是重新启动计算机。任何建议将不胜感激。

【问题讨论】:

  • 几乎总是最好将 DAO 与 Access 结合使用。
  • 你有 ADO 库的引用集吗?

标签: vba excel connection adodb


【解决方案1】:

我认为问题不在于 ADO,而在于代码中缺少错误处理。您绝对应该阅读它。

除非您另外指定,否则默认的错误处理模式会抛出一个消息框,并且在您单击“结束”后,它只会在它停止的那一行结束例程。查看 On Error Goto,并创建在处理错误后执行的块。您可以设置一个每次执行的代码块,无论是否出错,这将关闭您的连接并释放您的对象。这就是您“强制”关闭连接的方式,方法是确保关闭它的代码正常运行。基本外壳如下所示:

Sub MySub()
On Error Goto MySub_ErrorHandler

    '...Code here...
    '1.  If error happens, goto 2.

ExitMe:
    '4. Clean up and run the code which needs to definitely run here.  Close connections, deallocate your objects, etc.

    '5. Finally, exit the routine with all loose ends tied up. 
    Exit Sub
MySub_ErrorHandler:
    '2. Handle the error here...

    '3. Then go to ExitMe...
    Goto ExitMe

End Sub

将代码放入 ExitMe 中存在引发错误的危险;在这种情况下,代码执行将再次转到 MySub_ErrorHandler 并且您可以进入无限循环。因此,请小心在 ExitMe 中测试您的代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多