An Interactive Learning Tool

Proud to be a Teacher

Constants and Variables

In programming, a variable is a value or string that can change, depending on conditions or on information passed to the program. Typically, a program consists of instructions that tell the computer what to do and data that the program uses when it is running. The data consists of constants or fixed values that never change and variable values (which are usually initialized to "0" or some default value because the actual values will be supplied by a program's user). Usually, both constants and variables are defined as certain data types. Each data type prescribes and limits the form of the data. Examples of data types include: an integer expressed as a decimal number, or a string of text characters, usually limited in length.

A constant is a value that does not changed by the program during the normal execution of the code. A constant associated with an identifier can be named. constant help programmer and code shorten the time of writing and execution of the code.

For example, you might use the constant "Pi" to store the value 3.14159265... The value of "Pi" will not change throughout the course of your program, but it is useful to store this value in a Constant for ease of use.

Example of constant
Set MyRange = Range("A1:C5")
here if value defined to MyRange will be put in A1 to C5 total 15 cells.
Declaring Variables & Constants
Before using a variable or constant, you can declare it. This is done by adding a simple line of code to your macro, as follows.
To declare a variable:
Dim Variable_Name As Data_Type
Note that in the above line of code, Variable_Name should be replaced by your actual variable name and Data_Type should be replaced by one of the above listed data types. For example:
Dim sVAT_Rate As Single
Dim i As Integer
Constants are declared in a similar way, except a constant should always be assigned a value when it is declared. Examples of the declaration of constants in VBA are:
Const iMaxCount = 5000
Const iMaxScore = 100
Variable Name Examples:
Valid Variable Name Invalid Variable Name Sample Value
My_Car My. Car *Dot Not Allowed My New Car
Val1234 1234 *fixed value declared 1234
Long_Name_Can_beUSE He&HisFather *& is not acceptable He and his father
Group88 Student ID *Spacing not allowed Student ID
A or B A/B *Special Character not allowed America or Britain
Basically variables can store values, calculations, characters etc. and these can be static or changeable according to user input or by self made calculations.
Variables declared with Dim :
Dim MyID as Integer
Dim MyName as String
Dim MyBirthday as Date
Variable defined with primary values:-
MyId = 541452
MyName = Albert
MyBirthday = January 1, 1981

Terms of use Website Policy Contact us
© Copyrights 2020