Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Visual Basic
Expertise: Advanced
Nov 9, 2001



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Change the Key for an Object in a Collection

I have created a generic function for changing the key for an object in a collection:
'Module: Module1
    Option Explicit

    Public Function ChangeKey(Object As Object, 
NewKey As String, Collection As Collection) As Boolean
    Dim Item As Object
    Dim Index As Long
        For Each Item In Collection
            Index = Index + 1
            If Item Is Object Then
                If Len(NewKey) Then
                    Collection.Add Object, NewKey, , 
                    Collection.Add Object, , , Index
                End If
                Collection.Remove Index
                ChangeKey = True
                Exit For
            End If
    End Function

'Class: Class1
'Collection procedures not used in this example has 
been removed. 
    Option Explicit
    Private mCol As Collection
    Public Function Add(Optional Key As String) As Class2
    Dim objNewMember As Class2
        Set objNewMember = New Class2        
        objNewMember.Load Key, mCol        
        If Len(Key) = 0 Then
            mCol.Add objNewMember
            mCol.Add objNewMember, Key
        End If    
        Set Add = objNewMember
        Set objNewMember = Nothing
    End Function
    Public Sub Clear()
        Do While mCol.Count
            mCol.Remove 1
    End Sub
    Public Property Get Item(Index As Variant) As Class2
        Set Item = mCol(Index)
    End Property
    Private Sub Class_Initialize()
        Set mCol = New Collection
    End Sub    
    Private Sub Class_Terminate()
        Set mCol = Nothing
    End Sub

'Class: Class2
    Option Explicit
    Private mKey As String
    Private mCol As Collection
    Friend Sub Load(Key As String, Col As Collection)
        mKey = Key
        Set mCol = Col
    End Sub
    Public Property Get Key() As String
        Key = mKey
    End Property
    Public Property Let Key(vData As String)
        If mKey <> vData Then
            If ChangeKey(Me, vData, mCol) Then
                mKey = vData
                Err.Raise vbObjectError + 1, TypeName(Me) 
& ".Key", "Failed to change key"
            End If
        End If
    End Property

'Form: Form1
' * Add an Comand Button
Option Explicit

Private Sub Command1_Click()
Dim Col As Class1
Dim Item1 As Class2
Dim Item2 As Class2

    Set Col = New Class1
    Set Item1 = Col.Add()
    Item1.Key = "Test 1"
    Set Item1 = Col.Item("Test 1")
    Set Item2 = Col.Add("Test2")
    Item2.Key = "Test 2"
    Set Item2 = Col.Item("Test 2")
End Sub
Andreas Hillqvist
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date