(Excel Userform)检查是否已选中Userform中的所有复选框

时间:2017-06-14 04:52:24

标签: vba excel-vba excel

之前从未尝试过UserForm复选框,因此我甚至不知道如何指向用户表单中的复选框。

这就是我现在所拥有的......我知道,我知道,这是完全错误的。请帮帮忙?

Private Sub Step1_Confirm_Click()
    Dim i As Byte
    Dim Done As Boolean

    For i = 1 To 4
        If Step1_(i).value = True Then
            Done = True
        End If
    Next i

    If Not Done = True Then
        MsgBox "Please make sure you have done all"
    End If

End Sub

基本上我有:

  1. 名为IOSP_Acc_R_Approval_Step1

  2. 的用户形式
  3. 名为Step1_1的4个复选框; Step1_2; Step1_3; Step1_4

  4. 名为Step1_Confirm

  5. 的按钮
  6. 我希望按钮显示错误,如果不是所有复选框都被选中 - 这意味着必须检查所有复选框....(如果我的英语太糟糕,无法传达我的意思)

3 个答案:

答案 0 :(得分:3)

尝试下面的代码(代码中的解释作为注释):

Private Sub Step1_Confirm_Click()

Dim i As Long
Dim Ctrl As Control

' loop through all user_form control
For Each Ctrl In IOSP_Acc_R_Approval.Controls
    If TypeName(Ctrl) = "CheckBox" Then ' check if control type is Check-Box
        If Ctrl.Value = True Then ' check if check-box is checked
            i = i + 1
        End If
    End If
Next Ctrl

If i < 4 Then ' not all 4 check-boxes are checked
    MsgBox "Please make sure you have done all"
End If

End Sub

答案 1 :(得分:2)

您可以通过以下方式执行此操作:

  • 假设通过将标记设置为True
  • 来检查所有复选框
  • 迭代复选框,如果未选中,则将标志设置为False并退出
  • 在循环结束时,如果选中了所有复选框,则该标志仍为True

您可以使用Me.Controls集合动态参阅复选框,并传递"Step1_" & i之类的复选框名称。

示例代码:

Option Explicit

Private Sub Step1_Confirm_Click()

    Dim i As Long '<-- use Long, not Byte
    Dim blnResult As Boolean

    ' set a flag to assume that it is true that all checkboxes are checked
    blnResult = True

    ' get the value of each check box
    For i = 1 To 4
        If Me.Controls("Step1_" & i).Value = False Then
            blnResult = False
            Exit For '<-- skip loop if at least one box not checked
        End If
    Next i

    ' check the value of the flag
    If blnResult = False Then
        MsgBox "Please make sure you have done all"
    Else
        ' all boxes checked ...
        MsgBox "All checked"
    End If

End Sub

答案 2 :(得分:0)

    Done=true 
For i = 1 To 4
            Done = Done*Step1_(i).value
        Next i
if done `then`
msgbox "All checkboxes are checked"
end if