Variables in Excel VBA

Variables store values. The value of variable can change during the execution of a program.Variables are differentiated on the basis of type and scope. Type determines the kind of value a variable will store, whereas scope determines the validity of variable in a program.

Excel-VBA supports different variable types. Some of them are
 
Name  Type Details
Byte Numerical Whole number between 0 and 255.
Integer Numerical Whole number between -32'768 and 32'767.
Long Numerical Whole number between - 2'147'483'648 and 2'147'483'647.
Currency Numerical Fixed decimal number between -922'337'203'685'477.5808 and 922'337'203'685'477.5807.
Single Numerical Floating decimal number between -3.402823E38 and 3.402823E38.
Double Numerical Floating decimal number between -1.79769313486232D308 and 1.79769313486232D308.
String Text Text.
Date Date Date and time.
Boolean Boolean True or False.
Object Object Microsoft Object.
Variant Any type Any kind of data (default type if the variable is not declared).


Here we have few examples of the variable type and the way they are declared.





Consider, our excel sheet has Name, Age, Address, DOB data of a few person as shown in Figure.



 We add following line of codes between line sub workbook_open & end sub.
 
The first is where we have defined variables for holding name, age, address and DOB. Variable No_Of_Row stores count of rows with data. Later, we have used for..next loop to access each row and display the result in a message box.
















Apart from inbuilt data type, one can create customized data type to meet a particular requirement. Consider following code. This piece of code creates a new data type detail.






detail type variable can store 4 different of data i.e. String, Integer, String and Date. Usage of user-defined data type has been explained through following piece of code.

On execution, following result is obtained.