Home » excel » Excel-VBA How to know which dynamically created UserForm TextBox has changed?

Excel-VBA How to know which dynamically created UserForm TextBox has changed?

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have an excel UserForm that creates textboxes during execution time. code as follows;

Dim CompHandler() As New CCompHandler
Dim tb As MSForms.TextBox   
Dim count As Integer
For i in Range(something)
    If i = anotherthing Then
        Set tb = UserForm1.Controls.Add("Forms.TextBox.1", "tb" & count)
        With tb
            .Width = iTbWidth
            .Top = count * distance
            .Left = iTbLeft
            .Height = iTbHeight
            .Value = Cells(row, column)
            ReDim Preserve CompHandler(0 To count)
            Set CompHandler(count).TextBoxGroup = tb
        End With
    count = count + 1
    End If
Next i

I want to write back the changed value to the corresponding cell.
I’m already able to get when the box has changed and the new value with this code on a class called CCompHandler:

Option Explicit

Public WithEvents TextBoxGroup As MSForms.TextBox

Private Sub TextBoxGroup_Change()

    MsgBox TextBoxGroup

End Sub

So.. any ideas on how can I get which textbox has changed?
Or maybe is there a better way of doing that?
Thanks in advance

How to&Answers:

The Tag property is typically used for something like this. On creation add something like:

With tb
  ...
  .Tag = i.Address
...
End With

You can then access the Tag property later, with something like:

Debug.Print tbWhoseValueHasChanged.Tag

Your code snippet has a lot of undefined/unclear variables, including i. I assumed it was a range variable in the above.