Using collections as properties of an object in VBA - vba

With class module "Class1Test" as
Private pGreetings As Collection
Public Property Get Greetings() As Collection
Greetings = pGreetings
End Property
Public Property Let Greetings(Value As Collection)
pGreetings = Value
End Property
If I run the sub
Dim MyPhrases As Class1Test
Public Sub Test()
Set MyPhrases = New Class1Test
MyPhrases.Greetings.Add "Have a nice day"
End Sub
I get the a compile error "Argument not optional"
Why can't I add the string to the the collection myphrases.greetings ? Please forgive the newbie question. Just learning VBA.

A few things wrong.
Collection is an object, so you must use the Set keyword when assigning. Also in the Let procedure for consistency in naming conventions, I would use lGreetings instead of Value although that should not really matter.
Private pGreetings As Collection
Public Property Get Greetings() As Collection
Set Greetings = pGreetings
End Property
Public Property Let Greetings(lGreetings As Collection)
Set pGreetings = lGreetings
End Property
This will still raise an 91 error (Object variable or with block not set) because you have not instantiated the collection object. Probably the way you should do this is in the class module's Initialize routine.
Private Sub Class_Initialize()
Set pGreetings = New Collection
End Sub

Related

vba Class Property Values, setting default values, storing values to string

another stumped newb here, trying to wrap my head around a problem.
I'm trying to use a class module, instead of public variables, with property get and set.
I want to set these values in a userform with text boxes, and update a listbox in the userform as they are entered, preferably on a text box event _afterupdate,
When the user hits the save button I'd like the profile attributes to be stored to a range.
No doubt this is going to be a laughable mess, but I've been stumped for days, and I'm coming here hat in hand. I just can't figure it out.
Class Mod Example:
Private mProfileName As String
Private mStartDate As Date
Private mEndDate As Date
Private mOngoing As Boolean
Sub Class_Initialise()
'Set default values for properties
mLastName = "Enter Last Name"
mStartDate = "Enter Date"
mEndDate = Date
mOngoing = True
End Sub
'********************************
'The relevant property procedures:
'********************************
Property Get ProfileName() As String
ProfileName = mProfileName
End Property
Property Let ProfileName(Value As String)
mProfileName = Value
End Property
Property Get EndDate() As Date
EndDate = mEndDate
End Property
Property Let EndDate (Value As Date)
mEndDate = Value
End Property
Property Get Ongoing() As Boolean
Ongoing = mOngoing
End Property
Property Let Ongoing(Value As Boolean)
If mEndDate = Date Then
mOngoing = True
End If
End Property
In the Userform I currently have:
Option Explicit
'hopefully not needed:
'Private mTextBoxUpdated As Boolean
'Private mListBoxUpdated As Boolean
'Private mEnteredText As String
'Private mIndexText As String
Private DictThisForm As Dictionary
Private ProfileData As clsProfileData
Private Sub UserForm_Initialize()
Debug.Print "UserForm Intialised"
Set DictThisForm = New Dictionary
Debug.Print "DictThisForm Created"
Set ProfileData = New clsProfileData
Call UserForm_UpdateListBox
And this laughable mess: (not even close to working)
Sub UserForm_UpdateListBox()
With lbxListBox1
.Clear
.ColumnCount = 2
.AddItem
'.List(0, 1) = "Profile Name",ProfileData.ProfileName '
'another attempt
'the below throws a Type Mismatch Error
.AddItem ProfileData.ProfileName, "Profile Name"
.AddItem ProfileData.StartDate, "Start Date"
.AddItem ProfileData.EndDate, "End Date"
.AddItem ProfileData.OnGoing, "Ongoing?"
And (with privately declared module level variables)
Private Sub tbxProfileName_AfterUpdate()
ProfileData.FirstName = tbxProfileName.Text
enter code here
Call UserForm_UpdateListBox
End Sub
At the moment I'm just trying to test the class module and see if I can get the properties values into a variable, or better, get those property values into a range on a hidden page, maybe via a dictionary, and update the list from there? Getting the property values into a listbox seems to be an unwieldy mess...
Sub testClassProfile()
Dim getPropertyAsStringVar As String
Dim NewProfile As clsProfileData
Set NewProfile = New clsProfileData
getPropertyAsStringVar = NewProfile.FirstName
Debug.Print getPropertyAsStringVar
End Sub
Current Debug.Print output is "" ie zip. No default values.
Any advice greatly appreciated.
Please let me know if I'm asking too much at once and I'll try to narrow the scope of the question just to my current issue, I thought the context might be helpful...
Not really an "answer", but it's too hard to respond to your comment with another comment!
Here is an example of how you can pass a class to a userform. Might help!
The TestModule Code
Option Explicit
Public Sub test()
'//Basic declaration of a UserForm
Dim testUF As UserForm1
Set testUF = New UserForm1
'//Now we create a test class - see the Property Get/Set for the string.
Dim testC1 As Class1
Set testC1 = New Class1
testC1.TestString = "Hello"
'//In the UserForm, I've created a property that accepts a class. Assign the
"TestClass" instance tothe UserForm Instance
testUF.Class1 = testC1
testUF.Show
End Sub
...And here is the userform. Note the property that I've added to accept a class instance.
Option Explicit
Private classInstance As Class1
Public Property Get Class1() As Variant
Set Class1 = classInstance
End Property
Public Property Let Class1(ByVal vNewValue As Variant)
Set classInstance = vNewValue
End Property
Private Sub UserForm_Click()
Me.Caption = classInstance.TestString
End Sub
And the class:
Option Explicit
Private mtest As String
Public Property Get TestString() As String
TestString = mtest
End Property
Public Property Let TestString(ByVal vNewValue As String)
mtest = vNewValue
End Property
When you run the "Test" code, you will see that instances of a class and a userform (which is actually just a "Class" as well) are created, and one instance is passed to another. It is (behind the scenes) passed "by reference", so any changes made to TestCl within the userform would be retained outside of the class, allowing it to be modified by the UserForm, and then returned back to the controlling code for use later.
The signature for the Initialize method is
Private Sub Class_Initialize()
... that's not what you have so it will not be run when an object based on the class is created. To make sure it's correct, inside your class code module select "Class" from the left-hand drop-down at the top, then select the required method from the right-hand selection.
Edit: this looks off -
Property Get Ongoing() As Boolean
Ongoing = mOngoing
End Property
Property Let Ongoing(Value As Boolean)
If mEndDate = Date Then
mOngoing = True
End If
End Property
The Ongoing property doesn't really depend on the backing field or need to be set (since its value depends only on mEndDate, so you can drop the Let and just use a Get something like this -
Property Get Ongoing() As Boolean
Ongoing = (mEndDate <= Date)
End Property

Add A Method To A Property Of A Class

I am confused. I am new to VBA classes. I want to add multiple methods to a property of a class, or add properties to another property. I may not have the terminology correct?
I can add one property, but I want to drill down deeper.
For instance if I make a class person:
PersonClass.Features.Hair.Texture.Color
PersonClass.Features.Hair.Texture.Style
PersonClass.Features.Hair.Length
I am not sure how to go about this.
e.g.
MyClass.MyProperty.MyMethod1
MyClass.MyProperty.MyMethod2
MyClass.MyProperty.MyMethod3
or
MyClass.MyProperty.MyMethod1.MyMethod2
Here is an example to illustrate the concepts mentioned in the comments:
Main Form
Option Explicit
Private Sub Form_Load()
Dim p As Person
Set p = New Person
p.Features.Hair = "Red"
MsgBox p.Features.Hair
End Sub
Person Class
Option Explicit
Private m_Features As Features
Private Sub Class_Initialize()
Set m_Features = New Features
End Sub
Public Property Get Features() As Features
Set Features = m_Features
End Property
Features Class
Option Explicit
Private m_Hair As String 'this would actually be another class
'in your example
Public Property Get Hair() As String
Hair = m_Hair
End Property
Public Property Let Hair(ByVal Value As String)
m_Hair = Value
End Property

Wrong number of argument or invalid property assignment collection adding

I've been getting a
wrong number of argument or invalid property assignment collection
error for a long time now, but can't figure out what's wrong. I have a class and a Collection inside that class and a Sub to add values to that collection.
Private sumLosses As Collection
Private Sub Class_Initialize()
Set sumLosses = New Collection
End Sub
Public Property Get getSumLosses()
getSumLosses = sumLosses
End Property
Inside main module:
For Each clientCopy In clientsColl
clientCopy.getSumLosses.Add 200 'error
clientCopy.getSumLosses.Add (200) 'error
Next
Why does this fail and how do I add the items to a class' collection?
sumLosses is of type Collection therefore it is an object and has to be Set to another variable/function.
With using Set it should work:
Public Property Get getSumLosses() As Collection
Set getSumLosses = sumLosses
End Property
Also defining the property As Collection might be no bad idea (but this didn't cause the error).
You need to declare Public Property Get getSumLosses() as a Collection and use Set :
Private sumLosses As Collection
Private Sub Class_Initialize()
Set sumLosses = New Collection
End Sub
Public Property Get getSumLosses() as Collection
Set getSumLosses = sumLosses
End Property
:)

Class Method Can't Use Private Property of Same Class?

What am I misunderstanding about Private Properties in VBA classes? As a novice, I expected Private Properties to be accessible to other methods within the same class (module), but instead I get "Method or data member not found" when trying to compile.
Breaks as Private Property Let lngMarketID
Here's what I have in my standard module:
Option Explicit
Public Model As classModel
Set Model = New classModel
Model.Setup
with this class module named classModel:
Option Explicit
Private plngMarketID As Long
'plngMarketID Properties
Public Property Get lngMarketID() As Long
lngMarketID = plngMarketID
End Property
Private Property Let lngMarketID(ByVal lngMarketID As Long)
plngMarketID = lngMarketID
End Property
Public Sub Setup()
SetuplngMarketID
End Sub
Private Sub SetuplngMarketID()
Model.lngMarketID = CLng(DefaultLogicOptions.textboxMarketID.Value)
End Sub
Works as Public Property Let lngMarketID
The "Method or data member not found" highlights the .lngMarketID of the line in SetuplngMarketID. This compiles fine when I change Private Property Let lngMarketID to Public Property Let lngMarketID.
It's the "Model" in that line. Model is a global variable pointing to some specific instance of your class. From that object, only the public things are visible.
You want to refer to that from "inside" an arbitrary instance of your class, so just drop the Model prefix:
Private Sub SetuplngMarketID()
lngMarketID = CLng(DefaultLogicOptions.textboxMarketID.Value)
End Sub
You are calling "Model.lngMarketId", Model is the name of your variable of classModel object that isn't visible in the object it self.
you have to use "lngMarketId = Clng(something)"

Does setting an object to nothing also set it's child objects to nothing?

Say I have an object, Email, one of whose properties is an object called EmailSkinner.
The EmailSkinner is instantiated in the class_initialize subroutine like this.
private sub class_initialize()
set EmailSkinner = new MyEmailSkinner
end sub
Must I explicitly set the EmailSkinner object to nothing in the class_terminate subroutine of Email?
private sub class_terminate()
set EmailSkinner = nothing
end sub
Or does this happen automatically when I set the Email object itself to nothing?
This is an interesting question. Your assumption is correct any object's you instantiate inside the scope of the parent class will be released when the parent class is released from memory.
However as with all object instantiation in VBScript (and by extension Classic ASP) there is nothing wrong with explicitly releasing objects using the Class_Terminate event.
Remember though that "scope" is important here.
If your EmailSkinner object reference is declared outside of the parent class (regardless of whether it is instantiated inside the class) the reference will remain and will require Class_Terminate() to force the object reference to be released.
Examples
Object Reference is declared inside Class scope.
Class ParentObject
Private _ChildObject
Private Sub Class_Initialize()
Set _Object = new ChildObject()
End Sub
End Class
Object Reference is declared outside Class scope (wouldn't recommend this approach).
Dim GlobalObject
Class ParentObject
Private Sub Class_Initialize()
Set GlobalObject = new ChildObject()
End Sub
'GlobalObject reference will remain so we need to
'force it to be released.
Private Sub Class_Terminate()
Set GlobalObject = Nothing
End Sub
End Class
By default, Class objects are auto destroyed, but if you create new objects outside, you will need to release them from memory .
Is always recommended that we clean memory in all scenarios .
I made a small piece of code for you to test ( I hope this would be similar to what you are trying to explain, since you didn't show us your code ) .
This code help us to check if something remains in memory after some steps of execution and declaration ( just take out the apostrophes at bottom to test the code ) :
Class EmailSkinner
public color
public size
Private Sub Class_Initialize
color = "blue"
size = 300
End Sub
End Class
Class Email
public details
public name
Private Sub Class_Initialize
Set details = New EmailSkinner '//Module Scope
End Sub
Private Sub Class_Terminate
Set details = Nothing
End Sub
End Class
Set email1 = New Email '//Global Scope
With email1
.details.color = "black"
.details.size = 400
End With
''//Take out the apostrophe to test one of the next lines
'Response.Write email1.details.color '//ASP only
'wscript.echo email1.details.color '//Wscript only
Set email1 = Nothing