I have a userform which contain checkboxes and labels.
My goal is to enable or disable specific labels if checkboxes are true or false.
I have:
- a module in which I store my functions and subs
- a main module
- the userform
I could write in the userform:
Private Sub Checkbox1 ()
If Userform.Checbox1 = true then
Userform.label.enable = true
End if
However I have a few checkboxes and labels and I'd like to create a sub or function to simplify my code.
In the module in which I store my function I wrote:
Sub EnableMyLabels(Checkbox as object , Label as object)
If Userform.Checkbox = true then
Userform.label.enable = true
End If
and in my userform I tried to use it like this:
Call EnableMyLabels (Checkbox1 , Label1)
CodePudding user response:
Your Sub should be like
Sub EnableMyLabels(cb As MSForms.CheckBox, lbl As MSForms.Label)
If cb.Value = True Then
lbl.Enabled = True
End If
End Sub
And the call
EnableMyLabels Checkbox1, Label1
You might want to call it from an Event on the Checkbox, eg
Private Sub CheckBox1_Change()
EnableMyLabels CheckBox1, Label1
End Sub
CodePudding user response:
You should try the same principle but using Events.
On your VBE, at the Userform module select "Checkbox1" on the top dropdown.
Then select the method "Click" on the right top dropdown.
A method called Checkbox1_Click should have been created.
That code will run whenever the user clicks the checkbox.
Include all your "label logic" (or logic for other controls too) there.
CodePudding user response:
When you are directly passing the objects (passed byRef by default), then there is no need of the Userform
word in your code. Simply drop that and your code should work perfectly.
Sub EnableMyLabels(Checkbox as object , Label as object)
If Checkbox = true then
label.Enabled = true 'fyi - Enabled not Enable
End If
End if