VBA Collection Items Get Overwritten

rchaste

New Member
Joined
Mar 31, 2015
Messages
2
I am attempting to add form controls dynamically to a blank form, and build a collection of those controls so I can write my own events. I'm having limited success.

The controls are successfully adding to the form, appear to be adding to the collection, but my click() event only works for the last control on the form. When enumerating the collection, it appears that every item in the collection now holds a reference to only the last field.

When the form appears, five textboxes appear. Double clicking on the last field works, but none of the other 4.

Please ... save my brain from overload!


My class [cTextHandler]
Public WithEvents txt As MSForms.TextBox

Private Sub txt_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
MsgBox (txt)
End Sub


My form [UserForm1]
Code:
Option Explicit

Dim collText As Collection

Private Sub UserForm_Initialize()

    Dim row As Integer
    Dim Prev As Integer
    Dim txt As Control
    
    'event handlers
    Dim txtH As cTextHandler
    Set txtH = New cTextHandler
    Set collText = New Collection

    'Add 5 text boxes to blank form
    Prev = 1
    MsgBox ("Adding items to Collection")
    For row = 1 To 5
        'Add Controls to Form and Build Collection
        Set txt = UserForm1.Controls.Add("Forms.TextBox.1", "foo" & row)
        With txt
            .Value = "foo" & row
            .Width = 168
            .Height = 18
            .Top = Prev + 20
            .Left = 5
            .ZOrder (0)
        End With
        Prev = Prev + 20
       'Add Controls to Collection
        Set txtH.txt = txt
        collText.Add txtH
        MsgBox (txtH.txt)
    Next row

    'Print out the collection
    Dim o As Object
    Dim t As cTextHandler
    MsgBox ("List the Collection")
    For Each o In collText
        Set t = o
        MsgBox (t.txt)
    Next
End Sub
 
Last edited by a moderator:

Some videos you may like

Excel Facts

Can you AutoAverage in Excel?
There is a drop-down next to the AutoSum symbol. Open the drop-down to choose AVERAGE, COUNT, MAX, or MIN

RoryA

MrExcel MVP, Moderator
Joined
May 2, 2008
Messages
35,008
Office Version
365, 2019, 2016, 2010
Platform
Windows, MacOS
This line:
Code:
    Set txtH = New cTextHandler
needs to be inside your loop so that you create a new instance for each control.
 

Watch MrExcel Video

Forum statistics

Threads
1,099,503
Messages
5,468,998
Members
406,627
Latest member
IncandenzaH1997

This Week's Hot Topics

Top