繁体   English   中英

Excel VBA-将多个用户窗体复选框值写入单个单元格

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

我正在尝试采用具有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

将框架控件重命名为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
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

如果您想从“,蓝色,绿色,黄色”之类的输出中消除初始逗号,则必须更改添加这些字符串的代码,以检查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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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