遍历复选框以查看选中了哪些复选框

时间:2018-09-05 10:32:15

标签: vba excel-vba

我有一个包含10个复选框的用户窗体。

这些复选框中的每个复选框均应具有一个值。说复选框1应该包含值“ Medicine”,复选框2应该包含值“ Water”。

我为用户提供了检查其中任何一项并按提交的选项。在按下提交时,我想检查选中了哪些复选框并合并值。

即如果用户仅选中复选框1和2,则输出将为“ MedicineWater”。

而不是执行10个嵌套的IF语句,然后执行所有可能的排列,这将花费很长时间。我想知道是否有可能遍历复选框并查看被选中的复选框(标记为True),然后存储应分配给它的值。

我的简化代码是:

Private Sub Submit_Click()
Dim i as Long
Dim Val1 as String
Dim Val2 as String
Dim Array()
Dim Final as String

Val1 = "Medicine"
Val2 = "Water"

For i = 1 to 2
   If Me.CheckBox & i  = True Then
      Array = Val & i
      Final = Join(Array, "")
   End If
Next i

Msgbox (Final)
End Sub

有人可以告诉我如何正确执行此操作吗?

谢谢

1 个答案:

答案 0 :(得分:3)

我相信以下将满足您的期望:

Private Sub Submit_Click()
Dim Final As String
Dim ctrl As Control

For Each ctrl In Me.Controls
'loop through controls in your UserForm
 If TypeName(ctrl) = "CheckBox" Then 'if control is a CheckBox then
    If ctrl.Value = True Then 'if the checkbox is checked
        Final = Final & ctrl.Caption 'add the caption to the variable
    End If
 End If
Next ctrl

MsgBox (Final)
End Sub

更新:

如果您需要将给定复选框的标题分配给变量,则可以像下面这样,使用数组存储每个复选框的值,此示例将仅存储已选中复选框的值: / p>

Private Sub Submit_Click()
Dim Final() As String
Dim ctrl As Control
Dim counter As Integer

counter = 0
For Each ctrl In Me.Controls
'loop through controls in your UserForm
counter = counter + 1
ReDim Preserve Final(counter)
 If TypeName(ctrl) = "CheckBox" Then 'if control is a CheckBox then
    If ctrl.Value = True Then 'if the checkbox is checked
        Final(counter) = ctrl.Caption 'add the caption to the variable
    End If
 End If
Next ctrl
End Sub