Excel VBA - Writing multiple userform checkbox values to a single cell

别来无恙 提交于 2019-12-04 20:37:15

Rename the frame control to frameColours then you can loop its checkboxes & build your 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
mac
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

If you want to eliminate the initial comma from output like ", Blue, Green, Yellow", you're going to have to change the code that adds those strings to check whether colors is empty. Something like:

If chkBlue = true Then
    If colors = "" Then
        colors = "Blue"
    Else
        colors = colors & ", Blue"
    End If
End If

Since "Red" is the first color you add, you can assume that colors is empty:

If chkRed = True Then
      colors = "Red"
End If

You dont' need Else ... colors = colors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!