【问题标题】:Excel VBA - Writing multiple userform checkbox values to a single cellExcel VBA - 将多个用户表单复选框值写入单个单元格
【发布时间】:2013-02-26 22:02:00
【问题描述】:

我正在尝试获取从具有 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

【问题讨论】:

    标签: excel vba checkbox concatenation userform


    【解决方案1】:

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

    【讨论】:

    • 亚历克斯,看起来很棒。太感谢了。我会在这里尝试一下,让你知道它是怎么回事。我以前没有学过如何做到这一点,并且知道一定有更好的方法。
    • 效果很好。我必须做的唯一更改是在分隔符中添加一个空格,将其从“,”更改为“,”
    【解决方案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】:

      如果您想从“、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

      【讨论】:

      • 我喜欢(并赞成)@Alex K. 的解决方案。它使用更少的代码,并且如果您添加颜色也不需要更改代码。
      • 蒂姆,你是对的。亚历克斯有一个很好的解决方案。我也喜欢你的,因为它修复了我的代码。很高兴有两种方法来完成我打算做的事情。谢谢。
      猜你喜欢
      • 1970-01-01
      • 2019-03-19
      • 2014-06-12
      • 2017-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多