Generic Stack Class based on an encapsulated VB Collection
A lightweight, Collection-backed LIFO stack for VBA with:
- O(1) push/pop at the top (stored at position
1) - Safe enumeration (
For Each) via a proper COM enumerator - Clear error semantics (
Peek/Popon empty stack raise error 5) - Zero dependencies (pure VBA)
| File | Description |
|---|---|
Stack.cls |
Source file with Rubberduck annotations ('@Description, '@DefaultMember, '@Enumerator) |
Stack_WithAttributes.cls |
Ready-to-import version with VB attributes baked in — no Rubberduck required |
Both files are identical in behaviour. Import Stack_WithAttributes.cls if you are not using Rubberduck.
- Fast push/pop (top is position
1to avoid VB Collection tail-removal penalty) - Enumeration:
For Each item In Stack(via hidden[_NewEnum]) - Utility export:
Items([base])returns a 0- or 1-based array copy - Pure VBA, no external references, Rubberduck-friendly annotations
| Member | Type | Description |
|---|---|---|
Push(Item) |
Sub |
Adds an item at the top of the stack. |
Pop() |
Function |
Returns and removes the top item. Raises error 5 if empty. |
Peek (Default) |
Property |
Returns the top item without removing it. Raises error 5 if empty. |
Count |
Property |
Number of items. |
IsEmpty |
Property |
True if empty, else False. |
Clear |
Sub |
Removes all items. |
Items([base]) |
Function |
Returns all items as a Variant() array; base default = 0; arr(base) = top (most recently pushed). |
For Each |
Enumerator | Iterates top → bottom (don’t mutate during enumeration). |
Error behavior
- Empty stack on
Peek/PopraisesvbErrorInvalidProcedureCall (=5)with source"Stack.Peek"or"Stack.Pop".
Dim s As New Stack
s.Push "alpha"
s.Push "beta"
Debug.Print s.Peek ' -> beta (top)
Debug.Print s.Pop ' -> beta (removed)
Debug.Print s.Pop ' -> alpha (removed)
Debug.Print s.IsEmpty ' -> TrueTimings (ms) for one Push + one Pop, measured on Windows x64:
| # | Count | vba-stack | System.Collections.Stack |
|---|---|---|---|
| 1 | 10 | 0.00053 | 0.00527 |
| 2 | 100 | 0.00053 | 0.00528 |
| 3 | 1,000 | 0.00052 | 0.00529 |
| 4 | 10,000 | 0.00052 | 0.00534 |
| 5 | 100,000 | 0.00052 | 0.00531 |
Performance is consistent regardless of stack size. System.Collections.Stack uses late binding, which explains its relatively poor performance.
MIT © 2025 Vincent van Geerestein