Here is one example of function, which retrieve all data from table as recordset.
Hope this help.
' Declarations
Private m_objConnection As ADODB.Connection
Private m_objComm As ADODB.Command
Private m_ConnProvider As String
Private m_Path As String
Private strSQL As String
' Function has two optional parameters:
' a_updatable which means that you can update returning recordset if is true and
' a_sorted which means that returning recordset is sorted if is true
Public Function ReadData(Optional ByVal a_updatable As Boolean = False, Optional ByVal a_sorted As Boolean = False) As ADODB.Recordset
Dim GetRecords As New ADODB.Recordset
' Creating connection object
Set m_objConnection = New ADODB.Connection
' Creating connection string
m_connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\Data\db01.mdb;"
m_connStr = m_connStr & "Persist Security Info=False"
m_objConnection.ConnectionString = m_connStr
If a_updatable = True Then
m_objConnection.Mode = adModeShareExclusive
Else
m_objConnection.Mode = adModeShareDenyWrite
End If
On Error GoTo OpenData_Err
m_objConnection.Open
On Error GoTo 0
' Creating communication object to get data from database
' With comm object it is more flexible than directly assigned SQL string to recordset
Set m_objComm = New ADODB.Command
Set m_objComm.ActiveConnection = m_objConnection
' Table name is Tab_data and has Data_key as one od data fields
strSQL = "SELECT * FROM Tab_data"
If a_sorted = True Then
strSQL = strSQL & " ORDERED BY Data_key"
End If
' Create new returning recordset object
Set GetRecords.ActiveConnection = m_objConnection
m_objComm.CommandText = strSQL
m_objComm.CommandType = adCmdText
Set GetRecords.Source = m_objComm
On Error GoTo GetRecordSet_Err
' On this way you can open recordset on different and flexible way
GetRecords.Open strSQL, , adOpenKeyset, adLockPessimistic, adCmdText
Set GetRecordSet = GetRecords
On Error GoTo 0
Exit Function
OpenData_Err:
Set m_objConnection = Nothing
Set m_objComm = Nothing
' 100000 is your Error number
Err.Raise 100000, "ReadData", "Cannot open Database"
Exit Function
GetRecordSet_Err:
Set m_objConnection = Nothing
Set m_objComm = Nothing
' 100001 is your Error number
Err.Raise 100001, "ReadData", "Cannot get recordset"
End Function
' Calling this function
Sub CallThisFunction ()
'Declarations
Dim records As ADODB.Recordset
On Error GoTo ...
records = ReadData
On Error Goto 0
... your code
' You must destroy returning object from ReadData
Set records = Nothing
End Sub