Search code examples
vbacatia

Enable or disable button based on multiple conditions


I have a userform.

I want the OK button to be enabled only if the user selects CHECK mark, picks OPTIONA or OPTIONB and the TEXT button is clicked.

Userform
enter image description here

I tried this code but OK button activates if I do any one operation.

Option Explicit

Private Sub CancelBtn_Click()
    Unload Me
End Sub

Private Sub UserForm_Initialize()
    OkBtn.Enabled = False
End Sub

Private Sub Option1_Click()
    If Option1.Enabled = True Then
        OkBtn.Enabled = True
    End If
End Sub

Private Sub CheckBox1_Click()
    If CheckBox1.Enabled = True Then
        OkBtn.Enabled = True
    End If
End Sub

Private Sub TextEntry_Change()
    If TextEntry.Enabled = False Then
        OkBtn.Enabled = False
    Else: TextEntry.Enabled = True
        OkBtn.Enabled = True
    End If
End Sub
 
Private Sub TextBtn_Click()
    TextEntry.Text = "TEXT"
End Sub

Private Sub OkBtn_Click()  
    MsgBox " i am enabled"
End Sub

Solution

  • Incorporate this code into your form:

    Public TextPressed As Boolean
    
    Private Sub Option1_Click()
        Call EnableOKBtn
    End Sub
    
    Private Sub Option2_Click()
        Call EnableOKBtn
    End Sub
    
    Private Sub TextBtn_Click()
        Me.TextEntry.Text = "TEXT"
        TextPressed = True
        Call EnableOKBtn
    End Sub
    
    Sub EnableOKBtn()
        If TextPressed = True Then
            If Me.Option1 = True Or Me.Option2 = True Then
                Me.OKBtn.Enabled = True
            End If
        End If
    End Sub
    

    Basically it just uses a public boolean to tell if the text button has been pressed. Value changes to true when that happens. Then calls the separate sub "EnableOKBtn" which checks if either of the optionbuttons are true as well. If one of the options are true and the public boolean are true, it enables the ok button. Just disable your ok button by default in it's properties. That way you don't have to set it in the initialize event.

    enter image description here