vba static variable

' Import as a file MyStaticClass.cls:
VERSION 1.0 CLASS
BEGIN
  MultiUse = -1  'True
END
Attribute VB_Name = "MyStaticClass"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Option Explicit

Private mStaticCol As New Collection

Public Sub Push(ByVal pIndex As String, ByVal pValue As String)
Attribute Push.VB_Description = "Pushes a new value into StaticCol."
    mStaticCol.Add pValue, pIndex
End Sub

Public Property Get Element(ByVal pIndex As String) As String
Attribute Element.VB_Description = "Returns the element."
    Element = mStaticCol.Item(pIndex)
End Property
'--------------------------------------------------------------
' In a module:
Sub TesMe()
  With MyStaticClass        'No instanciation, mStaticCol is shared
        .Push "Jay", "circle"
        Debug.Print .Element("Jay")
    End With
End Sub

4.5
2

                                    ' Static variable inside a function
Function MyStaticFunction(ByVal pToAdd As Integer) As Integer
    Static iStatic As Integer       ' Keeps its value between calls
    iStatic = iStatic + pToAdd
    MyStaticFunction = iStatic
End Function
'---------------------------------------------------------------------
Sub TesMe()
  Debug.Print MyStaticFunction(1)	' 1
  Debug.Print MyStaticFunction(3)	' 4
End Sub

4.5 (2 Votes)
0
Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source