- Excel Functions
- Excel Formulas
- Excel Macro
- Training Programs
Using ADO in Excel VBA to retrieve records from databases.
ADO refers to ActiveX Data Objects and is one of the languages used by the industry to pull data from databases. ADO is readily available in Excel VBA. All you have to do is to make reference to the objects the VBA editor. There are a number of versions in VBA but I recommend using version 2.5 if your client could be using an older verion of Excel. If not, I recommend using version 2.8 which I did in one of my projects. I am using Excel 2002/XP and version 2.8 is already available in my VBA. To
activate the reference, go to the menu bar in the Visual Basic Editor (VBE) and select Tools -> References. In the pop up window, look for Microsoft ActiveX Data Objects 2.8 Library. Check the box on the left and click OK. You are now use ADO to pull data from databases such as Microsoft® Access, DBASE, SQL Server, IBM AS400.
Here are some sample codes you can use to retrieve databases. The very first thing you must do is to establish a connection to the database. You can use the following module to help you connect to an SQL server.
To connect using the above sample codes, you must create another sub procedure e.g. “Demo“
After establishing a connection to the database, you can then use another module to retrieve the records from the data table(s) in the database.
You can then add the following command in the main module to retrive the records. This must be in the same module where you have establish the connection to the database.
Call sqlRSRun(“Select * FROM ABC_Table”)
To put the records in an Excel worksheet, the fastest way is to use the CopyFromRecordset command. This is how you use it
Add this into the main Code, you will have the following set of code:
You can add in the column headers using the following code. This is why I started my range in A2 and not in A1. The reference to cells is another way to make reference to a cell in Excel, by using row and column number. Cells(1,1) refers to A1.
Learn how to use ADO to join 2 or more data tables together
Have your say about what you just read! Leave me a comment in the box below.
Share this page:
Enjoy this page? Please pay it forward. Here’s how…
Would you prefer to share this page with others by linking to it?
- Click on the HTML link code below.
- Copy and paste it, adding a note of your own, into your blog, a Web page, forums, a blog comment, your Facebook account, or anywhere that someone would find this page valuable.
<a href=”http://www.advanced-excel.com/”>Advanced Excel – From a Business Perspective</a><a href=”http://www.advanced-excel.com/”>Advanced Excel – From a Business Perspective</a>
Microsoft® and Microsoft Excel® are registered trademarks of Microsoft Corporation.
advanced-excel.com is in no way associated with Microsoft