我有一个包含10x复选框的用户表单。
每个复选框都应该有一个值。说复选框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
有人可以告诉我如何正确地做到这一点?
谢谢
我相信以下内容将符合您的期望:
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
更新:
如果您需要将给定复选框的标题分配给变量,您可以像下面一样,使用Array存储每个复选框的值,此示例仅存储已选中复选框的值:
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