• Hi All

    Please note that at the Chandoo.org Forums there is Zero Tolerance to Spam

    Post Spam and you Will Be Deleted as a User

    Hui...

  • When starting a new post, to receive a quicker and more targeted answer, Please include a sample file in the initial post.

Confusion between Static variables & Constant variables.

Hi All,

I am a learner in VBA, and confused in between static variables and constant varialbes.
Also which one is default. If would be great if explained with example.

Thanks in advance
 
Hi Gaurav ,

First , there is nothing like a constant variable. There are constants , and there are variables.

Constants are entities that cannot be changed within the code ; they are declared once , using a statement such as :

Const UPPERLIMIT = 32

The entity named UPPERLIMIT now has the value of 32 , and it will retain this value for the lifetime of the code execution ; any attempt to assign a different value to this entity , such as :

UPPERLIMIT = 5

will generate an error.

Constants assume the type that their assigned value gives them ; thus in the above example , UPPERLIMIT will be of type Integer ; if the declaration of the following entity MAXROWS is :

Const MAXROWS = 1048576

then MAXROWS will be of type Long.

More information is available here :

http://msdn.microsoft.com/en-us/library/x2a031a0.aspx

---------------------------------------------------------------------------------------
Variables are entities that can be changed within the code ; they are declared once , using a statement such as :

Dim just_another_variable As Integer

Following the above declaration , the entity named just_another_variable will have the default value of 0 , and it will retain this value till another statement within the code assigns a different value to this entity , such as :

just_another_variable = 5

Thus variables need to be declared , and thereafter assigned values within the code.

---------------------------------------------------------------------------------------

Static variables are those which are declared using the keyword Static , as in :

Static yet_another_variable as Integer

An example of how this is used , is given here :

http://msdn.microsoft.com/en-in/library/z2cty7t8.aspx

Narayan
 
You can also declare the Constant type during definition

eg:
Const MyInt As Integer = 5
Const MyInt2 As Long = 5
 
I would go one step further and suggest that one should explicitly define the constant's data type.

  • Constants' values cannot be changed at runtime.
  • Variables' values can be changed at runtime. Static variables are procedure level variables which retain their values between procedure calls.
 
Back
Top