如何在 运行 时间内在 excel 用户表单中添加文本框和命令按钮?
How to add text box and command button in excel user form during run time?
我想在 excel - vba 中的用户表单的 运行 时间内添加 n 个文本框和一个命令按钮。
当数字 'n' 时,我正在通过一个单元格值。
我想存储输入的数据(在 运行 时间创建的动态文本框中,当用户单击提交按钮时,该按钮也是 运行 时间创建的)
在 excel sheet .
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 sheet .
因此创建一个用户窗体并在设计时添加命令按钮,如下所示
在用户表单中添加以下代码
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 单元格的值对齐
我想在 excel - vba 中的用户表单的 运行 时间内添加 n 个文本框和一个命令按钮。 当数字 'n' 时,我正在通过一个单元格值。 我想存储输入的数据(在 运行 时间创建的动态文本框中,当用户单击提交按钮时,该按钮也是 运行 时间创建的) 在 excel sheet .
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 sheet .
因此创建一个用户窗体并在设计时添加命令按钮,如下所示
在用户表单中添加以下代码
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 单元格的值对齐