根据行数

时间:2015-09-22 17:40:45

标签: excel vba excel-vba textbox userform

VBA Excel Userform中是否有办法根据特定工作表上的行数自动在用户窗体上创建文本框?

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

  • A1:发票日期
  • B1:发票编号
  • C1:发票金额
  • D1:收到付款

现在有许多行数据(发票),并且无法知道有多少行与特定客户相关。加载用户窗体时,付款收到的文本框将为空,而发票日期,发票编号和发票金额将从工作表1中获取。

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

3 个答案:

答案 0 :(得分:0)

假设一个名为" 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 (i.e. "Invoice Data") the control name will be "txtC1"
' This box can be set by:

frmMain.Controls("txtC1").Value = 999



End Sub

答案 1 :(得分:0)

除了上述内容之外,还要向frmMain添加一个名为&#34; fmeMain&#34;并为fmeMain设置以下属性:

ScrollBars = 2 - fmScrollBarsVertical ScrollHeight = 800

向frmMain添加一个名为&#34; cmdTest&#34;的命令按钮。将以下子例程添加到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

答案 2 :(得分:0)

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

enter image description here

您可以在“显示表单”按钮中添加单击处理程序:

function previewFile()
{
    $filePath = $_FILES['fileToUpload']['tmp_name'];

    $excel = new Spreadsheet_Excel_Reader;      // creates object instance of the class
    $excel->read($filePath);

}

在TestForm代码中:

Sub FormButton_Click()
    TestForm.Show
End Sub

表单将如下所示:

enter image description here

可以在付费栏中输入值,并在点击“保存”按钮时将其复制到电子表格中。

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