Thursday, March 8, 2012

This listing demonstrates basic data retrieval from an Access database.

Sub DatabaseExample()
Dim rst As ADODB.Recordset
Dim sConnection As String
Dim sSQL As String
Dim rg As Range

On Error GoTo ErrHandler

' This is the range that will receive the data.

Set rg = ThisWorkbook.Worksheets(1).Range("a1")

' The database connection string. Double-check the path
' to the Northwind database on your computer.

sConnection = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C:\Program Files\Microsoft Office\" & _
"OFFICE11\SAMPLES\northwind.mdb"

' The query to execute

sSQL = "SELECT LastName, FirstName, Title FROM employees"

' Create & Open the recordset

Set rst = New ADODB.Recordset
rst.Open sSQL, sConnection

' Copy to the range

rg.CopyFromRecordset rst
rg.CurrentRegion.Columns.AutoFit

' Close the recordset when you're done with it.

rst.Close

ExitPoint:
Set rst = Nothing
Set rg = Nothing
Exit Sub

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

' resume at the ExitPoint label to clean up object variables
Resume ExitPoint
End Sub

No comments: