我有一个userform,在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
结果将弹出该单元格,如果有多个文本框具有值,则将用“,”逗号分隔。
试试吧
Cells(emptyRow, 15).Value = Cells(emptyRow, 15).Value & "," & stCode1Box.Value
未经测试:
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
你可以像你已经拥有的那样循环你的控件,而不是有一系列if ... elseif语句,你可以检查texbox.value
是不是""
,将值添加到数组,然后加入由你喜欢的任何东西分隔的数组。
请参阅下面的示例,它将您的值写入C5
上的单元格Sheet1
,假设您的userform
有一个名为cmdSubmit的commandbutton
(这适用于任意数量的textboxes
):
Private Sub cmdSubmit_Click()
Dim temp As Variant
Dim c As Control
Dim myCount As Long
'0 based array starting with a single element
ReDim temp(0 To 0)
myCount = 0
'Check each control for a textbox
For Each c In Me.Frame1.Controls
If TypeOf c Is MSForms.TextBox Then
'if there is a value in the texbox then assign it to an array
If c.Value <> "" Then
temp(myCount) = c.Value
myCount = myCount + 1
'set upperbound of the array +1 when a new value is found
ReDim Preserve temp(0 To UBound(temp) + 1)
End If
End If
Next c
myCount = 0
'Remove the last array element as it must be blank
ReDim Preserve temp(0 To UBound(temp) - 1)
'Create a string of each value joined with a comma and space
Dim myString As String
myString = Join(temp, ", ")
ThisWorkbook.Sheets(1).Range("C5").Value = myString
End Sub