Custom constant types in VBA

I would like to define a custom datatype in VBA and use it to create specific custom constants. For example:

Public Type Person
    Name as String
    Age as Integer
End Type

Public Sub CreatePerson
    Dim singer as Person
    singer.Name = "John"
    singer.Age = 37
End Sub

      

I would like to make the constant singer

constant, which will be visible in other subroutines / functions in the same module. Is it possible? If not, what's the best way to keep constant values ​​that are related to each other (like in the example above where is Name

connected to Age

)?

+3


source to share


1 answer


This is how I will do it.

The code in the module:

Option Explicit

Public Type Person
    Name As String
    Age As Integer
End Type


Private cvsinger As Person

Public Function singer() As Person

    Static ConstantHasBeenSet  As Boolean

    If Not ConstantHasBeenSet Then
        cvsinger.Name = "John"
        cvsinger.Age = 37
    End If

    singer = cvsinger

End Function

Public Sub CreatePerson()

    Debug.Print singer.Name, singer.Age

End Sub

      



This is a rather trivial case, but when the code to find the default values ​​takes longer to process, using ConstantHasBeenSet becomes useful

(Note that I would also use a similar method to set default values ​​for properties in a class)

+3


source







All Articles