简体   繁体   中英

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

I am trying to take the values passed from a userform that has 4 checkbox options and write them to a single concatenated cell.

When I select my userform like this:

在此处输入图片说明

I would like to save it to a single cell like this:

在此处输入图片说明

I tried accomplishing this with the following code (see below), but it doesn't work quite right with the commas and such if only the 2nd, 3rd, or 4th item is chosen without the first. I am convinced there is a better way but I can't figure it out or find an answer online.

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

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
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM