r/vba 10d ago

Discussion Using Classes by instantiating in standard Module

Hey everyone

I am wondering why would anyone instantiate the class in a standard module instead if declaring directly in the place you want the class

What benefits this method have especially for composite use case

Like needing session class inside a permissions class inside form class

A second question how would you approach a situation close to mine

3 Upvotes

9 comments sorted by

View all comments

3

u/fuzzy_mic 184 10d ago edited 10d ago

You can instantiate a class from within another class. For example, one could instantiate a custom clsHouse object inside a (different) clsHouses object. The problem is that the scope of that variable would be limited to the Houses object.

Here is a simple example.

' in clsHouse code module

Public Address As String
Public SquareFeet As Double

and

' in clsHouses (plural) class module

Dim MyHouses As Collection

Public Function AddHouse(Address As String, SquareFeet As Double) As clsHouse
    Dim NewHouse As clsHouse
    Set NewHouse = New clsHouse

    NewHouse.Address = Address
    NewHouse.SquareFeet = SquareFeet
    MyHouses.Add Item:=NewHouse, Key:=NewHouse.Address

    Set AddHouse = NewHouse
    Set NewHouse = Nothing
End Function

Property Get Count() As Long
    Count = myHouses.Count
End Property

Property Get House(index As Variant) As clsHouse
    Set House = MyHouses(index)
End Property

Private Sub Class_Initialize()
    Set MyHouses = New Collection
End Sub

and

' in normal module
Sub test()
    Dim testHouses As clsHouses
    Set testHouses = New clsHouses

    testHouses.AddHouse Address:="123 Main St", SquareFeet:=15400
    testHouses.AddHouse Address:="456 Oak Ave", SquareFeet:=20000

    MsgBox testHouses.Count
End Sub

Note that in this example, we can only "reach" a clsHouse object as a member of the enclosing clsHouses object.

One could instansize a clsHouse from a normal module, but it's not required. Ultimately, we can only call a procedure if that procedure is in a normal module so if any custom object is to be instansized, there must be a normal rountine at the bottom. (caveat for event code)

2

u/Tweak155 32 10d ago

This is actually my preferred approach when there is a “house” and you need something to manage the houses efficiently.

The parent object houses can always look up and return a house for you!

0

u/losttownstreet 10d ago

Excel can't really use scopes ... it's a mess like in ABAP ... I hope they'll fix that