将多个用户窗体文本框值组合到一个单元格中

combining multiple userform textbox values into one cell

我有一个用户表单,已填写并在电子表格中输入数据。 我添加的一个功能是 10 个文本框的框架,除非在前一个框中输入数据,否则这些文本框将保持隐藏状态,最多允许 10 个条目。 因为用户在这些文本框中输入参与者的姓名,所以我希望他们都填写电子表格的同一个单元格,并用逗号分隔。 起初我不假思索地输入了代码,即使没有添加名称,单元格中也会收到 9 个逗号。 从那以后,我设法获得了第二个文本框值,并在单元格中添加了一个逗号,但无法获得任何其他文本框 (3-10) 的值来执行相同的操作。

ws.Range("I" & LastRow).Value = tbPart1.Value
If Not IsEmpty(tbPart2.Value) Then
ws.Range("I" & LastRow).Value = tbPart1.Value & "," & tbPart2.Value
ElseIf Not IsEmpty(tbPart3.Value) Then
ws.Range("I" & LastRow).Value = tbPart1.Value & "," & tbPart2.Value & "," & tbPart3.Value

End If

遍历所有文本框并检查其值:

Dim i As Integer

For i = 1 To 10

    'Loop through all 10 Textboxes and add its value to the cell
    If Not Controls("tbPart" & i).Value = "" Then

        'Check if cell is empty
        If ws.Range("I" & LastRow).Value = "" Then
            ws.Range("I" & LastRow).Value = Controls("tbPart" & i).Value
        Else
            ws.Range("I" & LastRow).Value = _
            ws.Range("I" & LastRow).Value & ", " & Controls("tbPart" & i).Value
        End if
    End If
Next i

代码未经测试。

阿威尔,试试这样的东西。它应该能满足您的需求,而且代码非常灵活。您可以循环遍历所有文本框并更优雅地填充工作表,而不是为每个组合创建 If Then 语句。

Dim ctrl As Control
Dim ctrlName As String, ctrlNum As Integer

For Each ctrl In Me.Controls 'Loops through all controls on the Userform
    If TypeName(ctrl) = "TextBox" Then 'Only acknowledges TextBox Controls
        ctrlName = ctrl.Name
        ctrlNum = CInt(Replace(ctrlName, "tbPart", "")) 'Names each textbox by number
        If ctrlNum > 0 And ctrlNum < 11 And ctrl.Value <> "" Then 'cycles through textboxes 1-10
            If ws.Range("I" & NextRow).Value <> "" Then 'If cell isn't blank, preclude with comma
                ws.Range("I" & NextRow).Value = ws.Range("I" & NextRow).Value & ", " & ctrl.Text
            Else: ws.Range("I" & NextRow).Value = ctrl.Text 'otherwise value only
            End If
        End If
    End If
Next ctrl