Cat On A Spreadsheet
If you’ve worked with large datasets, you know that Excel alone isn’t always enough. Sometimes, your data lives in a database — SQL Server, Access, or even a cloud system — and pulling that data directly into Excel can supercharge your workflows. In this post, we’ll explore how to connect Excel VBA to different database systems using ADO (ActiveX Data Objects). You’ll learn how to:
Establish a connection
Run queries
Read and write data
Handle errors safely
Close everything cleanly
Let’s get started.
Before we begin, you’ll need to:
Open the VBA editor (Alt + F11).
Go to Tools → References.
Enable: Microsoft ActiveX Data Objects x.x Library (choose the highest version available, e.g., 6.1).
We’ll create a module called modDB that can connect to either SQL Server or Access and execute SQL commands safely.
This uses the same shared ErrorHandler module as in previous posts.
If any database connection or query fails, the error will be:
Captured with timestamp, procedure name, and description
Written to a log file
Emailed to VBAdmin@company.com
Here’s the ErrorHandler module again for context:
Let’s see it in action. This example pulls data from a SQL Server table and writes it into Excel.
Always close your connections (CloseDB) — otherwise Excel may hang.
For Access databases, use ConnectAccess "C:\path\to\Database.accdb".
Always wrap queries in error handling — SQL typos or bad credentials can trigger errors easily.
You can also parameterize queries or use stored procedures for cleaner, safer code.
By integrating VBA with databases:
You turn Excel into a powerful front-end for SQL systems.
Your workbooks can pull, edit, and push data live.
Logging ensures you never lose track of what went wrong.
In the next post, we can go further into parameterized queries and secure credential handling, including encrypting your connection strings and reading them from hidden config sheets or encrypted files.
Cat On A Spreadsheet