Enable/Disable Command Button

G

Guest

I am hoping someone might be able to point me in the right direction
regarding a feature I have no idea what syntax to use, or where to place it.

I have a form created in VBE. Within this Form is a Frame that has three
Check Boxes. Also on the Form, but not in the Frame, I have a Command Button.

I want the Command Button to be disabled unless all three Check Boxes are
ticked.

Any help would be very gratefully received.
 
I

Incidental

Hi Phil

The code below should do what you want, to test I set up a userform
with a frame containing the three checkboxes then added a button.
what the code does is it has a counter that you add one to if a
checkbox is checked and subtract one if the checkbox is blank, ten
when the counter reaches three the button will be enabled.

Option Explicit
Dim Ctrl As MSForms.Control
Dim i, CountChks As Integer

Private Sub CheckBox1_Click()

i = 1

CheckYourChecks

End Sub
Private Sub CheckBox2_Click()

i = 2

CheckYourChecks

End Sub
Private Sub CheckBox3_Click()

i = 3

CheckYourChecks

End Sub

Private Sub UserForm_Initialize()

i = 0

CountChks = 0

CommandButton1.Enabled = False

End Sub

Sub CheckYourChecks()

Set Ctrl = UserForm1.Controls("CheckBox" & i)

If Ctrl.Value = True Then

CountChks = CountChks + 1

Else

CountChks = CountChks - 1

End If

If CountChks = 3 Then

CommandButton1.Enabled = True

Else

CommandButton1.Enabled = False

End If

End Sub


Hope this helps

S
 
N

NickHK

You can use a bit flag, so if you need to vary the number of check boxes, it
is more easy to maintain.
Whilst this code is not the most compact, it shows the logic of the
procedure clearly.

Dim Flag As Long
Const ALLSET As Long = 2 ^ 0 + 2 ^ 1 + 2 ^ 2

Private Sub CheckBox1_Click()

If CheckBox1.Value = True Then
Flag = Flag Or 2 ^ 0
Else
Flag = Flag And Not (2 ^ 0)
End If

Call CheckStatus

End Sub

Private Sub CheckBox2_Click()

If CheckBox2.Value = True Then
Flag = Flag Or 2 ^ 1
Else
Flag = Flag And Not (2 ^ 1)
End If

Call CheckStatus

End Sub

Private Sub CheckBox3_Click()

If CheckBox3.Value = True Then
Flag = Flag Or 2 ^ 2
Else
Flag = Flag And Not (2 ^ 2)
End If

Call CheckStatus

End Sub

Private Sub CheckStatus()
CommandButton2.Enabled = ((Flag And ALLSET) = ALLSET)
End Sub

Private Sub UserForm_Initialize()
Flag = 0
Call CheckStatus
End Sub

NickHK
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top