Referencing the Set Property from the Get Property - vba

I came across this bit of vba code posted in another SO question. Is there any significance in referencing the Set property in the Get Property of a class?
Private WithEvents mctlEventButton As MSForms.CommandButton
Public Property Set EventButton(ctlButton As MSForms.CommandButton)
Set mctlEventButton = ctlButton
End Property
Why do this? ...
Public Property Get EventButton() As MSForms.CommandButton
Set EventButton = mctlEventButton
End Property
The code was showing how to use collections to iterate through a group of controls. The question wasnt really about that part of the code, so it wasnt addressed in the question. Using the example from the question, I ran into an issue with the bit I posted here because the Get Property was using the Set property. So when would that be useful?
Here is the link to the SO Question: object array or collection in VBA Excel

Public Property Get EventButton() As MSForms.CommandButton
Set EventButton = mctlEventButton
End Property
In the code above, Set EventButton = mctlEventButton won't call the following (try stepping through the code & you will see that it doesn't step into Set)
Public Property Set EventButton(ctlButton As MSForms.CommandButton)
Set mctlEventButton = ctlButton
End Property
On the other hand, this of it as a statement that is used to return a value.
Effectively, think of Get as
Public function EventButton() As MSForms.CommandButton
Set EventButton = mctlEventButton 'returning the value from the function
End Property
wrapped in form of a property for developers to do get/set.

Related

Create a class modules with parent and child classes in VBA

I am a novice user of class module.
I don't understand the concept of a class module well.
I want to configure a class module similar to the basic objects of Excel like Worksheet or Cells or ETC..
So I want to control it by creating a parent object and creating its child objects.
Child Class - Defect
Option Explicit
Private pDefectSymptom As String
Private pDefectLevel As Integer
Property Get DefectSymptom() As String
DefectSymptom = pDefectSymptom
End Property
Property Let DefectSymptom(ByVal vDefectSymptom As String)
pDefectSymptom = vDefectSymptom
End Property
Property Get DefectLevel() As Integer
DefectLevel = pDefectLevel
End Property
Property Let DefectLevel(ByVal vDefectLevel As Integer)
pDefectLevel = vDefectLevel
End Property
Function Delete()
'???
End Function
Property Get Parent() As Object
'???
End Property
Parent Class - Defects
Private Defects As New Collection
Function Add(DefectSymptom As String, Optional DefectLevel As Integer) As Defect
Dim NewDefect As Defect
Set NewDefect = New Defect
NewDefect.DefectSymptom = DefectSymptom
NewDefect.DefectLevel = DefectLevel
Defects.Add NewDefect
'Add = NewDefect 'Error! Like the open command of workbook, I want to return an object or just command
End Function
Property Get Count() As Long
Count = Defects.Count
End Property
Property Get Item(Index As Long) As Defect
Item = Defects(Index) 'Error! I don't know what raise Error.
End Property
My question are.
How to add Command like Open Command of workbook. Return or just command.
Why Raise Error Item Property? how to fix that?
Hiding Private variable. Because office office objects seem to be hidden.
enter image description here
If you have time, please help with Delete command and Parent command.
How to add Command like Open Command of workbook. Return or just
command.
You just need to return the newly created object in the function. Keep in mind since we're dealing with objects, we need to Set the object's reference.
Public Function Add(DefectSymptom As String, Optional DefectLevel As Integer) As Defect
Dim NewDefect As Defect
Set NewDefect = New Defect
NewDefect.DefectSymptom = DefectSymptom
NewDefect.DefectLevel = DefectLevel
Defects.Add NewDefect
Set Add = NewDefect '<- here
End Function
Why Raise Error Item Property? how to fix that?
Same as the above, you need to Set the object's reference.
Property Get Item(Index As Long) As Defect
Set Item = Defects(Index)
End Property
To delete, simply supply the index to the function. However, this method must reside where the collection is (parent) since a Defect object cannot delete itself.
Function Delete(ByVal Index As Long)
Defects.Remove Index
End Function
Lastly, to hold a reference to the parent, each child must hold a reference to it in a private variable. Then you need to set the parent when creating a new item using the keyword Me.
So in the Defect class, create a private field.
Private mParent As Defects
Property Set Parent(ByVal objDefects As Defects)
Set mParent = objDefects
End Property
Property Get Parent() As Defects
Set Parent = mParent
End Property
With this done, amend the Add() method to store the reference.
Public Function Add(DefectSymptom As String, Optional DefectLevel As Integer) As Defect
Dim NewDefect As Defect
Set NewDefect = New Defect
NewDefect.DefectSymptom = DefectSymptom
NewDefect.DefectLevel = DefectLevel
Set NewDefect.Parent = Me '<- here
Defects.Add NewDefect
Set Add = NewDefect '<- here
End Function
Not sure this is a good idea though. I tend to avoid circular references altogether, since a child can hold the parent in memory by holding a reference to it. You will need to make sure to clear the reference to the Parent when deleting the item.
Lastly, you should avoid creating the Defects collection like this. Instead, you should make use of the class constructor and destructor.
This method is called automatically when a new class is created:
Private Sub Class_Initialize()
Set Defects = New VBA.Collection
End Sub
This method is called just before the class is destroyed from memory.
Private Sub Class_Terminate()
Set Defects = Nothing
End Sub

Getting a collection property of a class take a property of another class of another type?

I wanted to first thank you all for the help you've given me implicitly over the last few months! I've gone from not knowing how to access the VBA IDE in Excel to writing fully integrated analysis programs for work. I couldn't have done it without the community here.
I'm currently trying to overhaul the first iteration of a data analysis program I wrote while learning how to code in VBA. While purpose driven and only really legible to myself, the code worked; but was a mess. From folks on this site I picked up Martin's Clean Code and gave it a read on how to try and be a better programmer.
From Martin's Clean Code, it was impressed on me to prioritize abstraction and decoupling of my code to allow for higher degrees of maintenance and modularization. I found this out the hard way since very minor changes requested above my pay grade would require massive and confusing rewrites! I'm trying to eliminate that problem going forward.
I am attempting to rewrite my code in terms of single responsibility classes (at least, where it is possible) and I am a bit confused. I apologize if my question isn't clear or if I'm using the wrong terminology. I want to be able to generate a collection of specific strings (the names of our detectors to be specific) with no duplicates from raw instrument data files from my lab. The purpose of this function is to assemble a bunch of metadata in a class and use it to standardize our file system and prevent clerical errors from newbies and old hands when they use the analysis program.
The testing initialization sub is below. It pops open a userform asking for the user to select the filepaths of the three files in the rawdatafiles class; then it kills the userform to free memory. The metadata object is currently for testing and will be rewritten properly when I get the output I want:
Sub setup()
GrabFiles.Show
Set rawdatafiles = New cRawDataFiles
rawdatafiles.labjobFile = GrabFiles.tboxLabJobFile.value
rawdatafiles.rawdatafirstcount = GrabFiles.tboxOriginal.value
rawdatafiles.rawdatasecondcount = GrabFiles.tboxRecount.value
Set GrabFiles = Nothing
Dim temp As cMetaData
Set temp = New cMetaData
temp.labjobName = rawdatafiles.labjobFile
'this works fine!
temp.detectorsOriginal = rawdatafiles.rawdatafirstcount
' This throws run time error 424: Object Required
End Sub
The cMetadata class I have currently is as follows:
Private pLabjobName As String
Private pDetectorsOriginal As Collection
Private pDetectorsRecheck As Collection
Private Sub class_initialize()
Set pDetectorsOriginal = New Collection
Set pDetectorsRecheck = New Collection
End Sub
Public Property Get labjobName() As String
labjobName = pLabjobName
End Property
Public Property Let labjobName(fileName As String)
Dim FSO As New FileSystemObject
pLabjobName = FSO.GetBaseName(fileName)
Set FSO = Nothing
End Property
Public Property Get detectorsOriginal() As Collection
detectorsOriginal = pDetectorsOriginal
End Property
Public Property Set detectorsOriginal(originalFilepath As Collection)
pDetectorsOriginal = getDetectors(rawdatafiles.rawdatafirstcount)
End Property
When I step through the code it starts reading the "public property get rawdatafirstcount() as string" and throws the error after "End Property" and points back to the "temp.detectorsOriginal = rawdatafiles.rawdatafirstcount" line in the initialization sub.
I think I'm at least close because the temp.labjobName = rawdatafiles.labjobFile code executes properly. I've tried playing around with the data types since this is a collection being assigned by a string but I unsurprisingly get data type errors and can't seem to figure out how to proceed.
If everything worked the way I want it to, the following function would take the filepath string from the rawdatafiles.rawdatafirstcount property and return for me a collection containing detector names as strings with no duplicates (I don't know if this function works exactly the way I want since I haven't been able to get the filepath I want to parse properly in the initial sub; but I can deal that later!):
Function getDetectors(filePath As String) As Collection
Dim i As Integer
Dim detectorsCollection As Collection
Dim OriginalRawData As Workbook
Set OriginalRawData = Workbooks.Open(fileName:=filePath, ReadOnly:=True)
Set detectorsCollection = New Collection
For i = 1 To OriginalRawData.Worksheets(1).Range("D" & Rows.Count).End(xlUp).Row
detectorsCollection.Add OriginalRawData.Worksheets(1).Cells(i, 4).value, CStr(OriginalRawData.Worksheets(1).Cells(i, 4).value)
On Error GoTo 0
Next i
getDetectors = detectorsCollection
Set detectorsCollection = Nothing
Set OriginalRawData = Nothing
End Function
Thanks again for reading and any help you can offer!
temp.detectorsOriginal = rawdatafiles.rawdatafirstcount
' This throws run time error 424: Object Required
It throws an error because, as others have already stated, the Set keyword is missing.
Now with that out of the way, a Set keyword is NOT what you want here. In fact, sticking a Set keyword in front of that assignment will only buy you another error.
Let's look at this property you're invoking:
Public Property Get detectorsOriginal() As Collection
detectorsOriginal = pDetectorsOriginal
End Property
Public Property Set detectorsOriginal(originalFilepath As Collection)
pDetectorsOriginal = getDetectors(rawdatafiles.rawdatafirstcount)
End Property
You're trying to assign detectorsOriginal with what appears to be some String value that lives in some TextBox control on that form you're showing - but the property's type is Collection, which is an object type - and that's not a String!
Now look at the property that does work:
Public Property Get labjobName() As String
labjobName = pLabjobName
End Property
Public Property Let labjobName(fileName As String)
Dim FSO As New FileSystemObject
pLabjobName = FSO.GetBaseName(fileName)
Set FSO = Nothing
End Property
This one is a String property, with a Property Let mutator that uses the fileName parameter it's given.
The broken one:
Public Property Set detectorsOriginal(originalFilepath As Collection)
pDetectorsOriginal = getDetectors(rawdatafiles.rawdatafirstcount)
End Property
Is a Set mutator, takes a Collection parameter, and doesn't use the originalFilepath parameter it's given at all!
And this is where I'm confused about your intention: you're passing what has all the looks of a String except for its type (Collection) - the calling code wants to give it a String.
In other words the calling code is expecting this:
Public Property Let detectorsOriginal(ByVal originalFilepath As String)
See, I don't know what you meant to be doing here; it appears you're missing some pOriginalFilepath As String private field, and then detectorsOriginal would be some get-only property that returns some collection:
Private pOriginalFilePath As String
Public Property Get OriginalFilePath() As String
OriginalFilePath = pOriginalFilePath
End Property
Public Property Let OriginalFilePath(ByVal value As String)
pOriginalFilePath = value
End Property
I don't know what you're trying to achieve, but I can tell you this:
Don't make a Property Set member that ignores its parameter, it's terribly confusing code.
Don't make a Property (Get/Let/Set) member that does anything non-trivial. If it's not trivially simple and has a greater-than-zero chance of throwing an error, it probably shouldn't be a property. Make it a method (Sub, or Function if it needs to return a value) instead.
A word about this:
Dim FSO As New FileSystemObject
pLabjobName = FSO.GetBaseName(fileName)
Set FSO = Nothing
Whenever you Dim something As New, VBA will automatically instantiate the object whenever it's referred to. In other words, this wouldn't throw any errors:
Dim FSO As New FileSystemObject
Set FSO = Nothing
pLabjobName = FSO.GetBaseName(fileName)
Avoid As New if you can. In this case you don't even need a local variable - use a With block instead:
With New FileSystemObject
pLabjobName = .GetBaseName(fileName)
End With
May not be your issue but you're missing Set in your detectorsOriginal Set/Get methods:
Public Property Get detectorsOriginal() As Collection
Set detectorsOriginal = pDetectorsOriginal
End Property
Public Property Set detectorsOriginal(originalFilepath As Collection)
Set pDetectorsOriginal = getDetectors(rawdatafiles.rawdatafirstcount)
End Property
So the error is one I've made a time or two (or more). Whenever you assign an object to another object, you have to use the Set reserved word to assign the reference to the Object.
In your code do the following:
In Sub setup()
Set temp.detectorsOriginal = rawdatafiles.rawdatafirstcount
And in the cMetadata class change the Public Property Set detectorsOriginal(originalFilepath As Collection) property to the following:
Public Property Get detectorsOriginal() As Collection
Set detectorsOriginal = pDetectorsOriginal
End Property
Public Property Set detectorsOriginal(originalFilepath As Collection)
Set pDetectorsOriginal = getDetectors(rawdatafiles.rawdatafirstcount)
End Property
Also in your function Function getDetectors(filePath as String) as Collection change the statement afterNext i` to
Set getDetectors = detectorsCollection
Also, I'm very glad to hear that you've learned how to use VBA.
When you're ready to create your own Custom Collections, check out this post. Your own custom Collections.
I also book marked Paul Kelly's Excel Macro Mastery VBA Class Modules – The Ultimate Guide as well as his Excel VBA Dictionary – A Complete Guide.
If you haven't been to Chip Pearson's site you should do so. He has a ton of useful code that will help your delivery your projects more quickly.
Happy Coding.

VBA: Adding class items to a collection within class

I'm trying to make a tree (kind of a composite pattern actually), but I just can't add the created items of a class to a collection of items in the parent.
Inside the class
Private pChildList As Collection
Private Sub Class_Initialize()
Set pChildList = New Collection
End Sub
Public Property Set ChildList(Value As CProduct)
pChildList.Add Value
End Property
Public Property Get ChildList() As Collection
ChildList = pChildList
End Property
The main function calling
Set Pro = New CProduct
Set Child = New CProduct
Pro.ChildList.Add Child
So the result should be a parent (Pro) with a Child in its pChildList collection, but I only get the error that "Argument is not optional".
Many thanks in advance!
You are just missing a Set in your property Get definition. A Collection is an object, you need to use the Set keyword to affect it to a variable.
Public Property Get ChildList() As Collection
Set ChildList = pChildList
End Property
To complement my answer following you comment:
Property Set are for Objects, Property Let are for base types. Those two properties are usually used to change the value of a member variable (and are expected to do that), that is to access the variable for writing, but you can do whatever you want in the code.
Property Get are usually used to return the value of a member variable (but once again, you can do whatever you want in code), that is to access the variable for reading.
Since there is no reason to change the pChildList itself, I would drop totally the Property Set.
You can also decide to completely hide the member variable and use member functions to add and remove Childs, for example:
Public Sub AddChild(vValue as CProduct)
pChildList.Add vValue
End Sub

VBA global class variable

My obstacle is trying to get multiple subs to recognize class variables. When I try to declare them globally, I get a compile error: "Invalid outside procedure". Then, when I run a public function or sub to declare the variables, they remain undefined in the other subs. I want multiple subs to recognize the variables because their values are supposed to be altered via UserForm, and then utilized in a different sub.
If it could work in this manner, great, but I understand that my design could fundamentally be flawed. Please advise!
This is my Class definition, inserted as a Class module named "cRSM":
Option Explicit
Private pName As String
Private pDesiredGrowth As Double
'Name of RSM
Public Property Get Name() As String
Name = pName
End Property
Public Property Let Name(Value As String)
pName = Value
End Property
'Growth property
Public Property Get DesiredGrowth() As Double
DesiredGrowth = pDesiredGrowth
End Property
Public Property Let DesiredGrowth(Value As Double)
If Value > 0 And Value < 1 Then
pDesiredGrowth = Value
End If
End Property
This is invalid procedure error (which I put in the Global Declarations section):
'Bedoya
Dim Bedoya As cRSM
Set Bedoya = New cRSM
Bedoya.Name = "Bedoya"
And this is the "variable not defined error" (within a private sub):
Private Sub Add_Click()
**Bedoya.DesiredGrowth** = Txt2.Value
Thank you for your time
In a standard module (I name mine MGlobals), put
Public Bedoya As cRSM
Then in another standard module (I name mine MOpenClose), put
Sub Initialize()
If Not Bedoya Is Nothing Then
Set Bedoya = New cRSM
End If
End Sub
Any default properties you want set should be set in the Class_Initialize procedure. In any procedure that you want to use Bedoya, use
Initialize
and it will instantiate the global variable if necessary. The only difference between this and the New keyword is that you can't accidentally instantiate the variable with this method. You either call Initialize or you don't. A lot of VBA developers use New, but almost never do for that reason.
If I understood well You want a global object.
You can put the declaration in module like
public Bedoya As cRSM
then you have create the object ... you can use a global event inside the Workbook like
Private Sub Workbook_Open()
Set Bedoya = New cRSM
Bedoya.initialize("Bedoya") 'a method to initialize private variables
End Sub
Now you can use the global object. You have to restart the excel file or run this method manually.
Is not good style to use global variables, but sometimes is the more easy to do :P
What you want to do nowadays is done using singleton Software Pattern, but this is for other day hehehe

Class property error VBA

I am getting runtine error 91: Object vriable or With block variable not set whne I run a simple class manipulation code.
Here are my classes
cTask:
Private pMile As cMile
Public Property Get Mile() As cMile
Set Mile = pMile
End Property
Public Property Set Mile(Value As cMile)
Set pMile = Value
End Property
Private Sub Class_Initializer()
Set Me.Mile = New cMile
End Sub
cMile:
Private pstatus As String
Public Property Get status() As String
status = ppstatus
End Property
Public Property Let status(Value As String)
pstatus = Value
End Property
And the sub:
Sub testt()
Dim ct As New cTasks
ct.Mile.status = "compl"
Debug.Print ct.Mile, ct.Mile.status
End Sub
The code goes from the sub to the get property in cTask. When about to execute the "End Propety" line the error pops up.
I guess something must be wrong with my classes but I don not know what. I have just recently started using classes. Any ideas?
Thank you
You have a typo:
Class_Initializer()
should be
Class_Initialize()
This prevents ct's Mile from being created so accessing it raises the error you see.
ppstatus is also spelt incorrectly.