Using Visual Basic 6

Previous chapterNext chapterContents


- 7 -
Using Data Types, Constants, and Variables


Storing Information in Variables

Figure 7.1 shows a simple addition program, AddNum.EXE, from the project Addnum.prj from the file vb6cp07.zip on the Web site dedicated to this book. The program enables users to enter two numbers. When they click the + button, the program processes the total, which is then displayed in a third text box.

FIGURE 7.1 AddNum is a simple addition program that shows you how to use variables.

While the data is being processed in your program, it's stored temporarily in variables. Think of a variable as a cup that can hold various amounts of jelly beans; you never know how many jelly beans are in the cup at any given time unless you look in the cup. The same is true for a variable. A variable can hold a different value at different times. You programmatically look into it to find out its value.

You use variables when you know that you'll have to deal with a quantity at some point but don't know its present value--such as the balance of your checking account. You know the account's balance today, but you have no idea what the balance will be in a week.

Declaring Variables

You create (that is, declare) a variable by using the following form:

Dim VarName As DataType


Understanding keywords

A keyword, also known as a reserved word, is a word reserved for Visual Basic's exclusive use; you can't use keywords for your own programming needs. Words such as Dim, As, New, ReDim, If, Then, Else, Loop, While, and End are all Visual Basic keywords. By default, Visual Basic uses the font color blue to show all keywords that you type in a Code window.
Visual Basic has many keywords. You know a word is a keyword if the word changes color after you type it in the code window. Also, you can look in the online documentation that comes with Visual Basic to obtain a detailed list and explanation of them all.


In this syntax,

Thus, the following example creates a variable, i, that's of data type Integer:

Dim i as Integer

Listing 7.1 shows the event procedure for the Click() event of the cmdAdd button. Three variables--x, y, and z (on lines 3, 6, and 9)--are declared. These variables are of type Integer. (Data types are discussed later in the chapter. For now, realize that you are making variables that will accommodate numbers. Also, if you type a letter such as a in a text box, the code won't work because it's expecting a number. Preventing this sort of error is addressed at the end of this chapter.) For more information about avoiding and finding errors in your code see Chapter 21, "Debugging Your Applications."

LISTING 7.1 07LIST01.TXT--The cmdAdd Event Procedure

01 Private Sub cmdAdd_Click()
02 `Declare a variable for the first number
03 Dim x As Integer
04
05 `Declare a variable for the second number
06 Dim y As Integer
07
08 `Declare a variable to hold the sum of both numbers
09 Dim z As Integer
10
11 `Convert the text inputted into the text box
12 `into an integer and assign it to the first variable
13 x = CInt(txtNumOne.Text)
14
15 `Convert the text inputted into the text box
16 `into an integer and assign it to the second variable
17 y = CInt(txtNumTwo.Text)
18
19 `Add the first two variables together and assign
20 `the result to the third variable
21 z = x + y
22
23 `Convert the third variable (which is an integer)
24 `to text and assign it to the text property of the
25 `TextBox for the result.
26 txtTotal.Text = CStr(z)
27 End Sub


Commenting code

Notice that some lines of code begin with an apostrophe (`), which tells Visual Basic that everything on that line or following the apostrophe isn't code and should be ignored by the compiler. Such a line of text offers some remarks or information about what your programming intention is. This is called commenting your code. Well-written code is heavily commented. Commenting your code helps you remember your thinking when you come back to your code at a later time. It also helps those who must maintain your code after you've written it.


Naming Variables

When you declare a variable, you must give it a name. Returning to the cup analogy, if you have two cups on a table that hold different amounts of jelly beans, you must be able to distinguish between the cups to work with them. Naming makes each variable distinct and easy to identify.

In naming a variable, you have tremendous flexibility. Variable names can be simple, or they can be descriptive of the information they contain. For example, you could name a counter variable i%, or you might want to use a more descriptive name, such as NumberOfRedJellyBeansForBob or NumberOfJellyBeansForDorothy. Although you're allowed great latitude in naming, you need to know about the following restrictions:

Some examples of incorrect variable naming are as follows:

On the other hand, the following examples work perfectly well:

MyNum&
i%
iNumOne
strInputValue
Number2#

To make your code easy to read, your variable names should describe their task but, to make your code easy to type, they should also be short. Many programmers use prefixes on their variables to indicate the type of data stored and the scope of the variable. For example, a prefix of g_int indicates a global or program-level variable that stores an integer. Table 7.1 describes suggested prefixes you can use with your variables.

TABLE 7.1 Variable and Control Prefixes

Prefix Variable/Control Example
b Boolean bLightsOn
c Currency cAmountDue
d Double dDollarPerGallon
db Database dbAccountsPayable
ds Dynaset dsOverDue
dt Date+time dtDateDue
Prefix Variable/Control Example
td TableDef tdEmployees
h Handle hWnd
i Integer iCounter
l Long lNum
str String strMessage
s Single sPay
a Array a_iMyArray
g Global g_iTotal
m Local to module or form m_iAmount
ani Animation button aniMain
cbo Combo box and drop-down list box cboMyList
chk Check box chkDoctorIn
clp Picture clip clpEmblems
cmd Command button cmdFirstName
com Communications comLineOne
ctr Control (used within procs when the specific type is unknown) ctrNext
dat Data datEmployees
db ODBC database dbTaxpayers
dir Directory list box dirProjects
dlg Common dialog dlgSettings
drv Drive list box drvMain
fil File list box filPictures
frm Form frmMain
fra Frame fraTeams
gau Gauge gauGas
Prefix Variable/Control Example
gpb Group button gpbApps
grd Grid grdMain
hsb Horizontal scroll bar hsbText
img Image imgMain
key Keyboard key status keyASCII
lbl Label lblLastName
lin Line linRed
lst List box lstStooges
mdi MDI child form mdiMain
mnu Menu mnuEdit
opt Option button optGender
ole OLE client oleMain
pnl 3D panel pnlFriends
shp Shape shpCircle
spn Spin control spnTemp
txt Text/edit box txtAddress
tmr Timer tmrBreak
vsb Vertical scrollbar vsbComments

Choosing the Correct Variable Type

You can store almost anything in a variable. A variable can hold a number, a string of text, or an instance of an object, including forms, controls, and database objects. This chapter looks specifically at variables that store numbers, strings, and logical values.

You can use a variable to hold any type of information, but different types of variables are designed to work efficiently with different types of information.

Returning to the earlier cup example, you might want to have a type of cup that can hold only jelly beans, only cherries, or only nails. What the cup is supposed to hold greatly influences how the cup is constructed. A cup that holds cherries might have little holes in the bottom for water to pass through. A cup to hold nails might be made of tough material so that the nails don't puncture or scratch it. The same is true of variables--the type of variable must match the data it's going to hold. When you declare a variable to be of a certain type, you're giving instructions to Visual Basic about how to build the variable to accommodate the type of data that the variable will have to hold.

Table 7.2 presents the types of variables available in Visual Basic. The table also shows the range of values that each variable can hold and the amount of memory required to store the information in the variable (sort of like the cup size). Understanding memory requirements is important if you want to optimize your code. To conserve system resources, you should use variables with smaller memory requirements whenever possible, but don't worry about optimizing code until you're comfortable with the concept of creating and using variables.


Sizing variables

At some point you may wonder whether you're using a variable of the right size, particularly with regard to numbers. A good rule of thumb is to go with the larger variable size if you don't have a very good idea of what the limit of your variable will be. For example, if you think that your program at some point might be required to use numbers with decimals or fractions, you might want to use Double and Single variable types instead of Integers and Longs.


TABLE 7.2 Variables Store Many Types of Information

Type Stores Memory Requirement Range of Values
Integer Whole numbers 2 bytes -32,768 to 32,767
Long Whole numbers 4 bytes Approximately +/- 2.1E9
Single Decimal numbers 4 bytes -3.402823E38 to -1.401298E-45 for negative values and 1.401298E-45 to 3.402823E38 for positive values
Double Decimal numbers (double-precision floating-point) 8 bytes -1.79769313486232E308 to -4.94065645841247E-324 for negative values and 4.94065645841247E-324 to 1.79769313486232E308 for positive values
Currency Numbers with up to 15 digits left of the decimal and 4 digits right of the decimal 8 bytes 922,337,203,685,477.5808 to 922,337,203,685,477.5807
String Text information 1 byte per character Up to 65,000 characters for fixed-length strings and up to 2 billion characters for dynamic strings
Byte Whole numbers 1 byte 0 to 255
Boolean Logical values 2 bytes True or False
Date Date and time information 8 bytes Jan 1st 100 to December 31st 9999
Object Pictures and any object reference 4 bytes N/A
Variant Any of the preceding data types 16 bytes + 1 byte per character N/A

You know how to name a variable and what a variable can store, but how do you tell the program what you want to store? In reality, you don't have to tell Visual Basic what a variable will contain. Unlike other languages, Visual Basic doesn't require you to specifically declare a variable before it's used. If a variable isn't declared, Visual Basic uses a default data type known as a variant, which can contain any type of information. Read more on variants in the following section.

It's a good idea to declare your variables before they're used. Declaring variables saves you time in the long run and makes your code much more reliable.

Making Explicit Declarations

Explicit declaration means that you must use a statement to define a variable. Each of the following statements can be used to explicitly declare a variable's type:

Dim VarName [As VarType][, VarName2 [As VarType2]]
Private VarName[As VarType][, VarName2[As VarType2]]
Static VarName[As VarType][, VarName2[As VarType2]]
Public VarName[As VarType][, VarName2[As VarType2]]

Dim, Private, Static, and Public are Visual Basic keywords that define how and where the variable can be used. VarName and VarName2 represent the names of the variables that you want to declare. As indicated in the syntax, you can specify multiple variables in the same statement as long as you separate the variables by commas. (The syntax shows only two variables, but you can specify any number.)

VarType and VarType2 represent the type name of the respective variables. The type name is a keyword that tells Visual Basic what kind of information will be stored in the variable. The type can be one of those specified in Table 7.2 or a user-defined type.


What's a variant?

A variant is a data type that knows how to be any data type. If you declare a variable to be of type variant, it can be an Integer, Double, String...whatever. Variables have a definite use in advanced programming. If you are a beginning programmer, however, you shouldn't use variants to avoid the labor of learning to use the proper data type for the proper situation.


As mentioned earlier, declaring a variable type is optional. If you include the variable type, you must include the keyword As. If you don't include a variable type, the Variant type (the default) is used. Using a variant for general information has two major drawbacks, however: it can waste memory resources, and the variable type can produce unpredictable default value behaviors, particularly with arrays.

The following code lines show the use of these declaration statements for explicitly declared variables:

Private iNumVal As Integer
Private iAvgVal As Integer, dInputval As Double
Static sCalcAverage As Single
Dim strInputMsg As String

In Visual Basic, you don't have to use the keywords Dim, Private, Static, or Public. In Visual Basic, you can use a variable name such as MyVal. If you were to put this code in your project, you would make a variable named MyVal as type Variant. MyVal would have a default value of empty. Whenever you use implicit declaration, Visual Basic considers that variable as type Variant. Using implicit declaration isn't recommended, however. Making a variable without a formal declaration is asking for trouble. If you use implicit declaration, then any time you make a spelling mistake or syntax error, Visual Basic will think that you're implicitly declaring another variable, which can lead to headaches beyond imagination. By using implicit declaration, the code below would return a zero from a "mistake" variable:

`Declare a variable to hold the value fo the winner
Dim iTheWinnner as Integer
`Assign a value to the winner variable
iTheWinner = 100
`This code will show you a message that says
`The winner has won: 0
`because you typed, iTheWhiner by mistake
MsgBox "The winner has won: " & CStr(iTheWhiner)

You can protect yourself. You can make the Visual Basic IDE force you to explicitly declare a variable. All you need to do is enter the keywords Option Explicit in the first line of the General section of your form or module. You can also configure the IDE to automatically do this for you whenever you add a form or module.

Configure the IDE to automatically require variable declaration

1. From the Tools menu, choose Options.

2. On the Editor page of the Options dialog, select the Require Variable Declaration check box (see Figure 7.2).

3. Click OK.

FIGURE 7.2 Itís always preferable to configure the VB IDE to require you to declare your variables.


After you set Option Explicit, if you fail to declare a variable, you'll receive the message Variable not defined when you try to compile your code. Visual Basic's integrated debugger highlights the offending variable and halts the compilation of your program. The benefit of this is that it helps you avoid code errors possibly caused by typographical mistakes. For example, you might declare a variable with the following statement:

Dim strMyName As String

If, in a later statement, you mistype the variable name, Visual Basic will catch the error for you. For example, the following statement would cause an error:

strMyNme = "Clark Kent"

Using Type Suffixes with Variables

In previous code examples, you saw that you use the As keyword to assign a data type to a variable. You can use another method to declare a variable and assign a data type to it--data-type suffixes. With this type of declaration, a special character is used at the end of the variable name when the variable is first assigned a value. Doing this automatically "types" (assigns a type to) the variables. There's no need to use the As keyword. The characters for each variable type are shown in Table 7.3.

TABLE 7.3 Variable Suffixes

Variable Type Suffix
Integer %
Long &
Single !
Double #
Currency @
String $
Byte None
Boolean None
Variable Type Suffix
Date None
Object None
Variant None

The code back in the section "Using Explicit Declarations" could be rewritten with type suffixes as follows:

Private NumVal%
Private AvgVal%, Inputval#
Static CalcAverage!
Dim InputMsg$


A controversy around suffixes

A controversy within the Visual Basic developer community surrounds the use of suffixes and prefixes. Some developers support the use of suffixes; others prefer the use of prefixes only. Whether to use suffixes, prefixes, or both is a decision usually made by the programming group to which you belong. Most programming groups have a document that defines the coding standard that you use during the course of a project. If you program with others, this is the standard that you should follow. The most important thing to remember is that your code must be easy to read, easy to maintain, and predictable to others with whom you work.


Using suffixes to assign a type to your variables is a quick, handy way to declare a variable. Also, using a suffix adds a new element of readability to your variable name. For example, now when you run across the variable NumVal% in your code, you know that the variable is of type Integer (from reading the suffix) and that its function is to be a value for a number (from reading the variable name).

Using Strings

A string is a collection of characters. The following are examples of different string values:

"Cheese"
"You have made an error!"
"a"
"July 4, 1776"
"75"

Notice that each collection of characters is enclosed by quotation marks (""). The quotation marks are very important; they tell Visual Basic that the enclosed characters are a string value. Characters not enclosed in quotation marks are considered to be a variable or a part of the language.

You might find the string value "75" a bit baffling. You might think that it's a value for an integer, but it's not. The following example illustrates the string-ness of "75":

strNum$ = "7" & "5"

Another use of strings that use numeric characters are ZIP codes and phone numbers. Notice that declaring the following ZIP code and phone number as strings allows you to use the - character:

strMyZipCode = "50311-0921"
strPhone = "1-515-555-1212"

Also, because they aren't number data types, you wouldn't and can't perform mathematical operations on them, such as addition and multiplication.

Some beginning programmers have trouble with this concept; it takes a bit of getting used to. If you look at the code in Listing 7.1, you'll see that the user's input into the text boxes is treated as numeric string characters that must be converted to integers (lines 13 and 17). Chapter 12, "Working with Strings and Typecasting," provides a more detailed look at this.

Using Variable-Length and Fixed-Length Strings

Most strings that you will use in your programs are of the type known as variable-length strings, which can contain any amount of text up to 64,000 characters. As information is stored in the variable, the size of the variable adjusts to accommodate the length of the string. There is, however, a second type of string in Visual Basic--the fixed-length string.

As the name implies, a fixed-length string remains the same size, regardless of the information assigned to it. If a fixed-length string variable is assigned an expression shorter than the defined length of the variable, the remaining length of the variable is filled with the space character. If the expression is longer than the variable, only the characters that fit in the variable are stored; the rest are discarded.

A fixed-length string variable can be declared only by using an explicit declaration of the form, such as the following:

Dim VarName As String * strlength

Therefore, to make a string, strMyString, that's always 128 characters long, you would declare it as follows:

Dim strMyString As String * 128

Notice that this declaration varies slightly from the previous declaration of a string variable. The declaration of a fixed-length string variable contains an asterisk (*) to tell Visual Basic that the string will be a fixed length. The final parameter, strlength, tells the program the number of characters that the variable can contain.

In the beginning, you probably won't have much need for fixed-length strings. As you advance, you will use them, particularly when it's time to program directly to Windows with the Windows API (Application Programming Interface).

Determining Where a Variable Can Be Used


Scope relates to declaration location

The scope of a variable is determined by not only the type of declaration used but also the declaration's location. For instance, the Dim keyword assumes different meanings in different parts of a form's code. You can use only the Private keyword on variables in the Declaration section.


In addition to telling Visual Basic what you want to be able to store in a variable, a declaration statement tells Visual Basic where the variable can be used. This area of use is called the scope of the variable. This is analogous to your phone number. You might have a phone number 555-2576, which can be reached by anyone inside your area code. However, if anyone outside your area code calls 555-2576, they will get that number as it applies within their area code. If you want to be reached from anywhere in the country, the person trying to reach you must use your area code before your local number. Conceptually, the scope of a variable is similar. You can have variables that can be seen locally only within a procedure, for instance, and you can have variables that can be seen globally from anywhere within a form, module, or even the whole program.

By default, a variable declared with a keyword such as Dim is local to the procedure in which it's created. For example, if you declare a variable in the event procedure for a CommandButton's Click() event procedure, it resides and is visible only within that event procedure. Therefore, to create variables that have a scope other than local, you must modify your declaration statement.

Making Variables Available Globally

In most programs, unless you have only one form and no code modules, you'll find that you need some variables that can be accessed from anywhere in the code. These are called Public variables. (Other programming languages might refer to these as global variables.) These variables are typically for holding information that's used throughout the program. They can also be used to indicate various conditions in the program.

To create a Public variable, you place a declaration statement with the Public keyword in the Declarations section of a module of your program. The following line shows the Public declaration of a variable of type Boolean (True/False):

Public bLightsOn as Boolean

In a form, the Public keyword has a special meaning. Variables defined as Public are considered to be very much like a property of the form and can be "seen" from anywhere in the program. These properties are referenced like the built-in properties of a form or control instead of like a variable. For example, you can have a string variable, strMyName, declared Public in the form frmMain, and you would access the string variable by using the following expression:

strSomeString = frmMain.strMyName

You can use the Public properties to pass information between forms and other parts of your program.

If you don't need to access a variable from everywhere in your program, you don't want to use the Public keyword in a declaration. Instead, you use the keyword Dim within a procedure. When the variable is declared inside a procedure, it can be used only within that procedure. This is typically known as a local variable.

The keyword Private is used within a form or module's Declaration section to make the variable visible only to the form or module within which it's created. This is typically known as a form- or module-level variable.

Keeping a Variable Local

At first glance, you might think that making all variables global is the easiest thing to do, but as your programs grow, this practice won't serve you well in the long run.

You saw in the preceding section that each procedure in a VB program can have its own variables. Each procedure can have variable names that might be common across other procedures, but because they are local to that procedure, none of the others know about them. Thus, you avoid what are called name collisions.

Think of it this way: You might have two procedures, ProcA and ProcB. ProcA creates two variables, x% and y%, and ProcB also creates two variables x% and y%. In ProcA, x% and y% are assigned values that, in turn, are passed as values to the Left and Top properties of a CommandButton, Command1.

In ProcB, the variable y% is assigned a value that's twice the value of x%. Both procedures have variables of the same name. However, because each set of variables was declared local to a distinct procedure, they are available only to the procedures in which they were declared (see Figure 7.3) .

FIGURE 7.3 Properly scoping your variables makes your code more reusable.

Using Static Variables

Most variables created inside a procedure are discarded by Visual Basic when the procedure is finished. Sometimes, however, you want to preserve the value of a variable even after the procedure runs. This often is the case when you call the procedure multiple times, and the value of a variable for one call to the procedure depends on the value left over from previous calls.


Using the Static keyword when declaring a procedure

If you use the Static keyword to declare a procedure, all variables in the procedure are treated as static.


To create a variable that retains its value even after the procedure is through running, you use the Static keyword in the variable declaration. This tells Visual Basic that the variable can be referenced only within the procedure but to hold on to the value because it will be needed again. For example, to declare a static variable for an integer, you use the following:

Static iNumOfClicks as Integer

A good use of a static variable would be where you needed to know how many times somebody clicked a CommandButton. If you Dim a counting variable in a click event procedure, the variable disappears when the click event is over and the variable goes out of scope; thus, you couldn't know how many times it was clicked. If you made the variable static, however, the value persists from click to click. Thus, if you put the preceding line into a click event, you have a permanent way to keep track of the number of clicks:

Sub MyButton_Click()
    Static iNumOfClicks as Integer
    iNumOfClicks = iNumOfClicks + 1
    MsgBox "Number of Clicks: " & CStr(iNumOfClicks)
End Sub

Static variables are commonly used in timer event procedures. You will read more about this in Chapter 16, "Working with Time and Timers."

Using Constants

Variables are only one way of storing information in the memory of a computer. Another way is to use constants. Constants in a program are treated a special way. After you define them (or they're defined for you by Visual Basic), you can't change them later in the program by using an assignment statement. If you try, Visual Basic generates an error when you run your program.

Constants are most often used to replace a hard-to-remember value, such as the color value for the Windows title bar. It's easier to remember the constant vbActiveTitleBar than the value 2147483646. You can also use a constant to avoid typing long strings if they're used in a number of places. For example, you could set a constant such as ERR_FILE_FOUND containing the string "The requested file was not found".

Often, constants are also used for conversion factors, such as 12 inches per foot or 3.3 feet per meter. The following code example shows how constants and variables are used:

Const METER_TO_FEET = 3.3
Meters# = CDbl(InputBox("Enter a distance in meters"))
DistFeet# = Meters# * METER_TO_FEET
MsgBox "The distance in feet is: " & CStr(DistFeet#)

Using Constants Supplied by Visual Basic

Visual Basic (as of version 4.0) supplies a number of sets of constants for various activities. There are color-definition constants, data-access constants, keycode constants, and shape constants, among others. The VB-supplied constants begin with the prefix vb.

The constants that you need for most functions are defined in the help topic for the function. If you want to know the value of a particular constant, you can use the Object Browser (see Figure 7.4). Access the Object Browser by clicking its icon in the Visual Basic toolbar or pressing the F2 key. You can use the list to find the constant that you want. When you select it, its value and function are displayed in the text area at the bottom of the dialog.

FIGURE 7.4 Select the appropriate constants from the Classes list to view the constants internal to Visual Basic.

Creating Your Own Constants

Although Visual Basic defines a large number of constants for many activities, sometimes you need to define your own constants. Constants are defined with the Const keyword statement to give the constant a name and a value, as shown in the following syntax:

Const CONSTANT_NAME [As ConstantType] = value


Naming conventions for constants

Constants are typically named with all uppercase characters and, if necessary, with an underscore character (_) to separate the characters into words: SECRET_NUMBER = 42. Now that Visual Basic supports its own constants and constants dedicated to classes, however, it's conventional to name constants in mixed case, with a lowercase prefix: snNumber = 42.


This statement appears similar to the declaration of a variable. As with declaring a variable, you provide a name for the constant and optionally specify the type of data it will hold. The Const keyword at the beginning of the statement tells Visual Basic that this statement defines a constant. This distinguishes the statement from one that just assigns a value to a variable. In declaring the type of a constant, you use the same types as you did for defining variables (refer to Table 7.2). Finally, to define a constant, you must include the equal sign (=) and the value to be assigned. If you're defining a string, remember to enclose the value in quotes ("").


What's a function?

A function is a named section of code that returns a value. You can reuse functions many times within your program. For calculation purposes, you can pass information into functions. The information that you pass into a function is called a parameter, also known as an argument. For more information about functions, see Chapter 18, "Writing Reusable Code with Subs and Functions."


Using the Assignment Statement

To use variables efficiently, you must also be able to assign information to the variable and manipulate that information. After you set up a variable, you need to store information in it. This is the job of the assignment statement. In the assignment statement, you specify a variable whose value you want to set. To assign a value to a variable, place an equal sign after the variable name and follow this with the expression that represents the value you want stored. The expression can be a literal value, a combination of other variables and constants, or functions that return a value. There's no limit on the complexity of the expression you use. However, even though Visual Basic will attempt to automatically convert mismatching data types, you should try to assign the correct type to the values that you assign to your program's variables. The following statements illustrate different assignment statements:

NumStudents% = 25
SumScores% = 2276
AvgScore% = SumScores% / NumStudents%
TopStudent$ = "Janet Simon"
BadStudent$ = txtStudent.Text

You can consider most properties of forms and controls as variables. They can be set at design time but also can be changed at runtime with an assignment statement. You can also use a property on the right side of a statement to assign its value to a variable for further processing. You saw this done in Listing 7.1. After the addition program shown in Figure 7.1 calculates the sum of the two entered numbers, it assigns the result to a third TextBox, as shown in lines 23-26:

`Convert the third variable (which is an integer)
`to text and assign it to the text property of the
`TextBox for the result.
txtTotal.Text = CStr(z)


Understanding type mismatch errors

A type mismatch error occurs when you try to assign a value to a variable that's not the expected data type. For example, if you create a variable x% of type Integer and try to assign a string value to it, you commit a type mismatch and receive a type mismatch error:

Dim x%
`Next line causes
`type mismatch error
x% = "Happy Birthday!"




Revisiting the Addition Program

Now that you've explored what variables are about and how to use them, you should have a better sense of what's going on in the addition program shown earlier in the chapter. If you look closely, though, you'll see that the programmer made an assumption about user input, which will result in a serious error. What happens when users don't enter a number into a text box but instead another sort of string value (see Figure 7.5)?

FIGURE 7.5 Don't assume that users will always enter the data type that your program requires.

The result is a crash.

To prevent such an occurrence, you could use the Visual Basic IsNumeric() function to check the value to make sure that the entry is indeed a numeric value. For example, before line 13 in Listing 7.1, you would enter the following line to prevent users from assigning any non-numeric character to the variable x%:

If IsNumeric(txtNumOne.Text) then
      x = CInt(txtNumOne.Text)
End if

Obviously, making sure that the right type of data is assigned to the right type of variable (what's referred to as data validation) is more than an academic exercise--it's a critical programming skill. You'll find out how to solve this problem in Chapter 9, "Working with Conditional Statements"; Chapter 21, "Debugging Your Applications"; and Chapter 12, "Working with Strings and Typecasting."


Previous chapterNext chapterContents

© Copyright, Macmillan Computer Publishing. All rights reserved.