根据行数自动创build文本框

有没有在VBA Excel用户窗体的方式来自动创build基于特定工作表上的行数在用户窗体上的文本框?

我的数据是从A1开始的Sheet 1,是:

  • A1:发票date
  • B1:发票号
  • C1:发票金额
  • D1:收到付款

现在有很多行数据(发票),而且不可能知道有多less行与特定的客户有关。 当发票date,发票号码和发票金额将从工作表1中取出时,付款收到的文本框将被清空。

那么就很容易填写付款收到的文本框付款可以应用于特定的发票。

假设一个名为“frmMain”的表格,然后添加4个文本框,下面的子例程应该这样做:

Private Sub AddTextBoxes() Dim ctlTextBox As MSForms.TextBox Dim intCol, intCols As Integer Dim strCName As String ' Determine number of columns intCols = 1 Do While Worksheets("Sheet1").Cells(1, intCols).Value <> "" intCols = intCols + 1 Loop ' Add text boxes For intCol = 1 To intCols - 1 strCName = "txtC" & intCol Set ctlTextBox = frmMain.Controls.Add("Forms.Textbox.1", strCName) With ctlTextBox .Top = 10 .Width = 50 .Height = 20 .Left = (intCol) * 60 .Value = intCol End With Next ' Assuming there is a column 1 (ie "Invoice Data") the control name will be "txtC1" ' This box can be set by: frmMain.Controls("txtC1").Value = 999 End Sub 

除了上述内容之外,向frmMain添加一个名为“fmeMain”的框架,并为fmeMain设置以下属性:

ScrollBars = 2 – fmScrollBarsVertical ScrollHeight = 800

向frmMain添加一个名为“cmdTest”的命令button。 将以下子例程添加到frmMain的代码模块中:

 Private Sub AddTextBoxes() Dim ctlTextBox As MSForms.TextBox Dim intCol, intRow, intTop As Integer Dim strCName As String intTop = 10 For intRow = 2 To 31 ' Assumes that row 1 contains header For intCol = 1 To 3 strCName = "txtC" & intCol & "R" & intRow Set ctlTextBox = frmMain.Controls("fmeMain").Add("Forms.Textbox.1", strCName) With ctlTextBox .Top = intTop .Width = 50 .Height = 20 .Left = 52 * intCol .Value = Worksheets("Sheet1").Cells(intRow, intCol).Value End With Next intTop = intTop + 25 Next End Sub Private Sub cmdTest_Click() AddTextBoxes End Sub 

如果你有这样的电子表格:

在这里输入图像说明

您可以将一个点击处理程序添加到显示表单button:

 Sub FormButton_Click() TestForm.Show End Sub 

在TestForm代码中:

 Option Explicit Const dateCol = 1 Const invoiceNumCol = 2 Const amountCol = 3 Const paymentCol = 4 Private Sub SaveButton_Click() Dim row As Range Dim box As Control For Each row In ActiveSheet.Rows On Error GoTo ExitHandler row.Cells(1, paymentCol).value = Me.Controls(row.row & paymentCol).value Next row ExitHandler: Exit Sub End Sub Private Sub UserForm_Initialize() Dim row As Range For Each row In ActiveSheet.Rows If row.Cells(1, dateCol).value = "" Then Exit For End If Call AddBox(row, dateCol) Call AddBox(row, invoiceNumCol) Call AddBox(row, amountCol) Call AddBox(row, paymentCol) Next row End Sub Private Sub AddBox(row, colIndex) Dim box As Control Const width = 50 Const padWidth = width + 4 Const height = 15 Const padHeight = height + 4 Const topMargin = 25 Const leftMargin = 5 Set box = Me.Controls.Add("Forms.TextBox.1", row.row & colIndex) box.Left = (colIndex - 1) * padWidth + leftMargin box.height = height box.width = width box.Top = (row.row - 1) * padHeight + topMargin box.value = row.Cells(1, colIndex).value End Sub 

该表单将如下所示:

在这里输入图像说明

值可以input到付费栏中,当点击保存button时,它们将被复制到电子表格中。

为了解释逻辑,它遍历每个填充行,创build适当的控件,并填充值。 在“保存”例程中,行再次循环,付款金额被复制回电子表格。