Runtime Error while dynamically adding controls to a userform

57 Views Asked by At

I'm getting "Object variable or with block variable not set" (Error 91) on the below mentioned line.

Set cmd = ActiveWorkbook.VBProject.VBComponents("UserForm1").Designer.Controls.Add("Forms.CommandButton.1", "cmdTst")

where cmd is defined as

Dim cmd As MSForms.CommandButton

The watch window for reference (Applied Break on the error line and on Pressing F8)

1

There are 1 best solutions below

0
Domenic On

It looks like you're trying to run your code within the UserForm code module. However, as @CDP1802 has already mentioned, you'll need to run the code within a regular module. Then, once your code adds the CommandButton, you'll need to add the UserForm to the UserForms collection, and invoke the Show method, if you want to show your UserForm.

Option Explicit

Sub test()

    Dim cmd As MSForms.CommandButton
    
    Set cmd = ActiveWorkbook.VBProject.VBComponents("UserForm1").Designer.Controls.Add("Forms.CommandButton.1", "cmdTst")

    VBA.UserForms.Add("UserForm1").Show

End Sub