Adding Control on Existing Userform on the fly

almoiter

New Member
Joined
Jul 21, 2013
Messages
7
What I missed. I already added the MS VBA Extensibility 5.3 on a VBA Reference. but still got an error. Please Help.

Line1: Dim objForm as object
Line2: Set objForm = ThisWorkbook.VBProject.VBComponents("UserForm1").Designer
Line3: Set Butn = objForm.Controls.Add("Forms.CommandButton.1")

The error is on Line3, "Runtime Error '91': Object Variable or With block variable not set"
 

Excel Facts

Ambidextrous Undo
Undo last command with Ctrl+Z or Alt+Backspace. If you use the Undo icon in the QAT, open the drop-down arrow to undo up to 100 steps.
This worked for me. But it would fail if the userform were visible or if called from the userform
Dim ufObj As Object, newButton As MSForms.CommandButton
Code:
Set ufObj = ThisWorkbook.VBProject.VBComponents("UserForm1").Designer
With ufObj
    Set newButton = .Controls.Add("Forms.CommandButton.1")
    With newButton
        .Top = 10
        .Left = 10
        .Caption = "new"
        .AutoSize = True
    End With
End With
 
Upvote 0
Thank you very much Mike, now I realized why it gives me error. The code was called on the same form (Userform1), on which i tried to add the button. the error is gone.

More power to you sir.
 
Upvote 0

Forum statistics

Threads
1,223,164
Messages
6,170,444
Members
452,326
Latest member
johnshaji

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top