Excel VBA – 将多个用户表单checkbox值写入单个单元格
我正在尝试从具有4个checkbox选项的用户窗体传递的值,并将它们写入单个连接的单元格。
当我像这样select我的用户表单:
我想将它保存到一个单元格中,如下所示:
我试着用下面的代码来完成这个(见下面的代码),但是如果没有第一,第二,第三或者第四个选项的话,它就不适用于逗号。 我相信有一个更好的方法,但我无法弄清楚或在网上find答案。
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
重命名框架控件frameColours
然后你可以循环其checkbox并build立你的string;
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
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
如果你想消除像“,Blue,Green,Yellow”这样的输出的初始逗号,你将不得不改变添加这些string的代码来检查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