Creating a Container Property in a VBA Class which returns Indexed Items (Excel VBA 2003)

StackOverflow https://stackoverflow.com/questions/16947849

  •  31-05-2022
  •  | 
  •  

Question

I started learning VBA for my job at the end of last summer, and I can proudly say this is the first time I haven't be able to find the answer on Google. I started teaching myself about Classes this week, and I have come across a situation where I would like to be able to identify an "indexed property" for my class.

Since that probably isn't the clearest explanation, here is a hypothetical example:

The class which I have created for my super awesome sandwich shop (clsSASS) contains properties for Calories, Weight in Grams, Price, and Ingredients. The first three are variables with very straight forward let and get statements. I.E.:

Public pCal As Integer 

Public Property Get Calories() As Integer
    Calories= pCal
End Property

Public Property Let Calories(Value As Integer)
    pCal = Value
End Property

Ingredients however is designed to contain, in order of entry, the list of ingredients. My initial instinct was to do something like this:

Public pIngd  As Collection

Public Property Get Ingredients(Value As Integer) As Collection
    Ingredients = pIngd(Value)
End Property

Public Property Set Ingredients(Object As Collection)
    Set pIngd = Object
End Property

So if Bacon were the first ingredient in the list (and let's be honest it always would be), something like clsNewSandwich.Ingredients(1) would return the string 'Bacon'.

The problem arose when I added a container property to a class, and then couldn't figure out how to identify the individual items in the container. So this may just be a simple syntax issue that has nothing to do with classes whatsoever.

Many Thanks!

*edited for clarity/continuity

Was it helpful?

Solution

OK - I will retract my advice about always naming let/set and Get the same, since in this case you cannot, since the "input" and "output" types are not the same. So, in the sample below I've named the property which just returns one ingredient as Ingredient

Class "clsSASS":

Dim pIngd As Collection

Property Set Ingredients(c As Collection)
    Set pIngd = c
End Property

Property Get Ingredient(v As Integer) As String
    Ingredient = pIngd(v)
End Property

Regular module:

Sub Tester()
Dim c As New Collection
Dim s As New clsSASS

    c.Add "bacon"
    c.Add "lettuce"
    c.Add "tomato"

    Set s.Ingredients = c

    Debug.Print s.Ingredient(1) 'bacon
    Debug.Print s.Ingredient(2) 'lettuce
    Debug.Print s.Ingredient(3) 'tomato

End Sub
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top