with Custom Class

To control what type of objects are placed into a collection, you can create a collection class.
Using a class gives you the ability to create custom replacements for the standard Add, Remove, Count and Item methods.
You can create a class that "wraps up" your collection and then provide the equivalent methods and properties to emulate the buit-in collection object.


Disadvantages

You will loose the default Item method, meaning that you must use the full syntax.

Dim sValue As String 
sValue = myCollection.Item(2) ' full syntax must be used
'instead of
sValue = myCollection(2) ' there is no default method

You will loose the ability to use a For-Each-Next loop (or enumeration functionality).

Dim lCount As Long 
Dim lCounter As Long
Dim sValue As String
lCount = myCollection.Count
For lCounter = 1 to lCount
   sValue = myCollection.Item(lCounter)
Next lCounter
'instead of
For Each sValue in myCollection ' for-each cannot be used
Next sValue

Class - colStringDataType

Create a new class module called "colStringDataType".

Private colStrings As Collection 

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

Public Function Add(ByVal sText As String)
   Call colStrigs.Add(Item:=sText, Key:=sText)
End Function

Public Sub Remove(ByVal vItem As Variant)
   colStrings.Remove vItem
End Sub

Public Property Get Item(ByVal vItem As Variant) As String
   Set Item = colStrings(vItem)
End Property

Public Property Get Count() As Long
   Count = colStrings.Count
End Property

Here is the code that uses this collection.
This collection can only contain text values and adding something that is not a string will generate an error.

Dim colTextOnly As colStringDataType 
colTextOnly = New colStringDataType
colTextOnly.Add "mon"
colTextOnly.Add "tue"
colTextOnly.Add "wed"
colTextOnly.Add 200 ' Error

© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext