Create a Global Procedure Stack

Problem

When you’re writing an application, you often need to know the name of the current procedure from within your code. For example, if an error occurs, you’d like to be able to have a generic function handle the error and display the name of the procedure in which the error occurred (and all the procedures that have been called on the way to get there). VBA doesn’t include a way to retrieve this information. How can you accomplish this?

Solution

By maintaining a list of active procedures, adding the current name to the list on the way into the procedure and removing it on the way out, you can always keep track of the current procedure and the procedure calls that got you there. There are many other uses for this functionality (see the next solution, for example), but one simple use is to retrieve the name of the current procedure in a global error-handling procedure.

The kind of data structure you’ll need for maintaining your list is called a stack. As you enter a new procedure, you “push” its name onto the top of the stack. When you leave the procedure, you “pop” the name off the stack. Figure 7-2 shows a graphical representation of a procedure stack in action. The arrows indicate the direction in which the stack grows and shrinks as you add and remove items.

The call stack and the sample routines to fill it

Figure 7-2. The call stack and the sample routines to fill it

To see the procedure ...

Get Access Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.