Thread: OpenRecordset
View Single Post
  #2   Report Post  
Posted to microsoft.public.excel.programming
TK TK is offline
external usenet poster
 
Posts: 177
Default OpenRecordset

Hi Fred:

Slow down son it's not that tough.

That example is DAO if your just learning ADO is the reconmended
route

copy and paste the following and pay attenshion
to the notes ' / notes

Private Sub CommandButton4_Click()

On Error GoTo ErrHandler

Dim Rg As Range
Set Rg = ThisWorkbook.Worksheets(2).Range("a1")

'//To use ADO objects in an application add a reference
'//to the ADO component. From the VBA window select
'Tools/References< check the box
' "Microsoft ActiveX Data Objects 2.x Library"

'You should fully quality the path to your file

Dim db_Name As String

'// this is where Access lives on this computer
db_Name = ("C:\Program Files\Microsoft Visual Studio\VB98\NWind.mdb")
'// where does it live on yours (
)

Dim DB_CONNECT_STRING As String

DB_CONNECT_STRING = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"data Source=" & db_Name & ";" & ", , , adConnectAsync;"

'Create the connection
Dim cnn As New ADODB.Connection
Set cnn = New Connection
cnn.Open DB_CONNECT_STRING

'Create the recordset
Dim Rs As ADODB.Recordset
Set Rs = New Recordset

'Determines what records to show
Dim strSql As String
strSql = "SELECT CompanyName, ContactName, City, Country " & _
"FROM Customers ORDER BY CompanyName"

'Retreive the records
Rs.CursorLocation = adUseClient
Rs.Open strSql, cnn, adOpenStatic, adLockBatchOptimistic

'Test to see if we are connected and have records
Dim num As Integer
num = Rs.RecordCount

If cnn.State = adStateOpen Then
MsgBox "Welcome to! " & db_Name & " Records = " & num,
vbInformation, _
"Good Luck TK"
Else
MsgBox "Sorry. No Data today."
End If

'Copy recordset to the range
Rs.MoveLast
Rs.MoveFirst
Rg.CopyFromRecordset Rs
Rg.CurrentRegion.Columns.AutoFit

'close connection
cnn.Close
Set cnn = Nothing
Set Rs = Nothing

Exit Sub

ErrHandler:
MsgBox "Sorry, an error occured. " & Err.Description, vbOKOnly
End Sub


Good Luck
TK