使用VBA验证复选框和单选按钮组

时间:2012-10-24 23:46:03

标签: excel vba

我有以下几组复选框和广播组,并想知道如何在VBA中单独验证它们。任何人都能指出我正确的方向吗?

例如,我要求至少在组和每个单选按钮组中选中复选框(优先级讲义> roomstruc roomtype )只需要进行选择。我很感激任何代码向我展示如何实现这一目标。

- 复选框

  

chk_week1,chk_week2,chk_week3,chk_week4,chk_week5,...,chk_week15

优先级 - 单选按钮

  

priority_y,priority_n

讲座式 - 单选按钮

  

lecturestyle_trad,lecturestyle_sem

roomstruc - 单选按钮

  

roomstruc_tiered,roomstruc_flat

roomtype - 单选按钮

  

roomtype_lecture,roomtype_lab

2 个答案:

答案 0 :(得分:1)

你可以尝试这样的事情。命名框架优先级可能会返回奇怪的结果,因此我重命名了您的框架frPriorityfrLectureStyle

Sub cbValidate_Click()
Dim ctl As Control, strOption As String, lLoop As Long

For lLoop = 1 To 15
    If Me.Controls("chk_week" & lLoop).Value = True Then GoTo nxtCheck0
Next

MsgBox "You didn't select a week"

nxtCheck0:

For Each ctl In Me.frPriority.Controls
    If ctl.Value = True Then GoTo nxtCheck1
Next

MsgBox "You didn't select a priority"

nxtCheck1:

For Each ctl In Me.frLectureStyle.Controls
    If ctl.Value = True Then GoTo nxtCheck1
Next

MsgBox "You didn't select a lecture Style"

nxtCheck1:

Unload Me
End Sub

答案 1 :(得分:1)

您可能会尝试类似下面的编码,因为当您在组中有许多控件时,它会变得乏味:

  1. 插入一个名为“MyForm的用户窗体,其复选框名为”chk01“,”chk02“....”chk20或您想要的复选框

  2. 将以下声明放在代码模块(不是表单模块)

    Public CheckBoxGroup(1 To 20) As New MyForm
    
  3. 将以下声明放在表单代码

    Public WithEvents ChkBoxGrp As CheckBox
    
  4. 以激活事件

    的形式初始化数组
    Private Sub UserForm_Activate()
    Dim i As Integer
        For i = 1 To 20 (or however many checkboxes you have
                set CheckBoxGroup (i).ChkBoxGrp = MyForm("chk" + Right("0" + CStr(i), 2))
        Next i
    End Sub
    
    Private Sub ChkBoxGrp_Click()
        Select Case val(Right(ChkBoxGrp.Name, 2))
                Case 1
                ‘Do whaever you want for chk01 box
            Case 2
                ‘Do whaever you want for chk01 box
            ……………
            End Select
    End Sub
    
  5. 您可以对其他复选框事件使用相同的事件处理