Display variable in userform

P

PJ

I would like to use custom userforms for various dialog boxes, error
trapping, etc. and wanted to know if it is possible to reference a string
variable on a userform. For example, say I have a variable called myVar in
my code and certain conditions are met where I want to display a userform. I
want to add a label with text on the userform and have it display the value
of myVar. Is there a way to do this?
 
S

Sam Wilson

Make myVar public - ie don't declare it in a sub, but before the first sub
put the line

Public myVar as variant

Then in your userform code you can refer to it.

Sam
 
R

Rick Rothstein

To follow up on Sam's posting.... go into the VB editor and copy/paste
this...

"Understanding Scope and Visibility"

into the Search Box and then click on the item with the same name in the
list that appears... this will give you more details about what Sam has
suggested to you.
 
P

PJ

Thanks for the help, but I'm still confused.

Say my conditions are met and I have created a "message string" in my code.
So when I have the code display the userform, how do I get the string to show
on the userform? If I add a label, can I set the value to the msgVar1? If
so, how? I was trying to set the caption of the label on the userform to the
variable, but didn't have any success. I'm not sure I'm going about this the
right way.

Thanks
 
P

PJ

OK I think I figured it out.

I declared "msgString1" as a public variable and set it to this in my code:
msgString1 = "Some text here..." & vbNewLine _
& vbNewLine & "And some more text here " & myVar1 & " more stuff."

Then I added a label named "msgVar1" on the userform and set it like so.
Form1.msgVar1 = msgString1
Form1.Show

It seems to work but I was hoping someone could confirm this is an
acceptable way of doing it.

Thanks - PJ
 
R

Rick Rothstein

OK I think I figured it out.
I declared "msgString1" as a public variable and set it to this in my
code:
msgString1 = "Some text here..." & vbNewLine _
& vbNewLine & "And some more text here " & myVar1 & " more stuff."

Then I added a label named "msgVar1" on the userform and set it like so.
Form1.msgVar1 = msgString1
Form1.Show

It seems to work but I was hoping someone could confirm this is an
acceptable way of doing it.

It is fine to do it that way. Another way would be to put the assignment
statement in the UserForm's Initialize event procedure. Doing it that way,
would automatically make the assignment when the UserForm is initially shown
(that is, after the first time it is shown in a session or the next time it
is show after having been Unload'ed) and you would not have to remember to
set it each time your code Show's the UserForm.
 

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