Skip to content

vgrstn/vba-stack

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

36 Commits
 
 
 
 
 
 
 
 
 
 

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).
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 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.


📄 License

MIT © 2025 Vincent van Geerestein

About

Generic Stack Class based on an encapsulated VB Collection

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages