选择多个复选框后打印 Excel VBA 中的字符串

Printing a string in Excel VBA after selecting multiple checkboxes

我在 excel VBA 上使用用户表单将数据输入到不同的 sheet 但我还没有找到将多个值连接在一起并在它们之间放置逗号的方法每个输入。使用所附图片的示例是,如果 Dusty Dry 和 Static 都被选中,则将输入到单元格中的值将为 "Dusty, Dry, Static"。有没有办法做类似的事情:

Range("R4").Value = If Dusty.Value = true then "Dusty"

If Dusty Then Range("R4") = "Dusty"

这是以下简称:

If Dusty.Value = True Then 
    Range("R4").Value = "Dusty"
End If

对于多个复选框,每个复选框这样应该没问题:

If Dusty Then Range("R4") = Range("R4") & "Dusty" & vbCrLf
If Friable Then Range("R4") = Range("R4") & "Friable" & vbCrLf

它将 Range("R4") 的值与新值连接起来。

试试,

Range("R4").Value = iif(dusty, "Dusty ", "") & _
                    iif(dry, "Dry ", "") & _
                    iif(damp, "Damp", "") & _
                    iif(static, "Static", "") & _
                    iif(abrasive, "Abrasive ", "") & _
                    iif(cohesive, "Cohesive ", "") & _
                    iif(hygroscopic, "Hygroscopic ", "") & _
                    iif(friable, "Friable ", ""))
Range("R4").Value = application.trim(Range("R4").Value)
Range("R4").Value = replace(Range("R4").Value, " ", ", ")

您也可以通过遍历窗体上的所有控件来实现此目的。这种方法的一些好处是您可以添加更多复选框而无需修改代码,它的代码字符明显少于其他方法,并且没有冗余代码(例如重复使用 iif() 和不同的参数)。

这种方法的主要缺点是如果您希望值按排序顺序排列。它们将按照创建复选框的顺序进行排序。

另一个考虑因素是,如果表单上有其他 CheckBox 控件,您不希望应用此控件。您可以添加额外的检查以查找 .Name 属性 上的前缀,或在 .Tag 属性 中设置某些内容,或将 CheckBoxes 放在框架内并更改 Me.ControlsFrame1.Controls.

Dim Control As Control, Data As String
For Each Control In Me.Controls
    If TypeName(Control) = "CheckBox" Then
        If Control.Value Then ' This is on a different line to prevent errors, VB checks all conditions of an If even if first one is false. 
            Data = Iif(Data <> "",Data & ", ","") & Control.Caption
        End If
    End If
Next

Range("R4").Value = Data 

请注意我是如何使用 Iif() 来更新 Data 的,因为您担心用逗号分隔值。