This page is an edited exerpt from:

Microsoft Visual Basic 5.0 Programmer's Guide

Chapter 5, Programming Fundamentals

Introduction to Variables, Constants, and Data Types

You often need to store values temporarily when performing calculations with Visual Basic. For example, you might want to calculate several values, compare them, and perform different operations on them, depending on the result of the comparison. You need to retain the values if you want to compare them, but you don't need to store them in a property.

Visual Basic, like most programming languages, uses variables for storing values. Variables have a name (the word you use to refer to the value the variable contains) and a data type (which determines the kind of data the variable can store). Arrays can be used to store indexed collections of related variables.

Constants also store values, but as the name implies, those values remain constant throughout the execution of an application. Using constants can make your code more readable by providing meaningful names instead of numbers. There are a number of built-in constants in Visual Basic, but you can also create your own.

Data types control the internal storage of data in Visual Basic. By default, Visual Basic uses the Variant data type. There are a number of other available data types that allow you to optimize your code for speed and size when you don't need the flexibility that Variant provides.


In Visual Basic, you use variables to temporarily store values during the execution of an application. Variables have a name (the word you use to refer to the value the variable contains) and a data type (which determines the kind of data the variable can store).

You can think of a variable as a placeholder in memory for an unknown value. For example, imagine you are creating a program for a fruit stand to track the sales of apples. You don't know the price of an apple or the quantity sold until the sale actually occurs. You can use two variables to hold the unknown values — let's name them ApplePrice and ApplesSold. Each time the program is run, the user supplies the values for the two variables. To calculate the total sales and display it in a Textbox named txtSales, your code would look like this:

txtSales.txt = ApplePrice * ApplesSold

The expression returns a different total each time, depending on what values the user provides. The variables allow you to make a calculation without having to know in advance what the actual inputs are.

In this example, the data type of ApplePrice is Currency; the data type of ApplesSold is an integer. Variables can represent many other values as well: text values, dates, various numeric types, even objects.

Storing and Retrieving Data in Variables

You use assignment statements to perform calculations and assign the result to a variable:

ApplesSold = 10 ' The value 10 is passed to the

' variable.

ApplesSold = ApplesSold + 1 ' The variable is

' incremented.

Note that the equal sign in this example is an assignment operator, not an equality operator; the value (10) is being assigned to the variable (ApplesSold).

Declaring Variables

To declare a variable is to tell the program about it in advance. You declare a variable with the Dim statement, supplying a name for the variable:

Dim variablename [As type]

Variables declared with the Dim statement within a procedure exist only as long as the procedure is executing. When the procedure finishes, the value of the variable disappears. In addition, the value of a variable in a procedure is local to that procedure — that is, you can't access a variable in one procedure from another procedure. These characteristics allow you to use the same variable names in different procedures without worrying about conflicts or accidental changes.

A variable name:

· Must begin with a letter.

· Can't contain an embedded period or embedded type-declaration character.

· Must not exceed 255 characters.

· Must be unique within the same scope, which is the range from which the variable can be referenced — a procedure, a form, and so on.

The optional As type clause in the Dim statement allows you to define the data type or object type of the variable you are declaring. Data types define the type of information the variable stores. Some examples of data types include String, Integer, and Currency. Variables can also contain objects from Visual Basic or other applications. Examples of Visual Basic object types, or classes, include Object, Form1, and TextBox.

For More Information For more information on objects, see "Programming with Objects" and "Programming with Components." Data types are discussed in detail in the section, "Data Types," later in this chapter.

There are other ways to declare variables:

· Declaring a variable in the Declarations section of a form, standard, or class module, rather than within a procedure, makes the variable available to all the procedures in the module.

· Declaring a variable using the Public keyword makes it available throughout your application.

· Declaring a local variable using the Static keyword preserves its value even when a procedure ends.

Implicit Declaration

You don't have to declare a variable before using it. For example, you could write a function where you don't need to declare TempVal before using it:

Function SafeSqr(num)

TempVal = Abs(num)

SafeSqr = Sqr(TempVal)

End Function

Visual Basic automatically creates a variable with that name, which you can use as if you had explicitly declared it. While this is convenient, it can lead to subtle errors in your code if you misspell a variable name. For example, suppose that this was the function you wrote:

Function SafeSqr(num)

TempVal = Abs(num)

SafeSqr = Sqr(TemVal)

End Function

At first glance, this looks the same. But because the TempVal variable was misspelled on the next-to-last line, this function will always return zero. When Visual Basic encounters a new name, it can't determine whether you actually meant to implicitly declare a new variable or you just misspelled an existing variable name, so it creates a new variable with that name.

Explicit Declaration

To avoid the problem of misnaming variables, you can stipulate that Visual Basic always warn you whenever it encounters a name not declared explicitly as a variable.

To explicitly declare variables

· Place this statement in the Declarations section of a class, form, or standard module:

Option Explicit


From the Tools menu, choose Options, click the Editor tab and check the Require Variable Declaration option. This automatically inserts the Option Explicit statement in any new modules, but not in modules already created; therefore, you must manually add Option Explicit to any existing modules within a project.

Had this statement been in effect for the form or standard module containing the SafeSqr function, Visual Basic would have recognized TempVal and TemVal as undeclared variables and generated errors for both of them. You could then explicitly declare TempVal:

Function SafeSqr(num)

Dim TempVal

TempVal = Abs(num)

SafeSqr = Sqr(TemVal)

End Function

Now you'd understand the problem immediately because Visual Basic would display an error message for the incorrectly spelled TemVal. Because the Option Explicit statement helps you catch these kinds of errors, it's a good idea to use it with all your code.

Note The Option Explicit statement operates on a per-module basis; it must be placed in the Declarations section of every form, standard, and class module for which you want Visual Basic to enforce explicit variable declarations. If you select Require Variable Declaration, Visual Basic inserts Option Explicit in all subsequent form, standard, and class modules, but does not add it to existing code. You must manually add Option Explicit to any existing modules within a project.


Often you'll find that your code contains constant values that reappear over and over. Or you may find that the code depends on certain numbers that are difficult to remember — numbers that, in and of themselves, have no obvious meaning.

In these cases, you can greatly improve the readability of your code — and make it easier to maintain — by using constants. A constant is a meaningful name that takes the place of a number or string that does not change. Although a constant somewhat resembles a variable, you can't modify a constant or assign a new value to it as you can to a variable. There are two sources for constants:

· Intrinsic or system-defined constants are provided by applications and controls. Visual Basic constants are listed in the Visual Basic (VB), Visual Basic for applications (VBA), and data access (DAO) object libraries in the Object Browser. Other applications that provide object libraries, such as Microsoft Excel and Microsoft Project, also provide a list of constants you can use with their objects, methods, and properties. Constants are also defined in the object library for each ActiveX control. For details on using the Object Browser, see "Programming with Objects."

· Symbolic or user-defined constants are declared using the Const statement. User-defined constants are described in the next section, "Creating Your Own Constants."

In Visual Basic, constant names are in a mixed-case format, with a prefix indicating the object library that defines the constant. Constants from the Visual Basic and Visual Basic for applications object libraries are prefaced with "vb" — for instance, vbTileHorizontal. Constants from the data access object library are prefaced with "db" — for instance, dbRelationUnique.

The prefixes are intended to prevent accidental collisions in cases where constants have identical names and represent different values. Even with prefixes, it's still possible that two object libraries may contain identical constants representing different values. Which constant is referenced in this case depends on which object library has the higher priority. For information on changing the priority of object libraries, see the "References Dialog Box" in Books Online.

To be absolutely sure you avoid constant name collisions, you can qualify references to constants with the following syntax:


Libname is usually the class name of the control or library. Modulename is the name of the module that defines the constant. Constname is the name of the constant. Each of these elements is defined in the object library, and can be viewed in the Object Browser.

Creating Your Own Constants

The syntax for declaring a constant is:

[Public|Private] Const constantname[As type] = expression

The argument constantname is a valid symbolic name (the rules are the same as those for creating variable names), and expression is composed of numeric or string constants and operators; however, you can't use function calls in expression.

A Const statement can represent a mathematical or date/time quantity:

Const conPi = 3.14159265358979

Public Const conMaxPlanets As Integer = 9

Const conReleaseDate = #1/1/95#

The Const statement can also be used to define string constants:

Public Const conVersion = "07.10.A"

Const conCodeName = "Enigma"

You can place more than one constant declaration on a single line if you separate them with commas:

Public Const conPi = 3.14, conMaxPlanets = 9, _

conWorldPop = 6E+09

The expression on the right side of the equal sign ( = ) is often a number or literal string, but it can also be an expression that results in a number or string (although that expression can't contain calls to functions). You can even define constants in terms of previously defined constants:

Const conPi2 = conPi * 2

Once you define constants, you can place them in your code to make it more readable. For example:

Static SolarSystem(1 To conMaxPlanets)

If numPeople > conWorldPop Then Exit Sub

Data Types

Variables are placeholders used to store values; they have names and data types. The data type of a variable determines how the bits representing those values are stored in the computer's memory. When you declare a variable, you can also supply a data type for it. All variables have a data type that determines what kind of data they can store.

By default, if you don't supply a data type, the variable is given the Variant data type. The Variant data type is like a chameleon — it can represent many different data types in different situations. You don't have to convert between these types of data when assigning them to a Variant variable: Visual Basic automatically performs any necessary conversion.

If you know that a variable will always store data of a particular type, however, Visual Basic can handle that data more efficiently if you declare a variable of that type. For example, a variable to store a person's name is best represented as a string data type, because a name is always composed of characters.

Data types apply to other things besides variables. When you assign a value to a property, that value has a data type; arguments to functions also have data types. In fact, just about anything in Visual Basic that involves data also involves data types.

You can also declare arrays of any of the fundamental types.

For More Information For more information, see the section, "Arrays," later in this chapter. Selecting data types to improve your application's performance is discussed in "Designing for Performance and Compatibility."

Declaring Variables with Data Types

Before using a non-Variant variable, you must use the Private, Public, Dim or Static statement to declare it As type. For example, the following statements declare an Integer, Double, String, and Currency type, respectively:

Private I As Integer

Dim Amt As Double

Static YourName As String

Public BillsPaid As Currency

A Declaration statement can combine multiple declarations, as in these statements:

Private I As Integer, Amt As Double

Private YourName As String, BillsPaid As Currency

Private Test, Amount, J As Integer

Note If you do not supply a data type, the variable is given the default type. In the preceding example, the variables Test and Amount are of the Variant data type. This may surprise you if your experience with other programming languages leads you to expect all variables in the same declaration statement to have the same specified type (in this case, Integer).

Numeric Data Types

Visual Basic supplies several numeric data types — Integer, Long (long integer), Single (single-precision floating point), Double (double-precision floating point), and Currency. Using a numeric data type generally uses less storage space than a variant.

If you know that a variable will always store whole numbers (such as 12) rather than numbers with a fractional amount (such as 3.57), declare it as an Integer or Long type. Operations are faster with integers, and these types consume less memory than other data types. They are especially useful as the counter variables in For...Next loops.

For More Information To read more about control structures, see "Introduction to Control Structures" later in this chapter.

If the variable contains a fraction, declare it as a Single, Double, or Currency variable. The Currency data type supports up to four digits to the right of the decimal separator and fifteen digits to the left; it is an accurate fixed-point data type suitable for monetary calculations. Floating-point (Single and Double) numbers have much larger ranges than Currency, but can be subject to small rounding errors.

Note Floating-point values can be expressed as mmmEeee or mmmDeee, in which mmm is the mantissa and eee is the exponent (a power of 10). The highest positive value of a Single data type is 3.402823E+38, or 3.4 times 10 to the 38th power; the highest positive value of a Double data type is 1.79769313486232D+308, or about 1.8 times 10 to the 308th power. Using D to separate the mantissa and exponent in a numeric literal causes the value to be treated as a Double data type. Likewise, using E in the same fashion treats the value as a Single data type.

The String Data Type

If you have a variable that will always contain a string and never a numeric value, you can declare it to be of type String:

Private S As String

You can then assign strings to this variable and manipulate it using string functions:

S = "Database"

S = Left(S, 4)

By default, a string variable or argument is a variable-length string; the string grows or shrinks as you assign new data to it. You can also declare strings that have a fixed length. You specify a fixed-length string with this syntax:

String * size

For example, to declare a string that is always 50 characters long, use code like this:

Dim EmpName As String * 50

If you assign a string of fewer than 50 characters, EmpName is padded with enough trailing spaces to total 50 characters. If you assign a string that is too long for the fixed-length string, Visual Basic simply truncates the characters.

Because fixed-length strings are padded with trailing spaces, you may find the Trim and RTrim functions, which remove the spaces, useful when working with them.

Fixed-length strings in standard modules can be declared as Public or Private. In forms and class modules, fixed-length strings must be declared Private.

For More Information See "Ltrim, RTrim Function and Trim Functions" in the Language Reference in Books Online.

Exchanging Strings and Numbers

You can assign a string to a numeric variable if the string represents a numeric value. It's also possible to assign a numeric value to a string variable. For example, place a command button, text box, and list box on a form. Enter the following code in the command button's Click event. Run the application, and click the command button.

Private Sub Command1_Click()

Dim intX As Integer

Dim strY As String

strY = "100.23"

intX = strY ' Passes the string to a numeric

' variable.

List1.AddItem Cos(strY) ' Adds cosine of number in

' the string to the listbox.

strY = Cos(strY) ' Passes cosine to the

' string variable.

Text1.Text = strY ' String variable prints in

' the text box.

End Sub

Visual Basic will automatically coerce the variables to the appropriate data type. You should use caution when exchanging strings and numbers; passing a non-numeric value in the string will cause a run-time error to occur.

The Boolean Data Type

If you have a variable that will contain simple true/false, yes/no, or on/off information, you can declare it to be of type Boolean. The default value of Boolean is False. In the following example, blnRunning is a Boolean variable which stores a simple yes/no setting.

Dim blnRunning As Boolean

' Check to see if the tape is running.

If Recorder.Direction = 1 Then

blnRunning = True

End if

The Date Data Type

Date and time values can be contained both in the specific Date data type and in Variant variables. The same general characteristics apply to dates in both types.

For More Information See the section, "Date/Time Values Stored in Variants," in "Advanced Variant Topics" (in Books Online only).

When other numeric data types are converted to Date, values to the left of the decimal represent date information, while values to the right of the decimal represent time. Midnight is 0, and midday is 0.5. Negative whole numbers represent dates before December 30, 1899.

The Variant Data Type

A Variant variable is capable of storing all system-defined types of data. You don't have to convert between these types of data if you assign them to a Variant variable; Visual Basic automatically performs any necessary conversion. For example:

Dim SomeValue ' Variant by default.

SomeValue = "17" ' SomeValue contains "17" (a two-

' character string).

SomeValue = SomeValue - 15 ' SomeValue now contains

' the numeric value 2.

SomeValue = "U" & SomeValue ' SomeValue now contains

' "U2" (a two- character string).

While you can perform operations on Variant variables without much concern for the kind of data they contain, there are some traps you must avoid.

· If you perform arithmetic operations or functions on a Variant, the Variant must contain something that is a number. For details, see the section, "Numeric Values Stored in Variants," in "Advanced Variant Topics" (in Books Online only).

· If you are concatenating strings, use the & operator instead of the + operator. For details, see the section, "Strings Stored in Variants," in "Advanced Variant Topics" (in Books Online only).

In addition to being able to act like the other standard data types, Variants can also contain three special values: Empty, Null, and Error.

The Null Value

The Variant data type can contain another special value: Null. Null is commonly used in database applications to indicate unknown or missing data. Because of the way it is used in databases, Null has some unique characteristics:

· Expressions involving Null always result in Null. Thus, Null is said to "propagate" through expressions; if any part of the expression evaluates to Null, the entire expression evaluates to Null.

· Passing Null, a Variant containing Null, or an expression that evaluates to Null as an argument to most functions causes the function to return Null.

· Null values propagate through intrinsic functions that return Variant data types.

You can also assign Null with the Null keyword:

Z = Null

You can use the IsNull function to test if a Variant variable contains Null:

If IsNull(X) And IsNull(Y) Then

Z = Null


Z = 0

End If

If you assign Null to a variable of any type other than Variant, a trappable error occurs. Assigning Null to a Variant variable doesn't cause an error, and Null will propagate through expressions involving Variant variables (though Null does not propagate through certain functions). You can return Null from any Function procedure with a Variant return value.

Variables are not set to Null unless you explicitly assign Null to them, so if you don't use Null in your application, you don't have to write code that tests for and handles it.

For More Information For information on how to use Null in expressions, see "Null" in the Language Reference in Books Online.

Introduction to Control Structures

Control structures allow you to control the flow of your program's execution. If left unchecked by control-flow statements, a program's logic will flow through statements from left to right, and top to bottom. While some very simple programs can be written with only this unidirectional flow, and while some flow can be controlled by using operators to regulate precedence of operations, most of the power and utility of any programming language comes from its ability to change statement order with structures and loops.

Decision Structures

Visual Basic procedures can test conditions and then, depending on the results of that test, perform different operations. The decision structures that Visual Basic supports include:

· If...Then

· If...Then...Else

· Select Case


Use an If...Then structure to execute one or more statements conditionally. You can use either a single-line syntax or a multiple-line block syntax:

If condition Then statement

If condition Then

End If

The condition is usually a comparison, but it can be any expression that evaluates to a numeric value. Visual Basic interprets this value as True or False; a zero numeric value is False, and any nonzero numeric value is considered True. If condition is True, Visual Basic executes all the statements following the Then keyword. You can use either single-line or multiple-line syntax to execute just one statement conditionally (these two examples are equivalent):

If anyDate < Now Then anyDate = Now

If anyDate < Now Then

anyDate = Now

End If

Notice that the single-line form of If...Then does not use an End If statement. If you want to execute more than one line of code when condition is True, you must use the multiple-line block If...Then...End If syntax.

If anyDate < Now Then

anyDate = Now

Timer1.Enabled = False ' Disable timer control.

End If


Use an If...Then...Else block to define several blocks of statements, one of which will execute:

If condition1 Then
[ElseIf condition2 Then
[statementblock-2]] ...

End If

Visual Basic first tests condition1. If it's False, Visual Basic proceeds to test condition2, and so on, until it finds a True condition. When it finds a True condition, Visual Basic executes the corresponding statement block and then executes the code following the End If. As an option, you can include an Else statement block, which Visual Basic executes if none of the conditions are True.

If...Then…ElseIf is really just a special case of If...Then...Else. Notice that you can have any number of ElseIf clauses, or none at all. You can include an Else clause regardless of whether you have ElseIf clauses.

For example, your application could perform different actions depending on which control in a menu control array was clicked:

Private Sub mnuCut_Click (Index As Integer)

If Index = 0 Then ' Cut command.

CopyActiveControl ' Call general procedures.


ElseIf Index = 1 Then ' Copy command.


ElseIf Index = 2 Then ' Clear command.


Else ' Paste command.


End If

End Sub

Notice that you can always add more ElseIf parts to your If...Then structure. However, this syntax can get tedious to write when each ElseIf compares the same expression to a different value. For this situation, you can use a Select Case decision structure.

For More Information See "If...Then...Else Statement" in the Language Reference in Books Online.

Select Case

Visual Basic provides the Select Case structure as an alternative to If...Then...Else for selectively executing one block of statements from among multiple blocks of statements. A Select Case statement provides capability similar to the If...Then...Else statement, but it makes code more readable when there are several choices.

A Select Case structure works with a single test expression that is evaluated once, at the top of the structure. Visual Basic then compares the result of this expression with the values for each Case in the structure. If there is a match, it executes the block of statements associated with that Case:

Select Case testexpression
[Case expressionlist1
[Case expressionlist2
[Case Else

End Select

Each expressionlist is a list of one or more values. If there is more than one value in a single list, the values are separated by commas. Each statementblock contains zero or more statements. If more than one Case matches the test expression, only the statement block associated with the first matching Case will execute. Visual Basic executes statements in the Case Else clause (which is optional) if none of the values in the expression lists matches the test expression.

For example, suppose you added another command to the Edit menu in the If...Then...Else example. You could add another ElseIf clause, or you could write the function with Select Case:

Private Sub mnuCut_Click (Index As Integer)

Select Case Index

Case 0 ' Cut command.

CopyActiveControl ' Call general procedures.


Case 1 ' Copy command.


Case 2 ' Clear command.


Case 3 ' Paste command.


Case Else

frmFind.Show ' Show Find dialog box.

End Select

End Sub

Notice that the Select Case structure evaluates an expression once at the top of the structure. In contrast, the If...Then...Else structure can evaluate a different expression for each ElseIf statement. You can replace an If...Then...Else structure with a Select Case structure only if the If statement and each ElseIf statement evaluates the same expression.

Loop Structures

Loop structures allow you to execute one or more lines of code repetitively. The loop structures that Visual Basic supports include:

· Do...Loop

· For...Next

· For Each...Next


Use a Do loop to execute a block of statements an indefinite number of times. There are several variations of the Do...Loop statement, but each evaluates a numeric condition to determine whether to continue execution. As with If...Then, the condition must be a value or expression that evaluates to False (zero) or to True (nonzero).

In the following Do...Loop, the statements execute as long as the condition is True:

Do While condition


When Visual Basic executes this Do loop, it first tests condition. If condition is False (zero), it skips past all the statements. If it's True (nonzero), Visual Basic executes the statements and then goes back to the Do While statement and tests the condition again.

Consequently, the loop can execute any number of times, as long as condition is nonzero or True. The statements never execute if condition is initially False. For example, this procedure counts the occurrences of a target string within another string by looping as long as the target string is found:

Function CountStrings (longstring, target)

Dim position, count

position = 1

Do While InStr(position, longstring, target)

position = InStr(position, longstring, target)_

+ 1

count = count + 1


CountStrings = count

End Function

If the target string doesn't occur in the other string, then InStr returns 0, and the loop doesn't execute.

Another variation of the Do...Loop statement executes the statements first and then tests condition after each execution. This variation guarantees at least one execution of statements:


Loop While condition

Two other variations are analogous to the previous two, except that they loop as long as condition is False rather than True.

Loop zero or more times Loop at least once

Do Until condition
Loop Do
Loop Until condition



Do loops work well when you don't know how many times you need to execute the statements in the loop. When you know you must execute the statements a specific number of times, however, a For…Next loop is a better choice. Unlike a Do loop, a For loop uses a variable called a counter that increases or decreases in value during each repetition of the loop. The syntax is:

For counter = start To end [Step increment]

Next [counter]

The arguments counter, start, end, and increment are all numeric.

Note The increment argument can be either positive or negative. If increment is positive, start must be less than or equal to end or the statements in the loop will not execute. If increment is negative, start must be greater than or equal to end for the body of the loop to execute. If Step isn't set, then increment defaults to 1.

In executing the For loop, Visual Basic:

1. Sets counter equal to start.

2. Tests to see if counter is greater than end. If so, Visual Basic exits the loop.

(If increment is negative, Visual Basic tests to see if counter is less than end.)

3. Executes the statements.

4. Increments counter by 1 or by increment, if it's specified.

5. Repeats steps 2 through 4.

This code prints the names of all the available Screen fonts:

Private Sub Form_Click ()

Dim I As Integer

For i = 0 To Screen.FontCount

Print Screen.Fonts(i)


End Sub

In the VCR sample application, the HighlightButton procedure uses a For...Next loop to step through the controls collection of the VCR form and show the appropriate Shape control:

Sub HighlightButton(MyControl As Variant)

Dim i As Integer

For i = 0 To frmVCR.Controls.Count - 1

If TypeOf frmVCR.Controls(i) Is Shape Then

If frmVCR.Controls(i).Name = MyControl Then

frmVCR.Controls(i).Visible = True


frmVCR.Controls(i).Visible = False

End If

End If


End Sub