Cat On A Spreadsheet
In the previous post, we built a reusable framework to capture and log VBA errors automatically. That’s a huge step forward for debugging complex projects. But there’s more we can do. Advanced VBA developers can take error handling to the next level with precise error tracing, call stack emulation, smarter logging, and even automated correction strategies. This post explores those techniques in detail.
The built-in Erl function returns the last executed line number if your code is numbered. By default, VBA doesn’t show line numbers — but you can add them manually (or with a utility).
Example:
And here’s the modified logger:
Now your log will tell you exactly where in the procedure the error occurred.
VBA doesn’t provide a built-in call stack (like higher-level languages do), but we can emulate one by manually tracking entry and exit points.
Example utility module:
Usage in a procedure:
This lets you see not only where an error happened, but how the code got there.
Not all errors are bugs. Some are expected conditions that can be handled gracefully. For example, trying to open a workbook that may not exist:
Use this approach to distinguish between errors you expect and ones you don’t.
Sometimes you don’t just want to log an error — you want your code to fix itself if possible.
Examples:
If a required worksheet is missing, create it.
If a file path is invalid, prompt the user to browse.
If a reference is broken, re-link it automatically.
Example:
Here, instead of crashing, the macro auto-corrects by creating the missing sheet.
Always log unexpected errors (with time, user, procedure, and line number).
Use Erl liberally in production code — it’s ugly but invaluable.
Differentiate expected vs unexpected errors (don’t over-log).
Include environmental details (Excel version, machine, user).
Fail gracefully — give users an informative but non-technical message.
Optionally notify developers (email critical failures).
VBA error handling often gets dismissed as clunky compared to modern languages — but with a little work, you can build a system that gives you:
Precise error location (Erl)
A call stack to trace execution
Smart distinction between expected/unexpected errors
Automatic correction where possible
A robust log for post-mortem debugging
This elevates VBA projects from fragile scripts to maintainable, production-quality software.
Cat On A Spreadsheet