2

I add CheckBox1 to my UserForm with this code:

Private Sub UserForm_Initialize()
    Dim opt As Variant
    Set opt = UserForm1.Controls.Add("Forms.checkbox.1", "CheckBox1", True)
End Sub

Now when I click on a CommandButton I want to Check if the CheckBox1 is checked or not:

Private Sub CommandButton1_Click()
    If CheckBox1.Value = False Then
        MsgBox "F"
    End If
End Sub

But this code doesn't work; I think because the check box is added dynamically.
This is just a simplification of the code for solving the problem.

1
  • 1
    You could also create opt as a Module variable rather than a Sub variable? Put Private opt As Control just after your Option Explicit and remove Dim opt As Variant, then you can use If Not opt.Value Then MsgBox "F" Commented Mar 28, 2018 at 8:38

2 Answers 2

2

This is what you are thinking of:

Option Explicit

Private Sub UserForm_Initialize()
    Dim opt As Variant
    Set opt = Me.Controls.Add("Forms.checkbox.1", "CheckBox1", True)
End Sub

Private Sub CommandButton1_Click()
    If Not Me.Controls("CheckBox1") Then
        MsgBox "F"
    End If
End Sub

However, depending on your experience and desires to write better code, you may decide to follow some MVC pattern in working with Forms. Read these for some more ideas about it:

Sign up to request clarification or add additional context in comments.

Comments

0

It will need to be as follows

Private Sub CommandButton1_Click()
If Me.Controls("Checkbox1").Value = False Then
MsgBox "F"
End If
End Sub

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.