Run time error 91 when trying to add controls to a collection

E

ExcelMonkey

Wy am I getting Run time error 91 when trying to add controls to my collection.

Public cntrlclctn1 As Collection
Sub thing()
Dim lbl As Control
Dim txtbx As Control

'Create controls
Set lbl = UserForm1.Controls.Add("Forms.Label.1")
lbl.Caption = "Label Text"
Set txtbx = UserForm1.Controls.Add("Forms.TextBox.1")
txtbx.Text = "Text Box Text"

'Add controls to collection
cntrlclctn1.Add (lbl)
cntrlclctn1.Add (txtbx)

UserForm1.Show
End Sub
 
J

Jim Thomlinson

You have declared a variable for the collection but you have not actually
created the collection object. So you are trying to add controls to a
collection object that as yet does not exist... Add this line...

set cntrlclctn1 = new collection
 
E

ExcelMonkey

Was missing the following:

Set cntrlclctn1 = New Collection

Fixed!

Thanks

EM
 
R

RB Smissaert

Try this:

Sub thing()

Dim lbl As Control
Dim txtbx As Control

'Create controls
Set lbl = UserForm1.Controls.Add("Forms.Label.1")
lbl.Caption = "Label Text"

Set txtbx = UserForm1.Controls.Add("Forms.TextBox.1")
txtbx.Text = "Text Box Text"
txtbx.Left = lbl.Width + 10

If cntrlclctn1 Is Nothing Then
Set cntrlclctn1 = New Collection
End If

'Add controls to collection
cntrlclctn1.Add lbl
cntrlclctn1.Add txtbx

UserForm1.Show

End Sub


RBS
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top