1. Lesson 2 of 8 Visual Basic Programming
1 of 4
Lesson 2: Variables
Author: Kasun Ranga Wijeweera
Email: krw19870829@gmail.com
Date: 2020 May 08
A variable is a storage location in memory of the computer that holds
information while the program is running.
The statement that creates a variable in memory is called
declaration of the variable. An example code is given below.
Dim x As Byte
Dim, As, Byte are keywords.
x is the variable name.
Byte is the data type.
Byte data type holds unsigned 8-bit integers that range in value
from 0 to 255.
The default value of Byte is 0.
The statement that assigns a value to a variable is called
initialization of the variable. An example code is given below.
x = 234
The equals sign in the statement works as the assignment
operator not as the equality operator.
The value on the right is assigned to the variable on the left.
0 0 0 0 0 0 0 0x
2. Lesson 2 of 8 Visual Basic Programming
2 of 4
234 = 111010102
Data Types in Visual Basic
Integer Byte, Short, Integer, Long
Floating-Point Single, Double, Decimal
Other Boolean, Char, String, Date
Data Types to Store Integers
Dim age As Byte vs. Dim age As Long
Several bytes of memory can be saved by storing age in a Byte
instead in a Long.
Now look at the code segment given below.
Dim num1, num2, num3 As Integer
num1 = 24
num2 = 57
num3 = num1 + num2
MessageBox.Show (num3)
1 1 1 0 1 0 1 0
Data Type Size
Byte 8 bits
Short 16 bits
Integer 32 bits
Long 64 bits
x
3. Lesson 2 of 8 Visual Basic Programming
3 of 4
The line Dim num1, num2, num3 As Integer creates three
memory blocks that hold default values.
num1 0
num2 0
num3 0
The line num1 = 24 assigns the value 24 to the variable num1.
num1 24
num2 0
num3 0
The line num2 = 57 assigns the value 57 to the variable num2.
num1 24
num2 57
num3 0
The line num3 = num1 + num2 assigns the sum of the values of
the variables num1 and num2 to the variable num3.
num1 24
num2 57
num3 81
4. Lesson 2 of 8 Visual Basic Programming
4 of 4
The line MessageBox.Show (num3) displays the value of the
variable num3 in a message box.
Note that an assignment changes only the left operand while the
right operand remains unchanged.
Rules for Variable Naming
The first character of a variable name must be either a letter
or an underscore.
Subsequent characters must be a letter, underscore, or digit.
Variable names cannot contain spaces, periods, or many other
kinds of characters.
The keywords in Visual Basic cannot be used as variable
names.