Excel VBA - programatically design a user form

Is it possible to place controls on a User Form at design time programatically?

Reason: to avoid having to manually name and align controls when there's a lot of them.
Who is Participating?

Improve company productivity with a Business Account.Sign Up

Roy CoxConnect With a Mentor Group Finance ManagerCommented:
This example adds a userform with TextBoxes and 4 buttons with their code. You can add other controls as you want.
Martin LissConnect With a Mentor Older than dirtCommented:
Yes it is, but the easiest thing to do is to put all the controls on the form that you'll ever need making all except the ones that you want to see at the start hidden.
Martin LissConnect With a Mentor Older than dirtCommented:
To do it dynamically you do something like this which assumes you have a userform with a textbox named txtOriginal and a command button named CommandButton1.

Private Sub CommandButton1_Click()
Controls.Add "Forms.Textbox.1", "txtNew", True
With Controls("txtNew")
    .Top = txtOriginal.Top + txtOriginal.Height + 20
    .Height = txtOriginal.Height
    .Width = txtOriginal.Width
    .Left = txtOriginal.Left
End With

End Sub

Open in new window

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

Martin LissConnect With a Mentor Older than dirtCommented:
If you want to add events to the created controls it's a little more complicated, so let me know.
hindersalivaAuthor Commented:
Roy, that's perfect :)
Thanks Martin. It helped too.
Roy CoxGroup Finance ManagerCommented:
Pleased to help
Martin LissOlder than dirtCommented:
You're welcome and I'm glad I was able to help.

If you expand the “Full Biography” section of my profile you'll find links to some articles I've written that may interest you.

Marty - Microsoft MVP 2009 to 2016
              Experts Exchange MVE 2015
              Experts Exchange Top Expert Visual Basic Classic 2012 to 2015
hindersalivaAuthor Commented:
Some really good stuff there Martin. Thanks.
Martin LissOlder than dirtCommented:
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.