Search code examples
vbaadodbrecordset

VBA. Cant get data from .mdb file. Operation is not allowed when object is closed


Here is my problem: I need to get data from .mdb file that is on the network hard drive. I am using ADODB to connect to it, but when i try to return field value from RecordSet that i created it returns error:

Operation is not allowed when the object is closed

Here is my code:

 Dim rs As New ADODB.Recordset
 Dim cmd As New ADODB.Command
    cmd.ActiveConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & dbPath & ".mdb"
    cmd.CommandText = SQLRequst
    cmd.CommandType = adCmdText
    cmd.CommandTimeout = 900
    rs.CursorLocation = adUseClient
    rs.Open cmd, , adOpenForwardOnly, adLockReadOnly
    Debug.Print rs.Fields(0)
Set cmd.ActiveConnection = Nothing
Set cmd = Nothing
Set rs.ActiveConnection = Nothing

At the moment i tried many different types of connection. The main thing thats makes me confused is that it connects to .mdb file and also creates RecordSet but most values are set to "Operation is not allowed when object is closed" I think the problem is with the way i am connecting and getting records sets because I use same method to connect to sql database and it works just fine.

Any help will be appreciated

*Edited : SQLRequest = "SELECT * FROM tblStack WHERE StackID=XXXXX"

Changed code to this:

Dim rs As New ADODB.Recordset
Dim conn As New ADODB.Connection

conn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & dbPath & ".mdb"

rs.Open SQLRequst, conn, adOpenForwardOnly, adLockReadOnly
Debug.Print rs.Fields(0) 

Set cmd.ActiveConnection = Nothing
Set cmd = Nothing
Set rs.ActiveConnection = Nothing

Still debug doesn't print anything and in Locals window shows that Fields(0).Value Operation is not allowed when the object is closed


Solution

  • Problem was in SQLRequst string :

    SQLRequest = "SELECT * FROM tblStack WHERE StackID='XXXXX'"
    

    It needed ''.