I've only just started wrapping my head around building classes in Class Modules for VBA. It has been fairly smooth sailing so far, but I ran into a small challenge which is very easily solved if I were making a conventional function in a Module: How can I set an optional boolean default value to True?
In a function or sub, I would simply solve this in the property list by implicit declaration:
Function SomeFunction(Optional bValue = True) as Variant ... End Function
In a Class Module using Let and Get properties, I haven't quite found my way around it yet since VBA defaultedly declares a Boolean variable as false. So I have, e.g.:
Private bValue as Boolean Public Property Let TrueOrFalse(myBoolProperty As Boolean) bValue = myBoolProperty End Property Private Property Get TrueOrFalse() As Boolean TrueOrFalse = bValue End Property Function SomeFunction() As Boolean SomeFunction = TrueOrFalse End Function
Bear in mind, I'm still learning, so even this simple code might be unsexy to the trained eye, but the question remains: How can I default bValue to True if I only want to use it as an Optional property?
Hopefully that made some sense..
Thank you for reading!vbaexcel-vbaexcel
The Class_Initialize method will allow you to set default values.
I set up my properties like:
Option Explicit Public pTrueOrFalse as Boolean '## This method will be invoked whenever you create a class object using the NEW keyword/etc. Private Sub Class_Initialize() pTrueOrFalse = True End Sub '## Property "Get" method, which returns the value when called Public Property Get TrueOrFalse() As Boolean TrueOrFalse = pTrueOrFalse End Property '## Property "Let" method, which assigns the value when called Public Property Let TrueOrFalse(lTrueOrFalse as Boolean) pTrueOrFalse = lTrueOrFalse End Property
When using these in your regular code, you can do something like:
Dim myClassObject as New [class object name] 'this will invoke the Initialize procedure MsgBox myClassObject.TrueOrFalse 'this will call upon the "Get" method myClassObject.TrueOrFalse = False 'This will call upon the "Let" method MsgBox myClassObject.TrueOrFalse