Logo 
Search:

MS Office Forum

Ask Question   UnAnswered
Home » Forum » MS Office       RSS Feeds

Question about Dim

  Asked By: Gail    Date: Feb 28    Category: MS Office    Views: 606
  

I tried to do following:

Dim x as integer
x =5

Sub test1()
y = x * 2
End Sub

Sub test2()
z = x /2
End Sub

Everything in the same module. Since I have to use x time and time
again, I'd like to dim it as a global variable. But it won't compile,
the error messsage is : "Invalid outside procedure."

Does anyone know why? How to declare a variable out of all following
subs then?

Share: 

 

3 Answers Found

 
Answer #1    Answered By: Viola Hanson     Answered On: Feb 28

To declare  a global  variable, go into the General section of your code mod
and use a 'public' declaration, i.e.,

Pubic gintX as Integer

However, another way you can do it is to pass the var. This might even be
safer, depending on the way you are using this. Because, realize that a
global will change throughout all subs. And that may not be what you want.

In other words...if the initial value is 5 and you multiple it by 2, then
the value will be reset. So when you later divide that value, you may want
to divide the number 5, but what you may now have is actually the number 10!

What you may really want here is to set a Constant. To do that, you would
set it also in the General declaration section at the top of your code
mod...but you would write it something like this...

Public Const INT_x = 5

Note that my personal naming convention is to make the prefix caps and then
an underscore...which helps me remember throughout my code that this
variable is that of a constant. My naming convention for globals is to add a
small 'g' before the prefix as shown in the global declaration above. Use
whatever works for you, but I strongly suggest you do something consistent
and different when declaring globals and/or setting constant values.

 
Answer #2    Answered By: Arthur Cole     Answered On: Feb 28

I believe that you need to also dim  y and z as well

try replacing
Dim x as integer
with
Dim x as integer, y as integer, z as integer

 
Answer #3    Answered By: Jim Williamson     Answered On: Feb 28

Declare x as a public variable  as follows:

Public x as integer

You might also consider reading up on "public" in the VBE Help file.

 
Didn't find what you were looking for? Find more on Question about Dim Or get search suggestion and latest updates.




Tagged: