1

我正在尝试获取从具有 4 个复选框选项的用户窗体传递的值并将它们写入单个连接单元格。

当我像这样选择我的用户表单时:

在此处输入图像描述

我想将它保存到这样的单个单元格中:

在此处输入图像描述

我尝试使用以下代码完成此操作(见下文),但如果仅选择第 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
4

3 回答 3

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
于 2013-03-11T16:33:04.133 回答
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
于 2013-03-13T17:44:51.537 回答
0

如果您想从“、Blue、Green、Yellow”之类的输出中消除初始逗号,您将不得不更改添加这些字符串的代码以检查是否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

于 2013-03-11T16:39:42.253 回答