4

Let's say I have a userform called MyUserForm that I use like

Dim form as MyUserForm
Set form = New MyUserForm
form.SomeVar = "Hi"
form.Show ' Displays "Hi" somewhere on the form

and all is fine and dandy. But the following, and this is what strikes me as odd, works as well:

MyUserForm.SomeVar = "Hi"
MyUserForm.Show

which looks like there's some implicitly declared object MyUserForm whose type is precisely the class MyUserForm! What is VBA really doing here? What are the rules governing this strange idiom? Thank you

2
  • well, make two MyUserForm instances and then call MyUserForm.Show and you will discover the hierarchy. One of the two MyUserForm is the active userform and you can reference it by MyUserForm.<whatever> but it's bad practice when you have more than one userform to call it using class name. It's better and recommended to always use a variable name that stores reference to the specific instance. Commented Mar 5, 2014 at 8:21
  • I'm not sure I understand the question. When a userform gets added to UserForms collection, you can reference it by its name in VBA code. One instance of it is ready for use immediately - you don't have to create a new instance of it's type. You need to do this if you want to have several of them. Commented Mar 5, 2014 at 8:24

1 Answer 1

1

This is the default instance of the userform. You should try and avoid it, because you won't have full control over instantiation and destruction. Have a look at this:

http://books.google.co.uk/books?id=VnegO0pMYlIC&pg=PA379&lpg=PA379&dq=automatic+instantiation+of+userforms+in+vba&source=bl&ots=DvHFJkO9Pz&sig=ZiQwsbmqd39kZrwO_joMxNBcwnI&hl=en&sa=X&ei=_-sWU4-gAZSShQf39oDoAg&ved=0CEgQ6AEwAg#v=onepage&q=automatic%20instantiation%20of%20userforms%20in%20vba&f=false

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! This is exactly what I was looking for and couldn't find on my own.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.