UserForm Variables

jstevens
GoldLounger
Posts: 2628
Joined: 26 Jan 2010, 16:31
Location: Southern California

UserForm Variables

Post by jstevens »

I'm having a challenge passing to a variable a UserForm.TextBox1.value.

Example: oVar = UserForm.TextBox1.Value

I have declared the variable (oVar) as a public variable within the Userform but cannot use the variable in a module.

Your assistance would be appeciated.
John
Regards,
John

User avatar
HansV
Administrator
Posts: 78487
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: UserForm Variables

Post by HansV »

You have to declare the variable in a standard module.

The code module of a userform (like that of a worksheet and like ThisWorkbook) is a class module. A public variable declared in a class module becomes a property of that class, it doesn't act as a "normal" public variable.

(You could keep the declaration in the userform module and use UserForm.MyVar to refer to it in other modules)
Best wishes,
Hans

jstevens
GoldLounger
Posts: 2628
Joined: 26 Jan 2010, 16:31
Location: Southern California

Re: UserForm Variables

Post by jstevens »

Hans,

I did think of your suggestion but I'm UserFormed challenged today.

Would you kindly attach a sample file depicting both of your solutions.

Regards,
John
Regards,
John

User avatar
HansV
Administrator
Posts: 78487
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: UserForm Variables

Post by HansV »

See the attached workbook (you have to enable macros).

First click the worksheet button to show the userform, then enter some text, and click the Hide UserForm button.

Then test the worksheet buttons below. The ones calling Test1 and Test3 should work, but the one calling Test2 should cause an error.

Finally, view the code in Module1 and in the module of UserForm1.
VariableDemo.xls
You do not have the required permissions to view the files attached to this post.
Best wishes,
Hans

jstevens
GoldLounger
Posts: 2628
Joined: 26 Jan 2010, 16:31
Location: Southern California

Re: UserForm Variables

Post by jstevens »

Hans,

Thank you for the example file. I was unloading the Userform instead of hiding it which cleared out the TextBoxes.

Regards,
John
Regards,
John

User avatar
rory
5StarLounger
Posts: 817
Joined: 24 Jan 2010, 15:56

Re: UserForm Variables

Post by rory »

Which is one reason you shouldn't really use the default instance of the class. If you declare a variable of the form class and use that, you would have had an error and realised that the form had been unloaded and therefore gone out of scope.
Regards,
Rory