Generic Queue Class based on a circular encapsulated VB Array
A lightweight, circular array-backed FIFO queue for VBA with:
- O(1) enqueue at the rear and dequeue from the front via circular buffer
- Safe enumeration (
For Each) via a proper COM enumerator - Clear error semantics (
Peek/Dequeueon empty queue raise error 5) - Zero dependencies (pure VBA)
| File | Description |
|---|---|
Queue.cls |
Source file with Rubberduck annotations ('@Description, '@DefaultMember, '@Enumerator) |
Queue_WithAttributes.cls |
Ready-to-import version with VB attributes baked in — no Rubberduck required |
Both files are identical in behaviour. Import Queue_WithAttributes.cls if you are not using Rubberduck.
- Circular buffer avoids data shifting on every
Dequeue - Dynamic resizing doubles on grow (
GrowthFactor = 2); shrinks by half when occupancy drops belowShrinkTrigger(25%) - Enumeration:
For Each item In Queue(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 |
|---|---|---|
Enqueue(Item) |
Sub |
Adds an item to the rear of the queue. |
Dequeue() |
Function |
Returns and removes the front item. Raises error 5 if empty. |
Peek (Default) |
Property |
Returns the front 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. |
For Each |
Enumerator | Iterates front → rear on a snapshot. (Mutation during iteration is safe but iterates the old snapshot.) |
Error behavior
- Empty queue on
Peek/DequeueraisesvbErrorInvalidProcedureCall (=5)with source"Queue.Peek"or"Queue.Dequeue".
Dim q As New Queue
q.Enqueue "alpha"
q.Enqueue "beta"
Debug.Print q.Peek ' -> alpha (front)
Debug.Print q.Dequeue ' -> alpha (removed)
Debug.Print q.Dequeue ' -> beta (removed)
Debug.Print q.IsEmpty ' -> TrueTimings (ms) for one Enqueue + one Dequeue, measured on Windows x64:
| # | Count | vba-queue-array | vba-queue (Collection) |
|---|---|---|---|
| 1 | 10 | 0.00073 | 0.00045 |
| 2 | 100 | 0.00072 | 0.00045 |
| 3 | 1,000 | 0.00034 | 0.00045 |
| 4 | 10,000 | 0.00035 | 0.00045 |
| 5 | 100,000 | 0.00040 | 0.00045 |
The array-based version is more memory-efficient and converges to faster performance at larger sizes. The Collection-based version has lower overhead at small counts. The circular buffer avoids data shifting on every Dequeue.
MIT © 2025 Vincent van Geerestein