一个单元格具有多个文本框值

时间:2019-03-24 21:24:08

标签: vba textbox cell frame userform

我有一个用户窗体,在用户窗体中有一个带有4个文本框的框架,我如何将这4个文本框的值传递到一个单元格中?用逗号或空格分隔。

我尝试在“提交”按钮中执行以下操作。

Dim t As MSForms.Control

For Each t In Me.Frame1.Controls
    If TypeOf t Is MSForms.TextBox Then
        If IsEmpty(stCode1Box) Then
        Exit For
        End If

        If stCode1Box Is Nothing Then
           'Cells(emptyRow, 15).Value = stCode1Box.Value
        ElseIf Not IsEmpty(stCode1Box) Then
           Cells(emptyRow, 15).Value = stCode1Box.Value
        ElseIf stCode2Box Is Nothing Then
           'Cells(emptyRow, 15).Value = stCode1Box.Value & ", " & stCode2Box.Value
        ElseIf Not IsEmpty(stCode2Box) Then
           Cells(emptyRow, 15).Value = stCode1Box.Value & ", " & stCode2Box.Value
        ElseIf stCode3Box Is Nothing Then
           'Cells(emptyRow, 15).Value = stCode1Box.Value & ", " & stCode2Box.Value & ", " & stCode3Box.Value
        ElseIf Not IsEmpty(stCode3Box) Then
           Cells(emptyRow, 15).Value = stCode1Box.Value & ", " & stCode2Box.Value & ", " & stCode3Box.Value
        ElseIf stCode4Box Is Nothing Then
           'Cells(emptyRow, 15).Value = stCode1Box.Value & ", " & stCode2Box.Value & ", " & stCode3Box.Value & ", " & stCode4Box.Value
        ElseIf Not IsEmpty(stCode4Box) Then
           Cells(emptyRow, 15).Value = stCode1Box.Value & ", " & stCode2Box.Value & ", " & stCode3Box.Value & ", " & stCode4Box.Value

        End If
    End If
Next t

结果将在该单元格上弹出,并且如果有多个文本框具有值,则将其之间用“,”逗号分隔。

3 个答案:

答案 0 :(得分:1)

未经测试:

Dim t As MSForms.Control, v
v = ""
For Each t In Me.Frame1.Controls
    If TypeOf t Is MSForms.TextBox Then
        v = v & iif(v <> "", "," , "") & Trim(t.Value)
    End If
Next t
Cells(emptyRow, 15).Value = v

答案 1 :(得分:0)

只需尝试

Cells(emptyRow, 15).Value = Cells(emptyRow, 15).Value & "," & stCode1Box.Value

答案 2 :(得分:0)

您可以像以前那样循环使用控件,而不是使用一系列if ... elseif语句,您可以检查texbox.value是否不是"",然后将值添加到数组中,然后加入由您喜欢的东西分隔的数组。

请参阅下面的示例,其中将您的值写入C5上的单元格Sheet1中,假设您的userform有一个名为cmdSubmit的commandbutton(这适用于任意数量的{ {1}}):

示例

textboxes

参考

  1. Array Function
  2. Join Function