Logo

Variables and Data Types

 

Introduction to Variables

 

Overview

When you write a program as a time sheet, you may decide that a user will type her weekly hours in one box and her salary in another box; then another box will display her weekly salary. When you are designing the program, you cannot predict the names of the people who will be using the program and you definitely cannot know the weekly hours they will get week after week. What you have to do is ask the computer to create temporary storage areas that one user can use while the program is running. If that box can be used to store a salary, when another user is using the same program, that box should be ready to receive new inputs, new salary for that other user.

The computer memory is made of small storage areas used to hold the things that a program needs while it is running. As a programmer, you specify these things, or you provide them to the computer; the computer then puts them in these storage areas. When you need one of them, you let the computer know. The machine located it and makes it available to you to use as you see fit.

A variable is a value you are ask the computer to store in its memory while the program is running.

 

Using a Variable

As stated already, a variable is an area of computer memory you use in your program. To use a variable, you must give it a name. There are rules you should, and usually must, follow when naming your variables. The name of a variable:

  • Must begin with a letter

  • Cannot have a period (remember that we use the period to set a property; in other words the period is an operator)

  • Can have up to 255 characters. Please, just because it is allowed, don't use 255 characters.

  • Must be unique inside of the procedure or the module it is used in (we will learn what a module is)

Once a variable has a name, you can use it as you see fit. For example, you can assign it a value and then use the variable in your program as if it represented that value.

 

Practical Learning: Using a Variable

  1. Start Microsoft Visual Basic and create a new application using Standard EXE
  2. Right-click the form and click View Code
  3. In the Code Editor, click the arrow of the Object combo box and select Form
  4. To use a variable, implement the Load event as follows:
     
    Private Sub Form_Load()
        SomeColor = vbRed
        
        BackColor = SomeColor
    End Sub
  5. Press F5 to test the application. Notice that it appears red
  6. After using the form, close it and return to MSVB

Variable Declaration

Unlike languages referred to as strongly typed, Visual Basic is so flexible you can use any variable just by specifying its name. When you provide this name, the computer directly creates an area in memory for it. Based on this, consider the following code section:
 

Private Sub Form_Click()
    SameColor = vbBlue
    
    SomeColor = vbRed
    
    SumColor = vbRed
        
    BackColor = SameColor
End Sub

Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
    SameColor = vbBlue
    
    SomeColor = vbRed
    
    SumColor = vbGreen
        
    BackColor = SumColor
End Sub

Private Sub Form_Load()
    SameColor = vbBlue
    
    SomeColor = vbRed
    
    SumColor = vbGreen
    
    BackColor = SomeColor
End Sub

If you execute this program, when the form displays, it would be painted in red. If the user clicks the form, it would be painted in blue. If the user presses a key, the form would be painted in green. There is some confusion in the program. It uses a variable that seems to have a name but initialize three times with different colors. Visual Basic allows you to directly use any name for a variable as you see fit. Fortunately, to eliminate the possibility of this confusion, you can first let Visual Basic know that you will be using a certain variable. Informing Visual Basic about a variable prior to using that variable is referred to as declaring a variable. When a variable has been declared, just like the variable not declared, the computer reserves an area of memory for it. 

To declare a variable, type the Dim keyword, like this:

Dim

On the right side of Dim, you must type a name for the variable, following the same rules we reviewed above. Here is an example of declaring and using a variable:

Private Sub Form_Load()
    Dim BackgroundColor

    BackgroundColor = vbRed
    
    BackColor = BackgroundColor
End Sub

Declaring a variable simply communicates to Visual Basic the name of that variable. You can still use a mix of declared and not-declared variable. This is demonstrated in the following event:

Once again, the compiler believes that you are using two variables; one is called BackgroundColor and the other is called SomeColor. This can still create a great deal of confusion because you may be trying to use the same variable referred to twice. The solution to this possible confusion is to tell Visual Basic that a variable cannot be used if it has not been primarily declared. To communicate this, on top of each file you use in the Code Editor, type

Option Explicit

This can also be done automatically for each file by checking the Require Variable Declaration in the Options dialog box.

 

Practical Learning: Using a Variable

  1. On the main menu of Microsoft Visual Basic, click Tools -> Options...
  2. Click the Editor property page. In the Code Settings section, put a check mark in the Require Variable Declaration check box
     
  3. Click OK
  4. Close Visual Basic without saving the project
  5. Start Microsoft Visual Basic and create a new application using Standard EXE
  6. Right-click the form and click View Code
  7. In the Code Editor, click the arrow of the Object combo box and select Form
  8. To use a variable, implement the Load event as follows:
     
  9. Press F5 to test the application
  10. Notice that you receive an error:
     
  11. Click OK
  12. On the Standard toolbar, click the End button
  13. Change the Load event as follows:
     
    Private Sub Form_Load()
        Dim BackgroundColor
        
        BackgroundColor = vbRed
        
        BackColor = BackgroundColor
    End Sub
  14. After using the form, close it and return to MSVB
  15. Click the arrow of the Procedure combo box and select Click
    • Implement the events as follows

Introduction to Data Types

 

Introduction

When you decide to use a variable, you are in fact asking the computer to use a certain amount of space to hold that variable. Since different variables will be used for different purposes, you should specify the kind of variable you intend to use, then the computer will figure out how much space is needed for a particular variable. Each variable you use will utilize a certain amount of space in the computer's memory.

Before declaring or using a variable, first decide what kind of role that variable will play in your program. Different variables are meant for different situations. The kind of variable you want to use is referred to as a data type. To specify the kind of variable you want to use, you type the As keyword on the right side of the variable's name. The formula to declare such a variable is:

Dim VariableName As DataType

Once you know what kind of variable you will need, choose the appropriate data type. Data types are organized in categories such as numbers, characters, or other objects.

 

String

A string is an empty text, a letter, a word or a group of words considered. To declare a string variable, use the String data type. Here is an example:

Private Sub Form_Load()
    Dim CountryName As String
End Sub

After declaring the variable, you can initialize. If you want its area of memory to be empty, you can assign it two double-quotes. Here is an example:

Private Sub Form_Load()
    Dim CountryName As String
    
    CountryName = ""
End Sub

If you want to store something in the memory space allocated to the variable, assign it a word or group of words included between double-quotes. Here is an example:

Private Sub Form_Load()
    Dim CountryName As String
    
    CountryName = "Great Britain"
End Sub 

You can also initialize a string variable with another.

Boolean

A Boolean variable is one whose value can be only either True or False. To declare such a variable, use the Boolean keyword. Here is an example:

Private Sub Form_Load()
    Dim IsMarried As Boolean
End Sub

After declaring a Boolean variable, you can initialize by assigning it either True or False. Here is an example:

Private Sub Form_Load()
    Dim IsMarried As Boolean
    
    IsMarried = False
End Sub

Like any other variable, after initializing the variable, it keeps its value until you change its value again.

 

Numeric Data Types

 

Introduction

A natural number is one that contains only one digit or a combination of digits and no other character, except those added to make it easier to read. Examples of natural numbers are 122, 8, and 2864347. When a natural number is too long, such 3253754343, to make it easier to read, the thousands are separated by a special character. This character depends on the language or group of language and it is called the thousands separator. For US English, this character is the comma. The thousands separator symbol is mainly used only to make the number easier to read.

To support different scenarios, Microsoft provides different types of natural numbers

Byte

A byte is a small natural positive number that ranges from 0 to 255. A variable of byte type can be used to hold small values such as a person's age, the number of fingers on an animal, etc.

To declare  a variable for a small number, use the Byte keyword. Here is an example:

Private Sub Form_Load()
    Dim StudentAge As Byte
End Sub
 

Integer

An integer is a natural number larger than the Byte. It can hold a value between 
-32,768 and 32,767. Examples of such ranges are: the number of pages of a book.

To declare a variable of type integer, use the Integer keyword. Here is an example:

Private Sub Form_Load()
    Dim MusicTracks As Integer
End Sub

Long Integer

A long integer is a natural number whose value is between –2,147,483,648 and 2,147,483,642. Examples are the population of a city, the distance between places of different countries, the number of words of a book.

To declare a variable that can hold a very large natural number, use the Long keyword. Here is an example:

Private Sub Form_Load()
    Dim Population As Long
End Sub

Decimal Data Types

 

Introduction

A real number is one that displays a decimal part. This means that the number can be made of two sections separated by a symbol that is referred to as the Decimal Separator or Decimal Symbol. This symbol is different by language, country, group of languages, or group of countries. In US English, this symbol is the period as can be verified from the Regional (and Language) Settings of the Control Panel of computers of most regular users:

Regional Options

On both sides of the Decimal Symbol, digits are used to specify the value of the number. The number of digits on the right side of the symbol determines how much precision the number offers.

 

Single

A single is a decimal number whose value can range from –3.402823e38 and –1.401298e-45 if the number is negative, or 1.401298e-45 and 3.402823e38 if the number is positive.

To declare a variable that can hold small decimal numbers with no concern for precision, use the Single data type. Here is an example:

Private Sub Form_Load()
    Dim CountryName As String
    Dim IsMarried As Boolean
    Dim StudentAge As Byte
    Dim Tracks As Integer
    Dim Population As Long
    Dim Distance As Single
End Sub

Double

While the Single data type can allow large numbers, it offers less precision. For an even larger number, Microsoft Visual Basic provides the Double data type. This is used for a variable that would hold numbers that range from 1.79769313486231e308 to –4.94065645841247e–324 if the number is negative or from 1.79769313486231E308 to 4.94065645841247E–324 if the number is positive.

To declare a variable that can store large decimal numbers with a good level of precision, use the Double keyword.

In most circumstances, it is preferable to use Double instead of Single when declaring a variable that would hold a decimal number. Although the Double takes more memory spaces (computer memory is not expensive anymore(!)), it provides more precision.

Here is an example of declaring a Double variable:

Private Sub Form_Load()
    Dim Distance As Double
End Sub

Currency

The Currency data type is used for a variable that can hold monetary values. To declare such a variable, use the Currency keyword. Here is an example:

Private Sub Form_Load()
    Dim CountryName As String
    Dim IsMarried As Boolean
    Dim StudentAge As Byte
    Dim Tracks As Integer
    Dim Population As Long
    Dim Distance As Single
    Dim StartingSalary As Currency
End Sub

Other Data Types

 

Date

A date is a numeric value that represents the number of days that have elapsed since a determined period. A time is a numeric value that represents the number of seconds that have elapsed in a day.

To declare a variable that can hold either date values, time values, or both, use the Date keyword. After the variable has been declared, you will configure it to the appropriate value. Here are two examples:

Private Sub Form_Load()
    Dim CountryName As String
    Dim IsMarried As Boolean
    Dim StudentAge As Byte
    Dim Tracks As Integer
    Dim Population As Long
    Dim Distance As Single
    Dim StartingSalary As Currency
    Dim DateOfBirth As Date
    Dim KickOffTime As Date
End Sub

Object

An Object is almost anything else that you want to use in your program. If you don't specify a data type or can't figure out what data type you want to use, you can use the Variant keyword or let Visual Basic use the Variant data type.

Variant

A Variant can be used to declare any kind of variable. You can use a variant when you can't make up your mind regarding a variable but, as a beginning programmer, you should avoid it.

Here is a table of various data types and the amount of memory space each one uses:

 

Data type Description Range
Byte 1-byte binary data 0 to 255
Integer 2-byte integer – 32,768 to 32,767
Long 4-byte integer – 2,147,483,648 to 2,147,483,647
Single 4-byte floating-point number – 3.402823E38 to – 1.401298E – 45 (negative values)
1.401298E – 45 to 3.402823E38 (positive values)
Double 8-byte floating-point number – 1.79769313486231E308 to
– 4.94065645841247E – 324 (negative values)
4.94065645841247E – 324 to 1.79769313486231E308 (positive values)
Currency 8-byte number with fixed decimal point – 922,337,203,685,477.5808 to 922,337,203,685,477.5807
String String of characters Zero to approximately two billion characters
Variant Date/time, floating-point number, integer, string, or object.

16 bytes, plus 1 byte for each character if a string value.

Date values: January 1, 100 to December 31, 9999

Numeric values: same range as Double

String values: same range as String Can also contain Error or Null values

Boolean 2 bytes True or False
Date 8-byte date/time value January 1, 100 to December 31, 9999
Object 4 bytes Any Object reference

 

Using Variables

 

Details on Declaring Variables

We have learned how to declare a variable as follows:

Dim CountryName As String

We also saw that we can declare different variables each on its own line as follows;

Dim FirstName As String
Dim LastName As String
Dim Salary As Currency
Dim AlreadyVisited As Boolean

If you have many variables of the same data type, you can declare them on the same line, each separated with a comma. Remember to specify their common type. Here is an example:

Private Sub Form_Load()
Dim CountryName, Address, City, State As String
Dim IsMarried As Boolean
Dim StudentAge As Byte
Dim Tracks As Integer
Dim Population As Long
Dim Distance As Single
Dim StartingSalary, WeeklyEarnings As Currency
Dim DateOfBirth, KickOffTime As Date
End Sub

When naming your variables, besides the above suggestions, you can start a variable's name with one to three-letter prefix that could identify the data type used. Here are a few suggestions:

 
Data Type Prefix Example
Boolean bln blnFound
Byte byt bytTracks
Date/Time dtm dteStartOfShift
Double dbl dblDistance
Error err errCantOpen
Integer int intNbrOfStudents
Long lng lngPopulation
Object obj objConnection
Single sng sngAge
String str strCountryName
Currency cur curHourlySalary
Variant var varFullName
 

Constants

 

Introduction

A constant is a value that doesn't change. There are two types of constants you will use in your programs: those supplied to you and those you define yourself.

The Carriage Return-Line Feed Constant

Visual Basic provides the vbCrLf constant. It is used to interrupt a line of code and move to the next line.

Built-in Constants: PI

PI is a mathematical constant whose value is approximately equal to 3.1415926535897932. It is highly used in operations that involve circles or geometric variants of a circle: cylinder, sphere, cone, etc.

 

 

Previous Copyright © 2004-2014 FunctionX, Inc. Next