Hour 7


During this hour you will learn

Handling Data

Computers are all about data processing. The computer blindly follows the programmer's orders and manipulates the data so that reports and other meaningful results can follow. Therefore, you must learn how to construct and work with data inside your Visual Basic programs. The Visual Basic programming language helps you transfer data back and forth between controls, the printer, the disk drives, the screen, the keyboard, the mouse, and the CPU (the brain of your computer). Therefore, to master the Visual Basic language, you must master the data that forms the program's foundation.

This hour's lesson explains what kinds of data Visual Basic recognizes and how to specify that data in Visual Basic terms. This lesson won't have much hands-on at the machine, because you'll be learning theory that you can't quite put into practice yet until you learn a few additional parts of the Visual Basic language. Nevertheless, this lesson provides the language fundamentals that the rest of this course will build on. By the time you finish this lesson, you'll be writing straight Visual Basic code like a pro.

Topic 1: Introducing Data Types

Data comes in all shapes and sizes. Your applications will work with text, numbers, pictures, sounds, and video. Also, your programs will manage combinations of the various kinds of data as well. This topic introduces you to the Visual Basic data types. Visual Basic supports a fixed number of data types. When your program works with any kind of data, you have to tell Visual Basic the data type. If you want your program to generate data, you have to tell Visual Basic the kind of data to generate.

FAST TRACK
Are you familiar with QBasic or previous versions of Visual Basic? If so, you'll see that Visual Basic 5 doesn't introduce anything new into the data type assortment. You might want to skip down to the next topic section to review variable storage.



Every programming language supports certain kinds of data types. When you familiarize yourself with data types, you'll begin to see how programming languages process data. You'll also begin to recognize the flow of data between program components. In a Visual Basic program, a control might send data the user entered to the running program for disk storage. (You'll learn about special holding places in memory that hold data in the later section "Variables Hold Data.") Not all data types can work together, so you'll have to make sure that you don't try to store one data type in a storage location designed to hold a different data type.

Overview

Visual Basic supports 12 data types. VB also supports user-defined data types that you can create (which are explained in Hour 21's lesson, "Accessing Files"). This topic section introduces you to the 12 data types and shows you examples of the different kinds of data that fit within those types. When learning a new language, you must learn how the language internally stores different data types because you sometimes can gain efficiencies when you know how the language stores data. Visual Basic categorizes the data types into numeric, text, and special data type groups.


This topic section concentrates on literal data, sometimes called constants. Literals are unchanging data values such as the number 823. When you know how to work with literals, you can easily comprehend how Visual Basic supports literals as well as variables, or data that changes. You learn about variables later in the section "Variables Hold Data." Generally, VB programmers use the term literals rather than constants because Visual Basic includes some special named constants, such as you find in the Properties window (for example, the three values in the Label control's Alignment drop-down list), that you can use in your programs when you want to designate special values.

Numeric Data

Visual Basic supports eight numeric data types. You'll see all of them at one time or another, so even if you don't consider yourself a "math person," you should get to know these data types. When you have to write a program that deals with ages, prices, counts, or virtually any other kind of numeric quantity, it will be your job to figure out the correct numeric data type to use. Visual Basic will do all the math, but you'll have to set up Visual Basic's data properly that so VB can do its job.

Numeric data generally falls into two categories: integers and decimals. An integer is a whole number that doesn't have a decimal place. The following values are integers:

Notice that 0 is an integer, and negative numbers can also be integers. As long as the number contains no fractional portion with a decimal point, you can think of the value as an integer. Common integers are ages, month and day numbers, counts, and other numeric values that you work with that typically contain no decimal part.

Decimal values, however, contain a fractional portion that follows a decimal point, even if that fractional portion is 0. Here are some sample non-integer decimal values:

Decimal values always have decimal points. Even if the decimal value ends with one or more zeros to the right of the decimal, the value is still considered to be a non-integer decimal value. The decimal point indicates a precision. In other words, the value 1.23 means that the value is precise to two decimal places. When you need to represent a numeric literal in your program, you'll type the literal inside the Code window. (You'll see later this hour how to type other kinds of literals.)


Decimal values are often called floating-point values.

Scientific Notation

You were probably reading along just fine until you saw the E's and D's in the preceding list of decimal values. The E stands for exponent. Because computers use exponents all the time, now would be a good time to familiarize yourself with them. The D stands for double-precision exponent, which provides more precision than the regular exponent. (The regular exponent is often called a single-precision exponent.)

Both data types represent a shorthand numeric notation called scientific notation. (You may see scientific notation with uppercase or lowercase E's and D's because the notation's letter case is insignificant.) Scientific notation lets you represent extremely large and extremely small decimal numbers without typing lots of zeroes or other digits to the right of the decimal point.

You can convert a scientific notation value to its real meaning by multiplying the number to the left of the D or E by 10 raised to the number after the E or D. Therefore, 3.120E+7 represents 31,200,000; you multiply 3.120 by 10 raised to the 7th power, or 10,000,000. If the exponent is negative, divide the number by 10 raised to the power. Therefore, 5.128172356D-4 represents .0005128172356, or 5.128172356 divided by 10,000. Use a double-precision exponent when you need Visual Basic to track decimal places that extend past seven digits.

If you don't use scientific programming, you may still see scientific notation occasionally. Visual Basic might display a value as a scientific notational amount to save room in certain situations. Data tables, such as ones you'll see throughout this hour's lesson, frequently use scientific notation to show extreme values within a limited amount of space.

Often, you'll need to know how much storage Visual Basic uses to hold numeric values. Although memory is cheaper than ever before, and although most computers have ample RAM these days, you'll want to write efficient programs and not use more memory than necessary to hold program data. Integers generally consume less memory space than decimal values because your computer doesn't have to keep track the extra precision required by decimals. As you learn more about data types in this lesson, you'll learn how much memory each type of number consumes.


Generally, you can't determine how much memory a value takes by the number itself. Surprisingly, the number 1.1 consumes more memory than 32,766. Fortunately, you won't have to bother too much with numeric literal storage requirements, but you'll need to be aware of how much memory each data type takes when you learn about storing numbers in your program variables later in this hour's lesson.

Integer Types

If the distinction between integers and decimals weren't enough, Visual Basic separates values into different kinds of integers and decimals. Table 7.1 describes the three kinds of integers.

Table 7.1 The Integer Data Types

Data Type

Storage

Range

Byte 1 byte

0 to 255

Integer 2 bytes

-32,768 to 32,767

Long 4 bytes

-2,147,483,648 to 2,147,483,647


Byte values are always zero or positive.

A byte is one memory location. Visual Basic uses the keyword Byte to represent the data type that holds very small integers ranging from 0 to 255. Therefore, if you need to hold people's ages, you might consider using Byte values because a person's age will never be negative or more than 255. However, if you need to keep track of integer measurements that go negative or go as high as 32,767, you must use an integer (represented in Visual Basic with the keyword Integer) or long integers (represented by Long).

Why not just use long integers for all integer values? After all, long integers hold virtually any integer you'll work with. But using longs for all integer data would be extremely inefficient. Visual Basic would have to store all data in 4 bytes and move 4 bytes every time the data moved or changed. Reserve such long integers for those data values that might require the extra range.

Decimal Types

Table 7.2 lists the decimal value data types that Visual Basic supports.

Table 7.2 The Decimal Data Types

Data Type

Storage

Range

Single 4 bytes

-3.402823E+38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E+38 for positive values

Double 8 bytes

-1.79769313486232E+308 to -4.94065645841247E-324 for negatives; 4.94065645841247E-324 to 1.79769313486232E+308 for positives

Currency 8 bytes

-922,337,203,685,477.5808 to 922,337,203,685,477.5807

Decimal 14 bytes

+/-79,228,162,514,264,337,593,543,950,335 if you use no decimal; +/-7.9228162514264337593543950335 with up to 28 decimal places


Technically, the currency data type is known as a scaled integer and stored as an extremely large integer value and converted to dollars and cents when needed. The scaling keeps the precision that you want for currency amounts, because you never want calculations to round currency values but always work out exactly to proper dollar and cent values. For practical purposes, however, you and Visual Basic can treat currency values as though they're decimals.

At this time, Visual Basic doesn't support the data type that the Decimal keyword represents except in special situations. Future versions may do more with this extremely precise decimal value.

For most applications, you'll use single-precision values (represented by the Single keyword) for most of your decimal values, unless your program requires extremely precise values that might take an extraordinary range as found in scientific and mathematical situations. Use double-precision (represented by the Double keyword) only for those extreme values. Of course, you'll use the currency data type for all monetary values so that Visual Basic can track the cents portions correctly.


Visual Basic is designed to work in any country that Windows supports. Therefore, if your International settings are set to Italy, Visual Basic prints your currency values with commas and decimal points reversed from the North American standard.

Text Data

As mentioned in Hour 1's lesson, Visual Basic's roots are in the BASIC programming language. Although BASIC was considered a beginner's language, its ease of use was the strength that kept it in use for a long time. When Microsoft decided to improve on the language, the company kept the fundamentals there so that new programmers would take to programming more quickly than otherwise would happen.

In addition to its ease of use, BASIC had another technical advantage over all other languages of its time and over just about all languages developed since: BASIC and its descendants fully support text data and provide a large collection of text-manipulation tools that other languages only dream about.

Computers simply don't work with text internally as well as numbers, especially large streams of text known as strings. (A string is a collection of zero or more characters considered to be one unit, such as a name, sentence, paragraph, or any other collection of characters a program needs to track.) BASIC's creators took the pain out of string programming by adding string processing to BASIC's core functions.

As an incarnation of BASIC, Visual Basic holds true to its roots by providing much text support. Table 7.3 describes the two kinds of text data types that Visual Basic supports. In almost every case, VB programmers refer to text, whether the text is a single character, or 200 characters, as string data.

Table 7.3 String Data Types

Data Type

Storage

Range

String(fixed length)

Length of string

1 to about 65,400 characters

String (variable length)

Length of string plus 10 bytes

0 to 2 billion characters

You always enclose string literals in quotation marks. A string can contain any character. Therefore, the following are all valid string literals:

"I love Rome"     "Z"     "w20kd-x302,m,x-222"   ""


Enclosing numeric digits inside quotation marks tells Visual Basic that the literal is a string, not a numeric literal. You can never perform math calculations with string literals, even if those literals contain valid numbers, unless you first convert the strings to numbers by using standard Visual Basic conversion methods that you'll learn about in later lessons (especially in Hour 14, "Using the Supplied Functions"). Quotation marks with nothing between them represent a zero-length string literal. Surprisingly, string literals with nothing in them, called empty strings or null strings, are used a lot as Visual Basic placeholders for future text.


Visual Basic supports a keyword called Null that you can store in strings and other kinds of data holders. Null indicates that the data contains no valid information, and you might initialize a storage area with Null.
The keyword Empty, if stored in a data location, indicates that you've not initialized the value yet. Empty numeric values contain 0 (or 0.0); empty strings contain "" and are zero bytes long.

As you can see in Table 7.3, Visual Basic uses the same keyword, String, to represent both fixed-length and variable-length strings. When working with string literals, the distinction isn't as critical as it will be when you work with string storage, as you learn in the next topic section.

Special Data

Table 7.4 lists the remaining data types that Visual Basic supports. Although one tends to think of data as falling into the numeric or string categories, Visual Basic's extra data types let you do more with today's kinds of data values such as dates and even object data such as graphic and sound files.

Table 7.4 Special Data Types

Data Type

Storage

Range

Date

8 bytes

January 1, 100 to December 31, 9999

Boolean

2 bytes

True or False only

Object

4 bytes

Any embedded object

Variant (with numbers)

16 bytes

Any value up to Double

Variant (with text)

Length of text plus 22 bytes

Same as variable-length String

The Variant data type can represent any kind of data, except fixed-length strings. Variant data (used with the Variant keyword) offers VB programmers all kinds of programming flexibility that didn't exist before Visual Basic arrived on the scene. Originally, the VB designers added the Variant data type to support data coming from form controls that had no real data type or that may take just about any form in many instances. As you work through this night-school tutorial, you'll learn more ways to use variants in your programs.

The Date data type holds the time as well as the date. Visual Basic lets you specify date or time value literals in several forms, as long as you enclose the date literal within pound signs (#). The following are all valid literals that represent the Date data type:

#April 6, 1937#

#4:54 am#

#23:01:21#

#1-2-1998#

#4-Mar-2004#


Basically, any date or time format that your computer recognizes, respecting the International settings you've set in Windows, the Date data type will represent.


Occasionally, your Visual Basic programs will have to convert a date value to a number or a numeric data type. Visual Basic stores the Date data type as an 8-byte floating-point number, so the conversion is possible. The value to the left of the decimal represents the date; the value to the right of the decimal point represents the time, where .0 is midnight and .5 is noon.

Visual Basic uses either a 24-hour clock or am and pm indicators, depending on the value of your Windows International date and time settings that you can adjust in your Windows Control Panel.

The Boolean data type represents true or false states. For example, if you needed to represent a past-due flag, you'd use the Boolean data type and store True or False (both are keywords) in the Boolean storage location. Occasionally, you may convert a Boolean value to a numeric data type; in that case, False becomes 0 and True becomes -1.

Example

Although this data type topic is one of the longest single topic sections in the book, the material is theory. In many cases, you don't have to worry about all the specific cases. In other words, if you need to send a number to a control inside a Visual Basic program (as opposed to doing so in the Properties window), you just type the number with the appropriate assignment statement and not worry whether the literal number is an Integer data type or Double data type or anything else.

Perhaps the most important lesson you can glean from this topic is the characters that must enclose certain literals. Never enclose numeric data types inside any characters; just type them directly like this:

45
-6756.4322

Also, never use commas inside numbers, unless your Windows International settings use the comma for the decimal position (in which case you shouldn't embed points inside numbers).

You can use scientific notation any time you want (for example, for 6756.4322 type 6.7564322E+3). However, you should save scientific notation for extremely small or extremely large numbers because scientific notation wouldn't save coding time otherwise.

"343", "Terry", "", "January 5, 2031", and "6104 West 2nd Street, #7" are all string literals due to the quotation marks. #January 5, 2031# is a Date literal because of the pound signs.

Next Step

In certain situations, you need to ensure that Visual Basic interprets a numeric literal as one of the specific data types. For example, you might type the literal 16 and need Visual Basic to store or display the value as a Long data type, even though 16 fits within a Byte or Integer data type.

Therefore, Visual Basic supports the data-type suffix characters in Table 7.5. These suffix characters let you specify the data type for numeric literals when you need to. Occasionally, Visual Basic also uses the data-type suffix characters when displaying numeric information. Therefore, if you type 16#, Visual Basic treats the number 16 as a double-precision value.

Table 7.5 Numeric Data-Type Suffix Characters

Suffix

Data Type

Character

Described

&

Long

!

Single

#

Double

@

Currency

The scientific notation's E represents a single-precision value and D represents double-precision value, so the corresponding letter indicates the scientific notation data types.

Topic 2: Variables Hold Data

Now that you've mastered data types, you'll have little trouble understanding how to store that data inside programs. Whereas literals don't change, storage locations do. For example, you might designate a storage location to hold the hours worked in a payroll application. The number of hours worked each week might change, so you can't use a literal (such as 40) to represent the current number of hours worked for each employee. Instead, you designate a variable to hold the value. Variables are named storage locations inside your program that hold values that can vary.

Overview

You, the VB programmer, are responsible for creating and naming variables in your programs. You need a variable for each storage value you want to track. If you need to keep track of a customer's name, account number, and balance, you'll need three variables.

Variables hold specific kinds of data. Integer variables hold integers and Byte variables hold byte values and so on. Visual Basic lets you create variables for every data type (except for the special Decimal data type, which Visual Basic doesn't support as fully as the other data types). This topic section teaches you how to declare variables. Before you can use a variable, you must declare the variable so that your program knows you need the variable storage later. Visual Basic lets you declare as many variables as you need. In many cases, the first few lines of a procedure list variable declarations.


You must give variables different names so that Visual Basic can distinguish one variable from another. Two variables can't have the same name within the same procedure.

Think of a variable as a box in your computer that holds only one value at a time. You can store a number in a numeric variable or a string in a string variable. No matter how long the string is, the string variable can hold the string but only one string at a time. If you store one string and then later store another string in the variable, the second string replaces the first one.

Declaring Variables with Dim

You must declare a variable before you can use the variable. When you declare the variable, you specify the variable's name and data type. A variable's name and data type never change. Visual Basic contains several statements that declare variables, but the most common statement is Dim. Dim stands for dimension. Although the Dim statement takes on many forms, here is a standard Dim statement format for declaring variables:

Dim VarName As DataType

The VarName is a variable name that you declare. DataType is any of the data types you learned in the previous topic section (except Decimal). Here are several variable declarations:

Dim Age As Byte

Dim Salary As Single

Dim FirstName As String


These statements declare three variables. If you typed these statements at the beginning of a procedure (immediately following the procedure's first line), any line in the rest of the procedure could use the variables. (The variables are known to be local to the procedure.)


Declaring strings can be confusing because of the two string data types. You'll see a more complete explanation of declaring string variables in this topic's "Next Step" section. If you want to review the Declarations section, look at Hour 6, "Understanding the VB Program Structure."


If you declare one or more variables at the beginning of a module (outside the procedures inside the Declarations area), the variables are available to the entire module. Good programming practices dictate that you keep data as local as possible, meaning that procedure-level variables generally protect values better and make for more maintainable programs. If a variable is needed in several procedures, however, you might choose to make the variable less local by declaring it in the Declarations area. If you replace Dim with Public, the variable is available to the entire application, even if the application contains multiple modules. Such global variables, however, often lend themselves to programming troubles if you use them for variables that don't need such a global scope. You might accidentally change a variable in one procedure that another procedure has initialized. You can safely declare and use variables without having to review variable names in every other part of your program if you stick to local variables only.

The variable's name must follow these naming rules:


Some programmers use underscores to separate words inside a variable name, as in First_name. However, more modern programming techniques prefer mixing uppercase and lowercase letters to distinguish between such words, as in FirstName.

The following are all valid variable names:

Many Visual Basic programmers prefix each variable name with a data-type prefix (see Table 7.6 for some prefix suggestions). If you prefix a variable with its data-type abbreviation, you'll rarely forget a data type and attempt to transfer a String variable to a Double variable some time. (Such transfers would cause problems.)

Table 7.6 Suggested Variable Name Prefixes

Prefix

Data Type

Example

bln Boolean blnIsOverTime
byt Byte bytAge
cur Currency curHourlyPay
dtm Date dteFirstBegan
dbl Double dblMicroMeasurement
int Integer intCount
lngLong lngStarDistance
obj Object objSoundClip
sng Single sngYearSales
str String strLastName
vnt Variant vntControlValue



Never do calculations with string variables, even if those variables hold numerical digits that look like numbers. If you need to work mathematically with a value stored in a String data type variable, convert and transfer the variable's value to a numeric variable before you perform the calculation.

Visual Basic does let you make several transfers that cause no conflict, such as putting a Single value into a Double variable or assigning a Byte value to an Integer or Double. Such assignments don't cause any problems because the target variable is large enough to hold the value. Also, the target variable is numeric, so the number transports well to the more precise data type. Transferring a Double to a Byte, however, could cause problems because Byte can't hold the range of values that a Double can.

If you don't declare variable names, one of two things will happen:

Table 7.7 Visual Basic's Variable Data-Type Suffix Characters

CharacterData TypeExample
% Integer Amount%
& Long Length&
! Single < Sales!
# Double Measurement#
@ Currency Cost@
$ String CompanyName$

Figure 7.1

The Require Variable Declaration option requires that you declare all variables before you use them.

Although you can voluntarily declare all variables before you use the variables, the Options Explicit statement or the checked Require Variable Declaration option tells Visual Basic to issue an error if you fail to declare a variable. Such safeguards are recommended; without them, if you inadvertently typed the amtGiven variable as amtGaven, your program won't work properly. What's more, the bug can be difficult to trace if your application is large and contains lots of code.

If you don't declare variables and if you don't have one of the declaration requirement options set, you can specify the data type of an undeclared variable by suffixing the variable name with one of the suffix characters in Table 7.7. Nevertheless, defining a variable as the Single data type with Dim is clearer and less error-prone than simply making up the variable at the time you use it with an add-on ! at the end of the name.

Example

Suppose that you need a variable that will hold the number of days worked in a month. The following statement declares such a variable:

Dim k As Integer

Although k is a valid variable name, the name has no relationship to its usage. Why not be more creative and name the variable as follows?

Dim intDaysWorked As Integer

Although this variable name requires more typing, you later can modify and maintain the program and know exactly what intDaysWorked holds and that the variable is an integer.


Good Boolean variable names usually can be phrased as questions or statements that their True and False values will describe, such as blnIsWorking, blnGetsTaxed, or blnPaidOvertime.

If you didn't explicitly declare the variable, you'd have to use the data-type suffix character any time you referenced the variable, such as intDaysWorked%. Without the suffix, Visual Basic would treat the variable as though it were of the Variant data type. Generally, you write better code if you stay away from the suffix characters and use Dim to declare all variables explicitly.

If you declare intDaysWorked at the top of a procedure, the variable is available only to that procedure. If you declare intDaysWorked in the module's Declarations section, intDaysWorked is available to every procedure in the module, but loses some of the protection from inside the procedure scope that it would have if you declare it at the top of a procedure. If you replace Dim with the Public keyword, the variable is available to the entire application, including other modules but is vulnerable to accidental changes from elsewhere in the code.

When you protect a variable by limiting its scope, you keep other procedures from changing the variable's value. Also, if you happen to name two variables the same name in two different procedures, those variables won't conflict if they're local just to their own procedure.


Try to avoid giving two variables within the same application the same name, except for work variables that hold temporary counts and totals. If the variables are global, you'll overwrite one with the other's value; if the variables are local to different procedures, you might get confused when you later modify the code.

If you want to declare two or more variables on the same line, you can do so like this:

Dim intNum1 As Integer, intNum2 As Integer

You must list the Integer keyword on both declarations. If you omit a Dim variable's data type, Visual Basic declares that variable as a Variant data type. Therefore, the following statement declares only one Single (sng4) and three Variant variables (sng1 through sng3):

Dim sng1, sng2, sng3, sng4 As Single

Next Step

The Dim statement works well for all data types but strings add one extra problem. If you're declaring variable-length strings, you can use Dim as you might expect. The following statement declares a string variable named strCity:

Dim strCity As String

strCity is a variable-length string. Therefore, you can store any string of any length into the variable. (The next topic explains how to store data in variables that you've declared.) When you store a string in strCity, such as "Miami" (the quotation marks don't get stored into the string variable but serve only to delimit the string literal), you can later store a different string, such as "Indianapolis", in strCity. Visual Basic expands and contracts a variable-length string during runtime as needed to hold the strings you transfer to the variables.



Use string variables for ZIP codes, phone numbers, and Social Security numbers. Although these kinds of values contain only numeric digits, you never perform math on them. When you must track such strings of digits, be sure to use string variables to hold the data.

If you want to declare a fixed-length string, you have to tell Visual Basic at the time that you declare the string exactly what maximum length the string will ever be. Add the Dim option * length like this:

Dim strCity As String * 15

The strCity string can now hold only strings up to 15 characters long (from zero to 15 characters).


Variable-length strings are certainly easier to work with than fixed-length strings, and take less effort to declare. Nevertheless, you may need to declare fixed-length strings when dealing with communications or disk file data, or when storing data that will appear in a fixed-length control such as a label.

Topic 3: Working with Variables

When you declare variables, Visual Basic creates the variable; reserves the name for that variable's scope; designates the variable's data type; and initializes the variable with a 0 for numeric variables, null strings ("") for variable-length strings, zeros for fixed-length strings, and the special keyword Empty for Variant data-typed variables. Your program then changes the variable's value right away, perhaps using the variable for a total or a counter. The data that your program stores in variables might come from a control, a dialog box, a literal that you type in the program, another variable, or a calculation.

Overview

This topic section explains how to use Visual Basic's assignment statement. The assignment statement transfers values into variables. You must declare the variables before assigning values to those variables; otherwise, you get an error unless you've turned off the explicit declaration options mentioned in the previous topic section.

The assignment statement is simple to use. All you must ensure is that you transfer the appropriate kind of data to the variable.


The Assignment Statement

Here is the assignment statement's format:

[Let] VarName = Expression

The square brackets indicate that the Let keyword is optional; hardly any VB programmer types Let. VarName is any valid variable that you've declared or defined with a suffix data-type character. Expression refers to a literal, a variable, a control, or a combination of such items in a manner that Visual Basic can convert to the correct data type.

If you wanted to assign an hourly pay rate to a variable that you've declared to be a Currency data type, the following statement would do just that:

curHourRate = 12.75

Of course, you could also write the following, but Let requires extra typing:

Let curHourRate = 12.75

Remember that you can apply data-type suffix characters to literals, so you could also write this:

curHourRate = 12.75@

Such literal data-type suffix characters aren't required. If you had omitted the @ on the currency literal, Visual Basic would convert the 12.75 to a Currency data type automatically before storing the value in curHourRate.


Make sure that you don't assign strings to any kind of numeric variables or numeric values to any kind of string variables. Visual Basic can't perform the automatic conversion on such data-type differences.

Be sure to remember the quotation marks if you assign a string literal to a string variable:

strMyState = "Oklahoma"

Keep in mind that a variable can hold only one value at a time. Therefore, if another statement in the program assigned another string to strMyState,

strMyState = "Indiana"

strMyState would now hold "Indiana" (without the quotation marks).

The Expression might be another variable. Therefore, the following statement would also store "Indiana" in the variable, because strMyState holds that value:

strNewState = strMyState

Don't treat the assignment as a move operation. The assignment sends a copy of whatever is on the right side of the equal sign to the variable on the left. The right side's variable still holds its value after the assignment finishes. Therefore, unlike a move operation, the assignment ensures that both variables hold the same value after the assignment takes place.

As a general rule, control values take on the Variant data type. Visual Basic performs the needed data type conversion if you assign a control value to a variable, as in

IntBookCount = txtBook.Text

Always remember to separate the control name from the property with the period, as shown.

This topic section has assigned only literals, controls, and variables to declared variables. The next hour's lesson explains how to assign more complex expressions to variables.

Example

When assigning literal dates and times to a Date variable data type, enclose the literals in pound signs. The following assignment statements assign a starting date and time to two Date data-typed variables:

dteDateStarted = #6-Jul-1992# dteTimeStarted = #08:30#

You can assign True and False directly to Boolean variables as follows:

blnGetsDiscount = False blnTaxed = True

The True and False literals are Visual Basic keywords that you can use both in assignments and elsewhere. Although you can assign numeric values to Boolean variables (and if you do, 0 converts to False and anything else converts to True), stick to the literals to make your programs as clear as possible.

Next Step

The assignment statement always takes the right side of the equal sign and transfers that side to the variable on the left. The assignment statement works for controls as well. If a variable holds a value you've defined and you want to send that variable's value to a control's property, you can put the control's property on the left of the equal sign to receive the assignment. Therefore, the following statement assigns a literal to a control property inside a Visual Basic procedure:

cmdClickMe.Caption = "Press &Here"

The following statement assigns a variable named strEntered to a label:

lblTitle.Caption = strEntered

If you put the first assignment inside the command button's Click event procedure, the command button's caption would change as soon as the user clicked the button. The event procedure might look something like this:

Private Sub mnuFileExit_Click()
cmdClickMe.Caption = "Press &Here"
End Sub

Summary

You're on your way to writing advanced Visual Basic programs! Although you didn't work hands-on with Visual Basic in this chapter, you learned programming theory that applies not only to Visual Basic, but to all other programming languages to some degree. This hour's topic taught you the importance of data types so that you can declare the correct kinds of data that your program needs to process.

After you declare your variables, your program can work with those variables by assigning values to the variables and using the values inside variables for other assignments. The assignment statement transfers data to and from controls as well as variables.


In the next hour, you'll learn how to complicate the assignment's right side somewhat. By writing expressions that Visual Basic evaluates to specific values, you can store the results of calculations inside variables.

Hour 7 Quiz

  1. What kinds of numeric data does Visual Basic support?
  2. Name the two kinds of string data Visual Basic works with.
  3. 3 What's the difference between a literal and a variable?
  4. True or false: "July 7, 1998" represents a Date data type literal.
  5. What's the difference between a fixed-length string and a variable-length string?
  6. Which of the following are valid variable names?
  7. X Boolean MrBoolean Amt1998 1998Amt DoRight My Age
  8. Why do we sometimes use scientific notation?
  9. What characters must surround string literals?
  10. How can the variable-name prefixes help you reduce program data conflicts?
  11. True or false: You can assign a literal to a control but not a control to a literal.

Hour 7 Homework Exercises

Convert the following scientific notational values to their actual values and tell the data type of each:

  1. Write the code that declares four variables: one for your first name, one for your last name, one for your age, and one for your ZIP code. Limit the first name's storage space to 10 characters. Make sure that you use the correct data type for the ZIP code.
  2. Write the declarations for two string variables: your country and your mother's first name. Limit each string to a maximum of 15 characters.
  3. Write assignment statements that fill your variables in exercise 2 with appropriate data.

© 1997, QUE Corporation, an imprint of Macmillan Publishing USA, a Simon and Schuster Company.