Managing Variables In Visual Basic

Started by magesh.p, Jul 24, 2008, 05:42 PM

Previous topic - Next topic

magesh.p

Managing Variables

Variables are like mail boxes in the post office. The contents of the variables changes every now and then, just like the mail boxes. In term of VB, variables are areas allocated by the computer memory to hold data. Like the mail boxes, each variable must be given a name. To name a variable in Visual Basic, you have to follow a set of rules.

Variable Names


The following are the rules when naming the variables in Visual Basic

    * It must be less than 255 characters
    * No spacing is allowed
    * It must not  begin with a number
    * Period is not permitted

Examples of valid and invalid variable names are displayed in Table 1

Table 1

Valid Name                                                 Invalid Name


My_Car                                       My.Car

ThisYear                                     1NewBoy

Long_Name_Can_beUSE                 He&HisFather                  *& is not acceptable


Declaring Variables


In Visual Basic, one needs to declare the variables before using them by assigning names and data types. They are normally declared in the general section of the codes' windows using the Dim statement.
The format  is as follows:

Dim Variable Name As Data Type

Example 2

Dim password As String
Dim yourName As String
Dim firstnum As Integer
Dim secondnum As Integer
Dim total As Integer
Dim doDate As Date

You may also combine them in one line , separating each variable with a comma, as follows:

Dim password As String,  yourName As String, firstnum As Integer,.............

If data type is not specified, VB will automatically declare the variable as a Variant.
For string declaration, there are two possible formats, one for the variable-length string and another for the fixed-length string. For the variable-length string, just use the same format as example 2 above. However, for the fixed-length string, you have to use the format as shown below:

Dim VariableName as String * n, where n defines the number of characters the string can hold.

Example 3:

Dim yourName as String * 10

yourName can holds no more than 10 Characters. 

Constants

Constants are different from variables in the sense that their values do not change during the running of the program.

Declaring a Constant

The format to declare a constant is

Const  Constant Name  As Data Type = Value

Example 4:

Const Pi As Single=3.142

Const Temp As Single=37

Const Score As Single=100
- An Proud Acumen -