Skip to content
vgrstnPublic

About

Generic Stack Class based on an encapsulated VB Collection

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

37 Commits

Folders and files

Repository files navigation

vba-stack

License: MIT Platform Architecture Rubberduck

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 / Pop on empty stack raise error 5)
  • Zero dependencies (pure VBA)

📁 Files

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.


📦 Features

  • Fast push/pop (top is position 1 to 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

⚙️ Public Interface

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); an empty stack returns an empty array (0 To -1).
For Each Enumerator Iterates top → bottom (don’t mutate during enumeration).

Error behavior

  • Empty stack on Peek / Pop raises vbErrorInvalidProcedureCall (=5) with source "Stack.Peek" or "Stack.Pop".

🚀 Quick Start

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     ' -> True

⏱️ Performance

Timings (ms) for one Push + one Pop, measured on Windows x64:

# Count vba-stack vba-stack-array
1 10 0.00060 0.00029
2 100 0.00061 0.00031
3 1,000 0.00064 0.00032
4 10,000 0.00063 0.00032
5 100,000 0.00059 0.00032

Performance is consistent regardless of stack size. The array-based vba-stack-array needs about half the time.

Why the top is at position 1: see VBA Collection performance.


📄 License

MIT © 2025 Vincent van Geerestein

About

Generic Stack Class based on an encapsulated VB Collection

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages