Excel VBA - How to force to close ADO connection?

I am trying to join an Excel spreadsheet to a local Access database using VBA, and I encountered the problem of the Access database being locked from a previous debug, and either throws error 3704 or 3709 (see below) when trying to debug.

Now I am new to VBA, so there is a high probability that I will connect it to the database incorrectly. Is there a way to force the database to close?

The following is the connection code:

    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

So, to check if the state is open, I wrote an if block to check, but this is when I get a "runtime error 3074: operation is not allowed when the object is closed" in the cn.CloseConnection line:

    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 - .

    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. , , select :

    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 . , , . .

+4
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.

+1

Source: https://habr.com/ru/post/1546618/


All Articles