VB CreateObject or Controls.Add

msvec

Board Regular
Joined
Feb 18, 2002
Messages
202
I'm trying to create a control dynamically, and while i've tried several things, nothing works...any ideas...here's what i've tried, and here are the errors i've received:

Set lblVar2 = Controls.Add("VB.Label", "lblVar2", True)

Error: Invalid Class String

Set lblVar2 = CreateObject("userForm.Label1")

Error: ActiveX component can't create object

any help would be most appreciated. thanks
 

Some videos you may like

Excel Facts

Shade all formula cells
To shade all formula cells: Home, Find & Select, Formulas to select all formulas. Then apply a light fill color.

Colo

MrExcel MVP,
Joined
Mar 20, 2002
Messages
1,456
Hi msvec, Here is a sample I made for you.
If you want to add only controls...please try this.

<pre>
<Font color=blue>'_/_/_/Sample1_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/</font>
'UserForm Module

Dim MyLabel1 As MSForms.Label

Private Sub UserForm_Initialize()
Set MyLabel1 = Controls.Add("Forms.Label.1")
MyLabel1.Caption = "What's up"
End Sub

<Font color=blue>'_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/</font>
</pre>

Or you want to use "Event" of controls, we can use "WithEvents" when
we declare variables like this. ..please try this too.

<pre>
<Font color=blue>'_/_/_/Sample2_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/</font>
'UserForm Module

Private WithEvents MyLabel1 As MSForms.Label

Private Sub MyLabel1_Click()
MsgBox "Cliked"
End Sub

Private Sub UserForm_Initialize()
Set MyLabel1 = Controls.Add("Forms.Label.1")
MyLabel1.Caption = "What's up"
End Sub
<Font color=blue>'_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/</font>
</pre>
 

Juan Pablo González

MrExcel MVP
Joined
Feb 8, 2002
Messages
11,959
Adding to Colo's sample... all the "codes" for adding controls at run time ar in the Online Help. Forms.TextBox.1, Forms.Label.1, etc.
 

msvec

Board Regular
Joined
Feb 18, 2002
Messages
202
Thanks you two...most helpful there colo...i never would have come up with that config. what does the "1" represent in ("Forms.Label.1") ??

just curious, but this works great for me...thanks.
 

Colo

MrExcel MVP,
Joined
Mar 20, 2002
Messages
1,456
Hi msvec,
The "1" represent in ("Forms.Label.1") is ProgID as follows(please see your help).

Syntax
Set Control = object.Add( ProgID [, Name [, Visible]])

Settings

ProgID values for individual controls are:

CheckBox Forms.CheckBox.1
ComboBox Forms.ComboBox.1
CommandButton Forms.CommandButton.1
Frame Forms.Frame.1
Image Forms.Image.1
Label Forms.Label.1
ListBox Forms.ListBox.1
MultiPage Forms.MultiPage.1
OptionButton Forms.OptionButton.1
ScrollBar Forms.ScrollBar.1
SpinButton Forms.SpinButton.1
TabStrip Forms.TabStrip.1
TextBox Forms.TextBox.1
ToggleButton Forms.ToggleButton.1
 

Watch MrExcel Video

Forum statistics

Threads
1,095,383
Messages
5,444,145
Members
405,269
Latest member
Kjtakke

This Week's Hot Topics

Top