VBA – Usage of Classes and Properties
VBA is an object-oriented language. As such, it is quite OK to create classes and to assign properties to these classes there. In the current article I will show how to create a class “clsPC” with three properties – Processor, Video and Price. Each property has a get and let. The idea is that the get takes the value, assigned to the property and the let assigns value to the property. Easy.
E.g., if you want to name a dog, you may name it “Lucy”, using the let property and whenever you want to know its name, you may use the get property to tell it to you.
This is how the clsPC looks like:
Option Explicit
Private sProcessor As String
Private sVideo As String
Private dPrice As Double
Private Sub Class_Initialize()
Dim i As Integer
Debug.Print "clsPC is initialized"
End Sub
Public Property Get Processor() As String
Processor = sProcessor
End Property
Public Property Let Processor(Value As String)
sProcessor = Value
End Property
Public Property Get Video() As String
Video = sVideo
End Property
Public Property Let Video(Value As String)
sVideo = Value
End Property
Public Property Get Price() As Double
Price = dPrice
End Property
Public Property Let Price(Value As Double)
dPrice = Value
End Property
Private Sub Class_Terminate()
Debug.Print "Terminated"
End Sub
A little hitch – I have added some code to be printed, whenever the class is initiated or terminated. So, whenever we have the following line:
set someVariable = new clsPC
we would have clsPC is initiated printed in the immediate window. In the code below I create two PCs and I assign properties to them. Then I add them to a collection and I print the properties. At the end I empty the two objects and I have “Terminated” printed. This is how my code looks like:
Option Explicit
Sub Main()
Dim pcExpensive As clsPC
Dim pcCheap As clsPC
Dim MyCollection As Collection
Dim item As clsPC
Set MyCollection = New Collection
Set pcExpensive = New clsPC
pcExpensive.Price = 100
pcExpensive.Processor = "i9"
pcExpensive.Video = "Radeon"
Set pcCheap = New clsPC
pcCheap.Price = 50
pcCheap.Processor = "i3"
pcCheap.Video = "Ati"
MyCollection.Add pcCheap
MyCollection.Add pcExpensive
For Each item In MyCollection
Debug.Print item.Price
Debug.Print item.Processor
Debug.Print item.Video
Next item
Set pcExpensive = Nothing
Set pcCheap = Nothing
Set MyCollection = Nothing
End Sub
At the end, it generates the following in the immediate window:
Enjoy it! 🙂
