VBA Textbox事件调用私有userform函数

时间:2018-04-17 23:45:12

标签: excel vba excel-vba

我正在尝试创建一个具有文本框字段的用户表单,并且在运行时,我将能够添加多少我需要的框。

目前,我已经创建了一个按钮来执行该操作,但我希望它能够自动创建新字段,只需按下' +'在盒子里关键。

我发现我可以创建一个自定义类模块来处理我创建的所有新框,但是我无法让这个类调用创建下一个框的函数。

我怎么说我的节目"每次我点击+,你都会创建一个新的盒子"?

到目前为止我所得到的是

clsObjHandler类模块:

Public WithEvents txtBoxCustom As MSForms.TextBox

Private Sub txtBoxCustom_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
    If KeyAscii = 43 Then
        createNewBox
        KeyAscii = 0
    End If
End Sub

UserForm模块:

Option Explicit
Dim colTbxs As Collection

Public Function createNewBox()
    Dim newField As Control
    Dim i As Integer
    Dim clsObject As clsObjHandler

    i = Me.Frame1.Controls.count

    Set newField = Me.Frame1.Controls.Add("Forms.TextBox.1", "SESPO" & i)

    newField.name = "SESPO" & i
    newField.Left = 12
    newField.Top = insertLineBtn.Top + 18
    insertLineBtn.Top = insertLineBtn.Top + 18
    insertPoForm.Height = insertPoForm.Height + 18
    Frame1.Height = Frame1.Height + 18
    insertPosBtn.Top = insertPosBtn.Top + 18
    newField.SetFocus

    Set clsObject = New clsObjHandler
    Set clsObject.txtBoxCustom = newField
    colTbxs.Add clsObject
    Set clsObject = Nothing

End Sub

1 个答案:

答案 0 :(得分:0)

我在类模块上使用Application.Run解决了。不知道这是否是最好的方法,但它确实有效。像这样:

Public WithEvents txtBoxCustom As MSForms.TextBox

Private Sub txtBoxCustom_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
    If KeyAscii = 43 Then
        Application.Run UserForm.createNewBox
        KeyAscii = 0
    End If
End Sub