Conditional Button Enabling based on Checkbox

T

Todd uttenstine

I have CheckBox1 and TextBox1 on a UserForm. What is the
code that would enable entry into TextBox1 if CheckBox1
has a check in it?

Thank you

Todd Huttenstine
 
C

Chip Pearson

Todd,

Try something like the following in the user form's code module:

Private Sub CheckBox1_Click()
Me.TextBox1.Enabled = CBool(Me.CheckBox1.Value)
End Sub
 
T

Todd Huttenstine

It still allows the user to click in the textbox if they
dont check the box first. Once they check the box and
then remove the check, then the code works, but I need the
code to work even if the user doesnt check the check box.
 
T

Todd Huttenstine

I cannot get that method to work flawlessly. I think I
need an if then statement.
 
Z

ZootRot

Rule no 2: don't make it complicated.

At design time, set the enabled property of the textbox to false, and the
value of the checkbox to unchecked.
Then add this code to the click event of the checkbox.

If Check1.Value = 1 Then
Text1.Enabled = True
Else
Text1.Enabled = False
End If
 
T

Todd Huttenstine

That still does not work properly. It works before I
check it, but after I check it and then take the check
out, I can still type in the box and its not supposed to
do that because there is no check in the box.
 
T

Todd Huttenstine

Got it! Changed the code to the following. All I had to
do was set the checkbox1.value to true instead of 1.

Thanx.

If Checkbox1.Value = True Then
Textbox2.Enabled = True
Else
Textbox2.Enabled = False
End If
 
V

Vasant Nanavati

Chip's code works perfectly for me. Are you sure you're following it exactly
and have provided all the information?
 
T

Todd Huttenstine

Yes It was working for me but it would not work before I
checked the check box. I am not sure why. I did get it
working with the if then code. Thank you.
 
C

Chip Pearson

Just out of curiosity, why the CBool?

Force of habit. In VB6, the Value property of a CheckBox returns an
Integer, not a Boolean. I like to do the conversion to boolean myself --
self-documenting code and all that.

Just in case the TripleState property of the CheckBox is True, the better
code would be as follows:

Private Sub CheckBox1_Click()
With Me.TextBox1
If IsNull(Me.CheckBox1.Value) Then
.Enabled = False ' or True, as desired
Else
.Enabled = Me.CheckBox1.Value
End If
End With
End Sub



--
Cordially,
Chip Pearson
Microsoft MVP - Excel
Pearson Software Consulting, LLC
www.cpearson.com
 

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