如何在运行时在Excel用户表单中添加文本框和命令按钮?

时间:2017-10-24 14:41:06

标签: excel vba excel-vba userform

我想在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工作表中存储值。

1 个答案:

答案 0 :(得分:0)

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

enter image description here

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

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

然后,您可以从工作簿模块

调用userform
Private Sub Workbook_Open()
    UserForm1.Show
End Sub

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

enter image description here