Userform to input into worksheet, using loops, for a subset of some textboxes

StackOverflow https://stackoverflow.com/questions/19993356

  •  30-07-2022
  •  | 
  •  

سؤال

The user can enter up to 10 members at once. Column A will be "Team Name" Column B will be "Number of Member" Column C will be "Member Name" It works for If Else but it is tedious for me to do it 10 times. I don't know how do I change it from If Else to 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
هل كانت مفيدة؟

المحلول

As i commented, access the controls by <FormName>.Controls(<ControlName>). Demostrating with a simple form:

UserForm1

Code:

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

When putting 10 in the txtNoMember and click the command button, Immediate Window gives:

ImmediateWindow

Now you need to workout the math between the i'th member to the loop index for the row to store the value.

Rough look the code you would use is (text boxes from 01 to 10):

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top