Home > Software engineering >  How to create _Change() Event for dynamically created TextBox in VBA UserForm?
How to create _Change() Event for dynamically created TextBox in VBA UserForm?

Time:11-14

I am trying to add _Change() event to dynamically created TextBox using classes in VBA. However there is nothing happening, when I try to run my code. Could you please point me where I am wrong?

I have got class conditionEventClass

Public WithEvents conditionEvent As MSForms.textBox

Public Property Let textBox(boxValue As MSForms.textBox)
    Set conditionEvent = boxValue
End Property

Public Sub conditionEvent_Change()
    MsgBox conditionEvent.Name & " changed."
End Sub

I have got following code in my module:

Sub addConditions()
    Dim conditionCommand As conditionEventClass
    Dim newTextBox As MSForms.textBox
    

        
    Set newTextBox = commandRequestForm.MultiPage1(1).Controls.Add("Forms.TextBox.1", "conditionValue", True)
    With newTextBox
         .Name = "conditionValue"
         .Left = 750
         .height = 15
         .Width = 100
         .Top = 20 
    End With
    
    Set conditionCommand = New conditionEventClass
    conditionCommand.textBox = newTextBox
    
End Sub

I expect that my sub conditionEvent_Change() is going to show msgBox. But unfortunately nothing happens.

CodePudding user response:

Talking about only a single Text Box, you can use the next simpler way:

1.Declare a private variable on top of the form code module (in the declarations area):

    Private WithEvents myTextBox As MSForms.TextBox
  1. Then, create the event for the above declared variable:
Private Sub myTextBox_Change()
   MsgBox activecontrol.name & " changed."
End Sub
  1. Use your adapted code as:
Sub addConditions()
    Dim newTextBox As MSForms.TextBox

    Set newTextBox = commandRequestForm.MultiPage1(1).Controls.Add("Forms.TextBox.1", "myTextBox", True)
    With newTextBox
         .left = 10
         .height = 15
         .width = 100
         .top = 20
    End With
    
    Set myTextBox = newTextBox
End Sub

For 1 to 3, 4 such controls you can use the simpler (above shown) way. If you need creating on the fly a lot of such controls, I can show you how to adapt your code...

CodePudding user response:

your text box is named conditionValue, therefore your event must also be named conditionValue_Change()

  • Related