excel 如何在VBA用户窗体中为动态创建的TextBox创建_Change()事件?

r55awzrz  于 2022-11-18  发布在  其他
关注(0)|答案(1)|浏览(97)

我正在尝试使用VBA中的类将**_Change()事件添加到动态创建的TextBox中。但是,当我尝试运行代码时,没有任何React。您能指出我哪里错了吗?
我已获得类
条件事件类**

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

我的模块中有以下代码:

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

我希望我的子**conditionEvent_Change()**会显示msgBox,但不幸的是什么也没发生。

8ehkhllq

8ehkhllq1#

如果只讨论单个文本框,您可以使用下一个更简单的方法:
1.在表单代码模块的顶部声明一个私有变量(在声明区域中):

Private WithEvents myTextBox As MSForms.TextBox

1.然后,为上述宣告的变数建立事件:

Private Sub myTextBox_Change()
   MsgBox activecontrol.name & " changed."
End Sub

1.使用您的改编代码作为:

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

对于1到3,4这样的控件,你可以使用更简单的方法(如上所示)。如果你需要创建很多这样的控件,我可以告诉你如何修改你的代码...

已编辑

请使用下一种工作方式,使用一个类将其分配给动态创建的多个文本框:
1.复制类模块中的下一个代码并将其命名为“clsTBox”

Option Explicit

Public WithEvents newTBox As MSForms.TextBox

Private Sub newTBox_Change()
   MsgBox newTBox.name & " changed."
End Sub

2.在表单代码模块的顶部声明一个Private变量:

Private TBox() As New clsTBox

1.使用下一个Sub建立三个文字方块,并将Click事件指派给它们:

Private Sub CreateThreeTB() 
    Dim i As Long, txtBox01 As MSForms.TextBox, leftX As Double, tWidth As Double, k As Long
    
    leftX = 20: tWidth = 50
    ReDim TBox(100) 'use here the maximum number of text boxes you intend creating
    For i = 1 To 3
         Set txtBox01 = Me.Controls.Add("Forms.TextBox.1", "dynTxtBox_" & i)
        With txtBox01
            .top = 10
            .left = leftX: leftX = leftX + tWidth
            .width = tWidth
            .Text = "something" & i
        End With
        
        Set TBox(k).newTBox = txtBox01: k = k + 1
    Next i
    ReDim Preserve TBox(k - 1)
End Sub

1.从Initialize事件或从另一个控件调用上面的Sub,使用新创建的文本框值并查看如何触发更改事件...

相关问题