禁用命令按钮,直到选择了特定的选项按钮

时间:2019-01-06 21:33:24

标签: excel vba

我有一个带有4个选项按钮的UserForm“ HRMForm”。用户必须至少选择这些选项按钮中的2个才能继续。在满足此要求之前,我希望禁用“提交”命令按钮。

我已经包含了每个选项按钮和命令按钮的名称: 1. optHRMCM 2. optHRMLI 3. optHRMPM 4. optHRMBE 5.命令按钮-btnHRMSubmit

我当前的代码字。但是,在用户选择正确的选项并启用了提交按钮之后,如果他们单击了这些选项按钮,则提交按钮将保持启用状态。如何编码使其恢复为禁用状态?

Private Sub optHRMLI_Click()

If Me.optHRMCM And Me.optHRMLI Then
   btnHRMSubmit.Enabled = True
End If

If Me.optHRMCM And Me.optHRMPM Then
   btnHRMSubmit.Enabled = True
End If

If Me.optHRMCM And Me.optHRMBE Then
   btnHRMSubmit.Enabled = True
End If

If Me.optHRMLI And Me.optHRMPM Then
   btnHRMSubmit.Enabled = True
End If

If Me.optHRMLI And Me.optHRMBE Then
   btnHRMSubmit.Enabled = True
End If

If Me.optHRMPM And Me.optHRMBE Then
   btnHRMSubmit.Enabled = True
End If

End Sub

1 个答案:

答案 0 :(得分:1)

我认为这是您需要的代码。只需替换其中的名称,它就在用户表单中。

Private Sub OptionButton1_Click()
  countOptions
End Sub

Private Sub OptionButton2_Click()
countOptions
End Sub

Private Sub OptionButton3_Click()
countOptions
End Sub

Private Sub OptionButton4_Click()
countOptions
End Sub

Private Sub UserForm_Initialize()

  CommandButton1.Enabled = False

End Sub

Sub countOptions()
 Dim cntrl As Control
 Dim Count As Integer
 Count = 0
 For Each cntrl In UserForm1.Controls

    If TypeOf cntrl Is msforms.OptionButton Then

       If cntrl = True Then
         Count = Count + 1
       End If

    End If
 Next

 If Count >= 2 Then
  CommandButton1.Enabled = True
 End If

End Sub