Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LIFO (Stack) Algorithm/Class for Excel VBA

Tags:

stack

excel

vba

I'm looking to implement a "Stack" Class in VBA for Excel. I want to use a Last In First Out structure. Does anyone came across this problem before ? Do you know external libraries handling structure such as Stack, Hastable, Vector... (apart the original Excel Collection etc...)

Thanks

like image 902
BlackLabrador Avatar asked Feb 02 '11 06:02

BlackLabrador


1 Answers

Here is a very simple stack class.

Option Explicit
Dim pStack As Collection
Public Function Pop() As Variant
    With pStack
        If .Count > 0 Then
            Pop = .Item(.Count)
            .Remove .Count
        End If
    End With
End Function
Public Function Push(newItem As Variant) As Variant
    With pStack
        .Add newItem
        Push = .Item(.Count)
    End With

End Function
Public Sub init()
    Set pStack = New Collection
End Sub

Test it

Option Explicit
Sub test()
    Dim cs As New cStack
    Dim i As Long
    Set cs = New cStack
    With cs
        .init

        For i = 1 To 10
            Debug.Print CStr(.Push(i))
        Next i

        For i = 1 To 10
            Debug.Print CStr(.Pop)
        Next i
    End With
End Sub

Bruce

like image 157
bruce Avatar answered Sep 27 '22 19:09

bruce