"Operation is not allowed when the object is closed."
"Operation is not allowed when the object is open."
"The connection cannot be used to perform this operation. It is either closed or invalid in this context."
What it means:
You tried to do something that is not appropriate for the current state (either Open or Closed) of the object (eg: Recordset/Connection).
Certain operations on database object variables (such as MoveFirst on a RecordSet object) can only be done when the object is in a particular state (for MoveFirst, the RecordSet must be Open).
How to solve it:
As you are getting one of these errors, you are unlkely to be aware of the following... whatever your situation, you should always close Recordsets and Connections when you have finished with them - otherwise you can waste large amounts of memory, and you also risk database corruption! The code to properly close Recordsets/Connections is like this:
VB Code:
rs.Close 'close the recordset, and release the memory
Set rs = Nothing
cn.Close 'close the connection, and release the memory
Set cn = Nothing
Right then, on to the solutions! If you get the "not allowed when .. closed" message, you need to Open the object (eg: rs.Open ...) before running the line of code that gave you the error.
For "not allowed when .. open", you need to Close the object (eg: rs.Close) before running the line of code that gave you the error. For example, you need to Close a Recordset before you can Open it again.
One issue tho is that you cannot Close a Recordset/Connection unless it is open. If it is possible in your program that the object will not have been opened (or already have been closed), you need to check that it is open before attempting to close it, eg:
VB Code:
'this method can be used for connections and recordsets
If (rs.State And adStateOpen) = adStateOpen Then rs.Close
If you are unsure that the object has even been Set, you will also need to check that, eg:
VB Code:
If Not rs Is Nothing Then
If (rs.State And adStateOpen) = adStateOpen Then rs.Close
Else
'if you are about to Open you need to also Set the object, eg:
Set rs = New ADODB.Recordset
End If
Note that despite other advice you may see on the forums, just running the Set on its own is not a valid method. While it appears to work, it does not actually close the existing Recordset/Connection - all it does is create another one, and leave the previous one in memory. It avoids the error messages, but in a very dubious way!