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