Returning an ADODB.Recordset from Function
To return an ADODB.Recordset in Visual Basic Application (VBA), from a function, the Recordset must be disconnected.
-
Function queryDatabase(strSQL, username, password) As ADODB.Recordset
-
-
'Declare our variables
-
Dim strConnection, conn, rs
-
-
'Initialisation
-
Set rs = New ADODB.Recordset
-
strConnection = "Provider=sqloledb;Data Source=serverName;Initial Catalog=DbName;User Id=username;Password=password"
-
Set conn = New ADODB.Connection
-
-
conn.Open strConnection
-
rs.CursorLocation = adUseClient
-
rs.Open strSQL, conn, ADODB.adOpenForwardOnly, ADODB.adLockBatchOptimistic
-
-
'Disconnect the connection
-
Set rs.ActiveConnection = Nothing
-
-
'Return the recordset
-
Set queryDatabase = rs
-
-
conn.Close
-
Set conn = Nothing
-
End Function
-
-
Sub main()
-
Dim rs As ADODB.Recordset
-
Set rs = queryDatabase("SELECT cols FROM DB", username, password)
-
-
'Now we can handle our recordset, returned from the function
-
rs.MoveFirst
-
While Not rs.EOF
-
MsgBox (rs("colName"))
-
rs.MoveNext
-
Wend
-
-
rs.Close
-
Set rs = Nothing
-
End Sub
Only a disconnected recordset is able to be passed around in your code and handled later.
