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

纵然是瞬间 提交于 2019-12-22 01:23:03

问题


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

回答1:


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



回答2:


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



回答3:


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



来源:https://stackoverflow.com/questions/15343473/excel-vba-writing-multiple-userform-checkbox-values-to-a-single-cell

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