I use the following from within some excel procedures to establish a connection to our database.
Private Const strConn As String = _
"PROVIDER=SQLOLEDB.1 ..."
Sub OpenConnection()
Set cn = CreateObject("ADODB.Connection")
cn.Open strConn
cn.CommandTimeout = 0
Set rs = CreateObject("ADODB.Recordset")
Set rs.ActiveConnection = cn
End Sub
In subsequent code I open the connection using various SQL strings.
I'd like to test if rs
is open so I know that it needs to be closed but the following does not work. How can I change the condition in the following to work?
If (rs.Open = True) Then
rs.Close
End If
The following works but I'd rather not use error trapping in this way:
On Error Resume Next
rs.Close
This topic is old but if other people like me search a solution, this is a solution that I have found:
So "myBase" is a Database Object, I have made a class to access to database (class with insert, update etc...) and on the module the class is use declare in an object (obviously) and I can test the connection with "[the Object].DBStats":
Edit : In DBOpen I use "OpenDatabase" and in DBClose I use ".Close" and "set myBase = nothing" Edit 2: In the function, if you are not connect, .version give you an error so if aren't connect, the errorHandler give you false
ADO Recordset has
.State
property, you can check if its value isadStateClosed
oradStateOpen
MSDN about State property
Edit; The reason not to check
.State
against 1 or 0 is because even if it works 99.99% of the time, it is still possible to have other flags set which will cause the If statement fail theadStateOpen
check.Edit2:
For Late binding without the ActiveX Data Objects referenced, you have few options. Use the value of adStateOpen constant from ObjectStateEnum
Or you can define the constant yourself to make your code more readable (defining them all for a good example.)