Storing and Retrieving Variables Question

  • Thread starter Thread starter JasonSelf
  • Start date Start date
J

JasonSelf

I am trying to store a Variable that is acquired by a text box 'Input1'
from a form that I had created. On this form the button 'button1'
should call the variable stored in input1 and display it in a message
box...this is mostly me trying to learn how to use variables....I have
a nice book on VBA sitting next to me and I am somehow missing the
whole variable thing...here is an example of my code that doesn't
work....any tips would be much appreciated.


Public Sub box1_Change()
Dim Input1 As String
Input1 = box1.Value
End Sub
----------------------------------------
Sub button1_Click()
MsgBox Input1
End SubPublic Sub box1_Change()

For the record I haven't really nailed down the Public Sub, Private Sub
and Sub meanings so if that is also incorrect it wouldn't surprise
me...my book does go into that stuff.
Thank you,
Jason Self
 
Just move your Dim statement to outside of your Sub procedure. The
problem is when you declare a variable inside a sub procedure it only
is valid within that sub procedure, to have it active for the entire
Form/Module, move it to the top of your program as either a Dim or
Private for it to be valid through the Form/Module, or a Public to have
it be valid through all Forms and Modules (Project).
 
Jason,

This does not work because Input1 is a local variable to the box1_Change
procedure. So when you try to reference it in the button1_Click procedure,
a new variable is created local to that procedure, and it has no value. If
you had used Option Explicit, which forces you to declare your variables, at
the head of your code, you would have got an error in the second procedure
that Input1 does not exits.

As it happens, you can reference the textbox directly from the button
procedure, like this


Private Sub button1_Click()
MsgBox box1.Value
End Sub

--

HTH

Bob Phillips
... looking out across Poole Harbour to the Purbecks
(remove nothere from the email address if mailing direct)
 
Back
Top