It's time to hone your multilingual skills and learn a new language! This hour's lesson explores the Visual Basic programming language. You'll learn how code goes together to form the application, and you'll learn how VB works with data. Your applications must be capable of processing many types of data values, and you'll master those data types before the hour is up.
The highlights of this hour include
As you write more powerful programs, you'll need to insert more and more of Visual Basic's programming language into your applications. The language, although one of the easiest to master, can be tricky in places. Nevertheless, if you start with the fundamentals, you'll have no trouble mastering the hard parts.
Remember that a VB program consists of the following:
Although you can create great-looking applications just by dragging controls onto forms and setting properties, the applications don't really become useful until you add code to tie the controls together and to perform calculations and data manipulation when needed. No control exists to calculate inventory accounting values; you must add the code to do things like that. The program code that you write is just a detailed set of instructions that tells Visual Basic how to manipulate data, perform input and output (known as I/O), and respond to the user.
New Term: I/O stands for input and output and refers to the practice of receiving data from a control, the user, or a data source such as the disk drive and sending data from your computer to the outside world, such as the screen or printer.
Before looking at specifics, you should take a moment to consider the location of the code in a VB application. You now know that much of the code in an application is comprised of small event procedures that respond to events. The form's controls often trigger the events when the user interacts with a control. Event procedures are not the only code that appears in an application, however. Code can appear in several places. This 24-hour tutorial concerns itself with code that appears in form modules and in standard modules.
New Term: A form module is a module file that holds one or more forms and the code that goes with each form.
New Term: A standard module is a file that holds code not related to a form.
A form module is code connected to a specific form. The form's event procedures appear in the form's form module as does other code that is not directly connected to events such as calculations and data sorting routines. Every application has at least one form, so every application contains at least one form module. When you add a new form to an application, Visual Basic adds a new form module to go with the form.
NOTE: Some applications, such as those that perform system utility functions and background processing tasks, never display their form. The form's Visible property is set to False.
Figure 5.1 helps illustrate the module concepts this section describes. All of
the application's modules reside in separate disk files even though Visual Basic
groups them together in a single project. You can consider all the project's files
as one entity during your application's creation and execution, but the files do
reside separately on the disk. The Project Explorer window keeps things together
in an orderly manner.
Figure 5.1. One or more modules can appear in an application.
A program that supports multiple forms (and therefore, multiple form modules) is either an MDI (for multiple-document interface) application or an SDI (for single-document interface). An MDI application, such as Word, can open several windows at once that contain different data documents. An SDI application, although it can contain multiple forms such as dialog boxes, only supports one data document (the Windows Notepad application is an SDI application because when you open a new document, the current one leaves the work area). No matter which kind of application you create, your application can contain multiple Form windows and, hence, can contain multiple form modules.
In addition to form modules, an application might contain one or more standard modules. Standard modules contain code and have no forms or controls associated with them. Although the code inside a standard module might manipulate a form or its controls, the code that you put in a standard module usually contains general-purpose code that you can use in several applications. For example, you might write some Visual Basic code that calculates wages using some special formulas that your company requires. If you need to use those calculations in several applications, store the calculations in a standard module and then add a copy of that standard module to each application instead of typing the code multiple times in multiple applications.
TIP: You will understand the differences in modules much more clearly as you progress through these 24 hours. For now, concentrate on getting the "big picture."
Fortunately, you don't have to do much to manage projects that require multiple
files. The Project Explorer window keeps track of things. As you add files to or
remove files from the application (by selecting from the menu that appears when you
right-click over the Project Explorer window), the Project Explorer window keeps
track of the guidekeeping. When you want to modify or add to one of the items in the
Project Explorer window, double-click the object's icon in the Project Explorer window,
and the form or code opens in the work area (see Figure 5.2).
Figure 5.2. The Project Explorer window displays the project's files.
NOTE: Visual Basic also supports class modules, but this guide does not discuss class modules in detail.
Now that you've got 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. Once you learn to represent and process data, you can then work with controls in ways that you could not without the language's help.
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 data type 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 data type categories such as an item that represents a check box-like value of True or False.
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.
NOTE: Controls almost always supply the Variant data type to your programs. Therefore, when your program receives a value from a control, the data type is Variant. You can, through a conversion routine or by implicit typing (when VB converts the data type for you as you store one data type in a location that is designed to hold a different data type), convert the control's data type to another data type. The Variant data type lets you store data in a variable when you don't know the specific data type of the variable.
Implicit typing is the process that VB performs when converting one data type to another.
Table 5.1 lists the data types that Visual Basic supports. As you work with Visual Basic, you'll become familiar with all the data types (with the possible exception of Decimal, which is not supported throughout the Visual Basic language yet).
Table 5.1. The Visual Basic data types.
|Data Type||Description and Range|
|Boolean||A data type that takes on one of two values only: True or False. True and False are Visual Basic reserved words, 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 data type not yet supported in Visual Basic except in a few advanced situations. The Decimal data type represents numbers with 28 decimal places of accuracy.|
|Double||Numeric values that range from -1.79769313486232E+308 to 1.79769313486232E+308. The Double data type is often called 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 data type is often called long integer.|
|Object||A special data type 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 data type 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 data type and used for control and other values for which the data type is unknown.|
New Term: 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 data types 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.
New Term: 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:
Typing 5.912E+6 is not a lot 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 uses the comma for the decimal position.
TIP: Visual Basic often displays value in the scientific notation format to save room on the screen or in a control. Therefore, you need to understand scientific notation, even if you never plan to use scientific notation, so you'll recognize its meaning when you see it.
Specifying Values A literal is a value that does not change. You will 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 data type, 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 data type due to the decimal.
When typing numeric literal values, you don't have to concern yourself with the data type because Visual Basic takes care of things for you and attaches the best data type for the calculation. If, however, you specify data of other data types, you must consider the way you type the data.
All String literal data contains surrounding quotation marks. The String literals do not include the quotation marks. The following are literals that take the String data type:
"Sams" "123 E. Sycamore St." "91829" "#$%^&*" "[Adam]" "Happy birthday!" ""
NOTE: The last string is called an empty string or a null string because the quotation marks are together without even a space between them.
You must embed date and time literals (Visual Basic uses the Date data type 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 data type to hold the value. Option and Check Box controls return their values in the Boolean data type. Many programmers use the Boolean data type to store two-value data such as yes/no or on/off values.
NOTE: You'll learn more about Variant and Object when you tie code to controls and forms later in this guide.
Although Visual Basic normally takes care of data types when you type number values, you might need to ensure that Visual Basic interprets a numeric literal as one of the specific numeric data types. For example, you might type the literal 86 and need Visual Basic to store or display the value as a Long data type even though 86 fits within a Byte or Integer data type.
You can use the data type suffix characters from Table 5.2 to override the default data type. The suffix characters let you specify the data type for numeric literals when you need to. Occasionally, Visual Basic will also use the data type 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 data type suffix characters.
|Suffix Character||Data Type||Example|
All your data cannot be literals. The information your program's users enter in controls such as text boxes is not 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 does not 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 data type of the variable.
NOTE: A variable can hold only one data type.
Once you declare variables, the variables always retain their original declared data type. 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 data type conversions are common and they typically do not 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 data type and also assigns a name to the variable.
Chapter 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 data types that you learned about in Table 5.1.
WARNING: Never declare two variables with the same name in the same location. That is, you cannot declare two variables with the name intNumber in the same event procedure.
The location of the Dim determines how you use the variable. If you include a special statement called the Option Explicit statement at the very top of a form module or at the top of a standard module (in a section called the general section that appears before all event procedures), you must declare all variables before you use them. Without Option Explicit, you can begin using a variable name without declaring the variable, but Visual Basic always assumes that the variable is a Variant data type. If Dim appears in an event procedure, the variable is visible (usable) only from within that event procedure and known as a local variable. If you use Dim in a module's general section, all variables in that module can access the variable (the variable is said to be global to the module). If you replace Dim with Public in a general section (the Public statement uses the same format as Dim), the variable is global to the entire module as well as every other module within the project. Standard module variables are almost always globally defined with Public so that other modules within a project you add the standard module to can access the variables. Generally, local variables are better than global with a few exceptions (this guide points out these exceptions at the appropriate times).
New Term: Global variables are variables that are available to the entire module or to the entire application.
New Term: 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 data type and that the variable's name is curProductTotal. Programmers often prefix variable names with a three-letter abbreviation that indicates the variable's data type, but such a prefix is not 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 data type. 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 data types.
|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 will 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 in strFirstName--such as "Joe"--and then a longer string in strFirstName--such as "Mercedes". 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 will 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:
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 is not 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 variables of the same data type 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
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. Variables hold data of specific data types and many lines inside a Visual Basic program consist of assignment statements that assign data to variables. Here is the format of the assignment statement:
VarName = Expression
New Term: 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 data type of Expression must match the data type 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 is 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 data type. 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.
New Term: Constant is another name for literal.
In addition to constants, you can assign other variables 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).
Private Sub cmdPress_Click () cmdPress.Caption = "Brush your teeth daily!" 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!.
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. For example, 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.
You should learn Visual Basic's math operators so you can calculate and assign expression results to variables when you code assignment statements that contain expressions. An operator is a symbol or word that does math and data manipulation.
Table 5.4 describes Visual Basic's primary math operators. Other operators exist, but the ones in Table 5.4 suffice for most of the programs that you write. Look over the operators. You are already familiar with most of them because they look and act just like their real-world counterparts.
Table 5.4. The primary math operators.
|+||Net + Disc||Adds two values|
|-||Price - 4.00||Subtracts one value from another value|
|*||Total * Fact||Multiplies two values|
|/||Tax / Adjust||Divides one value by another value|
|^||Adjust ^ 3||Raises a value to a power|
|& (or +)||Name1 & Name2||Concatenates two strings|
Suppose that you wanted to store the difference between the annual sales (stored in a variable named curAnnualSales) and cost of sales (stored in a variable named curCostOfSales) in a variable named curNetSales. Assuming that all three variables have been defined and initialized, the following assignment statement computes the correct value for curNetSales:
curNetSales = curAnnualSales - curCostOfSales
This assignment tells Visual Basic to compute the value of the expression and to store the result in the variable named curNetSales. Of course, you can store the results of this expression in a control's Caption or Text properties, too.
If you want to raise a value by a power--which means to multiply the value by itself a certain number of times--you can do so. The following code assigns 10000 to lngValue because 10 raised to the fourth power (10 times 10 times 10 times 10) is 10,000:
lngYears = 4 lngValue = 10 ^ intYears
No matter how complex the expression is, Visual Basic computes the entire result before it stores that result in the variable at the left of the equal sign. The following assignment statement, for example, is rather lengthy, but Visual Basic computes the result and stores the value in the variable named sngAns:
sngAns = 8 * sngFactor - sngPi + 12 * sngMonthlyAmts
Combining expressions often produces unintended results because Visual Basic computes mathematical results in a predetermined order. Visual Basic always calculates exponentiation first if one or more ^ operators appear in the expression. Visual Basic then computes all multiplication and division--working from left to right--before any addition and subtraction.
Visual Basic assigns 13 to intResult in the following assignment:
intResult = 3 + 5 * 2
At first, you might think that Visual Basic would assign 16 to intResult because 3 + 5 is 8 and 8 * 2 is 16. However, the rules state that Visual Basic always computes multiplication--and division if division exists in the expression--before addition. Therefore, Visual Basic first computes the value of 5 * 2, or 10, and next adds 3 to 10 to get 13. Only then does it assign the 13 to Result.
If both multiplication and division appear in the same expression, Visual Basic calculates the intermediate results from left to right. For example, Visual Basic assigns 20 to the following expression:
intResult = 8 / 2 + 4 + 3 * 4
Visual Basic computes the division first because the division appears to the left of the multiplication. If the multiplication appeared to the left of the division, Visual Basic would have multiplied first. After Visual Basic calculates the intermediate answers for the division and the multiplication, it performs the addition and stores the final answer of 20 in intResult.
NOTE: The order of computation has many names. Programmers usually use one of these terms: order of operators, operator precedence, or math hierarchy.
It is possible to override the operator precedence by using parentheses. Visual Basic always computes the values inside any pair of parentheses before anything else in the expression, even if it means ignoring operator precedence. The following assignment statement stores 16 in intResult because the parentheses force Visual Basic to compute the addition before the multiplication:
intResult = (3 + 5) * 2
TIP: Appendix A, "Operator Precedence," contains the complete Visual Basic operator precedence table. The table contains several operators that you have yet to learn about, so you might not understand the full table at this time.
The following expression stores the fifth root of 125 in the variable named sngRoot5:
sngRoot5 = 125 ^ (1/5)
As you can see from this expression, Visual Basic supports fractional exponents.
New Term: To concatenate means to merge two strings together.
One of Visual Basic's primary operators has nothing to do with math. The concatenation operator joins one string to the end of another. Suppose that the user entered his first name in a Label control named lblFirst and his last name in a Label control named lblLast. The following concatenation expression stores the full name in the String variable named strFullName:
strFullName = lblFirst & lblLast
There is a problem here, though, that might not be readily apparent--there is no space between the two names. The & operator does not automatically insert a space because you don't always want spaces inserted when you concatenate two strings. Therefore, you might have to concatenate a third string between the other two, as in
strFullName = lblFirst & " " & lblLast
Visual Basic actually supports a synonym operator, the plus sign (+), for concatenation. In other words, the following assignment statement is identical to the previous one (although the ampersand [&] keeps ambiguity down because of the plus sign's double usage with numbers and strings):
strFullName = lblFirst + " " + lblLast
Use the ampersand for string concatenation even though the plus sign works also. The ampersand is less ambiguous and makes for better programs.
NOTE: Remember that you'll use the Code window to enter code such as that which you see in this lesson. The Code window appears when you select View|Code or when you double-click a control to open its event procedure as you saw in Hour 3, "Controls and Properties."
In this lesson you have learned how to recognize and use Visual Basic data. Visual Basic supports 14 data types, and you must know how to specify literals and declare variables that take on those data types. Once you know the data types and variables, you can perform calculations that assign the results of expressions to variables and controls.
The next hour adds to your programming power by explaining a quick and simple way to display information and receive user input.
The quiz questions and exercises are provided for your further understanding. See Appendix C, "Answers," for answers.
12Months a 85 "curSalesForecast" Acctg98