Sams Teach Yourself Visual Basic 6 in 24 Hours

Sams Teach Yourself Visual Basic 6 in 24 Hours

By Greg Perry

Data Basics

Now that you have a better idea of how code goes together to support a Visual Basic application, you're ready to begin the specifics. This section teaches you all about the types of data that Visual Basic can manipulate.

Before you can perform data processing, you must understand data. When you are able to represent data properly, you can learn some commands to manipulate and process that data. Data is the cornerstone for learning the rest of the Visual Basic programming language. Although writing code that manipulates data might not seem to be as much fun as working with controls, you'll soon see the tie-in between controls and the code you write. After you learn to represent and process data, you can then work with controls in ways that you could not without the language's help.

You have heard various references to data throughout this tutorial. Data simply refers to information that will be processed by your program. Data is different from the VB instructions you write. The VB instructions you write simply process the data.

Datatypes

Data falls into three broad categories: numeric, string, and special. If you want to work with a number, you'll need to use a number that fits within one of VB's datatype categories. If you want to work with text data, you'll need to use a string. Other data might fall into one of several special datatype categories, such as an item (like the value of True or False) that represents a check box.

A string is a series of zero or more characters that you treat as a single entity. VB supports both fixed-length and variable-length strings.

Implicit typing is the process that VB performs when converting one datatype to another.

Table 5.1 lists the datatypes that Visual Basic supports. As you work with Visual Basic, you'll become familiar with all the datatypes (with the possible exception of Decimal, which isn't supported throughout the Visual Basic language yet).

Table 5.1. The Visual Basic datatypes.

Datatype Description and Range
Boolean A datatype that takes on one of two values only: True or False. True and False are reserved words in Visual Basic, meaning that you cannot use them for names of items you create.
Byte Positive numeric values without decimals that range from 0 to 255.
Currency Data that holds dollar amounts from -$922,337,203,685,477.5808 to $922,337,203,685,477.5807. The four decimal places ensure that proper rounding can occur. VB respects your Windows International settings and adjusts currency amounts according to your country's requirements. Never include the dollar sign when entering Currency values.
Date Holds date and time values. The date can range from January 1, 100, to December 31, 9999. (In the years following 9999, people will have to use something other than Visual Basic!)
Decimal A new datatype not yet supported in Visual Basic except in a few advanced situations. The Decimal datatype represents numbers with 28 decimal places of accuracy.
Double Numeric values that range from -1.79769313486232E+308 to 1.79769313486232E+308. The Double datatype is often known as double-precision.
Integer Numeric values with no decimal point or fraction that range from -32,768 to 32,767.
Long Integer values with a range beyond that of Integer data values. Long data values range from -2,147,483,648 to 2,147,483,647. Long data values consume more memory storage than integer values, and they are less efficient. The Long datatype is often called a long integer.
Object A special datatype that holds and references objects such as controls and forms.
Single Numeric values that range from -3.402823E+38 to 3.402823E+38. The Single datatype is often called single-precision.
String Data that consists of 0 to 65,400 characters of alphanumeric data. Alphanumeric means that the data can be both alphabetic and numeric. String data values may also contain special characters such as ^, %, and @. Both fixed-length strings and variable-length strings exist.
Variant Data of any datatype, used for control and other values for which the datatype is unknown.

Scientific Notation

An exponent is a power of 10 by which you want to multiply another value.

Table 5.1 contains Es and Ds in some numeric values. E stands for exponent, and D stands for double-precision exponent. The double-precision provides more accuracy than the regular exponent (often called a single-precision exponent). Both datatypes demonstrate a shorthand number notation called scientific notation. Scientific notation contains either uppercase or lowercase Es and Ds because the notation's letter case is insignificant.

Scientific notation is a shorthand notation for specifying extremely large or extremely small numbers.

Use scientific notation to represent extremely large and extremely small decimal numbers without typing a lot of zeros or other digits. You can convert a scientific notation value to its real value by following these steps:

  1. Raise 10 to the number after the D or E. The number 5.912E+6 requires that you raise 10 to the 6th power to get 1,000,000.
  2. Multiply the number at the left of the D or E by the value you got in step 1. The number 5.912E+6 requires that you multiply 5.912 by the 1,000,000 you got in the first step to get a final, meaningful result of 5,912,000.

Typing 5.912E+6 isn't much easier than typing 5912000, but when the number grows to the trillions and beyond, scientific notation is easier. By the way, you cannot insert commas when you enter Visual Basic numbers unless your International settings use the comma for the decimal position.

Specifying Values

A literal is a value that doesn't change. You'll sprinkle literals throughout your program. For example, if you need to annualize a monthly calculation, you'll surely multiply a value by 12 somewhere in the calculation because 12 months appear in each year. 12 is a literal and represents either a Byte, an Integer, or a Long datatype, depending on its context. If you multiplied the monthly value by 12.0, the 12.0 is also a literal, but 12.0 must be a Single or Double datatype due to the decimal.

When typing numeric literal values, you don't have to concern yourself with the datatype because Visual Basic takes care of things for you and attaches the best datatype for the calculation. If, however, you specify data of other datatypes, you must consider the way you type the data.

Quotation marks are required to designate a String literal, but the String literal doesn't actually contain the quotation marks. The following are literals that take the String datatype:

 "Sams"       "123 E. Sycamore St."     "91829"
 "#$%^&*"     "[Adam]"     "Happy birthday!"     "Angel Sue Bush"    ""

You must embed date and time literal values (Visual Basic uses the Date datatype to hold these values) inside pound signs (#). Depending on your International settings, you can specify the date or time in just about any valid date or time format, as in the following:

#12-Jan-1999#     #14:56#     #2:56 PM#     #December 5, 1998#

A Boolean literal is always True or False, so any time you must store or retrieve a True or False value, Visual Basic uses the Boolean datatype to hold the value. Option and Check Box controls return their values in the Boolean datatype. Many programmers use the Boolean datatype to store two-value data such as yes/no or on/off values.

Although Visual Basic normally takes care of datatypes when you type number values, you might need to ensure that Visual Basic interprets a numeric literal as one of the specific numeric datatypes. For example, you might type the literal 86 and need Visual Basic to store or display the value as a Long datatype even though 86 fits within a Byte or Integer datatype.

You can use the datatype suffix characters from Table 5.2 to override the default datatype. The suffix characters let you specify the datatype for numeric literals when you need to. Occasionally, Visual Basic will also use the datatype suffix characters when displaying numeric information. Therefore, if you type 86#, Visual Basic treats the number 86 as a double-precision value.

Table 5.2. Numeric datatype suffix characters.

Suffix Character Datatype Example
& Long 86&
! Single 86!
# Double 86#
@ Currency 86@

Variables Hold Data

All your data cannot be literals. The information your program's users enter in controls such as text boxes isn't literal data because the user can change information. In addition, your program has to have a place to hold information temporarily for calculations and for in-memory storage before sending information to a disk file or to the printer. To hold data that might change due to calculations or state changes within the application, you must declare variables. A variable is a named location that holds data.

Variables, unlike literals, can change. In other words, you can store a number in a variable early in the program and then change that number later in the program. The variable acts like a box that holds a value. The data you store in variables doesn't have to change, but often the program does change the contents of variables.

A program can have as many variables as you need it to have. Before you can use a variable, you must request that Visual Basic create the variable by declaring the variable before using it. To declare a variable, you tell Visual Basic the name and datatype of the variable.

After you declare a variable, it always retains its original declared datatype. Therefore, a single-precision variable can hold only single-precision values. When you store an integer in a single-precision variable, Visual Basic converts the integer to a single-precision number before the number gets to the variable. Such datatype conversions are common, and they typically don't cause many problems.

You use the Dim statement to declare variables (Dim stands for dimension). The Dim statement defines variables. Dim tells Visual Basic that somewhere else in the program the program will need to use a variable. Dim describes the datatype and also assigns a name to the variable.

Hour 2, "Analyzing Visual Basic Programs," describes the naming rules for controls, and you use the same naming rules for variables. Follow the naming rules when you make up names for variables. Whenever you learn a new statement, you need to learn the format for that statement. Here is the format of the Dim statement:

Dim VarName As DataType

VarName is a name that you supply. When Visual Basic executes the Dim statement at runtime, it creates a variable in memory and assigns it the name you give in the VarName location of the statement. DataType is one of the datatypes that you learned about in Table 5.1.

Global variables are variables that are available to the entire module or to the entire application. Local variables are variables that are available only to the procedure in which you define the variables.

The following statement defines a variable named curProductTotal:

Dim curProductTotal As Currency

From the Dim statement, you know that the variable holds the Currency datatype and that the variable's name is curProductTotal. Programmers often prefix variable names with a three-letter abbreviation that indicates the variable's datatype, but such a prefix isn't required. Table 5.3 lists these common variable prefix values. Please remember that you put these prefixes at the beginning of variable names just to remind yourself of the variable's datatype. The prefix itself has no meaning to Visual Basic and is just part of the name.

Table 5.3. Using variable name prefixes to maintain accurate datatypes.

Prefix Datatype Example
bln Boolean blnIsOverTime
byt Byte bytAge
cur Currency curHourlyPay
dte Date dteFirstBegan
dbl Double dblMicroMeasurement
int Integer intCount
lng Long lngStarDistance
obj Object objSoundClip
sng Single sngYearSales
str String strLastName
vnt or var Variant vntControlValue

The following statements define Integer, Single, and Double variables:

Dim intLength As Integer
Dim sngPrice As Single
Dim dblStructure As Double

If you want to write a program that stores the user's text box entry for the first name, you would define a string like this:

Dim strFirstName As String

You can get fancy when you define strings. This strFirstName string can hold any string from 0 to 65,500 characters long. You'll learn in the next section how to store data in a string. The strFirstName string can hold data of virtually any size. You could store a small string, such as "Joe", in strFirstName, and then a longer string, such as "Mercedes", in strFirstName. strFirstName is a variable-length string.

Sometimes you want to limit the amount of text that a string holds. For example, you might need to define a String variable to hold a name that you read from the disk file. Later, you'll display the contents of the string in a label on the form. The form's label has a fixed length, however—assuming that the AutoSize property is set to True. Therefore, you want to keep the String variable to a reasonable length. The following Dim statement demonstrates how you can add the * StringLength option when you want to define fixed-length strings:

Dim strTitle As String * 20

strTitle is the name of a String variable that can hold a string from 0 to 20 characters long. If the program attempts to store a string value that is longer than 20 characters in strTitle, Visual Basic truncates the string and stores only the first 20 characters.

Here's a shortcut: You can omit the As Variant descriptor when you define Variant variables. This Dim statement:

Dim varValue As Variant

does exactly the same thing as this:

Dim varValue

A good rule of thumb is to make your code as explicit as possible, so use As Variant to clarify your code intentions. If you begin calling a variable one name, you must stay with that name for the entire program. curSale isn't the same variable name as curSales. Use Option Explicit to guard against such common variable-naming errors. Visual Basic supports a shortcut when you need to define several variables. Instead of listing each variable definition on separate lines like this:

Dim A As Integer
Dim B As Double
Dim C As Integer
Dim D As String
Dim E As String

you can combine variable definitions on one line. Here's an example:

Dim A As Integer, C As Integer
Dim B As Double
Dim D As String, E As String

Putting Data in Variables

So far you have learned how to define variables but not how to store data in them. Use the assignment statement when you want to put data values into variables. Here is the format of the assignment statement:


   VarName = Expression
						

An assignment statement is a program statement that puts data into a control, a variable, or another object.

VarName is a variable name that you have defined using the Dim statement. Expression can be a literal, another variable, or a mathematical expression.

Suppose that you need to store a minimum age value of 18 in an Integer variable named intMinAge. The following assignment statement does that:

intMinAge = 18

To store a temperature in a single-precision variable named sngTodayTemp, you could do this:

sngTodayTemp = 42.1

The datatype of Expression must match the datatype of the variable to which you are assigning it. In other words, the following statement is invalid. It would produce an error in Visual Basic programs if you tried to use it:

sngTodayTemp = "Forty-Two point One"

sngTodayTemp is a single-precision variable, so you cannot assign a string to it. However, Visual Basic often makes a quick conversion for you when the conversion is trivial. For example, it's possible to perform the following assignment even if you have defined dblMeasure to be a double-precision variable:

dblMeasure = 921.23

At first glance, it appears that 921.23 is a single-precision number because of its size. 921.23 is actually a Variant data value. Visual Basic assumes that all data literals are Variant unless you explicitly add a suffix character to the literal to make the constant a different datatype. Visual Basic can easily and safely convert the Variant value to double-precision. That's just what Visual Basic does here, so the assignment works fine.

A constant is a value that doesn't change, whereas a literal is a certain data value.

In addition to constants, you can assign other variables' values to variables. Consider the following code:

Dim sngSales As Single, sngNewSales As Single
sngSales = 3945.42
sngNewSales = sngSales

When the third statement finishes, both sngSales and sngNewSales have the value 3945.42.

Feel free to assign variables to controls and controls to variables. Suppose, for example, that the user types the value 18.34 in a text box's Text property. If the text box's Name property is txtFactor, the following statement stores the value of the text box in a variable named sngFactorVal:

sngFactorVal = txtFactor.Text

Suppose that you defined strTitle to be a String variable with a fixed length of 10, but a user types Mondays Always Feel Blue in a text box's Text property that you want to assign to strTitle. Visual Basic stores only the first 10 characters of the control to strTitle and truncates the rest of the title. Therefore, strTitle holds only the string "Mondays Al".

You can instantly make data appear on a form by assigning the Text property of text boxes or the Caption property of labels and command buttons. No variables are required to do this. Suppose you put a command button named cmdPress on a form. The event procedure shown in Listing 5.1 changes the command button's Caption property and immediately places a new caption on the form (this occurs at runtime when this event procedure executes).

Example 5.1. An event procedure that assigns a new command button caption.

1: Private Sub cmdPress_Click ()
2: cmdPress.Caption = "Brush your teeth daily!"
3: End Sub

No matter what the command button's Caption property is set to at the start of the event procedure, when the user clicks the command button, this event procedure executes and the command button's caption changes to Brush your teeth daily!.

Some properties accept only a limited range of values. Assign only the number when a control's property can accept a limited range of values. For example, the possible values that you can select for a label's BorderStyle property in the Properties window are 0-None and 1-Fixed Single. To assign border style directly without using a named constant, assign just 0 or 1. Don't spell out the entire property. You can assign a fixed single-line border around a label like this:

lblSinger.BorderStyle = 1

Visual Basic includes a number of named literals internally that you can use for assigning such controls when the controls require a limited number of values. You can search the property's online help to see a list of named literals that you can assign. For example, not only can you assign 0 and 1 to a label's border, but you can also assign one of the named literals, vbBSNone and vbFixedSingle. Most named literals begin with the Visual Basic prefix vb.

Share ThisShare This

Informit Network