Using ODBCDirect
In this exercise, you will use ODBCDirect to retrieve data from the Northwind database. The Microsoft Access ODBC driver will be used to simulate access to an ODBC data source.
* To use ODBCDirect with Microsoft Excel
- Switch to Microsoft Excel.
- Open a new workbook.
- Start the Visual Basic Editor.
- Add a new module to the workbook.
- Add a reference to the Microsoft DAO 3.5 Object Library.
- Add the following declarations in the General Declarations section of the module.
Public wsODBC As Workspace Public cnODBC As Connection Public rsODBC As Recordset
- Create a new public sub procedure and name it LoadODBCData .
- Type the following code into LoadODBCData :
Dim iCounter As Integer Set wsODBC = DBEngine.CreateWorkspace("ODBC_ws","Admin","",dbUseODBC) Set cnODBC = wsODBC.OpenConnection _ ("New",dbDriverNoPrompt,False,"ODBC;DSN=nwind") Set rsODBC = cnODBC.OpenRecordset("Employees") Range("A1").Select iCounter = 1 Do Until rsODBC.EOF Cells(iCounter, 1).Value = rsODBC.Fields("FirstName") Cells(iCounter, 2).Value = rsODBC.Fields("LastName") rsODBC.MoveNext iCounter = iCounter + 1 Loop rsODBC.Close cnODBC.Close wsODBC.Close
* To test your application - Close the Visual Basic Editor and save the workbook as Ex2.xls .
- On the Tools menu, click Macro and then click Macros to open the Macro dialog box.
- Select LoadODBCData from the list and then click Run .
You should now see the list of employees entered into the spreadsheet.
- Save changes and close the workbook and exit from Microsoft Excel running.