Userform使用循环输入到工作表中,用于某些文本框的子集

时间:2013-11-15 04:07:41

标签: excel vba userform

用户一次最多可以输入10个成员。 A列将是“团队名称”B列将是“会员数”C列将是“会员名称” 它适用于If Else,但这对我来说是十分繁琐的。 我不知道如何将它从If Else更改为For Loop

'Using If Else
    Dim RowCount As Long
    RowCount = Worksheets("Sheet1").Range("A1").CurrentRegion.Rows.Count
    If txtNoMember.Value = 1 Then
        With Worksheets("Sheet1").Range("A1")
            .Offset(RowCount, 0).Value = txtTeamName.Text
            .Offset(RowCount, 1).Value = txtNoMember.Text
            .Offset(RowCount, 2).Value = txtMember01.Text
        End With
    ElseIf txtNoMember.Value = 2 Then
        With Worksheets("Sheet1").Range("A1")
            .Offset(RowCount, 0).Value = txtTeamName.Text
            .Offset(RowCount, 1).Value = txtNoMember.Text
            .Offset(RowCount, 2).Value = txtMember01.Text
            .Offset(RowCount + 1, 0).Value = txtTeamName.Text
            .Offset(RowCount + 1, 1).Value = txtNoMember.Text
            .Offset(RowCount + 1, 2).Value = txtMember02.Text
        End With
    End If

'Using For Loop
    Dim counter As Integer
    Dim times As Integer
    Dim RowCount As Long
    RowCount = Worksheets("Sheet1").Range("A1").CurrentRegion.Rows.Count
       For counter = 1 To txtNoMember.Value
            times = txtNoMember.Value - 1
            With Worksheets("Sheet1").Range("A1")
                .Offset(RowCount + times, 0).Value = txtTeamName.Text
                .Offset(RowCount + times, 1).Value = txtNoMember.Text
                .Offset(RowCount + times, 2).Value = txtMember01.Text
            End With

1 个答案:

答案 0 :(得分:0)

正如我评论的那样,通过<FormName>.Controls(<ControlName>)访问控件。用简单的形式演示:

UserForm1

代码:

Private Sub CommandButton1_Click()
    Dim i As Long, m As Long

    m = CLng(txtNoMember.Value)
    For i = 1 To m
        Debug.Print UserForm1.Controls("TextBox" & Format(i, "00")).Value
    Next
End Sub

将10放入txtNoMember并单击命令按钮时,立即窗口给出:

ImmediateWindow

现在你需要在第i个成员和循环索引之间训练数学,以存储值。

粗略查看您将使用的代码(01到10之间的文本框):

.Offset(RowCount + times, 0).Value = <FormName>.Controls("txtMember" & Format(times + 1, "00")).Text