Visual Basic Programming 1

Visual Basic Programming 1 Starting Visual Basic 1. Normally, you will have created a shortcut on your desktop to access Visual Basic. If not, access...
Author: Charleen Logan
5 downloads 3 Views 2MB Size
Visual Basic Programming 1

Starting Visual Basic 1. Normally, you will have created a shortcut on your desktop to access Visual Basic. If not, access it by using the Start – Programs – Microsoft Visual Basic series of clicks. 2. Upon opening the software, you will see the New Project window. To open a new project, left click the New tab and choose the Standard EXE option. To open an existing project, left click on the Existing tab and browse to choose the project from its storage location (hard drive, diskette, etc.). 3. Left Click the Open button.

Existing Tab New Tab Standard EXE option

Open button

3. At this point, the project design window will become visible with the first form already visible.

Visual Basic Programming 2

Project Name

Standard Toolbar

Form Name

Menu Bar

Project Explorer Window

Form Window Properties Window Toolbox Window

Project Container Window

Property Description Window

Form Layout Window

Standard Toolbar Add a Project

Save a Project

Add a Form

Open a Project Menu Editor

Break Program

Paste

Highlight Project Explorer, Properties, Form Layout, Object Browser, and Toolbox, respectively

Stop Program Start Program

Toolbox

Visual Basic Programming 3

Pointer

Picture Box

Label

Text Box

Frame

Command Button

Checkbox

Option Button

Combo Box

List Box

H.Scroll Bar

V.Scroll Bar

Timer

Drive List Box

Dir. List Box

File List Box

Shape

Line

Image

Data

Project Window View Object Button

View Code Button

Toggle (Show/Don‟t show) folders button Project Name and Icon Form Name and Icon

Visual Basic Programming 4

Programming Prefixes Prefix ani cbo ch3 chk clp cm3 cmd ctr dat dir dlg drv fil fr3 fra frm gpb gra grd

Control Animation button Combo box 3D Check box Check box Picture clip 3D Command button Command button Control (specific type unknown) Data Directory list box Common dialog box Drive list box File list box 3D frame Frame Form Group push button Grid

File Extensions .frm = Forms .vbp = Visual Basic Project .bas = Module

Prefix hsb img ils lbl lin lst mci mnu

Control Horizontal scroll bar Image Image list Label Line List box Multimedia MCI Menu

opt pic prg shp sli spn tlb tmr tre txt vtb

Option button Picture box Progress bar Shape Slider Spin button Toolbar Timer Tree view Text box Vertical scroll bar

Visual Basic Programming 5

Forms, Labels, Text Boxes, and Buttons The form is the vehicle in which all of the tools (Labels, Text Boxes, and Buttons) reside. It is the master container for a portion of an application and is the application‟s interface with the user.

Setting the Form’s Name and Caption Properties Example: We will build a form in which the user will be allowed to enter his/her name in a text box. We will call this program MyName. 1. Open Visual Basic and choose New – Standard EXE application. 2. Name the form by Left Clicking and dragging in the data side (the right side) of the Name property in the Property Window to highlight the default entry. Using the “frm” prefix, name the form “frmName” by typing it in this area 3. Change the caption property to reflect the name “MyName”

Caption appears at the top of the form.

Left click and drag to highlight the right side of the Name property and type frmName

Change the Caption property to MyName. (Notice it appears at the top of the form.)

Visual Basic Programming 6

Adding a Label to the Form 1. Add a label to the form by Left Clicking on the Label tool Place the mouse pointer on the form in the location where you would like to place the upper left hand corner of the label Left Click and drag the label onto the form 2. Change the label‟s Name property to “lblMessage” 3. Change the label‟s Caption property to “Please type your name” Notice how this caption appears inside the label 4. Change the label‟s visible property to False. (This will cause the label to disappear.)

Caption appears in the label Change the Name option

Change the Caption option

Note: Any tool or object inserted in a form can be moved by dragging it anywhere on the form. Also, any object can also be resized by dragging on an edit handle in a highlighted object just as an object in a Word Document or Excel spreadsheet.

Visual Basic Programming 7

Adding a Text Box to the Form 1. 2. 3. 4.

Left Click the Text Box tool in the tool window Drag a text box near the bottom of the form Change the Name property of the text box to “txtName” Change the Text property of the text box to a blank (Note that you will have to scroll down in the properties window to see the text property. Left click and drag over the default text entry Press the backspace key or the delete key on the keyboard to remove the default text

New name appears in the title window Text box tool

No text in the text box

Delete the default text property to make the text box blank

Visual Basic Programming 8

Adding Command Buttons to the Form 1. Left Click the Command Button tool in the tools window and drag two buttons on the form. 2. Change the name properties of these buttons to “cmdOK” and “cmdCancel”. 3. Change the caption properties of these buttons to “OK” and “Cancel” respectively.

OK and Cancel command buttons

Visual Basic Programming 9

Adding Code to Objects We want our program to do the following things: 1. When the user clicks anywhere on the form the label “Please type your name” should appear. 2. The user should then type his/her name in the text box. 3. The user should then click the OK button and the message “Hello _____” should appear in the text box with the name the user typed inserted in the line. 4. The user can then click on the Cancel button to leave the program. Follow these steps to create the application code:

Make the lblMessage Label Visible When the Form is Clicked 1. Left click on the View Code button located at the top of the project window. 2. When the Program Code view appears, click on the down arrow next to the Object window. (Will probably have the word General there.) 3. When the drop-down menu appears, choose the Form object.

Object Window

4. Click on the down arrow next to the Procedure window and choose the Click procedure.

Procedure Window

Visual Basic Programming 10

5. When the procedure code for Private Sub Form_Click( ) appears, left click below this line and indent (space) a couple of spaces and type the text “lblMessage.” 6. As soon as you type the period (.), a drop-down menu of properties will appear. Scroll to the Visible property and double click to place this property in the code you are typing.

Drop-down list of values

7. After the Visible property is added to the code, type an equal sign (=). Immediately, a drop-down list of available values (True or False) appears. Double click on True to make the text “Please type your name.” appear when the form is clicked on at run time.

Completed Code

Visual Basic Programming 11

Code the OK Button to Show the Desired Message in txtName Text Box 1. In the Program Code view, choose the OK command button (cmdOK) from the Object Window list. 2. Choose the Click procedure from the Procedure drop-down list. 3. The Private sub cmdOK_Click( ) procedure is now ready to code.

4. Type the following code inside the procedure : txtName.text = “Hello “ & txtName.txt

Code Hints: “ “ = Whatever is placed inside of quotation marks will be printed & = Will append a string to another string 5. The code is saying “the Text property of the txtName text box is equal to the string “Hello “ and its current text.” 6. Run the application by clicking the Run button 7. Exit the application by clicking the close button X in the application window.

Visual Basic Programming 12

An Alternate Method

1. Inside the Private sub cmdOK_Click( ) procedure, place the following code: Dim strName As String 1. Define the variable strName as a string 2.

strName = "Hello " & txtName.Text txtName.Text = strName

3.

Assign it the value of the contents of txtName preceded by the string “Hello “ Reassign the contents of txtName the value of strName

Code Hints: To declare a variable (such as strName), the syntax is as follows: Dim As Prefixes: Data Prefix Example Type Boolean bln blnBooleanVariable Byte byt bytVar Collection object col colThisObject Currency cur curMyCost Date(Time) dtm dtmBirthDate Double dbl dblThisVar Error err errThis Err Integer int intCounter Long lng lngThisVar Object obj objCircleOne Single sng sngThisVar String str strNameOne User-defined type udt udtMyUDT Variant vnt vntThisVar Example: To declare an integer variable Dim intCounter as Integer To declare a single precision variable Dim sngValOne as Single

Visual Basic Programming 13

Code the Cancel Button to Close the Application 1. In the Program Code view, choose the down arrow in the Objects window. 2. Left Click the cmdCancel object. 3. The Click procedure should appear by default. If not, click the down arrow and choose Click. 4. Insert the code “Unload Me” in the procedure‟s code section. Note: The automatic help guide appears telling you to enter an object after the word “Unload”. The word “Me” refers to the form currently active.

5. Now, when the application is run, it will end by either of two actions: Left Click the Close Window button at the top right corner of the form Left Click the Cancel button

Saving a Project 1. When saving a project (program) for the first time, you will be prompted to name both the project and the form. 2. Name the form the same name as that used in the Name property and use a recognizable name for the project First click the File menu option

Second, choose either the Save Project option (if saving to the default location) or Save Project As (if saving to a different location such as the diskette).

Visual Basic Programming 14

Exercise 1 1. Create an application that does the following things: Have the user enter two numbers in two separate text boxes If the user clicks on an Add button, the sum of these two numbers will be displayed in another text box labeled Result If the user clicks on a Mult button, the product of these two numbers will be displayed in the Result window If the user clicks on the Done button, the application will end Note: The following parameters should be included: 1. Both the Add and Mult buttons should be coded, including single precision numeric variables, to complete the calculation required and place the result in the Result text box. (Hint: Don‟t forget that since the contents of a text box are considered to be text, it will be necessary to use the Val function [from BASIC] to change these contents to numeric values.) 2. All buttons as well as the Result label should be set to size 14 – bold font and the “Please enter _ number” labels should be set for size 12 – bold font. 3. Follow all good programming conventions discussed in class. An example of the form appears below:

An example of the results appears below:

After pressing the Add button

Visual Basic Programming 15

Using Assignment to Change Property Values In exercise #1, we have created an application to either add or multiply two numbers entered in two separate text boxes. You may want to be certain that numbers have been entered in both boxes before allowing a calculation to occur. Therefore, it may be necessary to default the Enabled property for both the add and multiply command buttons to False until both text boxes have entries. Then, when both text boxes contain entries, change the enabled property to True. (Please note that the object names referred to may not be the same as yours, but they will be easy enough to discern). 1. In the project's View Object view, choose the Add command button (cmdAdd) and change its Enabled property to False. 2. Do the same for the cmdMult command button. 3. This will ensure that both buttons will not be enabled at the project's load time.

4. Return to the Code View and choose the txtNum1 text box object. 5. Choose the Change event and add the following code: Private Sub txtNum1_Change() Note that here, we are checking the If txtNum2.Text "" Then contents of the txtNum2 text box. cmdAdd.Enabled = True cmdMult.Enabled = True End If End Sub 6. Do the same with the Change event for the txtNum2 object Private Sub txtNum2_Change() Note that here, we are checking the If txtNum1.Text "" Then contents of the txtNum1 text box. cmdAdd.Enabled = True cmdMult.Enabled = True End If End Sub

Visual Basic Programming 16

7. The completed code appears below. Note that, every time the text property in either text box is changed, the other box is checked to be sure that it has an entry in it before the command buttons are enabled to do the calculations.

8. When this application is loaded, both command buttons are not enabled. But if one of the text boxes is changed by highlighting its contents and deleting it, the buttons remain enabled because we are only checking the contents of the other text box, not the selected one. (Try this by running your application. You could click a calculation button without re-entering a value in the text box.) Therefor, we need to also check the contents of the text box in which the editing is taking place. 9. Change the code to appear as it does below.

10. Now, any time one of the text boxes is changed, both command buttons are disabled and both text boxes are checked for contents. 11. It is now impossible to perform a calculation with one of the text boxes being empty.

Visual Basic Programming 17

Including Image Objects In our example, we will add a picture between the two text boxes holding the numbers we have entered. If we choose to add, we will display a plus sign between the numbers. If we choose to multiply, we will show a multiplication sign between the two numbers. These pictures can be created using Microsoft Paint and saving each (to your diskette or personal folder) as a bitmap image. We will call the addition sign Plus.Bmp and we will call the multiplication sign Mult.Bmp. After creating and saving these pictures, begin the following procedure. 1. Choose the Image object from the toolbar. 2. Drag a box to the appropriate size and place it between the text boxes. 3. Name the image imgPlus in the properties window.

New Image Object

Name the image

Image Object

4. Change the Visible property for the image to False so it will not appear when the form is loaded.

Visual Basic Programming 18

5. Set the Stretch property for the image to True. This will ensure that the image loaded into the image object will be sized to fit the size of the image object. If this property were set to false, the image may be cut off if the image object were sized too small.

6. Set the Picture property for the image box by  Left clicking in the right side of the Picture property row.  Left clicking on the three-dot button that appears.



Choose the Plus.Bmp file from the resulting window.

7. After all this is done, create the imgMult image object and place it directly over top of the imgPlus image object. 8. Set the properties exactly as those of the imgPlus image object with the exception of the Picture property. (Choose the Mult.Bmp file instead.)

Visual Basic Programming 19

9. Add the following code to the cmdAdd button click event. This code will cause the multiplication sign, if it is visible, to be removed and the plus sign to become visible.

Programming Hint: Note the remarks added to the right of the code. These remarks can be added by preceding each remark with an apostrophe ( ' ). 10. Do the same thing with the cmdMult command button's click event.

11. Add the following code to both the txtNum1 and the txtNum2 text box change event to remove either sign if any changes are made to the numbers entered.

Visual Basic Programming 20

Review Object Form

Procedure Load Click

Property

Name Caption Command Button

Click Name Caption Enabled Font Visible

Label

Click Change Name Caption Enabled Visible

Text Box

Change Click Name Alignment Enabled Text Visible

Image Box

Click Name Enabled Picture Stretch Visible

Effect Code takes effect when the form is loaded Code executes when form is clicked on Name of the form – frm---Title in upper left corner of form Code executes when button is clicked Name of command button – cmd---Text that appears on the face of the button Is button available ? True / False Size and style of the caption text Is button visible when the form loads? True / False Code executes when the label is clicked on Code executes when the text of the label is changed Name of the label – lbl----Text within the label Is label dark (True) or “gray out”(False) ? Is label visible? True / False Code executes when contents is changed Code executes when text box is clicked Name of the text box – txt----Position of text – Left, Right, or Centered Is text box dark (True) or gray (False)? Text contents of the text box Is text box visible at run time? True / False Code executes when clicked on Name of the image box – img--Is box dark (True) or gray (False)? Picture file to appear in the image box Does image shrink or expand to fit the size of the image box? True / False Is the box visible at run time? True / False

Visual Basic Programming 21

Exercises 1. Create an application that will print your first name, middle name, and last name in separate text boxes, depending upon which text box you click on.

2. Create an application that does the following things: Enter two numbers Provide command buttons to add the numbers, subtract the second number from the first number, multiply the numbers, divide the second number into the first number Provide a text box to display the result Provide a “Done” command button to exit the application

3. Create an application that does the following Provide a command button labeled “Hello” Provide a command button labeled “Goodbye” When the “Hello” command button is clicked, have a smiley face (You may have to create it in MS Paint.) appear and the word “Hello!” appear in a text box on the form When the “Goodbye” command button is clicked, have a frowning face appear on the form and the word “Goodbye!” appear in the text box created above

4. Create an application that does the following Create three text boxes with three different questions Create three “answer” text boxes (one for each question) Provide an “Answer” command button Show the question in a given text box only when it is clicked on Show the answer in its answer text box when the “answer” command button is clicked

Visual Basic Programming 22

Variable Assignments When creating applications, you will want to manipulate numeric values and store them in variables. Variables must be dimensioned when created. That is, they must be assigned a type as well as a name (See page 12 for naming conventions.). 1. At the beginning of the object‟s event code, type the word Dim to start dimensioning a variable. 2. Next, name the variable according to its correct prefix (i.e. a string variable should start with the str prefix and an integer variable should start with a int prefix.). 3. Then, add the name. 4. Next, type the word as. 5. Finally, enter the type of variable you are creating. Example: To create an integer variable named Num1, you would type the following code – Dim intNum1 as Integer 6. The variable is now ready to receive an integer value within the code. 7. The variable is only recognizable within the subroutine in which it was created. 8. The same variable can be created within a different subroutine without values crossing over between the subroutines. 9. Variables can be used before being created, but their values at that point are equal to zero. In order to not allow a variable to be used before it is dimensioned, add the Option Explicit command to the general section of the form module. Choose the General object from the drop down list Type the Option Explicit command General object chosen

Example Returning to our “Addition and Multiplication” exercise, let‟s assign the values found in the two text boxes to variables and then, perform the calculation requested. 1. Add the Option Explicit statement to the General portion of the module. (See above)

Visual Basic Programming 23

2. Change the code for the cmdAdd button‟s click action to the following: Private Sub cmdAdd_Click() Dim intNum1 As Integer ' Dimension the intNum1 variable imgPlus.Visible = True imgMult.Visible = False If txtNum1.Text "" And txtNum2.Text "" Then intNum1 = Val(txtNum1.Text) + Val(txtNum2.Text) txtResult.Text = intNum1 End If End Sub 3. Make a similar change to the cmdMult command button „s click action. (See below) Private Sub cmdMult_Click() Dim intNum1 As Integer imgPlus.Visible = True imgMult.Visible = False If txtNum1.Text "" And txtNum2.Text "" Then intNum1 = Val(txtNum1) * Val(txtNum2) txtResult.Text = intNum1 Note the change to a End If multiplication sign End Sub 4. Notice that, in both the cmdAdd and cmdMult click events, we used the same variable (intNum1). Because dimensioned variables are local to the event in which they are created, this will cause no problem.

Visual Basic Programming 24

Debugging Using the Immediate Window As an application is developed, the results of calculations or assignments may not be exactly what the programmer had in mind. In these cases, it is important for the programmer to be able to view the results of calculations or assignments as they are executed within the code. that is the purpose of the Immediate Window. 1. To make the immediate window visible, either press Ctrl + G on the keyboard simultaneously, or click on View from the main menu and choose Immediate Window from the drop down list.

2.

The Immediate Window will now appear on the Visual Basic Programming Screen

Immediate Window

Visual Basic Programming 25

3. In order to use the immediate window, the term Debug.Print must be inserted next to the result that it is desired to view. Example: In our addition / multiplication application, if we wanted to view the calculation as it occurs in the code for the cmdAdd and cmdMult buttons, we would add the following code to these events.

The Debug.Print code is followed by a descriptive string (optional) to differentiate between the addition and multiplication calculations. Next, is a semicolon ( ; ), followed by the variable representing the result of the calculation.

4. When the application is run, any time the code inside the cmdAdd or cmdMult click events is run, the result of the calculation being performed along with its text description will appear in the Immediate Window. 5. If we run the application and click the Add button followed by the Multiply button, the results will appear as depicted on the next page.

Visual Basic Programming 26

First, the Add button is clicked

Results in the Immediate Window

Then, the Multiply button is clicked

Results in the Immediate Window

Visual Basic Programming 27

Data Types Visual Basic includes many built-in data types. A listing of these data types and a brief explanation of each appears below. Data Type Will Represent Single Numbers with a value up to 3.438 that could contain a decimal point Double Numbers with a value up to 1.8308 that could contain a decimal point Integer Whole numbers up to 32,767 Long Whole numbers greater than 32,767 Currency Numbers that represent money String A group of characters Boolean Only two valid values … True or False The value limits discussed in the table above extend an equal distance to the negative If a decimal value is assigned to an integer or long data type, the value is rounded to the nearest integer. In order to assign a string literal to a string variable, it must be enclosed in quotes.

Data Type Naming Conventions A table of prefixes for all data types is presented on page 12. Proper programming style dictates the use of these prefixes.

Multiple Variable Declarations More than one variable can be assigned with one DIM statement. Since the DIM statement is used to assign variable type as well, all variables in a single DIM statement must be of the same type. Example To assign variables X and Y to be integers, the DIM statement would look like the one appearing below. DIM intX, intY as Integer

Option Explicit This command causes the program to generate an error message if a variable is used without first being dimensioned. If option explicit is not used, a variable referenced inside a program is assigned a value of zero. Place it in the General section of the Form module

Visual Basic Programming 28

To make it mandatory that all variables throughout the project must be dimensioned before being used, set this option as follows: Choose the Options item from the Tools menu

Then, place a check in the Require Variable Declaration option

Require Variable Declaration Option

Then, click OK

Automatic Type Conversion If an Integer variable is assigned a value with a decimal point, the value is automatically rounded to the nearest integer. If a text box contains a number for its text and that number is used in a calculation, Visual Basic will automatically change the text version of the number to a numeric value.

Visual Basic Programming 29

Modulus Division Modulus Division returns the remainder of a division. Suppose we want to find out if 273 is divisible by 3. We perform modulus division (273 mod 3) If the result is equal to zero, then we know that there is no remainder from that division. Hence, 273 is divisible by 3. The code may look like the following: intremainder = 273 mod 3 If intremainder = 0 then txtResult.text = “273 is divisible by 3” Endif

Option Buttons Option buttons (or Radio buttons) are designed to provide a group of possible responses from the user, only one of which is permitted at a time. For instance, suppose we want the user to decide whether to add or multiply the two numbers in our Example 1 calculator project:

Option Button Tool Name Property Caption Property

The Caption Property assigns the text that labels the option designated by that particular option button When the program is run, the option button that is clicked will contain the highlight and any other option button that was formerly highlighted will lose the highlight. After setting the code as it appears below, the application will display either the sum or product of the two numbers, depending upon which control button is highlighted.

Visual Basic Programming 30

Option Explicit

Private Sub optAdd_Click() txtAnswer.Text = Val(txtFirst.Text) + Val(txtSecond.Text) End Sub Private Sub optMult_Click() txtAnswer.Text = Val(txtFirst.Text) * Val(txtSecond.Text) End Sub Private Sub txtFirst_Change() optAdd.Enabled = False optMult.Enabled = False If txtFirst.Text "" And txtSecond.Text "" Then optAdd.Enabled = True optMult.Enabled = True End If End Sub Private Sub txtSecond_Change() optAdd.Enabled = False optMult.Enabled = False If txtFirst.Text "" And txtSecond.Text "" Then optAdd.Enabled = True optMult.Enabled = True End If End Sub The application will appear as below:

The Value property can be set to true (chosen) or false (not chosen) The Alignment property can be set to left or right to align the caption on that side of the option button.

Visual Basic Programming 31

Frames Frames are used to group option buttons related to the same choice. The application appears below complete with a frame around the option buttons.

Frame Tool

Caption Property

C

The Caption Property assigns the text to appear at the top of the frame. In this case, the caption is “Choose an Operation”.

Constants Values that will not change can be assigned so that they can be used without constantly having to write the value. For instance, if we wanted to use the value of Pi as 3.14, we could assign this value to a constant (PI for example) and use it instead. The code would look like that below: Const dblPi As Double = 3.14 Now, whenever the value for Pi is used, we need not type 3.14, we simply need to use dblPi.

Visual Basic Programming 32

If … Then Statements The If … Then statement is used when a condition must be tested in order to either execute or skip a section of code. For instance, suppose the value of the variable intX must be greater than 10 in order to place the text “Greater Than 10” in the “txtResponse” text box. The code would appear as below: If intX > 10 Then txtResponse.Text = “Greater Than 10” End If Note the following aspects of the statement: The If … Then statement is always ended with the End If section. The condition tested must be between the If and the Then portion of the statement. If the condition is True, the code between the If and the End If portion of the statement will be executed. If the condition is False, the code between the If and the End If portion of the statement will not be executed.

Boolean Relational Operators Operator = < >=

Meaning

Equal to Less than Less than or Equal to Greater than Greater than or Equal to Not equal to

Roundoff Errors Care must be taken when testing equalities involving floating point numbers because the rounding of these numbers. For instance, rounding off .8 results in a binary form of 0.1100110011 … . Since this number never reaches an end, it must be rounded and will, therefore not be equal to any finite number unless this math has been done and that particular number has been used to conduct the test in the IF portion.

If … Then… Else Statements The “Else” portion of this statement provides a logical alternative to the condition in the “If” statement, other than simply moving on to the next area of the code. Simply stated, if the If criteria is true, the Then portion of the statement will execute. Otherwise, the Else portion will execute. As with all “If … Then” statements, it is good programming style to indent the code inside of the If, Then, and Else portions of the code.

Visual Basic Programming 33

Nested If … Then … Else Loops Additional criteria can be included within a given loop using the Else … If option. For instance, suppose we wanted to do the following: 1. Have the user place a number in a text box 2. Have a different label appear saying “Large” if the number is greater than 75, “Medium” if the number is greater than 25 and less than 76, or “Small” if the number is 25 or less. 3. The above would occur after a command button was clicked

4. We use an “If … Then … Else” statement in the text box‟s change procedure to either enable or disable the “Calculate” button: If txtNumber.Text “” Then cmdCalculate.Enabled = True Else cmdCalculate.Enabled = False End If 5. Then, in the cmdCommand button‟s click procedure, we need to use nested “If … Then … Else” statements to decide which label (Small, Medium, or Large) should appear: Private Sub cmdCalculate_Click() If txtNumber.Text > 75 Then lblSmall.Visible = False lblMedium.Visible = False lblLarge.Visible = True Else If txtNumber.Text > 25 Then lblSmall.Visible = False lblMedium.Visible = True lblLarge.Visible = False Else lblSmall.Visible = True lblMedium.Visible = False lblMedium.Visible = False End If End If End Sub

Main Nested If/Then

If/Then

Visual Basic Programming 34

If … Then … ElseIf This option is usually used to decide between three or more options. It eliminates the creation of many separate nested If/Then loops. Changing the application referred to previously, the code would appear as below: Private Sub cmdCalculate_Click() If txtNumber.Text > 75 Then lblSmall.Visible = False lblMedium.Visible = False lblLarge.Visible = True ElseIf txtNumber.Text > 25 Then lblSmall.Visible = False lblMedium.Visible = True lblLarge.Visible = False Last option usually only needs “Else” Else lblSmall.Visible = True lblMedium.Visible = False lblLarge.Visible = False End If End Sub

Only one If/Then statement needed

Generating Random Numbers Random numbers are extremely useful when designing games or computerized study programs. The random number generator function is called Rnd. It will generate a random number within the range 0 through 1 In order to generate numbers within a range of integers, use the following formula: (High number – Low number + 1) * Rnd + Low number For instance, to generate a random number between 5 and 10, the formula would be (10 –5 +1) * Rnd + 5 = 6 * Rnd + 5 The random numbers generated by the formula above will be real numbers and not necessarily integers To be certain that the numbers generated are integers, utilize the Int or Fix functions.

Int Function The Int function returns an integer less than or equal to its argument. The integer returned by Int(3.7) is 3 The integer returned by Int(-15.23) is –16

Fix Function The Fix function will truncate or cut off the numbers to the right of the decimal point The integer returned by Fix(3.7) is 3 The integer returned by Fix(-15.23) is –15

Visual Basic Programming 35

Randomize Random numbers are generated by seeding the generator with the time from the system clock in the computer. Running a program to randomly generate numbers will generate the same random numbers each time until the generator is re-seeded. The Randomize command should be placed in the Form_Load procedure of the form in which the generator is run. In this way, new numbers will be generated each time the form is loaded.

Scope When a variable is created within a procedure, it is said to be “local” to that procedure. That is, it cannot be accessed by any other procedure outside of the one in which it was created. The same is true for constants. These are known as local declarations. Therefore, the scope of the particular variable or constant is the procedure in which it has been declared. Since the scope is local, another procedure within the same form module can use the exact same variable or constant without any problems. If, on the other hand, the programmer wishes a variable or constant to be recognized throughout the entire form module, it can be declared as a global declaration. Global variables and constants are declared in the general section of the form module. They are declared in the same way as any other variable or constant except that the key word Private should be used instead of dim when declaring a variable. In the case of a constant, the key word Private should be used before the keyword Const. It is always best to avoid using global declarations and stick with local ones. This is because the programmer runs the risk of using a global variable locally. Dimensioning a local variable that is the same as a global variable will change the value of the variable or constant within that procedure. The following code shows how to declare a global variable and constant

Visual Basic Programming 36

The application will execute as follows:

When the Global button is clicked

When the Local button is clicked

Logical Operators Logical operators are the boolean operators And; Or; Not. They return a value of either True or False. Example If we wanted to enable a command button called cmdCalculate if and only if the number entered in text box txtNumber is within the range 10 through 30 If Val(txtNumber.Text) > 9 AND Val(txtNumber.Text) < 31 Then cmdCalculate.Enabled = True End if Operator And Or Not

Function All conditions must be true in order for the expression to be true Any condition can be true in order for the expression to be true The opposite must be true in order for the expression to be true

Logical operators are most often used in If … Then statements

Message Box Message boxes provide information to the user as to what he/she may have done wrong while running an application. They require the user to click an OK button in order to continue. For example, the following code:

Visual Basic Programming 37

Will result in the following application when the number is out of range

Password Applications To password protect your application, you need to make the first form of the application a password form. It must be coded so that, if the password entered is correct, the next form will appear and the password form is unloaded. For example the following code

Results in the following application if the password is incorrect Note the asterisks as the user types the password. This is done by setting the password textbox PasswordChar property to “*”. Any other character could be used as well.

Visual Basic Programming 38

Or the following application if the password is correct

Counters Counters keep track of the number of times an action takes place. For instance, you may only want to give a user three chances to correctly enter the correct password and then unload the application. An example of this appears below. Variables are updated by placing them on both sides of the equal sign (=) and adding or subtracting some value from the right side. ( For example : intX = intX + 1) It is important to remember that, if a variable is to be updated in more than one procedure within the module, it must be declared as a global variable. Also, if the variable‟s value is used throughout the entire module and it is dimensioned locally, every time the local procedure is executed the variable is re-dimensioned which will set its value back to zero. Global counter variable declaration

Increment the counter variable each time the user enters the wrong password. Then, check how many incorrect entries were made.

Visual Basic Programming 39

Check Boxes Check boxes work exactly the same way as option buttons except for the fact that more than one can be checked at a time. The important properties are: Property Definition Options Name The name by which it is called Use the “chk” prefix Caption The label next to the individual box Up to the user Value Its possible settings Set to either checked, unchecked, or grayed during design. Changed to vbChecked, vbUnchecked, or vbGrayed during runtime. Alignment Where the box is with respect to the Left or right of the caption caption The Click event is usually coded for each box.

For example, if we wanted a caption to be any combination of bold, underlined, or italics, we would use the following application:

Here are some of the various results

Visual Basic Programming 40

Printing a Form Objects have properties and methods. One such method is the PrintForm method which allows a form to be printed by the printer. Using dot notation, the syntax for this method is .PrintForm. In our example, by adding a print button called cmdPrint, and adding the following code, we can print the form at the printer. Note the reference to the current form as “me”. This is the easiest way to refer to a current form. Alternatively, we could have said “frmStyles.PrintForm” since frmStyles is the name of the form to print.

Visual Basic Programming 41

Do Loops Do loops execute instructions repeatedly while a given set of criteria is true. The criteria are acted upon inside the loop so that, eventually, it becomes false. At that time, control of the code passes from the loop and continues with the code immediately following it.

Do – Loop While This loop will execute at least one time. When the end of the loop is reached (Loop While) the criteria are analyzed and the decision is made whether or not to execute the code within the loop again. For example, the following loop will continue adding one to the value of the text box txtNum until the total exceeds 25. Then, the label lblGotIt will appear. intTotal = Val(txtNum.Text) The loop begins Do at the Do statement

intTotal = intTotal + 1 Loop While intTotal 8192 intWidth = InputBox("Enter a width 1 - 8192", "Enter Width") Loop shpShape1.BorderWidth = intWidth End Sub Depending upon the command button that is clicked, the shape will be either a rectangle, square, circle, or oval. When the Border Width button is clicked an input box allows the user to choose a border width (see above). Option buttons are provided to choose fill colors for the object (remember that the FillColor property will be ignored unless the FillStyle property is set to something other than the default transparent). The Border Style option buttons allow the user to choose a value for the BorderStyle property. Note that any style other than solid will not work if the BorderWidth property is set to anything other than 1.

Visual Basic Programming 90

The Fill Styles option buttons allow the user to choose a value for the FillStyle property. When this property is set to transparent, the FillColor property is ignored. The Border Color frame contains option buttons to choose a value for the BorderColor property. Below is a sample of how the code may appear: Chooses a shape

Uses Visual Basic constant to choose a value for FillColor Uses the RGB function to choose a value for BorderColor

Picture Boxes With a picture box, you can place graphics and images into your application. Unlike the image object, the picture box can accommodate either an image or a graphic. The picture box demands more system resources because it is more versatile.

Picture Property This property assigns an image or graphic file to the picture box. It can be assigned using the picture property in the properties window at design time. It can also be assigned at run-time using the following procedure: Suppose we create a simple drawing and save it to a diskette as “SMILEY.BMP”. This image was created as a 256-color bitmap image using Microsoft Paint.

Visual Basic Programming 91

To insert this drawing into a picture box at design time, we use the picture property as below:

Click the triple dot button in the picture property to open the file window. Browse to find the file Click on Open At this point, the picture will appear in the picture box.

Visual Basic Programming 92

It can also be assigned at run-time as follows: picPicture1.Picture = LoadPicture(“A:\Smiley.BMP”)

BorderStyle Property This property has two options at design time, Fixed Single, or None. Fixed single provides a somewhat indented appearance as in the picture above. The “None” option creates a flat look as below: To set the BorderStyle property at run-time, the options are 0 for “None” or 1 for “Fixed Single”. The code is picPicture1.BorderStyle = 1

AutoSize Property You will notice that the entire picture does not fit inside the picture box. If the AutoSize property is set to “True”, the picture box will expand to accommodate the entire picture. This property can be set to either True or False and can be set at design time or run-time. Below is the result of setting the property to “True”:

Visual Basic Programming 93

Moving Shapes and Picture Boxes Shapes and graphics are stored in containers. This container can be either a form or a picture box. These objects can be moved within their container. Below is a list of the location properties: Property Explanation Left Changes the distance between the left edge of the object and the left edge of the container Top Changes the distance between the top edge of the object and the top edge of the container Width Changes the width of the object Height Changes the height of the object

Twips Twips are units of measure (1 inch = 1,440 twips and 1 cm. = 567 twips) that are used in the Move Method.

Visual Basic Programming 94

Move Method The move method includes arguments to move an object left, top, width, and height in that order. Moving and object a negative value will move it toward that particular edge or decrease that particular distance. Example: We will animate the jet plane in the form below so that it flies toward the left edge of the form:

Create the picture box and, using the picture property, insert the jet plane image Change the picture box‟s BorderStyle property to “None” so it appears more seamlessly in the form Add the “Animate” command button and code it like this: By subtracting the value of intNum from the Left property, we get the effect of acceleration as the plane approaches the left margin. This is because the value of intNum increases by 5 each time through the loop. By changing the code as it appears at the left, we create a more steady movement. This is because we subtract 5 twips each time through the loop instead of increasing the value as above.

Visual Basic Programming 95

If we wanted to increase the altitude as we move toward the left, we simply add the following code to the second example above:

Graphic Methods Coordinate System Graphic images are positioned via a X and Y coordinate grid. The “X” coordinate is the distance the object is from the left margin of the container. The “Y” coordinate is the distance the object is from the top of the container.

Line Method The line method is as follows: object.Line(x1,y1)-(x2,y2),color,BF Parts of the Method Part Explanation (x1,y1) Indicates the starting point of the line in twips from the left and top (x2,y2) Indicates the stop point of the line in twips from the left and top color Indicates the color of the line with Visual Basic color constants BF “B” indicates that a box should be formed from the coordinates “F” indicates that the box should be filled in with color Example:

Note that the line starts 10 twips right of the left margin of the form and runs 1990 twips to the right. The line is positioned 500 twips from the top of the form.

Visual Basic Programming 96

Here, we draw a diagonal line. By adding the “B” option to the method, we can form a box. The “F” option will fill the box with blue color.

Note: If you would like to add one of the optional values such as a box, but would not like to designate a color, the color place must be saved using a comma. frmMethods.Line(10,500)-(2000,1500),,BF

Circle Method The Circle Method takes the form: object.Circle(x,y),radius,color,start,end,aspect ratio Part (x,y) radius color start stop aspect ratio

Circle Method Explanation The center point of the circle in twips from the left and top The size of the radius in twips Visual Basic color constant for the circle Starting point of the arc in Pi-radians (not used for complete circle) ending point of the arc in Pi-radians (not used for complete circle) Specifies a circle or ellipse

(x,y); radius; color; and aspect ratio are values. Start and stop are values within the range 0 through 2 .

Visual Basic Programming 97

Observe the code below. Each of the command buttons creates the shape above it. The circle is farthest to the left (note the “x,y” coordinates of each object). Note that Visual Basic constants or the RGB function can be used to designate color. The ellipse is created using the aspect ratio portion. An aspect ratio greater than 1 will produce a tall ellipse. An aspect ratio less than 1, will produce a flat ellipse. When drawing an arc beginning at the leftmost point of the circle and ending at the right-most point, you would use a beginning point of (3.14) and an end point of 0. / 2 (1.57)

2 (0)

(3.14) .

3 / 2 (4.71) (- /2)

Pset Method The Pset method draws a dot at the prescribed position and included a color option: Pset (2000,3000),vbGreen The code above draws a green dot 2000 twips right of the left margin and 3000 twips below the top margin of the container.

Visual Basic Programming 98

PaintPicture Method The PaintPicture method allows a picture existing in one container to be painted into another container. Below is an example where the picture in the “picPicture1” picture box is painted into the “picPicture2” picture box. Note the code below In this case, the picture placed in the picPicture1 picture box via its Picture property is painted into the picPicture2 picture box to its left. In this case, the picture is positioned 10 twips from the left margin of the picture box and 10 twips below the top margin of the picture box.

Cls Method This method clears any graphics inside a container. So to clear the picture in the “picPicture2” picture box, we would add this code to an “Erase” command button. picPicture2.Cls Note the code in the cmdErase command button. When it is clicked, it clears the picture from the picPicture2 picture box.

Visual Basic Programming 99

Container Properties Affecting Graphics AutoRedraw When set to True, the drawn object will appear in the container. When set to False, the drawn object may not appear.

DrawStyle Changes the style of the outline of the object. Constant vbSolid vbDash vbDot vbDashDot vbDashDotDot vbInvisible vbInsideSolid

Definition Solid Line Dashed Line Dotted Line Combination of dashes and dots One dash followed by two dots The line is not seen A form of double line

DrawWidth Sets the thickness of the line. The value is expressed in terms of a number ranging from 1 through 32,767. In order for the BorderStyle property to work, the DrawWidth property must be set to 1 except for solid or inside solid styles.

FillColor Changes the fill color of the object. It is assigned via the Visual Basic constants or RGB function. (Don‟t forget that the FillStyle must not be set to transparent in order for FillColor to work).

FillStyle See the previous section on graphic object FillStyle. These options are identical.

ForeColor This property changes the color of the outline for the graphic contained within the container. It can be assigned, again, using the Visual Basic constants or RGB.

Visual Basic Programming 100

Timer Object A timer object is used to execute code at specific timed intervals. It is very handy for animation effects.

Name Property The name of a timer object should begin with the prefix tmr. The Timer Object will appear on the form in design mode but will not appear at run-time.

Interval Property The amount of time that passes before the Timer event procedure is executed. It is expressed in milliseconds (1/1000 of a second). So an interval of 1 second would be expressed as 1000. The acceptable range for this property is 0 through 64,767.

Enabled Property Can be set to either True or False. When the enabled property is set to False, the timer event will not be called.

Timer Event The timer event occurs after the interval has expired. Following the event, the interval countdown begins again. Remember that the interval is set in milliseconds. Below is an example where the picture changes from a smile to a frown and vice versa every second.

The code for the above application appears on the next page.

Visual Basic Programming 101

Create a global boolean variable to track the condition of either a smile or frown Set the boolean to false when the form loads

Set up the timer object so that, if the boolean is false, clear the picture object and draw a smiling face. Then, set the boolean to true.

If the boolean is not false (therefore it is true), clear the picture object and draw a frowning face. Then, set the boolean to false. Below is the creation of the timer object. Note that the interval was set to 1000 or 1 second. Also, note that the timer object appears in design mode but not at run-time.

Visual Basic Programming 102

Moving Line Objects Line objects are created by designating their beginning (X1,Y1) and ending (X2,Y2) coordinates. Therefore, by changing these coordinates, we can move the line. Below is an example where a line was created using the line tool.

Create a global variable to keep track of the number of movements that the line will make.

When the “Enable” button is clicked, the timer object is enabled (Its enabled property was set to False at design time.) The timer object executes every ¼ second (its interval was set to 250). Each time, it moves the X1, Y1, X2, and Y2 coordinates of the line by 10 twips. It will execute 50 times since the global variable, intX is incremented by one each time the timer executes.

The timer object is disabled after 50 movements.

Visual Basic Programming 103

Animation Animation effects can be created by making alternating graphic objects‟ visible properties from true to false. Below is an example of a bouncing ball animation. The ball will appear to bounce up in the air, following the path of the picture boxes inserted in the application as it appears to the left. The code for this application appears below:

A global integer variable is created When the “Bounce” button is clicked, the timer object is enabled. The series of ball pictures were created as an array. The “picBall(0)” object visible property was set to “True” at design time. The timer interval was set to 500 (1/2 second). Every ½ second, the current picture box array‟s visible property is set to False unless it is the last picture (picBall(6)). Then, the intX variable is incremented by one and its corresponding picture array object‟s visible property is set to true, creating the illusion of a bouncing ball.

Visual Basic Programming 104

Adding Sound To add sound to an application, you will need to use the MMControl control. If this tool is not available on your toolbar, you can add it by following this procedure: Choose Project from the Menu Bar. Choose Components from the Drop-down Menu. Click on Microsoft Multimedia Control 6.0 to check it. Click on OK. The Multimedia Control should now be in your Visual Basic Toolbar.

Name Property Multimedia objects should begin with the prefix “mmc”.

Device Type This property chooses the type of device that will be needed. Below are a couple of possibilities regarding sound files: Control Name Files used WaveAudio .WAV Files CDAudio Music From CD

Enabled Property When this property is set to True, the multimedia object can play sounds. When it‟s set to False, it cannot play sounds.

FileName Property This property chooses the file to be played and can be set at design time or via dot notation at run-time.

Visible Property This property hides the object if it is set to False and allows it to be seen if it is set to True.

Visual Basic Programming 105

Using Wav Sounds You can insert files with a “.WAV” extension by using the OLE object and choosing “Wav Sound”.

As soon as the OLE object is inserted in the form, the “Insert Object” window opens and a large number of options appear. Scroll to Wave Sound Decide if you want to create the file New (microphone is required) or create it from a file. Then, click OK.

Creating the Wave File After you click OK, the sound recorder will appear. Be sure a microphone is connected to your sound card. Click the Record Button Record through the microphone Close the sound recorder When you run the application, the recording will play when the object is double clicked. Record Button

Applying the Wave Sound from a File Instead of choosing Create New, choose Create From File. At that point, a window will open allowing you to browse for the desired file.

Visual Basic Programming 106

Browse to the folder containing the sound file you want Click on the desired file Click Insert Now, when the application is run and the OLE object is double clicked, the inserted Wave file will play.

Visual Basic Programming 107

Sequential Access Files One of the advantages of using arrays to hold data for a program is that it is an extremely fast way of accessing information that the program may need. The biggest disadvantage is that, once the program is halted, all of the data in the array is lost. Thus, it is good to be able to save data permanently on disk for later access and use during subsequent application runs. This is accomplished via data files. Most data files are sequential files; that is, data is stored in order from the first item saved through the last. Access to individual pieces of data (known as records) is done by moving from record 1 through the last record, using the data in the program, and accessing the next record.

Opening a File Sequential data files can only be opened for one mode at a time. The possibilities are Input, Output, or Append. Mode Input

Output

Append

Direction Reads data into a program Writes data to a newly opened file. If this file existed before, it is deleted and a new, empty file is created Writes data to an existing file without deleting it and re-creating it. The new data is added to the existing data

Code Open for input as i.e. Open C:\Data\file1 for input as #1

Open for output as i.e. Open C:\Data\File1 for output as #1

Open for append as i.e. Open C:\Data\File1 for append as #1

FreeFile Function Since it is possible to have more than one file open at a time, it is nice to know, upon opening the next file, what the next available file number is. FreeFile returns this value. So, for example, if we already have 2 files open, (numbers 1 and 2) FreeFile will return a 3. intFNum = FreeFile Open “C:\Data\thisFile” for input as #intFNum

Visual Basic Programming 108

Reading & Writing Text from a File In order to read data from a file, it must be opened for input. Then, the Line Input command reads a complete line of text from the data file. Line Input File1 Record # 1 2 3

Text Tom Morrow Willie Makeit Betty Wont 

intF = FreeFile open “File1” for input as #intF for x = 1 to 3 Line Input #intF,strTextLine lstResult.additem strTextLine next x

  

Assigns intF the value of the next available file number Opens the “File1” file for input Reads each of the 3 lines of text into the variable strTextLine Places each line of text in the lstResult text box

lstResult Tom Morrow Willie Makeit Betty Wont

EOF Maybe you are not sure how many lines of text or records exist in the file. The EOF function returns true if there are no more lines or records in the file. Changing the code above to use the EOF function: intF = FreeFile open File1 for input as #intF Do While not(EOF(intF)) Line Input #intF,strTextLine lstResult.additem strTextLine Loop In the above example, the program will continue to read lines of text until it reaches the end of the file. Using this method substantially lessens the possibility of trying to read a line of text or a record after reaching the end of the file, which will result in an error and will stop the program.

Visual Basic Programming 109

vbCrLf There may be times where the text may not be neatly entered in separate lines. Such may be the case when pulling words out of a sentence. Instead of pressing enter, the vbCrLf function may be used to add the end of line character in a text file. In the following example, we:  Open the form with an input box to input a complete phrase  Check each character of the phrase, adding it to a long string unless the character is a space. In which case, we insert a vbCrLf  After reading through the entire phrase, we write the new string (with the vbCrLf) to a text file. We then close the file.  When we click the Generate List command button, we open the text file for input and add the entire phrase to the list box

Open “strF” for Input Place each line of text into the list box with the vbCrLf designating a new line

Open “strF” for Output and enter the text for “strPhrase”

If the character is not a space, we add it to “strWord”. If it is a space, we insert a vbCrLf into “strWord” Place the string created with the loop into the file

The resulting application appears on the next page…..

Visual Basic Programming 110

Multi-Line Text Box Above, we used a list box to show the results. A text box can also be used if its MultiLine Property is set to true. Then, if multiple lines appear, scroll bars will automatically appear. Scroll Bar Properties Scroll bar properties can be set only if the text box’s MultiLine property is set to true. At runtime, the options are: vbSBNone = Scroll bars will not appear vbHorizontal = Horizontal scroll bar will appear vbVertical = Vertical scroll bar will appear As separate lines of text are read from a text file, they can be added to the text box using the vbCrLf to start a new line Do while not EOF(1) Line Input #1,strData lstListBox.Text = lstListBox.Text & strData & vbCrLf Loop

Visual Basic Programming 111

Reading & Writing Records to a File Most times, data will need to be stored in various types such as numbers and writing it to text files won‟t fit the bill. So, it is necessary to write data to files with varying data types. Suppose we want to keep inventory data for a grocery store. We need to keep track of each item in inventory by its name, unit of measure, and amount. We open the form and open a sequential data file (F:\Ch11Data) for output. We then use a series of input boxes to enter the following data: Item Name Amount in Stock Unit of Measure Potatoes 100 pounds Eggs 75 dozen Beans 250 cans

Here, we write the three data elements in the record to the data file. (Note the comma delimiter)

Visual Basic Programming 112

Next, we enter the item searching for in the txtSearch text box and, go through the data file until we find its name. If we encounter an end of file, we know that the item is not in the data base.

Data is read from the file one record at a time. (Note the comma delimiter)

Here, we check to see if the item searching for is in the data base.

Closing a Data File Always remember to close the data file before ending the program. Data is cached in memory when sent to a file. It is only written when the buffer is full or when the file is closed. So, ending a program without closing could result in lost data.

Visual Basic Programming 113

Appending Data to a File As mentioned before, a data file can be opened without losing all of its contents so that additional data can be added to it by opening it for append. Using the code from the previous example, we do this by simply replacing the mode from output to append. Open “Ch11Data” for append as #1

Updating and Deleting Records It is now clear that writing and reading data to and from files is pretty much a one-way street. That is, a file can be opened for output/append or input only. So if we want to change or delete a record in a file, we need to : 1. Open the original file for input 2. Open a second file for output 3. Read each record from the input file, checking for some key as to which record we want to change or delete (In our grocery store example, we could look for the item name.) a. Write each record that we do not want to change or delete to the output file b. Change or delete the record(s) we want and write these new records to the output file 4. Delete the original (input) file 5. Rename the new (output) file as the original file‟s name To illustrate the procedure, we examine the following application that:  Opens the “Ch11Data” data file for input  Uses its contents to list all item names in a list box  Allows the user to choose an item from the list  Reads through each record, writing other records to a “temp” file  Places the data from that item‟s record in text boxes for editing  Replaces the edited data for the record into the “temp” file  Finishes reading all of the other data from the original file and writing it to the “temp” file  Closes both files  Deletes the original file  Renames the “temp” file as the original

Visual Basic Programming 114

We will change the amount from 75 to 77 and click “Change Record”. Running this application again reveals the change made to the data.

Here is the code:

Open the “Ch11Data” file for input and the “temp” file for output.

Go through all of the records, placing each record’s item name in the list box.

The record pointer moves from record to record as it reads data. Closing the file allows the record pointer to be replaced at the beginning of the file upon re-opening it.

Visual Basic Programming 115

Reopening the file following the previous close sets the record pointer at the beginning of the file.

Each record is read and, if it’s “strItem” value does not match the “strTarget” from the list box, that record is written to the “temp” file. When a match is found, the data from that record is placed in the three text boxes in the form for editing.

After the changes are made to the targeted record in the text boxes and the “Change Record” button is clicked, that record is written to the “temp” file.

Then, the program continues through the rest of the “Ch11Data” file reading each record and writing it to the “temp” file. Delete the “Ch11Data” file and rename the “temp” file as “Ch11Data” with its edited data.

Visual Basic Programming 116

Deleting and Renaming Files At the end of the code in the previous segment, there exists two lines of code – one that deletes the original “Ch11Data” file followed by one that renames the “temp” file as “Ch11Data”. Kill The Kill command simply deletes the file following it. In the code above, it is deleting the “Ch11Data” file from the F: drive. The file to be deleted must be closed. Name The Name command follows this syntax: Name As So, in the example above, it is renaming “temp” on the F: drive “Ch11Data” on that same drive. The file to be renamed must be closed and there cannot be another file with the new name in the same folder.

Visual Basic Programming 117

Starting Visual Basic ...................................................................................................................................... 1 Standard Toolbar ........................................................................................................................................ 2 Toolbox ...................................................................................................................................................... 2 Project Window .......................................................................................................................................... 3 Programming Prefixes .................................................................................................................................... 4 File Extensions ............................................................................................................................................... 4 Forms, Labels, Text Boxes, and Buttons ........................................................................................................ 5 Setting the Form‟s Name and Caption Properties ...................................................................................... 5 Adding a Label to the Form ........................................................................................................................ 6 Adding a Text Box to the Form .................................................................................................................. 7 Adding Command Buttons to the Form...................................................................................................... 8 Adding Code to Objects ................................................................................................................................. 9 Make the lblMessage Label Visible When the Form is Clicked ................................................................. 9 Code the OK Button to Show the Desired Message in txtName Text Box ...............................................11 An Alternate Method .............................................................................................................................12 Code the Cancel Button to Close the Application .....................................................................................13 Saving a Project .............................................................................................................................................13 Using Assignment to Change Property Values..............................................................................................15 Including Image Objects ................................................................................................................................17 Review ...........................................................................................................................................................20 Variable Assignments ....................................................................................................................................22 Debugging Using the Immediate Window ....................................................................................................24 Data Types .....................................................................................................................................................27 Will Represent .......................................................................................................................................27 Data Type Naming Conventions ...............................................................................................................27 Multiple Variable Declarations..................................................................................................................27 Option Explicit ..........................................................................................................................................27 Automatic Type Conversion ..........................................................................................................................28 Modulus Division ..........................................................................................................................................29 Option Buttons ..............................................................................................................................................29 Frames ...........................................................................................................................................................31 Constants .......................................................................................................................................................31 If … Then Statements ....................................................................................................................................32 Boolean Relational Operators ....................................................................................................................32 Operator .................................................................................................................................................32 Equal to......................................................................................................................................................32 Roundoff Errors .........................................................................................................................................32 If … Then… Else Statements ........................................................................................................................32 Nested If … Then … Else Loops ..................................................................................................................33 If … Then … ElseIf .......................................................................................................................................34 Else ..........................................................................................................................................................34 Generating Random Numbers .......................................................................................................................34 Int Function ...............................................................................................................................................34 Fix Function ..............................................................................................................................................34 Randomize .................................................................................................................................................35 Scope .............................................................................................................................................................35 Logical Operators ..........................................................................................................................................36 Function .................................................................................................................................................36 Message Box .................................................................................................................................................36 Password Applications ..................................................................................................................................37 Counters ........................................................................................................................................................38 Check Boxes ..................................................................................................................................................39 Printing a Form ..............................................................................................................................................40 Do Loops .......................................................................................................................................................41

Visual Basic Programming 118 Do – Loop While .......................................................................................................................................41 intTotal = Val(txtNum.Text) .................................................................................................................41 Do ..........................................................................................................................................................41 Do While – Loop .......................................................................................................................................41 Infinite Loops ............................................................................................................................................41 Input Box .......................................................................................................................................................41 Syntax ........................................................................................................................................................42 Example .....................................................................................................................................................42 Accumulators.................................................................................................................................................43 Example .....................................................................................................................................................43 String Conversion Functions .........................................................................................................................44 LCase .........................................................................................................................................................44 UCase ........................................................................................................................................................44 StrConv ......................................................................................................................................................44 Manipulating Strings .................................................................................................................................45 Left ........................................................................................................................................................45 Right ......................................................................................................................................................45 Mid Function .........................................................................................................................................45 Mid Statement .......................................................................................................................................46 Len Function..........................................................................................................................................46 InStr Function ........................................................................................................................................46 For … Next Loop ..........................................................................................................................................47 Generating Strings .........................................................................................................................................47 String .........................................................................................................................................................47 Space .........................................................................................................................................................48 & ................................................................................................................................................................48 vbTab .........................................................................................................................................................48 vbCrLf .......................................................................................................................................................48 Comparing Strings .........................................................................................................................................49 StrComp.....................................................................................................................................................49 Like............................................................................................................................................................49 Sub Procedures ..............................................................................................................................................50 General Procedures ....................................................................................................................................50 Syntax ....................................................................................................................................................50 Example .................................................................................................................................................50 Call ............................................................................................................................................................50 Syntax ....................................................................................................................................................50 Example .................................................................................................................................................50 Line Continuation ......................................................................................................................................50 Example .................................................................................................................................................50 Value Parameters .......................................................................................................................................51 Syntax ....................................................................................................................................................51 Example .................................................................................................................................................51 Reference Parameters ................................................................................................................................52 Documenting Procedures ...........................................................................................................................53 Static Variables ..........................................................................................................................................53 Syntax ....................................................................................................................................................53 Example .................................................................................................................................................54 Function Procedures ..................................................................................................................................55 Syntax ....................................................................................................................................................55 Example .................................................................................................................................................55 Creating a Function ...............................................................................................................................56 Object Parameters ......................................................................................................................................56 Example .................................................................................................................................................56 Built-in Mathematical Functions ...................................................................................................................57 ABS ...........................................................................................................................................................57

Visual Basic Programming 119 SQR ...........................................................................................................................................................57 SGN ...........................................................................................................................................................57 IsNumeric ..................................................................................................................................................57 Round ........................................................................................................................................................58 Formatting Numeric Output ..........................................................................................................................58 Format ...................................................................................................................................................58 Built-in Business Functions ...........................................................................................................................59 PMT ...........................................................................................................................................................59 Syntax ....................................................................................................................................................59 PV ..............................................................................................................................................................60 FV ..............................................................................................................................................................61 List Box .........................................................................................................................................................63 Event or Method ....................................................................................................................................63 Combo Box....................................................................................................................................................67 Property .................................................................................................................................................67 Underscore.....................................................................................................................................................68 Application Properties ...................................................................................................................................69 Focus .........................................................................................................................................................69 Access Key ................................................................................................................................................69 Tab Order ..................................................................................................................................................70 Built-In Trigonometric Functions ..............................................................................................................72 SIN ............................................................................................................................................................72 COS ...........................................................................................................................................................72 TAN ...........................................................................................................................................................72 Converting Degrees to Radians .................................................................................................................72 Converting Radians to Degrees .................................................................................................................72 Inverse Trigonometric Functions ...................................................................................................................73 ATN ...........................................................................................................................................................73 To use ATN to calculate the ARCSINE of an Angle in Radians ..............................................................73 To use ATN to calculate the ARCCOSINE of an Angle in Radians .........................................................73 Logarithmic and Exponential Functions ........................................................................................................73 LOG ...........................................................................................................................................................73 Using LOG to Calculate the Logarithm of a Number to A Base ...............................................................74 EXP ...........................................................................................................................................................74 Variable Arrays .............................................................................................................................................75 Array Declaration ......................................................................................................................................75 Dim strEmp(5) as String ........................................................................................................................75 Upper Bound .............................................................................................................................................75 Lower Bound .............................................................................................................................................75 Option Base ...............................................................................................................................................75 Option Base 1 or Option Base 0 .........................................................................................................75 Array Declaration Using Upper and Lower Bounds..................................................................................75 Dim strEmp(1 to 5) as String .................................................................................................................75 Const lngLowBound as Long = 1 ..........................................................................................................75 Array Initialization ....................................................................................................................................75 Array Index................................................................................................................................................75 LBound and UBound Functions ................................................................................................................76 Run-Time Error .........................................................................................................................................76 For … Next ....................................................................................................................................................76 Dim lngIndex as Long ...........................................................................................................................76 Array Parameters ...........................................................................................................................................76 Function AddChar(ByRef strEmp() As String) As Integer ...................................................................76 Arrays With Meaningful Indexes ..................................................................................................................77 Searching an Array ........................................................................................................................................77 Dynamic Arrays ............................................................................................................................................77 ReDim .......................................................................................................................................................77

Visual Basic Programming 120 Preserve .....................................................................................................................................................78 Control Arrays ...............................................................................................................................................78 Index Property ...........................................................................................................................................78 LBound and UBound Properties ................................................................................................................80 Count .........................................................................................................................................................80 Control Arrays as Parameters ....................................................................................................................81 Removing an Object From a Control Array ..............................................................................................81 Two Dimensional Arrays ..............................................................................................................................81 Declaring a Matrix .....................................................................................................................................81 Dim strName(1,4) as String ...................................................................................................................81 Declaring a Matrix Using Upper and Lower Bounds ............................................................................81 Dim strName(1 to 2,1 to 5) as String .....................................................................................................81 LBound and UBound Functions ................................................................................................................82 Dim intLowRow, intHighRow, intLowCol, intHighCol as Integer .......................................................82 Nested For…Next Loops ...........................................................................................................................82 Dim intRow, intCol as Integer ...............................................................................................................82 Dynamic Matrix.........................................................................................................................................82 Color ..............................................................................................................................................................83 Color Properties at Design Time ...............................................................................................................83 BackColor ..............................................................................................................................................83 ForeColor...............................................................................................................................................84 Setting Colors at Run Time .......................................................................................................................84 Built-In Visual Basic Colors......................................................................................................................85 RGB Function............................................................................................................................................85 Practice Application Using Color ..........................................................................................................85 Adding Lines to an Application.....................................................................................................................85 Line Properties...........................................................................................................................................86 Name .....................................................................................................................................................86 BorderColor ...........................................................................................................................................86 BorderStyle ............................................................................................................................................86 BorderWidth ..........................................................................................................................................87 Objects and Form BackColor ....................................................................................................................87 Adding Shapes to an Application ..................................................................................................................87 Shape Property ..........................................................................................................................................87 Name Property ...........................................................................................................................................88 BackColor Property ...................................................................................................................................88 BackStyle Property ....................................................................................................................................88 BorderColor Property ................................................................................................................................88 BorderStyle Property .................................................................................................................................88 BorderWidth Property ...............................................................................................................................88 FillColor Property ......................................................................................................................................88 FillStyle Property.......................................................................................................................................88 Picture Boxes .................................................................................................................................................90 Picture Property .........................................................................................................................................90 BorderStyle Property .................................................................................................................................92 AutoSize Property .....................................................................................................................................92 Moving Shapes and Picture Boxes ................................................................................................................93 Twips .........................................................................................................................................................93 Move Method ............................................................................................................................................94 Graphic Methods ...........................................................................................................................................95 Coordinate System.....................................................................................................................................95 Line Method ..............................................................................................................................................95 Circle Method ............................................................................................................................................96 Pset Method ...............................................................................................................................................97 PaintPicture Method ..................................................................................................................................98 Cls Method ................................................................................................................................................98

Visual Basic Programming 121 Container Properties Affecting Graphics .......................................................................................................99 AutoRedraw...............................................................................................................................................99 DrawStyle ..................................................................................................................................................99 DrawWidth ................................................................................................................................................99 FillColor ....................................................................................................................................................99 FillStyle .....................................................................................................................................................99 ForeColor...................................................................................................................................................99 Timer Object................................................................................................................................................100 Name Property .........................................................................................................................................100 Interval Property ......................................................................................................................................100 Enabled Property .....................................................................................................................................100 Timer Event .............................................................................................................................................100 Moving Line Objects ...................................................................................................................................102 Animation ....................................................................................................................................................103 Adding Sound ..............................................................................................................................................104 Name Property .........................................................................................................................................104 Device Type ............................................................................................................................................104 Enabled Property .....................................................................................................................................104 FileName Property...................................................................................................................................104 Visible Property .......................................................................................................................................104 Using Wav Sounds ......................................................................................................................................105 Creating the Wave File ............................................................................................................................105 Applying the Wave Sound from a File ....................................................................................................105 Sequential Access Files ...............................................................................................................................107 Opening a File .........................................................................................................................................107 FreeFile Function.................................................................................................................................107 Reading & Writing Text from a File .......................................................................................................108 Line Input ............................................................................................................................................108 EOF .....................................................................................................................................................108 vbCrLf .....................................................................................................................................................109 Multi-Line Text Box................................................................................................................................110 Scroll Bar Properties............................................................................................................................110 Reading & Writing Records to a File ......................................................................................................111 Closing a Data File ..................................................................................................................................112 Appending Data to a File .........................................................................................................................113 Updating and Deleting Records ...............................................................................................................113 Deleting and Renaming Files ..................................................................................................................116 Kill .......................................................................................................................................................116 Name ...................................................................................................................................................116