我正在尝试从具有4个复选框选项的userform传递的值,并将它们写入单个连接的单元格。
当我选择这样的用户形式时:
我想将它保存到这样的单个单元格中:
我尝试使用以下代码完成此操作(请参阅下文),但是如果只选择第2,第3或第4项而没有第一项,则使用逗号并不正常。我确信有更好的方法,但我无法弄清楚或在网上找到答案。
Private Sub cmdSave_Click()
Dim colors As String
If chkRed = True Then
colors = "Red"
Else
colors = colors
End If
If chkBlue = True Then
colors = colors & ", Blue"
Else
colors = colors
End If
If chkGreen = True Then
colors = colors & ", Green"
Else
colors = colors
End If
If chkYellow = True Then
colors = colors & ", Yellow"
Else
colors = colors
End If
With colorsSheet
.Cells(ActiveCell.Row, 1).Value = colors
End With
Unload Me
End Sub
答案 0 :(得分:4)
将帧控件重命名为frameColours
,然后您可以循环其复选框&建立你的字符串;
Dim chk as Control
Dim colors as string, delimiter as string
for Each chk In Me.frameColours.Controls
if typeOf chk Is msforms.CheckBox then
if (chk.Value) then
colors = colors & delimiter & chk.Caption
delimiter = ","
end if
end if
next
With colorsSheet
.Cells(ActiveCell.Row, 1).Value = colors
End With
答案 1 :(得分:1)
Private Sub Submit_Click()
Dim lngIndex As Long, strTemp As String
For lngIndex = 1 To 16
'There are 16 check boxex, hence 1 to 16 is given
If Me.Controls("CheckBox" & lngIndex) Then
strTemp = strTemp & Me.Controls("TextBox" & lngIndex).Value & vbLf
'Returns you the output in a new line within the same cell.
End If
Next lngIndex
Sheets("Sheet1").Range("A1").Value = Left$(strTemp, Len(strTemp) - 1)
End Sub
答案 2 :(得分:0)
如果要从“蓝色,绿色,黄色”等输出中删除初始逗号,则必须更改添加这些字符串的代码,以检查colors
是否为空。类似的东西:
If chkBlue = true Then
If colors = "" Then
colors = "Blue"
Else
colors = colors & ", Blue"
End If
End If
由于“红色”是您添加的第一种颜色,因此您可以认为colors
为空:
If chkRed = True Then
colors = "Red"
End If
你不需要Else ... colors = colors