VBA - Dynamic UserForms (Controls Created Dynamically)
Did you know that you can add and remove controls from a UserForm (also known as custom dialog boxes) at run-time? This means
that you can change your UserForms based on certain conditions that exist during the operation of your VBA project—you’re not
limited to the design of the UserForm that you created in the VBA designer!
Below is the sample code, this will create one checkbox control and one command button contol in runtime.
'Copy and paste the below code in one module and run the macro.
----------------------------------------------------------------
Sub CreateControls()
Dim CtrlChk As MSForms.CheckBox
Dim CtrlCMD As MSForms.CommandButton
Dim CtrlObj As New clmodCHK
'Load UserForm1
With UserForm1 'Create an user form(userform1) to display controls.
' Set object for CheckBox Control
Set CtrlChk = .Controls.Add("Forms.CheckBox.1", "ChkBox1") '
CtrlChk.Top = 50
CtrlChk.Left = 50
CtrlChk.WordWrap = False
CtrlChk.Caption = "Checkbox Created at Runtime"
Set CtrlObj = Nothing
' Set CtrlObj.chkCtrl = CtrlChk
'Command button
Set CtrlCMD = .Controls.Add("Forms.CommandButton.1", "cmdCB1")
CtrlCMD.Top = 100
CtrlCMD.Left = 50
CtrlCMD.WordWrap = False
CtrlCMD.AutoSize = True
CtrlCMD.Caption = "CommandButton Created"
Set CtrlObj = Nothing
Set CtrlObj.cmdCtrl = CtrlCMD
End With
End Sub
----------------------------------------------------------------
No comments:
Post a Comment