【问题标题】:How to add text box and command button in excel user form during run time?如何在运行时在 Excel 用户表单中添加文本框和命令按钮?
【发布时间】:2023-03-10 06:49:01
【问题描述】:

我想在 excel - vba 中的用户表单运行时添加 n 个文本框和一个命令按钮。 虽然数字“n”,但我正在通过一个单元格值。 我想存储输入的数据(在运行时动态创建的文本框中,当用户单击也是运行时创建的提交按钮时) 在 Excel 表中。

For i = 1 To ssheet.Cells(2, 2).Value
        Set txtB1 = Controls.Add("Forms.TextBox.1")

        With txtB1
            .Name = "d" & i
            .Height = 25
            .Width = 150
            .Left = 105
            .Top = 20 + 10 * i * 4
        End With


Set cCont = Controls.Add("Forms.CommandButton.1", "Button", True)

    With cCont
        .Caption = "Submit"
        .Top = 60 + 10 * ssheet.Cells(2, 2).Value * 4
        .Left = 105

    End With

在这里我可以按要求显示,但无法触发用户按钮单击并将值存储在 excel 工作表中。

【问题讨论】:

  • 您希望在单击命令按钮时将单元格中的数据存储到文本框中?
  • 我想在单击命令按钮时将用户在文本框中输入的数据存储到单元格中。
  • 实际上我的要求是使用用户表单将 N 个数据(字符串)存储到单元格中。我从 Cell(2,2).value 获取 N 个。
  • 1.不知道如何为运行时生成的按钮添加命令_click代码的语法。 2.并从运行时生成的文本框中为单元格赋值。我知道上面运行时之前添加的元素。
  • 我知道为什么你想在运行时创建文本框,但你真的需要在运行时添加按钮吗?如果该按钮已经在用户窗体上,那会容易得多(您可以最初隐藏该按钮并仅在您有> 1个文本框时才显示它)

标签: vba excel userform


【解决方案1】:

所以创建一个用户表单并在设计时添加命令按钮,如下所示

在用户表单中添加以下代码

Private Sub CommandButton1_Click()
    For i = 1 To ssheet.Cells(2, 2).Value
        ssheet.Cells(i, 5).Value = Controls("d" & i).Value
    Next i
    Unload UserForm1
End Sub

Private Sub UserForm_Initialize()
    If ssheet.Cells(2, 2).Value > 0 Then
        For i = 1 To ssheet.Cells(2, 2).Value
            Set txtB1 = Controls.Add("Forms.TextBox.1")
            With txtB1
                .Name = "d" & i
                .Height = 25
                .Width = 150
                .Left = 10
                .Top = 30 * (i - 1) + 5
            End With
        Next i

        With CommandButton1
            .Caption = "Submit"
            .Top = 30 * (i - 1) + 5
            .Left = 10
        End With

        With Me
            .Width = 200
            .Height = 200
            .ScrollTop = 0
            .KeepScrollBarsVisible = fmScrollBarsVertical
            .ScrollBars = fmScrollBarsVertical
            .ScrollHeight = 30 * i + 5
        End With
    Else
        CommandButton1.Visible = False
    End If
End Sub

然后您可以从工作簿模块调用用户表单

Private Sub Workbook_Open()
    UserForm1.Show
End Sub

当您加载表单时,文本框将根据 B2 单元格的值创建和对齐

【讨论】:

    猜你喜欢
    • 2011-07-26
    • 1970-01-01
    • 2012-05-25
    • 1970-01-01
    • 2017-11-21
    • 2013-06-12
    • 1970-01-01
    • 2012-05-12
    • 1970-01-01
    相关资源
    最近更新 更多