VBA: Class Module: Get and Let - vba

I have no experience with custom classes and a really simple question, but I found it difficult to google this:
I've come across an example (source) for using custom classes.
Module 1
Sub clsRectAreaRun()
'This procedure instantiates an instance of a class, sets and calls class properties.
Dim a As Double
Dim b As Double
Dim areaRect As New clsRectArea
a = InputBox("Enter Length of rectangle")
b = InputBox("Enter Width of rectangle")
areaRect.Length = a
areaRect.Width = b
MsgBox areaRect.rArea
End Sub
class module 'clsRectArea'
'Example - Create Read-Only Class Property with only the PropertyGet_EndProperty block.
Private rectL As Double
Private rectW As Double
Public Property Let Length(l As Double)
rectL = l
End Property
Public Property Get Length() As Double
Length = rectL
End Property
Public Property Let Width(w As Double)
rectW = w
End Property
Public Property Get Width() As Double
Width = rectW
End Property
Public Property Get rArea() As Double
'Read-Only property with only the PropertyGet_EndProperty block and no PropertyLet_EndProperty (or PropertySet_EndProperty) block.
rArea = Length * Width
End Property
My question is regarding this part of the code:
areaRect.Length = a
areaRect.Width = b
MsgBox areaRect.rArea 'rArea = Length * Width
From what I've read, that Get and Let properties have the same name is kind of the point. But I have to ask, how does the code know if it's supposed to call Get or Let? Is it simply down to if, in this case, Length and Width are to the left or to the right of the equal sign? As in, when you want to assign a value to the property, it automatically recognizes it's Let and if it's on the right, like for rArea here, the code is supposed to retrieve the value, so it's Get?
I know, extremely basic, but I'm not 100% sure and I simply want to know if I'm not messing up the something basic.

You can convince yourself which property method is being called by adding MsgBox's to the code in the class module.
For example:
Public Property Let Length(l As Double)
rectL = l
MsgBox "Let Length called."
End Property

Related

Assigning Values to properties in Structures

In the below code "f" is an instance of the Class FORM which has a property "s" of type SIZE, a structure which has been defined in the code. My question is: When I try to assign values to the attributes of property "s" of the instance "t" directly it does not work: That is the statement f.s.height = 15 does not work. My confusion is arising from the fact that when I print the values of the property "s" of the instance "f", I am able to print the individual attributes of the structure SIZE but the same cannot be done while assignment of value. Assignment of values require me to call the constructor. Why is it so? What is preventing the assignment of the value to the attributes of "s": i.e. f.s.height & f.s.width?
Module Module1
Sub Main()
Dim f As New MyForm()
f.s = New Size(2, 5) 'Works Fine
f.colour = "Red" 'Assignment works just fine
'Below: Individual elements cannot be acceessed for assignment. WHY?
f.s.height = 15 'Doesn't Work
f.s.height = +2 'Doesn't work
'Individual elements can be accessed while printing
Console.WriteLine("Widht = {0}", f.s.width)
Console.WriteLine("Height = {0}", f.s.height)
Console.ReadLine()
End Sub
End Module
Class MyForm
Public Property s As Size
Public Property colour As String
End Class
Public Structure Size
Dim height As Integer
Dim width As Integer
Public Sub New(ByVal w As Integer, ByVal h As Integer)
width = w
height = h
End Sub
End Structure
Pls help.
The compiler should be indicating "Expression is a value and therefore cannot be the target of an assignment".
Change Size from a Structure to a Class (and Dim to Property) to fix the problem:
Public Class Size
Property height As Integer
Property width As Integer
Public Sub New(w As Integer, h As Integer)
width = w
height = h
End Sub
End Class
By the way, you'll also see this behaviour with the standard System.Drawing.Size which is defined as a Structure rather than a Class. (So is Point and probably others.)
This behavior is fundamental to value types (Structures). Conceptually, an instance of a value type is supposed to represent a single immutable value, and any instances with the same value are all supposed to be equivalent. As you have observed, you can get very surprising behavior if you try to change parts of an existing value type. It's really not intended for you to be able to alter them piecewise.
For this reason, I will always recommend that the members of a value type should be marked as ReadOnly so that you get blocked from trying to change them after construction.
If you want to be able to treat something like a mutable object instance instead of an immutable value, it needs to be a reference type (a Class). That's what they're designed to do.
After a lot of searching I came across the following article which probably explains the reason why we are not able to directly access the height/width attribute of the SIZE structure through an instance of the FORM class. Requesting people to go through this as the author has given a lot of details:
http://www.albahari.com/valuevsreftypes.aspx
PLs feel free to share any difference in opinion.

Using a Sub with Arguments in a class module [duplicate]

This question already has answers here:
VBA does not accept my method calling and gives Compile error: Syntax error [duplicate]
(2 answers)
Closed 4 years ago.
I have a Sub in a regular Module where my code is mainly taking place. In a class module i have a sub, requiring Arguments which are not properties of the class module itself. Now i have trouble with getting the code started.
I made an example code with a minimum of lines, so you can see what i planned to do.
First the class module "clsCity":
Option Explicit
Public area As Single
'Public l As Single 'Working, but not desired solution:
'Public h As Single 'Working, but not desired solution:
Sub calcArea(length As Single, height As Single)
area = length * height
End Sub
Now the program itself:
Sub Country()
Dim BikiniBottom As New clsCity
Dim l As Single
Dim h As Single
Bikinibottom.calcArea(l,h) 'Error: "vba: Compile Error: expected: ="
'Working, but not desired solution:
'Bikinibottom.calcArea 'Where l and h are properties of clsCity
End Sub
As you can see, i plan to calculate the area of Bikinibottom with variables "l" and "h", which are not properties of clsCity. I get the error "vba: Compile Error: expected: =" when pressing enter. What do i do wrong? This is a sub and not a function, a "=" should not be necessary.
I know it would work to use the commented code. However, this is just a short example, please keep in mind that in my real code it is not a sophistic solution to make "l" and "h" a property of clsCity (they are properties of other class modules!)
Ok i managed to do it this way:
in class module:
Function calcArea(length As Single, height As Single)
calcArea = length * height
End Function
and in my main code:
BikiniBottom.area = BikiniBottom.calcArea(l, h)
So basicly my problem is solved.
Still curious how it is possible to use Subs with Arguments in a class module. Ideas?
I'd write this
Option Explicit
Sub Country()
Dim BikiniBottom As New clsCity
BikiniBottom.Length = 2
BikiniBottom.Height = 3
Debug.Print BikiniBottom.area
End Sub
and then for the class I'd use property procedures ...
Option Explicit
Private m_Length As Single
Private m_Height As Single
Public Property Let Length(rhs As Single)
m_Length = rhs
End Property
Public Property Get Length() As Single
Length = m_Length
End Property
Public Property Let Height(rhs As Single)
m_Height = rhs
End Property
Public Property Get Height() As Single
Height = m_Height
End Property
Public Function area() As Single
area = m_Length * m_Height
End Function

Constant With Dot Operator (VBA)

I want to have a catalog of constant materials so I can use code that looks like the following:
Dim MyDensity, MySymbol
MyDensity = ALUMINUM.Density
MySymbol = ALUMINUM.Symbol
Obviously the density and symbol for aluminum are not expected to change so I want these to be constants but I like the dot notation for simplicity.
I see a few options but I don't like them.
Make constants for every property of every material. That seems like too many constants since I might have 20 materials each with 5 properties.
Const ALUMINUM_DENSITY As Float = 169.34
Const ALUMINUM_SYMBOL As String = "AL"
Define an enum with all the materials and make functions that return the properties. It's not as obvious that density is constant since its value is returned by a function.
Public Enum Material
MAT_ALUMINUM
MAT_COPPER
End Enum
Public Function GetDensity(Mat As Material)
Select Case Mat
Case MAT_ALUMINUM
GetDensity = 164.34
End Select
End Function
It doesn't seem like Const Structs or Const Objects going to solve this but maybe I'm wrong (they may not even be allowed). Is there a better way?
Make VBA's equivalent to a "static class". Regular modules can have properties, and nothing says that they can't be read-only. I'd also wrap the density and symbol up in a type:
'Materials.bas
Public Type Material
Density As Double
Symbol As String
End Type
Public Property Get Aluminum() As Material
Dim output As Material
output.Density = 169.34
output.Symbol = "AL"
Aluminum = output
End Property
Public Property Get Iron() As Material
'... etc
End Property
This gets pretty close to your desired usage semantics:
Private Sub Example()
Debug.Print Materials.Aluminum.Density
Debug.Print Materials.Aluminum.Symbol
End Sub
If you're in the same project, you can even drop the explicit Materials qualifier (although I'd recommend making it explicit):
Private Sub Example()
Debug.Print Aluminum.Density
Debug.Print Aluminum.Symbol
End Sub
IMO #Comintern hit the nail on the head; this answer is just another possible alternative.
Make an interface for it. Add a class module, call it IMaterial; that interface will formalize the get-only properties a Material needs:
Option Explicit
Public Property Get Symbol() As String
End Property
Public Property Get Density() As Single
End Property
Now bring up Notepad and paste this class header:
VERSION 1.0 CLASS
BEGIN
MultiUse = -1 'True
END
Attribute VB_Name = "StaticClass1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Option Explicit
Save it as StaticClass1.cls and keep it in your "frequently needed VBA code files" folder (make one if you don't have one!).
Now add a prototype implementation to the text file:
VERSION 1.0 CLASS
BEGIN
MultiUse = -1 'True
END
Attribute VB_Name = "Material"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Option Explicit
Implements IMaterial
Private Const mSymbol As String = ""
Private Const mDensity As Single = 0
Private Property Get IMaterial_Symbol() As String
IMaterial_Symbol = Symbol
End Property
Private Property Get IMaterial_Density() As Single
IMaterial_Density = Density
End Property
Public Property Get Symbol() As String
Symbol = mSymbol
End Property
Public Property Get Density() As Single
Density = mDensity
End Property
Save that text file as Material.cls.
Now import this Material class into your project; rename it to AluminiumMaterial, and fill in the blanks:
Private Const mSymbol As String = "AL"
Private Const mDensity As Single = 169.34
Import the Material class again, rename it to AnotherMaterial, fill in the blanks:
Private Const mSymbol As String = "XYZ"
Private Const mDensity As Single = 123.45
Rinse & repeat for every material: you only need to supply each value once per material.
If you're using Rubberduck, add a folder annotation to the template file:
'#Folder("Materials")
And then the Code Explorer will cleanly regroup all the IMaterial classes under a Materials folder.
Having "many modules" is only a problem in VBA because the VBE's Project Explorer makes it rather inconvenient (by stuffing every single class under a single "classes" folder). Rubberduck's Code Explorer won't make VBA have namespaces, but lets you organize your VBA project in a structured way regardless.
Usage-wise, you can now have polymorphic code written against the IMaterial interface:
Public Sub DoSomething(ByVal material As IMaterial)
Debug.Print material.Symbol, material.Density
End Sub
Or you can access the get-only properties from the exposed default instance (that you get from the modules' VB_PredeclaredId = True attribute):
Public Sub DoSomething()
Debug.Print AluminumMaterial.Symbol, AluminumMaterial.Density
End Sub
And you can pass the default instances around into any method that needs to work with an IMaterial:
Public Sub DoSomething()
PrintToDebugPane AluminumMaterial
End Sub
Private Sub PrintToDebugPane(ByVal material As IMaterial)
Debug.Print material.Symbol, material.Density
End Sub
Upsides, you get compile-time validation for everything; the types are impossible to misuse.
Downsides, you need many modules (classes), and if the interface needs to change that makes a lot of classes to update to keep the code compilable.
You can create a Module called "ALUMINUM" and put the following inside it:
Public Const Density As Double = 169.34
Public Const Symbol As String = "AL"
Now in another module you can call into these like this:
Sub test()
Debug.Print ALUMINUM.Density
Debug.Print ALUMINUM.Symbol
End Sub
You could create a Class module -- let's call it Material, and define the properties a material has as public members (variables), like Density, Symbol:
Public Density As Float
Public Symbol As String
Then in a standard module create the materials:
Public Aluminium As New Material
Aluminium.Density = 169.34
Aluminium.Symbol = "AL"
Public Copper As New Material
' ... etc
Adding behaviour
The nice thing about classes is that you can define functions in it (methods) which you can also call with the dot notation on any instance. For example, if could define in the class:
Public Function AsString()
AsString = Symbol & "(" & Density & ")"
End Function
...then with your instance Aluminium (see earlier) you can do:
MsgBox Aluminium.AsString() ' => "AL(169.34)"
And whenever you have a new feature/behaviour to implement that must be available for all materials, you only have to implement it in the class.
Another example. Define in the class:
Public Function CalculateWeight(Volume As Float) As Float
CalculateWeight = Volume * Density
End Function
...and you can now do:
Weight = Aluminium.CalculateWeight(50.6)
Making the properties read-only
If you want to be sure that your code does not assign a new value to the Density and Symbol properties, then you need a bit more code. In the class you would define those properties with getters and setters (using Get and Set syntax). For example, Symbol would be defined as follows:
Private privSymbol as String
Property Get Symbol() As String
Symbol = privSymbol
End Property
Property Set Symbol(value As String)
If privSymbol = "" Then privSymbol = value
End Property
The above code will only allow to set the Symbol property if it is different from the empty string. Once set to "AL" it cannot be changed any more. You might even want to raise an error if such an attempt is made.
I like a hybrid approach. This is pseudo code because I don't quite have the time to fully work the example.
Create a MaterialsDataClass - see Mathieu Guindon's knowledge about setting this up as a static class
Private ArrayOfSymbols() as String
Private ArrayOfDensity() as Double
Private ArrayOfName() as String
' ....
ArrayOfSymbols = Split("H|He|AL|O|...","|")
ArrayOfDensity = '....
ArrayOfName = '....
Property Get GetMaterialBySymbol(value as Variant) as Material
Dim Index as Long
Dim NewMaterial as Material
'Find value in the Symbol array, get the Index
New Material = SetNewMaterial(ArrayOfSymbols(Index), ArrayofName(Index), ArrayofDensity(Index))
GetMaterialBySymbol = NewMaterial
End Property
Property Get GetMaterialByName(value as string) ' etc.
Material itself is similar to other answers. I have used a Type below, but I prefer Classes over Types because they allow more functionality, and they also can be used in 'For Each' loops.
Public Type Material
Density As Double
Symbol As String
Name as String
End Type
In your usage:
Public MaterialsData as New MaterialsDataClass
Dim MyMaterial as Material
Set MyMaterial = MaterialsDataClass.GetMaterialByName("Aluminium")
Debug.print MyMaterial.Density

Property Let creates an unwanted variable

I can't find anything on this anywhere so here's my problem (although it is mostly a cosmetic one):
I have a class being used as a custom data type, but when I look in the locals or watch window I see that each Property Let has created an extra variable, which clutters the window with redundant variables and information (and potentially takes up extra space).
Example:
In class module Class1:
Private data As Integer
Property Get X() As Integer
X = data
End Property
Property Let X(ByVal Value As Integer)
data = Value
End Property
And to test:
Sub Test1()
Dim TestClass As Class1
Set TestClass = New Class1
TestClass.X = 100
End Sub
In the locals window:
Am I supposed to be recycling this extra variable somehow or am I doing something else wrong?
--- If you look at stock Excel objects (like a Worksheet) there are no duplicate variables whatsoever.
Edit: To clarify, I want to know if there is a way to hide the Property in the locals/watch window to make them easier to navigate.
It's fine. data is your private variable and X is just property. Nothing wrong about that. But you should consider naming convention, setters and getters for private variable should be somehow consistent, for example:
'Member variable, pName - private Name
Private pName As String
'Properties
Property Get Name() As String
Name = pName
End Property
Property Let Name(val As String)
pName = val
End Property

Can two VBA Class properties write to each other to simulate overloading?

Say I have a class called Vc that represents a geometric vector AB.
We can define a Vector either by two points (xA, yA, xB, yB) or by a point, a distance and an angle (xA, yA, Len, Angle).
I would like to write the class Vc such that its properties can both be optional (to accommodate the above two methods of definition) and be performing automatically the calculation needed to "fill the missing optional
data": that is if the user writes to the properties xA, yA, xB, yB, then
the missing properties Len and Angle be automatically calculated by the code,
and vice versa.
Now to simply the coding, I will treat a similar problem instead of the
geometric problem:
suppose i have two numbers NbA and NbB, with NbA = 2 NbB, and the user can enter either NbA or NbB,
I tried this code, hoping that at least NbB be calculated by NbA
(or entered by the user)
Private pNbA As Double
Private pNbB As Double
Public Property Get NbA() As Double
NbA = pNbA
End Property
Public Property Let NbA(value As Double)
pNbA = value
End Property
Public Property Get NbB() As Double
NbB = pNbB
End Property
Public Property Let NbB(NbA As Double)
pNbB = NbA * 2
End Property
But when testing I got NbB = 0 (while nbA=1):
Sub TestAbove()
Dim aTest As TestClass
Set aTest = New TestClass
aTest.nbA = 1
MsgBox aTest.nbB 'this gives 0
End Sub
I hope that i can solve this issue within the properties
part itself of the class, without resorting to writing a lot
of methods that would introduce duplication of definitions,
I am afraid.
In VB.NET you would use a Nullable(Of Double).
In VBA for the same purpose you can use Variant/Empty:
Private pNbA As Variant ' Empty by default
Public Property Get NbA() As Double
if IsEmpty(pNbA) then NbA = 2 * NbB else NbA = pNbA
End Property
Public Property Let NbA(value As Double)
pNbA = value
End Property
However I believe it would be better if you defined class properties in a way that they only return stored values and do not depend on each other, and create several constructor functions in a module that would accept your different sets of arguments and initialize all fields of the class properly as if all properties were supplied.