VISUAL BASIC For Engineers & Scientists. Shahab D. Mohaghegh, Ph.D. Professor Petroleum & Natural Gas Engineering West Virginia University

Size: px
Start display at page:

Download "VISUAL BASIC For Engineers & Scientists. Shahab D. Mohaghegh, Ph.D. Professor Petroleum & Natural Gas Engineering West Virginia University"

Transcription

1 VISUAL BASIC For Engineers & Scientists Shahab D. Mohaghegh, Ph.D. Professor Petroleum & Natural Gas Engineering West Virginia University March 1997

2 TABLE OF CONTENTS Chapter 1: Problem Solving with Visual Basic Introduction 1.1 Solving Problems with Visual Basic 1.2 Using a Five-Step Problem-Solving Process 1.3 The Five-Step Problem-Solving Process in Visual Basic Summary References Chapter 2: An Introduction to Visual Basic Introduction 2.1 Event Driven Programming 2.2 Visual Basic Environment Menu Bar Toolbar Toolbox The Form Window Project Window Properties Window Code Window Debug Window 2.3 Creating Graphical user Interface (GUI) 2.4 Objects and Controls Object / Control Properties Object / Control Procedures 2.5 Menus and Dialog Boxes 2.6 File Access Opening and Closing Files from within a Program Reading from a File Writing to a File 2.7 Writing Code General Declaration 2.8 Using On Line Help 2.9 Conventions Summary References

3 Chapter 3: Engineering Computation with Visual Basic Introduction 3.1 Writing your First Program (Windows Application) The Hello Program Writing Visual Basic Code Improving the First Program The New Hello Program Try It! 3.2 Visual Basic Variables and Operators Data Types Variable Declaration Local and Global Variables Constants Operators in Visual Basic The Operator Program Code Interpretation Operators Combination and Formulas Operator Precedence Mathematical Functions The Functions program Code Interpretation Other Operators Try It! 3.3 Visual Basic Decision Structures If... Then Decision Structure The New Operator Program Code Interpretation Select - Case Decision Structure The Enhanced Operator Program Code Interpretation Try It! APPLICATION: Electrical Engineering APPLICATION: Chemical Engineering Summary References

4 Chapter 4: File Access and Engineering Graphs with Visual Basic Introduction 4.1 Visual Basic Loops and Arrays For...Next Loops Do Loops Try it! 4.2 File Access in Visual Basic Opening and Closing Files from within a Program Reading from a File Writing to a File 4.3 Engineering Graphs with Visual Basic Histograms Pie Charts XY plots Try It! APPLICATION: Petroleum Engineering APPLICATION: Mechanical Engineering Summary References Chapter 5: Engineering Applications with Visual Basic APPLICATION: ELECTRICAL ENGINEERING Equipment Reliability Simulation Data Electric Circuit Model Spacecraft Data Analysis APPLICATION: CHEMICAL ENGINEERING Temperature Conversion Waste Water Treatment APPLICATION: CIVIL ENGINEERING Simply Supported Beams Earthquake Measurements APPLICATION: MECHANICAL ENGINEERING Stride Estimation Composite Materials Accelerometer Model APPLICATION: PETROLEUM ENGINEERING

5 Oil Well Production Oil and Gas Property Evaluation APPLICATION: AEROSPACE ENGINEERING Wind Tunnel Computation of Lift and Drag Forces Terrain Navigation APPLICATION: ENVIRONMENTAL ENGINEERING Timber Growth SCIENTIFIC APPLICATIONS Bacteria Growth (Biology) Carbon Dating (Archeology) Light Pipes (Physics) Climatology Data (Meteorology) Roots of Equations (Mathematics)

6 1 Visual Basic Environment Learning a programming language is an essential part of any engineering education. Much can be said about usefulness and necessity of programming languages in an Engineering curriculum. One thing that usually cannot be said about programming languages such as Fortran, C, or C++ is that, they are exciting. What sets Visual Basic apart from other high level programming languages, is the excitement it initiates in those that are learning it. This is of special importance to freshman engineering students, since it contributes to the very important issue of retention. Visual Basic provides a rich set of technically oriented commands and functions that will prove more than sufficient for solving any engineering problems during a 4 year engineering program, as well as a graduate program. Visual Basic Environment In this chapter you will explore the Visual basic environment. A unique programming environment that at the beginning can be a bit intimidating, but once you have completed this chapter, you will find that it is actually a rich and user friendly environment. Lets us start with the first dialog box that you will encounter once you start Visual Basic. Figure 1-1 shows the Visual Basic s New Project dialog box. Using this dialog box you will initiate your first project in Visual Basic. As you can see this dialog box has three tabs. The New tab lets you initiate a new application. In this course you will mostly create Standard.EXE applications, i.e. stand alone windows programs. Shahab D. Mohaghegh Chapter ONE -1

7 Figure 1-1. Visual Basic s New Project dialog box. Visual Basic also allows you to create other applications such as ActiveX controls and DLLs (Dynamic Link Libraries sharable subprograms used by other programs) or other applications as viewed in this dialog box. There are two other tabs. Existing tab lets you open existing Visual Basic projects to edit or modify, while the Recent tab provides you with a list of most recently created or edited Visual Basic projects. To start a new project, click on the Standard.EXE icon and then click on the Open button. The window shown in Figure 1-2 will open. We now explore the components of this window one by one. The Menu bar is at the very top. Menu bar contains most of the utilities that are available to you in the Visual Basic environment. Such as File, Edit, View, etc. Click on each of these items to see the available utilities. Shahab D. Mohaghegh Chapter ONE -2

8 Figure 1-2. New project environment. Under the Menu bar is the Tool bar. Tool bar contains some of the most often used items from the Menu bar in small icons. Move the mouse pointer on each icon and leave it for a moment and the function of the icon will appear in a small sidebar. Figure 1-3. Visual Basic Environment Menu bar. Shahab D. Mohaghegh Chapter ONE -3

9 Figure 1-4. Visual Basic environment Tool bar. The Toolbox in the Visual Basic environment contains the controls (also referred to as objects) that are most often used in developing applications. Throughout this textbook you will learn how to use all these controls. Figure 1-5. Visual Basic environment Toolbox. In the following table the controls in the toolbox will be introduced one at a time. In the following chapters these controls will be used in different applications and their properties will be explored. Pointer It does not draw a control. Pointer, lets you select, resize or move a control already on a form. Picture Box Displays graphics, as a container that receives output from graphics and print methods. Label Displays text that can not be changed, like caption under a graphic. It can be changed by program codes. Shahab D. Mohaghegh Chapter ONE -4

10 Text Box Holds text that the user can either enter or change, or text generated by application. Frame Allows you to create a visual or functional grouping for controls. Draw the Frame first, and then draw controls inside the frame, to form a group. Command Button Creates a button the user can choose (click) to carry out a sequence of instructions. Check Box To choose between yes/no, true/false, and include/ exclude or multiple choices when more than one item may be chosen. Option Button This control is used to select one item from a group of items. Combo Box Combines the features of list box and text box. The user can either choose an item from the list or enter a value in the text box. List Box Displays a list of items from which the user can choose one. Timer Used to activate a specific event at set intervals. This control is invisible at run time. VScrollBar (vertical scroll bar) HScrollBar (horizontal scroll bar) DriveListBox DirListBox (directory Provides a graphical tool for moving through lists or selecting data ranges. Provides a graphical tool for moving through lists or selecting data ranges. Displays valid disk drives at run time. Displays directories and paths at run time. list box) Shahab D. Mohaghegh Chapter ONE -5

11 FileListBox Shape Displays a list of files at run time. Used to draw a variety of shapes such as a rectangle, square, rounded square, oval, or circle, etc. Line Used to draw a variety of line styles on your form at design time. Image Displays a graphical image from a bitmap, icon, metafile as well as JPG or GIF files. It is decorative and uses fewer resources than a PictureBox. Data Provides access to data in databases through bound controls on your form. OLE Allows you to link and embed objects from other applications in your Visual Basic application. Table 1-1. Most frequently used controls in the Visual Basic environment. There are three other windows that appear in the Visual Basic environment. They are Project window, Properties window and the Layout window. Project window provides an explorer type view of all the forms and modules in the project, while Properties window provides a list of all the properties available for each control with their corresponding value. Shahab D. Mohaghegh Chapter ONE -6

12 Figure 1-6. Visual Basic s Project window. Layout window shows the relative location of the forms on the screen. As you change the location and size of the forms the changes are reflected in the Layout window. Figures 1-6 and 1-7 shows Visual Basic s Project, Properties and Form Layout windows. You can change the location of the application window (the form) by moving its location in the Form Layout window. To change the location of the form in the Form Layout window simply click on it (where its written Form1) and drag it to any location in the in the monitor s picture. Figure 1-7. Visual Basic s Properties and Form Layout windows. Shahab D. Mohaghegh Chapter ONE -7

13 Form window, shown in Figure 1-8, is the main window in the Visual Basic environment. This is the window within which the application interface is developed. You develop the application interface by placing controls in the Form. Figure 1-8. Visual Basic s Form window. You can change the size of the form by clicking on the handles and dragging them. Once the controls are placed in this window and their properties are assigned in the Properties window it is time to attach codes to each control as needed. Attaching code to the control means writing the sequence of instructions that pertains to each control. In order to write the code for each control you must first bring up the code-editing window for that control. You can do that by double clicking on the control. If you wish to attach code to a Form, you should double click on the Form itself. Shahab D. Mohaghegh Chapter ONE -8

14 Figure 1-9. Visual Basic s code editing window. Once the code edit window appears, the control that the code is being written for is shown in the top left Combo Box and the event procedure is shown in the top right Combo Box. Visual Basic is an event driven programming language. This simply means that the applications that are developed using Visual Basic, much like any other windows applications, will act upon the users actions (event procedures) such as Click, DoubleClick, DragDrop, MouseDown, etc. Whenever you want the control in your application to respond to an event, you put the instructions in the appropriate event procedure. Of course the user does not initiate all the events. Sometimes events are consequence of other events. For example as you start an application the main Form is loaded in the memory and shows up on the screen. This is a Form_Load event, which simply means that the Load event procedure is activated on the Form control. Using the Shahab D. Mohaghegh Chapter ONE -9

15 arrow in the left Combo Box will show all the controls that are used in the application and clicking on the arrow of the right Combo Box shows all the available procedure for the control that is shown on the left Combo Box. Control Properties Every control in a Visual Basic application has certain characteristics called properties. These properties dictate the way a control looks, size, color, and screen location among other things. When you place a control in your application (either by drag and drop or by double clicking on it) the property window will display the properties corresponding to that control. There is a default value for each property. You may change these values to fit the purposes of your application. Once a control is placed on a Form, Visual Basic automatically will issue a name for that control. This is the name that the control will be known by, to the rest of the application. When you write codes for that control you notice that the name that Visual Basic has given to this control appears in the top left Combo Box of the code edit window. This name can be changed, just like any other property of the control, from the Properties window. The Name property is the first property that appears in the Property window. Figure 1-10 shows a form that has a Command Button control placed in it. The Property window for the Command Button control is also shown in this Figure. Shahab D. Mohaghegh Chapter ONE -10

16 Figure Properties of the Command Button Once a control like the Command Button control is placed on the Form, it has Command1 written on it. This is called the caption. This may become a little confusing since the Name property of the control that is also Command1. In other word, both the Name and the Caption (what appears on the Command Button control) properties have the same value. To distinguish between them, the Caption on the Command Button control was changed to Click on Me, and the Font property was changed too. Another note worthy item is that when there are more than one control present in the application during the design time, the properties of the control that is selected will appear in the Properties window. Note the handles around the Command Shahab D. Mohaghegh Chapter ONE -11

17 Button control in Figure These handles are indicators that Command Button control has been selected. Try It! Open Visual Basic and start a Standard.EXE project. In the Form that appears place a Command Button control by double clicking on it in the Toolbox. Change the properties of the control by making it larger. Now try to change the Caption on the control, then change the Font. Repeat this operation for the Text Box control and the Label control. What If? Write your first program by following these steps: Open Visual Basic and start a Standard.EXE project. Place a Command Button on the Form. Change the Caption property to Click on me to end the Program. Using the handles on the control, change its size until the above Caption appears on a single line. Change the Font to Arial (Bold). Double click on the Command Button control to bring up the code-editing window. In the Command1_Click() event procedure, between the two provided lines (they read Private Sub Command1_Click() and End Sub ) type end. Shahab D. Mohaghegh Chapter ONE -12

18 Then run the program by clicking on the (Play Button) in the Tool bar. First Visual Basic Program In this application you are asked to write a program that only consists of a Form and a Command Button. When the application starts it should show the Form with the Command Button in the center of it. The wording on the Command Button should read Click on Me to End the Program. When that Button is clicked the application should close. 1 Problem Statement Write an application that can be closed (terminated) click of a button. 2 Input/Output Description There are no particular inputs and out puts in this application. There are actions and outcomes instead. The action is the click of the Command Button by the user and the outcome should be the termination of the program. 3 Application Development Open the Visual Basic and choose the Standard.EXE from the opening window. Double Click on the Command Button control in the Toolbox. This will place a Command Button control on the empty Form. The Command Button is now selected on the Form. You can see the handles around it. Also, the Properties window is displaying the properties of the Command Button that it has given the Name Command1. Shahab D. Mohaghegh Chapter ONE -13

19 Click on the Caption property in the Property window and change its value from Command1 to Click on Me to End the Program. Using the handles of the Command Button increase the size of the Command button so the text can be shown on a single line. Now click on the form itself to select it. You will notice that the Property window is now displaying the Form properties. Change the Caption property value from Form1 to First Program. Double click on the Command Button. This will bring up the code-editing window. Make sure that the word Command1 appears in the top left Combo Box and the word Click is displayed in the top right Combo Box. First line of this window should read Private Sub Command1_Click() and there is an amply line and then End Sub. In the empty line just type end. Close the code-editing window by clicking on the cross (X) on the top right corner of the window. The code-edit window should look like Figure Figure Code-editing window Click on the Play Button to run your program. When you program is running, by clicking on the Command Button the program will terminate. Shahab D. Mohaghegh Chapter ONE -14

20 Now click on File on the Menu bar, and then click on Save Project As This will bring up a dialog box that asks you to name each form involved in your project and at the end name the entire project. Give your project the proper name (Project 1 for example). Click on File again and then on Make Project1.EXE. This will generate an executable file called Project1.EXE, which you can click on to run your program in the Windows operating system environment. The program interface should look like this. Figure First program interface. The Hello World Program In this application you are asked to write a program that consists of a Form a Label and a Command Button. When the application starts it should show the Form with a large Hello World written on it in blue. The Command Button is for termination of the application. 1 Problem Statement Write an application that displays Hello World and can be closed by click of a button. Shahab D. Mohaghegh Chapter ONE -15

21 2 Input/Output Description There are no particular inputs and out puts in this application. There are actions and outcomes instead. The action is the click of the Command Button by the user and the outcome should be the termination of the program. 3 Application Development Open the Visual Basic and choose the Standard.EXE from the opening window. Double Click on the Label control in the Toolbox. This will place a Label control on the empty Form. The Label is now selected on the form. You can see the handles around it. Also, the Properties window is displaying the properties of the Label that it has given the Name Label1. Click on the Caption property in the Property window and change its value from Label1 to Hello World. Click on the Font Property. This will cause a small button with three dots on it to appear on the left of the Font value. Click on that button to bring up the Font dialog box. Use the dialog box and choose the font of your choice in bold and size of around 20. Then click on the ForeColor property to change the Font color. Double click on the Command button control in the Tool box to place a Command Button control on the Form Click on the Caption property in the Property window and change its value from Command1 to &Exit. This will cause the word Exit to appear on the Command Button in this Form Exit. The fact that E is underlined simply means clicking on this button is the same as clicking <control> E on the keyboard. Use the Font property of the Command Box to change the caption s Font. Now click on the form itself to select it. You will notice that the Property window is now displaying the Form properties. Change its caption to Hello World Program Double click on the Command button. This will bring up the code-editing window. Shahab D. Mohaghegh Chapter ONE -16

22 Make sure that the word Comand1 appears in the top left Combo Box and the word Click is displayed in the top right Combo Box. First line of this window should read Private Sub Command1_Click() and there is an empty line and then End Sub. In the empty line just type end. Close the Code Editing window by clicking on the cross (X) on the top right corner of the window. Click on the Play Button to run your program. When you program is running, by clicking on the Command Button the program will terminate. Now click on File on the Menu bar, and then click on Save Project As This will bring up a dialog box that asks you to name each form involved in your project and at the end name the entire project. Give your project the proper name (Project 2 for example). Click on File again and then on Make Project2.EXE. This will generate an executable file called Project2.EXE, which you can click on to run your program in the Windows operating system environment. Your interface should look like this. Figure Hello World program interface. Shahab D. Mohaghegh Chapter ONE -17

23 Summary In this chapter you learned about the Visual Basic development environment. You learnd about Menu bar, Tool bar, Toolbox, Project window, Properties window, Layout window, Form window, Code Editing window, and different controls that appear in the Toolbox. You also learned how to write simple Visual Basic applications. Keywords Menu bar Tool bar Toolbox Project window Properties window Control Code Application Exercises 1. Write a Visual Basic program (Develop a Visual Basic Application) that displays your name in full and terminates with click of a button. 2. Write a Visual Basic program (Develop a Visual Basic Application) that displays your name, your University s Name and your Major. This information should appear in three different sizes, colors and fonts. Your program (application) should terminate with click of a button. Shahab D. Mohaghegh Chapter ONE -18

24 2 Basic Computations with Visual Basic In this chapter you will be introduced to several basic computation methods using Visual Basic. In this chapter you will learn about variables, data types, operators, two different types of decision structures. You will also be writing more sophisticated Visual Basic programs. It is important that you follow the path provided by this manuscript and complete the exercises at the end of the chapter. Introduction In this chapter you will start by writing your first program. This will be a very simple program, and does not require writing any code. You will write your first line of code once you try to improve this program. In writing this first program you will use the knowledge that you have acquired during the previous chapter. After writing the first program you will be introduced to other concepts in Visual Basic such as variables, operator, and decision structure. Each one of these concepts are introduced in detail and new windows applications (programs) will be developed at each stage. WRITING VISUAL BASIC CODE One of the outstanding features of Visual Basic is that you can accomplish a lot by writing only a few lines of code. In Visual Basic, code is also referred to as program statement. A program statement can be as simple as a single word; Shahab D. Mohaghegh Chapter TWO - 19

25 Example: Beep This statement causes the computer speaker to make a beep sound. A program statement can also be quite sophisticated. One of the most usual forms of the program statements is as follows: Object name. property name = value Example: Label1.Caption = Hello World This program statement assigns the words Hello World to the Caption property of an object called Label1. This format is used when you are trying to assign or change a property of an object or control from within a program. Many of the properties for each object is usually set at the beginning of a program, not by writing any code, rather by using the properties window as was mentioned in the previous chapter. IMPROVING THE FIRST PROGRAM In the previous chapter you wrote your first program, it is time to use other objects/controls to improve this program. We will use Command Button and Text Box controls to improve the Hello Program. The New Hello Program 1. Open a new Visual Basic Project by clicking on the "New Project" on the "File" menu, and selecting Standard.EXE from the list of icons. 2. Select "Save As..." from the File menu. A dialog box appears with Form1.frm in the File Name window. Type "New Hello" in place of Form1 and click "O.K." (Make sure you are in the directory that you want). Another dialog box appears with Shahab D. Mohaghegh Chapter TWO - 20

26 Project1.vbp in the File Name window. Type "New Hello" in place of Project1 and click "O.K." 3. Develop the interface using the following information. Object Property Value Form Caption The New Hello Program Name frmhello Text Box Name txthello Multiline Alignment Text True Center {Delete the Text1} Command Button Caption &Display Name cmddisplay Command Button Caption &Clear Name cmdclear Command Button Caption &Exit Name cmdexit In order to make the text appear in the center of the Text Box control the Alignment property of the Text Box is changed to center. This change will only take place if the Multi-line property of the Text Box control is changed to True. Also note that we have added a & before letter D in the Display Command Box Caption properties. This will cause Visual Basic to execute this command (same as clicking on the Command Button) when the user uses the keyboard (holding the Control button and pushing the letter D). The form will look like Figure 2-1: Shahab D. Mohaghegh Chapter TWO - 21

27 Figure 2-1. The New Hello Program Interface. 4. Attach code to the Interface Now its time to attach some code to the objects. For instance the program should end once the command button exit is clicked. Codes for each object or control is written in that control s code-editing window. To view and write code in the code-editing window you can either double click on the control or click once and then click on View Code in the project window. To attach code to the Exit Command Button, double click on this button, you will see the following window: Figure 2-2. Code-editing window for the Exit Command Button. Shahab D. Mohaghegh Chapter TWO - 22

28 Please notice a few things about this window, which is true for all code windows: The name of the form where the control is located is printed in the top left corner. This tells you that you are writing the code for this Form. In the object drop-down list (Combo Box), at top left, you will see a list of all controls in this Form. The form (frmhello) contains 4 controls (Exit Command Button, Display Command Button, Clear Command Button, and Text Box). In addition to these controls you can see two more entries, namely, Form and General. This is a complete listing of controls and objects that you can attach code to. In the procedure drop-down list (Combo Box) at the top right there is a list of available procedures for each object. Depending on what object and procedure is displayed at these two drop-down lists, two lines of codes is written in the body of the window. These lines are not to be interfered with. Visual Basic provides you with starting and ending code lines for each object and its procedure. Write the desired code for that object and procedure between the provided starting and ending lines. In most of the programs that are developed throughout this book, there will be an Exit button that terminates the program. This button is always programmed the same as it appears above. Therefore whenever in this book you see an Exit button, you may assume it simply has an End in its Click event procedure, unless mentioned otherwise. Writing Code for the Display Button Double click on the Display button. Type the following statements in the code-editing window. Shahab D. Mohaghegh Chapter TWO - 23

29 txthello.text = Hello...World... Figure 2-3 shows the code-editing window for the Display command button after the code has been written. Figure 2-3. Code-editing window for the Display button. Please note that three different text colors is used. Black for the code. Green for comments, specified by (single quote) Blue for reserved words. These are words used by Visual Basic, such as commands, key words, and functions. With this code you are simply changing the Text property of the txthello Text Box object to Hello...World.... This code is executed whenever the Display Command Button is clicked. Hence the first line in the Code Window provided by Visual Basic is: Private Sub cmddisplay_click() Shahab D. Mohaghegh Chapter TWO - 24

30 Which corresponds to cmddisplay control and Click procedure. Now add the following code to the Clear Command Button. txthello.text = Which means whenever this Command Button is clicked, change the text property of the txthello Test Box to (blank). You have now completed the new and improved Hello program. 5. Generate the executable file for this Program by clicking on File in the menu bar and choosing Make EXE File.... The Make EXE File dialog box appears and you will be asked if you would like to save the executable file in New Hello.exe. Accept by clicking O.K. Anatomy of an Event Procedure Looking at Figure 2-3 one notices several distinct features. These features are common among all the event procedures. Let s visit each component of the even procedure in more detail. The first component is the word Private. This means that this procedure is private to this form and can only be seen by procedures in this form. The alternative of a Private procedure is a public procedure. A public procedure can be seen and used by all the forms and modules in a project. The second word after Private is the word Sub. This indicates that this is a subprocedure as opposed to a function. If it were a function then the second word would be Function instead. A sub-procedure in Visual Basic is equivalent to a sub-program or a subroutine in other high level programming language. Shahab D. Mohaghegh Chapter TWO - 25

31 Next in Figure 2-3 we see the term cmddisplay_click(). This is the name of the procedure. Every procedure within a form must have a unique name. It includes three parts. First is the name of the control (cmddisplay in this case) followed by a under score character. The second part immediately after the under score character is the event. In Figure 2-3 the click event is identified. The last part is the empty parentheses (). This means that the procedure does not expect to receive any information from the procedure or event that calls it. Such information is usually in the form of parameters or arguments that are passed to the event procedure. The last component in the Figure 2-3 is the word End Sub. This indicates that the procedure has reached its end. Try It! Writing a program in Visual Basic that displays different information about you when different Command Buttons are clicked. You may start with Name, Last Name, Address, and Telephone Number. Make sure your program contains a Clear Command Button. VISUAL BASIC VARIABLES AND OPERATORS Variables are temporary memory locations that can contain different types of data. In computer programming data is stored in variables for later retrieval. In Visual Basic variables are also used to transfer information to an object property. When naming variables in your Visual Basic programs you should adhere to the following conventions: Shahab D. Mohaghegh Chapter TWO - 26

32 Keep it as short as possible without making it too cryptic. It should be intuitive and descriptive. It should start with a letter. There should be no periods in the variable name. It should be less than 256 characters long. You may use upper and lower case characters (Visual Basic is not case sensitive). You may use numbers. You should not use reserved names such as Visual Basic Keywords, Objects or properties. DATA TYPES It is a common practice in computer programming to declare the type of the variable that is being used. Variable type refers to the type of data that the variable is hosting. Following is a list of data types used in Visual Basic: Data Type Size Range Integer 2 bytes -32,768 Through 32,767 Long Integer 4 bytes -2,147,483,648 through 2,147,483,648 Single(precision floating point) 4 bytes x10 38 through x10 38 Double (precision floating point) 8 bytes x through x Currency 8 bytes -922,337,203,685, through 922,337,203,685, String 1 byte/character 0 through 65,535 characters Shahab D. Mohaghegh Chapter TWO - 27

33 Boolean 2 bytes true/false Date 8 bytes January 1,100 through December 31,9999 Variant 16 bytes(number) All data type range 22 bytes+1 byte/character(string) Table 2-1. Data types in Visual Basic. When you do not specify the type of a variable in a declaration statement it takes the default type which is a variant. As you can see in the above table, variant type allows the variable to take both text (string) and number. Variables with variant data type can store all the data types mentioned above and switch format automatically. It is highly recommended that you use specific data types for specific tasks and variables. For example a counter should always be an integer. Declaring variables at the beginning of each program emphasizes discipline, and saves memory and increases program efficiency. As you can see from the above table using variant data types, although convenient, is not the most efficient way of programming. VARIABLE DECLARATION There are two ways to declare variables in Visual Basic. Implicit declaration is when you start using a variable simply by assigning a specific data type to it. Explicit declaration is when you declare each variable at the beginning of the program. Using Option Explicit statement in the general declaration section of a program forces Visual Basic to generate an error message if a variable is not declared. This way you make sure that you are using only explicit form of variable declaration. To declare a variable as a specific data type use the following format: Shahab D. Mohaghegh Chapter TWO - 28

34 Dim Counter As Integer Dim Velocity As Single Dim Distance As Single Dim LastName As String Local and Global Variables If a variable is declared in a specific event procedure, i.e. cmddisplay_click(), then it is a local variable and can only be used in that event procedure with the declared format. If you want to use this variable in another event procedure, then you must declare it again. In order to make a variable available to all the controls and procedures in your program, you need to declare it as a global variable. This is done by declaring the variable in the General (declaration) event procedure. This event procedure is available through the Code Window as the first item in the Object drop-down list and first item in the Proc: drop-down list as seen in the following figure. Figure 2-4. The Code Editing Window. Constants Constants are numbers that their value does not change throughout your project. In many engineering problems there are constant numbers that are used quite often. In Visual Shahab D. Mohaghegh Chapter TWO - 29

35 Basic you can declare a constant by using the keyword "Const". One of the more familiar constants is π. To declare π as a constant in Visual Basic use the following format. Const pi= OPERATORS IN VISUAL BASIC Mathematical operations in Visual Basic take place by the use of operators. Operators will help us add, subtract, multiply, divide and exponentiate numerical values. Following is a list of mathematical operations used in Visual Basic. Operator Meaning Example ^ Exponentiation 3 ^3=27 * Multiplication 3 * 3=9 / Division 3 / 3=1 \ Integer Division 7 \ 2=3 - Subtraction 3-3=0 + Addition 3+3=6 Mod Remainder Division 9 Mod 2=1 Table 2-2. Operators in Visual Basic. The Operators Program Now lets try writing a Visual Basic program to examine each of the operations mentioned above. 1. Open a new Visual Basic Project by clicking on the "New Project" on the "File" menu, and selecting Standard.EXE from the list of icons. Shahab D. Mohaghegh Chapter TWO - 30

36 2. Select "Save As..." from the File menu. A dialog box appears with Form1.frm in the File Name window. Type "Operators" in place of Form1 and click "O.K." (Make sure you are in the directory that you want). Another dialog box appears with Project1.vbp in the File Name window. Type "Operators" in place of Project1 and click "O.K." 3. Develop the interface using the following information. Object Property Value Form Name frmoperators Caption The Operators Program Text Boxe Name txtnumber1 Multilin Alignment True Center Text Box Name txtnumber2 Multiline Alignment True Center Text Box Name txtresult Multiline Alignment Forecolor True Center Red Label Caption First Number Label Caption Second Number Label Caption Result Command Button Name cmdexit Caption &Exit Command Button Name cmdadd Caption &Add Shahab D. Mohaghegh Chapter TWO - 31

37 Command Button Name cmdsubtract Caption &Subtract Command Button Name cmdmultiply Caption &Multiply Command Button Name cmddivide Caption &Divide Command Button Name cmdinteger Caption &IntegerDivide Your program s interface should look like this: Figure 2-5. The Operators program interface. 4. Attach code to the Interface Declarations of variables Click on the "View Code" in the Project Window In the "Object"drop-down list select "General" and in the "Proc:"drop-down list select (declarations) Type the following codes in this window Shahab D. Mohaghegh Chapter TWO - 32

38 Dim x As Single Dim y As Single Dim z As Single Or you may type: Dim x, y, z As Single Your Code Window should look like this: Figure 2-6. Variable declaration in Visual Basic. Addition Double click on the Add Command Button Visual Basic responds by opening the Code Window Type the following lines in the Code Window x = Val (txtnumber1.text) y = Val (txtnumber2.text) z = x + y txtresult.text = z Shahab D. Mohaghegh Chapter TWO - 33

39 Figure 2-7. Code Editing window for cmdadd Command button. Subtraction Double click on the Subtract Command Button Write the following code in cmdsubtract Code Window x = Val (txtnumber1.text) y = Val (txtnumber2.text) z = x - y txtresult.text = z As you can see this code is identical to the code that was typed in the cmdadd_click() event procedure. The only difference is that the value assigned to variable z is the subtraction of x and y and not the addition. Other Operations Do the same as you did for the add and the subtract Command Buttons for the other Command Buttons namely, Multiply, Divide and Integer Divide. Only change the operator for each Command Button as applicable. Shahab D. Mohaghegh Chapter TWO - 34

40 5. Generate the executable file for this Program by clicking on File in the menu bar and choosing Make EXE File.... The Make EXE File dialog box appears and you will be asked if you would like to save the executable file in Operators.exe. Accept by clicking O.K. Code Interpretation In the first line you are assigning the user input or the value of the Text property of the txtnumber1 Text Box to the variable x. While the program is running, user will type the first number for the operation in this Text Box. Your code will instruct Visual Basic to retrieve this value and assign it to the Text property of the txtnumber1 object. The same is true for txtnumber2 object in the second line of the code. Then the two variables x and y are added together and the result is assigned to the variable z. The variable z is then assigned to the Text property of the txtresult object that will consequently be displayed in the interface. OPERATOR COMBINATION AND MATHEMATICAL FORMULAS Combining the mathematical operators that were discussed above carries out many engineering calculations. By combining mathematical operators with mathematical functions (that will be covered in this section), you can handle majority of the engineering calculations. These combinations are called mathematical formulas that describe certain behaviors. For example following mathematical formula describes the distance of the center of gravity from a reference plane in a hollow cylinder sector: 3 3 ( ) C = 2 2 ( )a r r s s sin a Shahab D. Mohaghegh Chapter TWO - 35

41 Operator Precedence A mathematical formula processes a combination of variables and operators. Following is a valid Visual Basic program statement: X = / 4-1 * 3^2 Above calculation may have several different results depending on which operator is executed first. For example is 12 added to 8 and the result is then divided by 4 or 9 is first divided by 4 and the result is added to 12? Visual Basic executes mathematical operators in a specific order. Following is the order of precedence that operators are executed in Visual Basic. Operator Order of Precedence ^ First * and / Second \ Third Mod Forth + and - Fifth Table 2-3. Operators order of precedence in Visual Basic. In the above expression 3^2 is executed first. Then 9 (the result of 3^2) is multiplied by 1 and 8 is divided by 4. The above expression reduces to: Which will add up to 5. X = Shahab D. Mohaghegh Chapter TWO - 36

42 When writing formulas in Visual Basic, it is recommended to use parentheses to separate calculations. In Visual Basic, parentheses take precedence over everything else. Innermost parentheses are always executed first regardless of the operators they contain. Therefore use of parentheses forces precedence in calculations. Consider the following expression: Y = 3 + 5^2 / 9 * 2^3 10 If we present this expression in this format to Visual Basic the result will be , but this expression should resemble the following formula: Y = Above expression has a value of To make sure that the formula is presented to the Visual Basic correctly, we must use parentheses. So the expression should be written as: Y = (3 + 5^2) / (9 * 2^3-10) which will result in the correct answer. Shahab D. Mohaghegh Chapter TWO - 37

43 Mathematical Functions For more number crunching power, Visual Basic provides a set of mathematical functions. Functions operate on a variable, an expression or a value that is provided as an argument (n). Following is a list of some of the Visual Basic functions. Function Sin(n) Cos(n) Tan(n) Atn(n) Abs(n) Exp(n) Purpose Returns the sine of the angle n. the angle is expressed in radians Returns the cosine of the angle n. the angle is expressed in radians Returns the tangent of the angle n. the angle is expressed in radians Returns the arctangent of n, in radians Returns the absolute value of n Returns the constant e to the power n Rnd(n) Generates a random number between 0 and 1 Sgn(n) Sqrt(n) Str(n) Val(n) Returns -1 if n is less than zero, 0 if n is zero, and +1 if n is greater than zero Returns the square root of n Converts a numeric value to a string Converts a string value to a number Table 2-4. Pre-defined functions in Visual Basic. You will find that majority of the mathematical formulas in engineering are a combination of the above functions and mathematical operators. We will now write a program that uses some mathematical operators as well as mathematical functions. Shahab D. Mohaghegh Chapter TWO - 38

44 The Function Program Now we will write an application that allows user to change the angle from 0 to 360 degrees using a sliding horizontal scroll bar. In 4 different Text Boxes user will see the current value of the angle, as well as the sine, cosine and the tangent of that angle. 1. Open a new Visual Basic Project by clicking on the "New Project" on the "File" menu, and selecting Standard.EXE from the list of icons. 2. Select "Save As..." from the File menu. A dialog box appears with Form1.frm in the File Name window. Type "Functions" in place of Form1 and click "O.K." (Make sure you are in the directory that you want). Another dialog box appears with Project1.vbp in the File Name window. Type " Functions" in place of Project1 and click "O.K." 3. Develop the interface using the following information. Object Property Value Form Name frmfunctions Caption The Functions Program Text Box Name txtangle Multiline Alignment True Center Text Box Name txtsine Multiline Alignment True Center Text Box Name txtcosine Multiline Alignment True Center Text Box Name txttan Shahab D. Mohaghegh Chapter TWO - 39

45 Multiline Alignment True Center Label Caption ANGLES in Degrres Label Caption Sine Label Caption Cosine Label Caption Tangent Label Caption 0 Label Caption 360 Label Caption Angles in Degrees Command Button Name cmdexit Caption &Exit Horizontal Scroll Bar Name hsbfunctions Min 0 Max 360 Value 180 Your program s interface should look like this: Figure 2-8. The Functions Program Interface. Shahab D. Mohaghegh Chapter TWO - 40

46 In the Horizontal Scroll Bar control, we have changed the settings on three properties other than the Name property. These are Min, Max and Value properties. Min and Max properties set the lower and upper limits of the scroll bar and Value property determines the initial location of the sliding thumb. You may use the Font and ForeColor properties in the Label and the Text Box controls to change the typeface, size, and the color of the fonts. 4. Attach code to the Interface Declaration of variables Click on the "View Code" in the Project Window In the "Object"drop-down list select "General" and in the "Proc:" dropdown list select (declarations) Type the following codes in this window 'Declare Variables and Constants Dim x As Single Dim y As Single Dim w As Single Dim z As Single Const pi = Write the code for the Horizontal Scroll Bar control Double click on the Horizontal Scroll Bar control to bring up its Code Window. Write the following code in the hsbfunctions_change() event procedure. Shahab D. Mohaghegh Chapter TWO - 41

47 'Read The angle from the Scroll Bar and x = hsbfunctions.value txtangle.text = x 'Change it to radians a = x * pi / 180 'Calculate the Functions and show them y = Sin(a) txtsine.text = y w = Cos(a) txtcosine.text = w z = Tan(a) txttan.text = z 5. Generate the executable file for this Program by clicking on File in the menu bar and choosing Make EXE File.... The Make EXE File dialog box appears and you will be asked if you would like to save the executable file in Functions.exe. Accept by clicking O.K. Code Interpretation In the first line you are assigning the current value of the scroll bar to the variable x. In the second line value of x is displayed in the txtangle Text Box. Then the angle is changed to radians, since the functions we will be using will need their arguments to be in radians. In the next six lines we first calculate the sine, cosine and tangent of the angle and then they are displayed in the proper Text Box control. Shahab D. Mohaghegh Chapter TWO - 42

48 OTHER OPERATORS Visual basic has other operators beside mathematical operators that were just covered. These are called comparison operators and logical operators. Next section will be devoted to these kinds of operators. Try It! Write a program that accepts user s inputs in Centimeters and provides inches, feet and meters as output. VISUAL BASIC DECISION STRUCTURES Visual Basic allows you to add logic to your program as well as to control the flow of your program. Using the decision structure you can evaluate any given situation and take the appropriate action. In other words Visual Basic s decision structure allows you to examine a condition and use the outcome of the condition to decide which program statements to execute next. You can do this in Visual Basic using two different types of decision structures. If...Then decision structure and Select Case decision structure. IF... THEN DECISION STRUCTURE Using comparison operators within an If... Then decision structure you can control the order in which the program statements are executed. An If... Then decision structure has one of the following formats: If condition Then statement or If condition Then Shahab D. Mohaghegh Chapter TWO - 43

49 statement1 statement2 End If or If condition Then statement1 Else statement2 End If or If Condition1 Then Statement1 Statement2 ElseIf Condition2 Then Statement3 Statement4 ElseIf Condition3 Then Statement5 Statement6 End If As you see the If... Then decision structure can have several formats. You should use the comparison operators to evaluate the conditions such as Greater Than, Less Than, and others. Following table shows Visual Basic s comparison operators. Shahab D. Mohaghegh Chapter TWO - 44

50 Comparison Operator Meaning = Equal to <> Not Equal to > Greater Than < Less Than >= Greater Than or Equal to <= Less Than or Equal to Table 2-5. Comparison operators in Visual Basic. Example: If Option1.Value=True Then Label1.Caption= First Option Is Selected or Dim TempFahrenheit As Single, TempCelsius As Single If TempCelsius<>100.0 Then TempFahrenheit=(9.0/5.0)*TempCelsius+32 Text1.Text=TempFahrenheit End If or Dim interval As Integer, Counter As Integer If interval<100 Then Counter=Counter+1 Else Counter=Counter+2 End If Shahab D. Mohaghegh Chapter TWO - 45

51 or Dim Temperature As Single If Temperature<50 Then Text1.Text= The Temperature is too Low ElseIf Temperature>50 and Temperature<100 Then Text1.Text= Temperature ElseIf Temperature>100 Then Text1.Text= The Temperature is too High End If As you probably have noticed there are times that you have to combine more than one condition to make a new condition. In the last example the second ElseIf condition states that If Temperature is between 50 and 100 Then... which needs more than one condition to be met. In such cases you should use logical operators. Following is a list of logical operators and their meaning in Visual Basic. Logical Operator Meaning And If both conditional expressions are True, then the result is True. Or If either conditional expressions are True, then the result is True. Not If the conditional expressions is False, then Shahab D. Mohaghegh Chapter TWO - 46

52 the result is True. If the conditional expressions is True, then the result is False. Xor (Exclusive Or) If one and only one of the conditional expressions is True, Then the result is True. If both are True, or if both are False, then the result is False. Table 2-6. Logical operators in Visual Basic. Following table displays the result of combination of comparison and logical operators in a compact form: A B Not A A or B A and B False False True False False False True True True False True False False True False True True False True True Table 2-7. Combination of logical operators in Visual Basic. Now lets use the if... Then decision structure in a program. The New Operators Program This program is a different version of the program that was developed in the last section. Now instead of using a separate command button for mathematical operations we will try to implement the same idea through the If... Then decision structure and use of the Frame and the Option Button objects or controls. Shahab D. Mohaghegh Chapter TWO - 47

53 1. Open a new Visual Basic Project by clicking on the "New Project" on the "File" menu, and selecting Standard.EXE from the list of icons. 2. Select "Save As..." from the File menu. A dialog box appears with Form1.frm in the File Name window. Type "New Operators" in place of Form1 and click "O.K." (Make sure you are in the directory that you want). Another dialog box appears with Project1.vbp in the File Name window. Type "New Operators" in place of Project1 and click "O.K." 3. Develop the interface using the following information. Object Property Value Form Name frmnewoperators Caption The New Operators Program Text Box Name txtnumber1 Multiline Alignment True Center Text Box Name txtnumber2 Multiline Alignment True Center Text Box Name txtresult Multiline Alignment Forecolor True Center Red Label Caption First Number Label Caption Second Number Label Caption Result Command Button Name cmdexit Caption &Exit Shahab D. Mohaghegh Chapter TWO - 48

54 Command Button Name cmdcalculate Caption &Calculate Frame Name frmnewopt Caption Pick an Operator Option Button Name OptAdd Caption Add (+) Value True Option Button Name OptSubtract Caption Subtract (-) Option Button Name OptMultiply Caption Multiply (*) Option Button Name OptDivide Caption Divide (/) Option Button Name OptInteger Caption Integer Division (\) Option Button Name OptExponent Caption Exponentioation (^) At this point few notes on the use of Option Buttons and Frames should be mentioned. Usually, Option Button controls are used in a group of options from which the user selects only one. In this problem all mathematical operators are grouped together. You group Option Button controls by drawing them inside a container such as a Frame control. To group Option Button controls in a Frame, draw the Frame first, and then draw the Option Button controls inside the Frame control. All Option Button controls within the same container act as a single group. Shahab D. Mohaghegh Chapter TWO - 49

55 When a user selects an Option Button or a mathematical operation, the other Option Button controls or mathematical operations in the same group are automatically unavailable. Also making the Value property of the OptAdd Option Button to be True, this Option Button will become the default choice in the group. The interface that you just developed should look like this: Figure 2-9. The Enhanced Operators program interface. 4. Attach code to the Interface Declarations of variables Click on the "View Code" in the Project Window In the "Object"drop-down list select "General" and in the "Proc:"drop-down list select (declarations) Type the following codes in this window Dim x As Single, y As Single, z As Single Calculate Command Button Shahab D. Mohaghegh Chapter TWO - 50

56 Double click on the Calculate Command Button Visual Basic responds by opening the Code Window Type the following lines in the Code Window 'Read in the first and the second numbers x = Val (txtnumber1.text) y = Val (txtnumber2.text) 'Find which option is selected and then take appropriate action If OptAdd.Value = True Then z = x + y ElseIf OptSubtract.Value = True Then z = x - y ElseIf OptMultiply.Value = True Then z = x * y ElseIf OptDivide.Value = True Then z = x / y ElseIf OptInteger.Value = True Then z = x \ y ElseIf OptExponent.Value = True Then z = x ^ y End If 'Write the Result in the txtresult Text Box txtresult.text = z Shahab D. Mohaghegh Chapter TWO - 51

57 5. Generate the executable file for this Program by clicking on File in the menu bar and choosing Make EXE File.... The Make EXE File dialog box appears and you will be asked if you would like to save the executable file in NewOperators.exe. Accept by clicking O.K. Code Interpretation As in the previous program, in the first two lines you are assigning the values of the Text property of the txtnumber1 and txtnumber2 (user input) to the variables x and y. The If... Then decision structure will identify which mathematical operation should be executed by examining the Value property of all the six Option Buttons available. The Option Button with a True Value property, which will be the option selected by the user at run time, will be executed and the result of the operation is assigned to the variable z. The variable z is then assigned to the Text property of the txtresult object that will consequently be displayed in the interface. SELECT CASE DECISION STRUCTURE Flow of a program can also be controlled using the Select Case decision structure. Select Case decision structure lets you execute one of the several statements or group of statements. Select Case decision structure has the following format: Select Case Variable Case value1 Statement1 Statement2 Case value2 Statement3 Statement4 Shahab D. Mohaghegh Chapter TWO - 52

58 End Select When a Select Case decision structure is used, the process begins with the Select Case keyword followed by the variable that is going to be examined. Value1, value2,... refer to the variable. Once a Case value matches that of the variable the statement or statements following that Case value are executed and then the decision structure is completed. Example: Dim SemestersCompleted As Integer Select Case SemestersCompleted Case 1 Label1.Caption= You are a Freshman Case 3 Label1.Caption= You are a Sophomore Case 5 Label1.Caption= You are a Junior Case 7 Label1.Caption= You are about to Graduate Soon End Select Select Case decision structure supports comparison operators. There are two keywords that you must use while using comparison operators with the Select Case decision structure. These keywords are Is and To. Following example illustrate their use. Example: Dim SemestersCompleted As Integer Shahab D. Mohaghegh Chapter TWO - 53

59 Select Case SemestersCompleted Case Is < 3 Label1.Caption= You are a Freshman Case 3 To 6 Label1.Caption= You are half Way There Case Is > 6 Label1.Caption= You are About to Graduate End Select Now the use of Select Case decision structure is illustrated through a program. The Convert Program This program accepts values in degrees Celsius and converts them to degrees Fahrenheit, Rankin, and Kelvin as requested by the user. 1. Open a new Visual Basic Project by clicking on the "New Project" on the "File" menu, and selecting Standard.EXE from the list of icons. 2. Select "Save As..." from the File menu. A dialog box appears with Form1.frm in the File Name window. Type "Convert" in place of Form1 and click "O.K." (Make sure you are in the directory that you want). Another dialog box appears with Project1.vbp in the File Name window. Type "Convert" in place of Project1 and click "O.K." 3. Develop the interface using the following information. Object Property Value Form Name frmconvert Shahab D. Mohaghegh Chapter TWO - 54

60 Caption TheConvert Program Text Box Name txtcelsius Multiline Alignment True Center Text Box Name txtnew Multiline Alignment True Center Label Caption Temperature Conversion Font {As you wish} Label Caption Degrees Celsius Label Caption Convert To: Label Caption {Blank} Name lblresult Command Button Name cmdexit Caption &Exit Command Button Name cmdconvert Caption &Convert Combo Box Name cmbconvert List Fahrenheit Rankin Kelvin Text {Blank} A Combo Box control combines the features of a Text Box control and a List Box control. A Combo Box control displays a list of items from which the user can make a selection. The first item in the list is ListIndex 0, and the value of the ListCount property is always one more than the largest ListIndex value. In the Combo Box of this program Shahab D. Mohaghegh Chapter TWO - 55

61 you entered three words, namely, Fahrenheit, Rankin, and Kelvin. These words will show up in the Combo Box in the order that they appear in the List property, once the arrow in the Combo Box is clicked. Each of them has an associated index number that starts from 0 for Fahrenheit, and ends with 2 for Kelvin. Also note that we have left the Caption property of lblresult control Blank. This is the label that refers to the converted temperature. Since we do not know in advance which of the three available temperature systems are going to be selected for conversion, we will assign the proper Caption to this label once the selection is made. The program interface will look like this: Figure The Convert program interface. Please note that upon the start of the program Fahrenheit is shown in the Combo Box as default. We will see how that is accomplished. 4. Attach code to the Interface Declarations of variables Click on the "View Code" in the Project Window Shahab D. Mohaghegh Chapter TWO - 56

62 In the "Object"drop-down list select "General" and in the "Proc:" drop-down list select (declarations) Type the following codes in this window Dim x As Single, y As Single Initialization Remember that you were asked to leave the Text property of the cmbconvert control blank. In order to make the cmbconvert control to display its default value (Fahrenheit), we instruct the Visual Basic to do it upon loading the interface or the main Form, by assigning the List(0) property to the Text property of the Combo Box cmbconvert. Double click on the main Form (frmconvert) Visual basic responds by opening the Code Window Write the following code in the Form_Load () event procedure. 'Initialize the Combo Box cmbconvert.text = cmbconvert.list(0) Convert Command Button Double click on the Calculate Command Button Visual basic responds by opening the Code Window Type the following lines in the Code Window 'Read the user input in the Text Box x = txtcelsius.text Shahab D. Mohaghegh Chapter TWO - 57

63 'Use the appropriate formula to convert the Temperature 'and change the Label Caption accordingly Select Case cmbconvert.text Case cmbconvert.list(0) y = (9 / 5) * x + 32 lblresult.caption = "Degrees Fahrenheit" Case cmbconvert.list(1) y = (9 / 5) * x lblresult.caption = "Degrees Renkin" Case cmbconvert.list(2) y = x lblresult.caption = "Degrees Kelvin" End Select 'Write the result in the Text Box txtnew.text = y 5. Generate the executable file for this Program by clicking on File in the menu bar and choosing Make EXE File.... The Make EXE File dialog box appears and you will be asked if you would like to save the executable file in Convert.exe. Accept by clicking O.K. Shahab D. Mohaghegh Chapter TWO - 58

64 Code Interpretation As in the previous programs, first line is for assigning the value of the Text property of the txtcelsius to the variables x. The Select Case decision structure will identify which conversion should be executed by examining the Text property of all the cmbconvert control. Since the selectable alternatives in the Combo Box each have an index assigned to them such as List(0), List(1) and List(2) from the List property of the cmbconvert control, this identification is quite easy. The Case with the matching index of the List property will be executed and the result of the operation is assigned to the variable y. Furthermore in each case the Caption property of the lblresult Control is updated with the proper string that reflects the conversion. The variable y is then assigned to the Text property of the txtnew object that will consequently be displayed in the interface. Try It! Write a program that accepts user s age as inputs and returns your opinion of the user s age (Young, Old,...) as output. Try it once with the Text Box control for the output and once with the Label control. What If? Write an application that uses both Check Box controls and Option Button controls. Shahab D. Mohaghegh Chapter TWO - 59

65 Electrical Engineering Application In this application you will create an application that calculates circuit equivalent resistance as well as voltage drop. 1 Problem Statement Determine the line current, the circuit equivalent resistance, and the I1 R1=1.0 Ω 16V + I2 R3=4.0 Ω I3 - R2=2.0 Ω R4=3.0 Ω voltage drop across the R 4 for the following circuit. 2 Input/Output Description The following diagram shows the input and the output of the program. The inputs are resistance of all the resistors and the voltage of the battery and the outputs are line current, circuit equivalent resistance and the voltage drop. Equivalent Resistances Resistances Line Current Voltage Voltage Drop Shahab D. Mohaghegh Chapter TWO - 60

66 3 HAND EXAMPLE Lets use the values given in the diagram to calculate our desired outputs. V = R I Parallel Resistors: 1/R P = 1/R 2 + 1/R 3 = 1/ /4.0 R P = 4.0/3.0 Ω Series Resistors: R T = R 1 + R P + R 4 = / = 16.0/3.0 Ω R T = 5.3 Ω Line Current: V = R I I = V (1/R T ) = 16 (3.0/16) = 3.0 A Voltage Drop: V 4 = R 4 I = 3.0 * 3.0 = 9.0 V 4 ALGORITHM DEVELOPMENT To calculate the desired output we need to follow these steps: 1. Read the resistance of each resistor 2. Read the voltage of the battery 3. Calculate the equivalent resistance of the resistors in parallel 4. Calculate the total equivalent resistance 5. Calculate the line current 6. Calculate the voltage drop 7. Display the results Shahab D. Mohaghegh Chapter TWO - 61

67 5 TESTING Input the values from section 3 above (hand example) and check the results. Then input new values for resistors and voltage and check the results. APPLICATION DEVELOPMENT Following the steps in part 4 as applied to the Visual Basic, we follow the five-step procedure for the application development. The Circuit Program 1. Open a new Visual Basic Project by clicking on the "New Project" on the "File" menu, and selecting Standard.EXE from the list of icons. 2. Select "Save As..." from the File menu. A dialog box appears with Form1.frm in the File Name window. Type "Circuit" in place of Form1 and click "O.K." (Make sure you are in the directory that you want). Another dialog box appears with Project1.vbp in the File Name window. Type "Circuit" in place of Project1 and click "O.K." 3. Use the following objects to build the interface. Only the minimum information about the interface is provided in this table. It is expected that you be able to complete the interface using only the provided information. Object Property Value Form Name frmcircuit Text Box Name txtr1 Text Box Name TxtR2 Text Box Name TxtR3 Text Box Name TxtR4 Shahab D. Mohaghegh Chapter TWO - 62

68 Text Box Name txtvolt Label Caption W Font Symbol Command Button Name cmdcalculate Command Button Name cmdexit Text Box Name txtequivresist Text Box Name txtlinecurrent Text Box Name txtvoltagedrop The interface should look like this: Figure The circuit program interface. 4. Attach code to the Interface Declarations of variables Click on the "View Code" in the Project Window Shahab D. Mohaghegh Chapter TWO - 63

69 In the "Object"drop-down list select "General" and in the "Proc:"drop-down list select (declarations) Type the following codes in this window Dim R1 As Single, R2 As Single, R3 As Single Dim R4 As Single, V As Single Dim Rt As Single, I As Single, VD As Single Calculation Double click on the Calculate Command Button Visual Basic responds by opening the Code Window Type the following lines in the Code Window 'Read the Resistors and Voltage R1 = Val (txtr1.text) R2 = Val (txtr2.text) R3 = Val (txtr3.text) R4 = Val (txtr4.text) V = Val (txtvolt.text) 'Calculate the parallel resistance Rp = 1 / ((1 / R2) + (1 / R3)) Rt = R1 + Rp + R4 'Display the total Resistance txtequivresist.text = Rt Shahab D. Mohaghegh Chapter TWO - 64

70 'Calculate the Line Current I = V / Rt 'Display the Line Current txtlinecurrent.text = I 'Calculate the Voltage Drop VD = R4 * I 'Display the Voltage Drop txtvoltagedrop.text = VD 5. Generate the executable file for this Program by clicking on File in the menu bar and choosing Make EXE File.... The Make EXE File dialog box appears and you will be asked if you would like to save the executable file in Circuit.exe. Accept by clicking O.K. Biomedical Engineering Application In this application you are asked to compute the growth of a colony of bacteria in a petri dish. It is a widely used assumption that bacteria growth follows an exponential model. It is a function of three different parameters, namely, initial bacteria population, time and the medium in which the bacteria is growing. It is also known that the wetter the medium, the easier will be for the bacteria to grow. The effect of the medium in the mathematical equation is modeled by a time coefficient. The exponential equation governing this phenomenon looks like this: Shahab D. Mohaghegh Chapter TWO - 65

71 Ynew = Yold * [Exp (coef. * Time)] In this application you are asked to develop an application that gives the user the option of inputting medium time coefficient, initial bacteria population and the time of growth. The program should calculate the new bacteria population given the media and time. 1 Problem Statement Provide the user with final bacteria population using the initial population, media time coefficient and the growth time. 2 Input/Output Description Inputs to this application will be initial bacteria population, media time coefficient and the growth time. The output of this program will be the final bacteria population after the growth time elapsed. 3 HAND EXAMPLE Lets calculate the new bacteria population after 2 days in a medium with a time coefficient of Lets asume that initial bacteria population in the colony was 15. Ynew = Yold * [Exp (coef. * Time)] New population will be: Ynew = (15) * [Exp (1.380 * 2)] Ynew = 237 Shahab D. Mohaghegh Chapter TWO - 66

72 4 ALGORITHM DEVELOPMENT To calculate the desired output we need to follow these steps: 1. Read the initial population and time 2. Read the media time coefficients 3. Calculate the new population of bacteria 4. Each time check and see if the values of time and initial population has changed. 5. Only the results of those media that has been checked should be visible. 5 TESTING Input the values from section 3 above (hand example) and check the results. Then input new values for initial population, time and media time coefficient and check the results. APPLICATION DEVELOPMENT Following the steps in part 4 as applied to the Visual Basic, we follow the 5 step procedure for the application development. The Biomedical Program 1. Open a new Visual Basic Project by clicking on the "New Project" on the "File" menu, and selecting Standard.EXE from the list of icons. 2. Select "Save As..." from the File menu. A dialog box appears with Form1.frm in the File Name window. Type "Biomedical" in place of Form1 and click "O.K." (Make sure you are in the directory that you want). Another dialog box appears with Project1.vbp in the File Name window. Type "Biomedical" in place of Project1 and click "O.K." Shahab D. Mohaghegh Chapter TWO - 67

73 3. Use the following objects to build the interface. Only the minimum information about the interface is provided in this table. It is expected that you be able to complete the interface using only the provided information. Object Property Value Frame Caption Media Time Coefficients -Text Box Name txtdefdry Text Text Box Name txtdefwet Text Text Box Name txtdefmod Text Frame Caption Input Data -Text Box Name txtyold Text 10 -Text Box Name txttime Text 2 Frame Caption Medium type -CheckBox Name chkdry Caption Value Dry medium 1- Checked -CheckBox Name chkmoderate Caption Moderate medium -CheckBox Name chkwet Caption Wet medium Frame Caption Number of bacteria Shahab D. Mohaghegh Chapter TWO - 68

74 -Text Box Name txtdryynew Text {Blank} -Text Box Name txtmoderateynew -Text Box Name txtwetynew Command Button Name cmdcalculate Command Button Name cmdexit The interface should look like this: Figure The biomedical engineering application interface. 4. Attach the following codes to the interface. Variable declaration Dim D As Single, M As Single, W As Single Shahab D. Mohaghegh Chapter TWO - 69

75 Private Sub txtyold_change() txtdryynew.text = "" txtmoderateynew.text = "" txtwetynew.text = "" End Sub Private Sub txttime_change() txtdryynew.text = "" txtmoderateynew.text = "" txtwetynew.text = "" End Sub Private Sub chkdry_click() If chkdry.value = 1 Then txtdryynew.visible = True lbldrymedium.visible = True Else: txtdryynew.visible = False lbldrymedium.visible = False End If End Sub Private Sub chkmoderate_click() If chkmoderate.value = 1 Then txtmoderateynew.visible = True lblmoderatemedium.visible = True Else: txtmoderateynew.visible = False lblmoderatemedium.visible = False Shahab D. Mohaghegh Chapter TWO - 70

76 End Sub End If Private Sub chkwet_click() If chkwet.value = 1 Then txtwetynew.visible = True lblwetmedium.visible = True Else: txtwetynew.visible = False lblwetmedium.visible = False End If End Sub Private Sub cmdcalculate_click() 'Read the Time Coefficients D = Val(txtdefDry.Text) M = Val(txtdefMod.Text) W = Val(txtdefWet.Text) 'Calculate new Bacteria population txtdryynew.text = Format(txtyold.Text * Exp(D * _ txttime.text), "###.##") txtmoderateynew.text = Format(txtyold.Text * _ Exp(M * txttime.text), "###.##") txtwetynew.text = Format(txtyold.Text * Exp _ (W * txttime.text), "###.##") End Sub Shahab D. Mohaghegh Chapter TWO - 71

77 Private Sub cmdexit_click() End Sub End 5. Generate the executable file for this Program by clicking on File in the menu bar and choosing Make EXE File.... The Make EXE File dialog box appears and you will be asked if you would like to save the executable file in Biomedical.exe. Accept by clicking O.K. Summary In this chapter you learned about objects or controls such as Label, Text Box, Command Button, Frame, Check Box, Combo Box, Horizontal Scroll Bar, and Option Button. You also learned about variables and operators, data types, local and global variables, and operator combination and mathematical functions. You now know how to write Visual Basic code. Furthermore you learned about If Then decision structure, Select Case decision structure and logical operators. Keywords Operators Decision Structure Local Global Variables Shahab D. Mohaghegh Chapter TWO - 72

78 Exercises 1. Write an application that can convert length, area and volume units in metric system to English units, and visa versa. 2. Write an application that given a person s date of birth will calculate his/her age in years, months, weeks, days, hours, minutes, and seconds. 3. Write an application that calculates the molecular weight of hydrocarbons, given the number of carbon and hydrogen atoms. 4. Write an application that calculates the area and perimeter of many different geometric shapes. 5. Write an application that as input gets the speed of a car in miles per hour from a sliding bar and converts it to kilometer per hour. Your application must display the speed in new units as the slide bar moves. Shahab D. Mohaghegh Chapter TWO - 73

79 3 Engineering Computation with Visual Basic In this chapter you will be introduced to several engineering computation methods using Visual Basic. These methods include reading data from and writing data into files, performing sophisticated computations using loop structures and arrays. By the end of this chapter you will also be able to graph functions and data to visualize the results of your computations. Introduction In this chapter we will start by loops in Visual Basic that allows the user to repeat a sequence of instructions many times. We will visit two kinds of loop structures in Visual Basic. Arrays and their similarities and differences with regular variables, how to declare them and when to use them is the subject of the next section. You will see why loops and arrays naturally go together. The Chapter will continue by introducing you to data access through files, and how to read and import data files and also how to write the results of your calculations into data files. The last part of the Chapter will be about graphs. You will learn how to use graphs in your applications to help you visualize the data that you are working with. You will learn different numerical methods and how a graph make these methods more useful. As we progress through this chapter we introduce different concepts and go into details on at least one particular application on each topic. Each section will build on the subjects learnt from the past topics. In order to provide you with more practice on the covered topics, applications that are introduced will have components of the previous topics. Shahab D. Mohaghegh Chapter THREE - 74

80 Loops in Visual Basic Loops are one of the most important topics in programming. This section will introduce you to the implementation of loops in Visual Basic. Loop structure is employed whenever the programmer tries to repeat a series of instructions and statements over and over. There are several kinds of loops in Visual Basic. We will cover three different kinds of loops in this section. For Next Loop The first kind of loops in Visual Basic that is going to be discussed is the For Next loop. The For Next loop has the following general structure: For counter = start To end [Step step] [statements] Next [counter] Where "counter" is an integer that keeps track of the loop operation, the number for "start" should be smaller than the number for "end" in the case of positive steps, and visa versa in the case of negative steps. [Step step] is an optional argument, if missing the step is considered to be +1, this argument becomes important when we want to increment using different steps. Example: x = 0 For i = 2 To 10 Step 2 x = x + i Next i Shahab D. Mohaghegh Chapter THREE - 75

81 In this example the x starts with being equal to 0. The loop is executed 5 times. It starts with i = 2 and steps by 2 until it reaches 10, therefore values of i will be 2, 4, 6, 8, and 10. During the first cycle 2 will be assigned to x since it had the value of 0 and i = 2 was added to it. During the second cycle where the value of i = 4, and the value of x = 2 (from the last cycle) the new value of x becomes = 6. During this operation the value of i is incremented by 2 at each cycle and added to the previous value of x. What would be the value of x at the end of this operation? In the above example the value of the counter i was increasing during each cycle. This was due to the fact that we specified a positive step of 2. The value of the step can be negative which would cause a decrement in the value of the counter instead of an increment. Example: x = 0 For i = 10 To 2 Step -2 x = x + i Next i What would be the value of x at the end of this operation? EXIT FOR Statement There will be occasions that you wish to exit the loop under certain circumstances. The "Exit For" statement provides means for such circumstances. It goes without saying that you will choose to exit the loop when a particular condition is met before all the cycles of a loop are completed. Therefore a conditional statement such as an If statement will be necessary for this operation. The "Exit For" statement has the following syntax. For counter = start To end [Step step] Shahab D. Mohaghegh Chapter THREE - 76

82 [statements] If [condition] Then Exit For End If Next counter Following example will demonstrate the use of "Exit For" statement. Example: x = 0 For i = 2 To 10 Step 2 x = x + i If (x > 10) Then Exit For End If Next i In the above example you can see that only three out of the five cycles are implemented. During the third cycle the value of x becomes 12 which causes the condition of the If statement to be true. At this pint the "Exit For" statement is executed and the program is kicked out of the loop. The fourth cycle will never take place. The "Exit For" is a powerful statement. It has the potential to save time by preventing inutile calculations. Shahab D. Mohaghegh Chapter THREE - 77

83 Do While Loop The second type of loop covered in this book is the Do While Loop. This loop is used to execute statements while a certain condition is true. It will stop operation as soon as the condition becomes false. The syntax of this loop is presented bellow: Do While condition Loop [ statements ] Following example shows how this loop operation works. Example: m = 0 x = 0 Do While m<20 x = x + i m = m +1 Loop Recall that in the previous section (the For Next loop) the counter was incremented automatically. In this loop implementation you must increment the counter within the loop. In the above example we used "m" as a counter and incremented it within the loop. Just as the "Exit For" statement in the previous section there is a "Exit Do" statement in the Do While loop. The operation of the do loops is very similar. Do While Loop is considered to be a condition based loop. It may not be connected to any counter. The best use of this method is when a statement must be executed over and over but the final number of loops is unknown. Practically the loop is executed until the condition is satisfied. Shahab D. Mohaghegh Chapter THREE - 78

84 Example: Do While ( input_value > 0 ) Input_value = InputBox ( Enter a negative number ) Loop In the above example the programmer wants the user to input a negative number. But users can make mistake and that might make the entire program to malfunction. In order avoid such incidents the programmer may use the above Do While loop. Such precautions are sometimes called error handling and are routinely used by programmers. The instruction is repeated while the user enters a positive number and the rest of the program is not executed until the user does what the programmer wants, which is entering a negative number. Shahab D. Mohaghegh Chapter THREE - 79

85 Arrays in Visual Basic As an engineer you will be working with large amounts of data. Most of the information that engineers deal with is in the form of numeric data. As an effective engineer you should be able to manipulate data to infer conclusions, to recognize patterns, or to visualize trends. So far you have learned that in order to use data in a Visual Basic program you have to store them in variables. The question is that what will you do when the number of data points increase. It is going to be very inefficient and impractical to declare a different variable for each data point. Imagine that you have a file that contains average daily temperature for the entire 1997, and you are going to write a Visual Basic Program to calculate the average annual temperature for the year It is going to be hard and inefficient to declare 365 different variables and store the data one by one. And then calculate the average. There must be a better way. Well, there is. In this section you will learn about arrays in Visual Basic. You will use arrays to develop new applications. Arrays can be defined as a group of variables that share the same name and the same data type. Different elements in this group of variables are distinguished by a unique integer called an index or a subscript. The index or subscript that identifies a particular element of an array appears in front of the array s shared name enclosed in a set of parentheses. Following is an example of an array with corresponding values for average temperature for the past 4 days. AveTemp(1) = 65.5 AveTemp(2) = 68.2 AveTemp(3) = 63.9 AveTemp(4) = 64.5 Shahab D. Mohaghegh Chapter THREE - 80

86 As you see all the above variables share the same name AveTemp and are distinguished from one another through the index 1 through 4. Arrays occupy consecutive locations in the computer memory once they are declared. Array is a powerful tool for programmers that make writing codes easier. In order to demonstrate the use of arrays a problem will be solved first without and then with the use of arrays. The problem is in the field of engineering economics. Engineering economics is an important component of all engineering disciplines. It is hard to find an engineering program that does not require a course in engineering economics. In a nutshell, engineering economics is the application of economic principals in engineering. After all, as engineers your job is to find the best solutions to problems and some time what distinguishes the best solution from others is the economic feasibility. In the engineering economics one of the fundamental issues is the time value of the money. It emphasizes on the fact that one dollar today have a higher value than one dollar at a future time, say one year from now. When evaluating engineering projects for their feasibility one needs to have a yardstick to compare two similar projects to one another. One of the most used and wellrecognized yardsticks that incorporate the time value of money is the Net Present Value or NPV. Net Present Value is the overall economic value of the project with today s dollar. This is due to the fact that usually each project requires a certain amount of investment in the beginning and has the potential to make money in the years ahead. The algebraic summation of in-flow (revenue) and out-flow (cost) of the money during the life of the project is called Net Cash Flow. In such summation any kind of income such as sales is denoted as positive cash flow and money spend such as operating cost, payroll and maintenance are denoted as negative cash flow. Shahab D. Mohaghegh Chapter THREE - 81

87 In the problem being discussed below, we look at a certain project that has a certain net cash flow and we try to calculate a net present value for this project. Net Present Value Calculations Let s see how Net Present Value of a project is calculated. This way it would easier for you to follow the logic of the program. Let s assume that a particular engineering project will result in the following Net Cash Flow (NCF). Net Cash Flow Year 0 (investment) -$500,000 Net Cash Flow Year 1 $130,000 Net Cash Flow Year 2 $230,000 Net Cash Flow Year 3 $148,000 Net Cash Flow Year 4 $180,000 Net Cash Flow Year 5 $193,000 Table 3-1. Net cash flow of a potential project. Net Cash Flow (NCF) for each year is calculated by subtracting all the money spent in that year from the total income for the year. For example if the project makes $250,000 at the end of the year but $120,000 were spend during the year on labor, and maintenance then the NCF for that year would be $130,000. Let's further assume that the interest rate will remain the same throughout the life of the project as 7.5%. In order to calculate the Net Present Value of this project we have to convert the NCF for each year to its value at today's dollar. Following formula is used to calculate the present value of any future lump sum. Shahab D. Mohaghegh Chapter THREE - 82

88 presentvalue = futurevalue n ( 1+ i) In the above equation i denotes the interest rate in fractions (in this case i = 0.075) and exponent n represent the number of years of the cash flow. So the present value of the NCF for the first and second years are calculated as: (130,000) / ( ) 1 = 120, (230,000) / ( ) 2 = 199, Net Cash Flow Present Value Net Cash Flow Year 0 (investment) -$500,000 -$500,000 Net Cash Flow Year 1 $130,000 $120, Net Cash Flow Year 2 $230,000 $199, Net Cash Flow Year 3 $148,000 $119, Net Cash Flow Year 4 $180,000 $134, Net Cash Flow Year 5 $193,000 $134, Table 3-2. Net cash flow and present value for the potential project. The present value of all of the Net Cash Flow values are added together to calculate the Net Present Value of the project. We will first try to solve this problem without using the concept of arrays. We will then use the concept of arrays and solve the problem again. This way you can clearly see the advantages of using arrays in solving engineering problems. Another point that will be Shahab D. Mohaghegh Chapter THREE - 83

89 discussed in the following problem is the power of Visual Basic in handling control arrays (object arrays), which are an array of Visual Basic objects. The Net Present Value Calculator Program 1. Open a new Visual Basic Project by clicking on the "New Project" on the "File" menu, and selecting Standard.EXE from the list of icons. 2. Select "Save As..." from the File menu. A dialog box appears with Form1.frm in the File Name window. Type "NPV Calculator in place of Form1 and click "O.K." (Make sure you are in the directory that you want to be). Another dialog box appears with Project1.vbp in the File Name window. Type "NPV Calculator " in place of Project1 and click "O.K." 3. Develop the interface using the following information. Please note that starting now, no information will be provided regarding the font selection for different controls. Selection of the font type, font size, font attributes, and font color will be left to you to choose them per your taste. Object Property Value Form Caption NPV Calculator Name frmmain Label Caption Net Present Value Calculator Name lbltitle Label Caption Net Cash Flow Name lblncf Label Caption Year 0 Name lbly0 Label Caption Year 1 Shahab D. Mohaghegh Chapter THREE - 84

90 Name lbly1 Label Caption Year 2 Name lbly2 Label Caption Year 3 Name lbly3 Label Caption Year 4 Name lbly4 Label Caption Year 5 Name lbly5 TextBox Name txtncf0 TextBox Name txtncf1 TextBox Name txtncf2 TextBox Name txtncf3 TextBox Name txtncf4 TextBox Name txtncf5 Label Caption Annual Interest Rate % Name lblrate TextBox Name txtinterestrate CommandButton Caption &Calcualte Name cmdcalculate Label Caption Annual Interest Rate % Name lblrate Label Caption Net Present Value Name lblnpvtilte Label Caption Name lblnpvalue CommandButton Caption &Exit Shahab D. Mohaghegh Chapter THREE - 85

91 Name cmdexit Please note that the caption property of label named lblnpvalue is blank. This has been done on purpose as you will see. The result of the calculation will be assigned to the caption of this label. Once the development of the interface is completed the interface of the application should look like that of Figure 4-1 below. Figure 3-1. The Net Present Value Calculator Program Interface. 4. Attach code to the Interface Declarations of variables Click on the "View Code" in the Project Window In the "Object" drop-down list select "General" and in the "Proc:" drop-down list select (declarations) Type the following codes in this window Declaring variables Shahab D. Mohaghegh Chapter THREE - 86

92 Dim NCF0 As Single, NCF1 As Single, NCF2 As Single Dim NCF3 As Single, NCF4 As Single, NCF5 As Single Dim PV0 As Single, PV1 As Single, PV2 As Single Dim PV3 As Single, PV4 As Single, PV5 As Single Dim InterestRate As Single, Factor As Single, NetPV As Single Calculate Command Button Double click on the Calculate Command Button Visual Basic responds by opening the Code Window Type the following lines in the Code Window Reading the Net Cash Flow values from the Text Boxes NCF0 = Val(txtNCF0.Text) NCF1 = Val(txtNCF1.Text) NCF2 = Val(txtNCF2.Text) NCF3 = Val(txtNCF3.Text) NCF4 = Val(txtNCF4.Text) NCF5 = Val(txtNCF5.Text) 'Calculating the interest factor InterestRate = Val(txtInterestRate.Text) / 100# Factor = InterestRate + 1# 'Calculating Net Present Value PV0 = NCF0 PV1 = NCF1 / (Factor ^ 1) Shahab D. Mohaghegh Chapter THREE - 87

93 PV2 = NCF2 / (Factor ^ 2) PV3 = NCF3 / (Factor ^ 3) PV4 = NCF4 / (Factor ^ 4) PV5 = NCF5 / (Factor ^ 5) NetPV = PV0 + PV1 + PV2 + PV3 + PV4 + PV5 'Assigning the calculated NPV to label for display lblnpvalue.caption = NetPV 5. Run the program and test it to see if it works properly. 6. Generate the executable file for this Program by clicking on File in the menu bar and choosing Make EXE File...". The Make EXE File dialog box appears and you will be asked if you would like to save the executable file in NPVCalculator.exe. Accept by clicking O.K. Code Interpretation Once the involved variables are declared in the general declaration, the net cash flow values are read and assigned to NCF0 to NCF5 variables respectively. Then the interest rate is read and assigned to the variable InterestRate. The interest rate is provided in percent and must be converted to fraction before it is used in the program. Dividing the interest rate by 100 would change it into a fraction. Then the variable "Factor" is calculated by adding the integer number 1 to the interest rate. The present value of a future lump sum is calculated as was demonstrated in the previous section. The Net Present Value is then assigned to the Caption property of the lblnpvalue, which will be displayed on the interface. Shahab D. Mohaghegh Chapter THREE - 88

94 Now we will rewrite the code for the NPV Calculator program using arrays. You will notice that the code for this program is much more compact and easier to follow. We will show you more than one way of writing this code at the end of the program in the code interpretation section. The Net Present Value Array Program 1. Open a new Visual Basic Project by clicking on the "New Project" on the "File" menu, and selecting Standard.EXE from the list of icons. 2. Select "Save As..." from the File menu. A dialog box appears with Form1.frm in the File Name window. Type "NPV Array in place of Form1 and click "O.K." (Make sure you are in the directory that you want). Another dialog box appears with Project1.vbp in the File Name window. Type "NPV Array " in place of Project1 and click "O.K." 3. Develop the interface using the following information. Looking at the Figure 3-2 you will see that the interface for this program is very much like the NPV Calculator program. There are two differences between these two interfaces. First is that the NPV Array program has slots for 7 years while the previous program has slots for 5 years. The second difference will be discussed after the following table. Object Property Value Label Caption Year 0 Name lblyear TextBox Name txtncf Shahab D. Mohaghegh Chapter THREE - 89

95 For this program instead of creating seven separate Text Box controls one at a time and giving each of them a unique name, only one Text Box is created. Then we copy the Text Box control six times to have a total seven Text Box controls. We copy the control by either pressing the copy icon on the toolbar or press <control> c or click on Edit and then select copy from the menu. Then paste it by either pressing the paste icon on the toolbar or press <control> v or click on Edit and then select paste from the menu. At this point a dialog box will appear containing the following message: "You already have a control named txtncf. Do you want to create a control array?" Answer yes. You will see that the newly copied Text Box has all the properties of the previous Text Box but one. Scroll down the "properties window" until you see the index property. The index property of this new Text Box has a value of 1 while the index property of the original Text Box has a value of 0. You just created a control array. Each of the elements in this array is a Text Box control with the common name of txtncf and is distinguished from other elements in the array by the index. The control array is shown as txtncf( ). Repeat this step six more times. Shahab D. Mohaghegh Chapter THREE - 90

96 Figure 3-2. The Net Present Value Array Program Interface. You will see that you have created a Text Box control array that has a total of eight elements indexing from 0 to 7. Repeat this operation for the label lblyear. You may change the caption property of each element of the label control array as it is shown in the Figure Attach code to the Interface Declarations of variables Click on the "View Code" in the Project Window In the "Object" drop-down list select "General" and in the "Proc:" drop-down list select (declarations) Type the following codes in this window Dim NCF(7) As Single, PV(7) As Single Dim InterestRate As Single, Factor As Single, NetPV As Single Calculate Command Button Double click on the Calculate Command Button Visual Basic responds by opening the Code Window Type the following lines in the Code Window Initializing the Net Present Value for new calculation NetPV = 0 Shahab D. Mohaghegh Chapter THREE - 91

97 Reading the Net Cash Flow values from the TextBoxes For i = 0 To 7 Step 1 NCF(i) = Val(txtNCF(i).Text) Next i 'Calculating the interest factor InterestRate = Val(txtInterestRate.Text) / 100# Factor = InterestRate + 1# 'Calculating Net Present Value For i = 0 To 7 Step 1 PV(i) = NCF(i) / (Factor ^ i) NetPV = NetPV + PV(i) Next i 'Assigning the calculated NPV to label for display lblnpvalue.caption = NetPV 5. Run the program and test it to see if it works properly. 6. Generate the executable file for this Program by clicking on File in the menu bar and choosing Make EXE File.... The Make EXE File dialog box appears and you will be asked if you would like to save the executable file in NPVArray.exe. Accept by clicking O.K. Shahab D. Mohaghegh Chapter THREE - 92

98 Code Interpretation Starting with the declaration, Dim NCF(7) As Single, PV(7) As Single We are declaring an array named NCF that has a total of 8 elements starting from 0 to 7. The elements are NCF(0), NCF(1), NCF(2),, NCF(7). As you can see the code is much more compact and implicit. Next we initialize the NPValue to zero. This is to make sure that every time we are performing a new calculation the Net Present Value from the previous calculation is not being carried over to the new problem. Next is the following set of statements: For i = 0 To 7 Step 1 NCF(i) = Val(txtNCF(i).Text) Next I This is a "For Next" loop structure. The variable i is the counter as was explained in the previous section. It also plays the role of the index in this case. As i steps from 0 to 7 every single element in the NCF( ) array is assigned a value. Each element of the NCF array takes the value of the Text property of the corresponding TextBox control array txtncf( ). The second loop calculates the present value of each entry and then calculates the summation of the present values, which is the Net Present Value. Actually there is an even easier way of writing the code for this program. Following is another shorter version of this program. Test it and see how it works. Shahab D. Mohaghegh Chapter THREE - 93

99 Initializing the Net Present Value for new calculation NetPV = 0 'Calculating the interest factor InterestRate = Val(txtInterestRate.Text) / 100# Factor = InterestRate + 1# 'Reading the Net Cash Flow values from the TextBoxes For i = 0 To 7 Step 1 NCF = Val(txtNCF(i).Text) PV = NCF / (Factor ^ i) NetPV = NetPV + PV Next i 'Assigning the calculated NPV to label for display lblnpvalue.caption = NetPV Data and File Access in Visual Basic As an engineer you will be working with large amounts of data. Most of the information that engineers deal with is in the form of data that is stored in files and/or databases. In this section you will learn how to create a file, read data form the file and write into a file. The sequence for file access in Visual Basic includes the following three steps: 1. Opening an existing file, or creating a non-existing file. Shahab D. Mohaghegh Chapter THREE - 94

100 2. Reading the data in the file and assigning them to variables, or writing the content of some variables into the file. 3. Closing the file. Reading from Sequential Files When reading data from a file, the first step to is open an existing file where data resides. Files in Visual Basic are opened using the Open statement. The syntax for opening a file is: Open pathname For mode As [ # ] filenumber Where pathname mode filenumber includes the drive, directory or folder and the file name specifies the file mode: Append, Binary, Input and Output a valid file number. Each file when opened has a proper number. Two files can not have the same filenumber in the same program. Example: Open "c:\my documents\datafile.txt" For Input As # 1 In above statement the programmer is opening an existing file called "datafile.text". According to the path that is identified in the statement this file resides on the c: drive in a directory called "my documents". The file has been identified as an input file and given a number 1. Since most of the data in engineering applications is stored in ASCII (numbers and characters as opposed to binary) the focus of this book will be on manipulation of ASCII files. Now that the file has been opened, in order to read from it the Input statement should be used. The Input statement has the following syntax: Shahab D. Mohaghegh Chapter THREE - 95

101 Input # number, expressionlist Where number is the file number define when we opened the file. expressionlist is the list of variables the data will be stored in. And finally the file is close using the Close statement. Example: Open "c:\my documents\datafile.txt" For Input As # 1 Input # 1, x, y Close # 1 In the above example the data in the file is apparently in three columns. The programmer has chosen to assign the data in first column to a variable called "x", the data in the second column to variable "y". Please note that the programmer must declare these variables before using them. Once the file has been given a number it would be referred to using that number throughout the program. This way you don't have to type all the information about the file every time you are going to use it. Note that both Input and Close statements refer to the file using its number. Writing to a Sequential Files There are two statements used to write in a sequential file. The syntax of these two statements is given below: Print # number, expressionlist Write # number, expressionlist Shahab D. Mohaghegh Chapter THREE - 96

102 Please note that all the three steps mentioned before are needed here too. In this case the Open statement will create a new file called outputfile.txt if it already does not exist in the "my document" directory. Example: Using the Print statement or Open "c:\my documents\outputfile.txt" For Output As # 1 Close # 1 Print # 1, x, y or using the Write statement or Open "c:\my documents\outputfile.txt" For Output As # 1 Close # 1 Write # 1, x, y EOF Function Lets assume that we know the number of columns in a data file. We assumed that there were two columns of data in the "datafile.txt" file in the previous example. This is quite common because we usually know what type of problem we are solving and what kind of information is available for solving the problem. What is usually unknown is number of data or records that are available for each parameter. In other words we usually know how many columns we have but we seldom know how many lines of data exists in a file. If we have that information the work is easy. Lets assume that we have prior knowledge that the file "datafile.txt" includes two columns and 20 lines of data. In order to read all the data in that file we may write the following code. Shahab D. Mohaghegh Chapter THREE - 97

103 Example: 'Declare variables Dim x (20) as double, y (20) as double Open "c:\my documents\datafile.txt" For Input As # 1 Close # 1 For i = 0 to 20 Input # 1, x (i), y (i) Next i If the number of lines (rows) of data is not known you should use the "End Of File" EOF function in the Visual Basic. This function detects the ending of the file and flags Visual Basic that the end of the file has been reached there are no more data. The syntax of the EOF function is as follows: EOF (# number) Where Number is the number assign to the file. This function can be used as a stand-alone function or in conjunction with "Not" as the negation. Example: 'Declare variables Dim x as Double, count as Integer 'Initialize variables x = 0 count = 0 'Open the file and read the data Open c:\ temp\ data.txt For Input As # 1 Shahab D. Mohaghegh Chapter THREE - 98

104 Do While Not EOF (1) Input # 1, x count = count + 1 Loop Close # 1 In this example the data is only one column and is included in a file named "data.txt" that resides in the 'temp" directory in the "c:" drive. We do not know how many pieces of data are in the file and we would like to find the total number of data in the file. In other words we want to count the number of lines in this file without actually opening it. The variable "count" is declared as an integer and will hold the number of lines in the file. After opening the file we start reading the data in the file and each time we read a data we increment the variable count by 1. By the time we reach the End Of File (EOF) we have counted all the lines in the file. The Read Write Program 1. Open a new Visual Basic Project by clicking on the "New Project" on the "File" menu, and selecting Standard.EXE from the list of icons. 2. Select "Save As..." from the File menu. A dialog box appears with Form1.frm in the File Name window. Type "ReadWrite in place of Form1 and click "O.K." (Make sure you are in the directory that you want). Another dialog box appears with Project1.vbp in the File Name window. Type "ReadWrite" in place of Project1 and click "O.K." 3. Develop the interface using the following information. Figure 3-3 presents the interface developed for this application. Use the table below and try to develop an interface similar to that shown in Figure 4-3. Please note that the label Shahab D. Mohaghegh Chapter THREE - 99

105 controls are not being shown in this table. At this point in the course you are expected to know how to use the label control and make it look the ways you want. Figure 3-3. The Net Present Value Array Program Interface. Object Property Value Text Box Name txtnumber Text Box Name txtxvalmin Text Box Name txtxvalmax Text Box Name txtyvalmin Text Box Name txtyvalmax Command Button Name cmdread Command Button Name cmdwrite Command Button Name cmdminmax Command Button Name cmdexit Shahab D. Mohaghegh Chapter THREE - 100

106 4. Attach code to the Interface Declarations of variables Click on the "View Code" in the Project Window In the "Object" drop-down list select "General" and in the "Proc:" drop-down list select (declarations) Type the following codes in this window Option Explicit Dim x(20) As Single, y(20) As Single Dim i As Integer, j As Integer Dim counterf As Integer Read From File Command Button Double click on the Read From File Command Button Visual Basic responds by opening the Code Window Type the following lines in the Code Window Open "c:\my Documents\Input.txt" For Input As 1 i = 1 Do While Not EOF(1) Input #1, x(i), y(i) i = i + 1 Loop Close #1 Shahab D. Mohaghegh Chapter THREE - 101

107 counterf = i - 1 txtnumber.text = counterf Write To File Command Button Double click on the Write To File Command Button Visual Basic responds by opening the Code Window Type the following lines in the Code Window Open "c:\my Documents\Output.txt" For Output As 2 For i = 1 To counterf Step 1 Print #2, x(i), y(i) Next Close #2 Determine Min and Max Command Button Double click on the Determine Min and Max Command Button Visual Basic responds by opening the Code Window Type the following lines in the Code Window Dim k1 As Single, k2 As Single For i = 1 To counterf Step 1 For j = i + 1 To counterf Step 1 If x(i) >= x(j) Then k1 = x(i) Shahab D. Mohaghegh Chapter THREE - 102

108 x(i) = x(j) x(j) = k1 End If Next Next For i = 1 To counterf Step 1 For j = i + 1 To counterf Step 1 If y(i) >= y(j) Then k2 = y(i) y(i) = y(j) y(j) = k2 End If Next Next txtxvalmin.text = x(1) txtxvalmax.text = x(counterf) txtyvalmin.text = y(1) txtyvalmax.text = y(counterf) 5. Run the program and test it to see if it works properly. 6. Generate the executable file for this Program by clicking on File in the menu bar and choosing Make EXE File.... The Make EXE File dialog box appears and you will be asked if you would like to save the executable file in ReadWrite.exe. Accept by clicking O.K. Shahab D. Mohaghegh Chapter THREE - 103

109 Code Interpretation After declaring all the necessary variables, following code is written for the Read command button. It starts by opening the file that contains the data we are trying to read. Open "c:\my Documents\Input.txt" For Input As 1 The above code uses the open statement and provides the absolute path to the data file Input.txt. Absolute path refers to a path that goes as far back as the disk drive to provide the address for the file. The For Input As 1 indicates the file as one to read from and assigns a number to the file for future reference. i = 1 Do While Not EOF(1) Input #1, x(i), y(i) i = i + 1 Loop Close #1 counterf = i - 1 txtnumber.text = counterf Above code first initializes the index i to one, and then using a Do While loop starts reading the data one at a time. The condition Not EOF (1) indicates that the statements following in the body of the loop are to be executed until the End Of the File is reached and the number 1 in the parentheses refers to the file Input.txt as it was numbered in the open statement. In the body of the loop the code Input #1, x(i), y(i) indicated that data from file number 1 is to be assigned to arrays "x" and "y". Note that at the beginning the value of i is initialized to one. Therefore, the two numbers in the first Shahab D. Mohaghegh Chapter THREE - 104

110 line will be assigned to x (1) and y (1). The statement "i = i + 1" is then executed. This will increment the index i to two. The statement "Loop" indicates the closure of the "Do While Loop" structure. Since after reading the first line of the data from the data file "Input.txt" the EOF is not reached and thus the condition is not met, then the loop continues. Now i has a value of 2, and the next line (line 2) of the data file is read and assigned to x (2) and y (2) and then i is incremented again and so on, until the End Of the File is reached and the loop ends. At this point the file "#1" is closed since we no longer need this file. Note that by incrementing the index i every time that we moved to a new line we have actually counted the number of lines in the data file. We now pass this value to an integer variable called "counterf" using the statement " counterf = i - 1", and subsequently assign "counterf" to the text property of " txtnumber" text box to be displayed on the interface. Next is the code for the "Write" command button. The same logic works here but this time we write to a new file. Following line of code opens the file "Output.txt" if it already exists in the path indicated otherwise would create a file in that directory and names it "Output.txt". It indicates that it is an "Output" file and gives it a number 2. Open "c:\my Documents\Output.txt" For Output As 2 Then using a "For... Next" loop structure and the command "Print" we write each value of the arrays "x" and "y" into the file number 2. Since we now know how many numbers are in each of the "x" and "y" arrays (counterf) we indicated it in our loop structure. Once the loop is completed we close the file using the "Close" command and reference number of the output file which is 2. Shahab D. Mohaghegh Chapter THREE - 105

111 For i = 1 To counterf Step 1 Print #2, x(i), y(i) Next Close #2 The next part of the code is to find the minimum and maximum value in array "x" and "y". The following code is used to accomplish this task. For i = 1 To counterf Step 1 For j = i + 1 To counterf Step 1 If x(i) >= x(j) Then k1 = x(i) x(i) = x(j) x(j) = k1 End If Next Next In this code there is a nested loop structure which means that on loop structure is inside another loop structure. The first loop starts from the first element in the array and goes to the end. The second loop structure loops through all the remaining elements and compares each element with the rest. For example there are 13 elements in this array. In this nested loop structure we start with the first element "i=1" and then the inside loop starts from "j=2" all the way to "j=13" and compares the first element of the array x (1) with all the other elements namely x (2) through x (13). Then the outer loop is incremented and in the next round x (2) is compared with x (3) through x (13) and so on until all the elements are covered. At the end minimum and maximum values are saved Shahab D. Mohaghegh Chapter THREE - 106

112 and using the following code they are passed to the interface to be displayed. This is done for both arrays separately. txtxvalmin.text = x(1) txtxvalmax.text = x(counterf) Try It! Generate a data file (using any ASCII editor such as note pad) that includes numbers 1 through 10. Save the file. Write a program that reads this file and creates another file that contains two columns of data. The first column is the same as the file you read from and the second column includes the square of the number in the first column. What If? Write the same program as in Try It, but this time use the EOF function. Graphing Data in Visual Basic As engineers you will be working with massive amounts of data. This will be the data that you have collected or have been collected by others and your job is to analyze them. Making sense of the data is an important engineering task. One of the best ways to initiate data analysis is to plot the data and look for trends and patterns. In this section we cover one method that you can use to look at your data. There are more than one way to display data as a graph in Visual Basic. We cover a technique that uses the "Picture Box" control in this section. When using "Picture Box" Shahab D. Mohaghegh Chapter THREE - 107

113 control to display data, we use the "PSet" method. A method in Visual Basic is when you ask a control to do something. The "PSet" method sets a point on an object (in this case a "Picture Box" control) to a specified color. The syntax for using the "PSet" method with an object (we are going to use it with the "PictureBox" object in this section) is as follows: object.pset [Step] (x, y), [color] The terms in square brackets [ ] are optional. The optional term [Step] is a keyword specifying that the coordinates (x, y) are relative to the current graphics position given by the CurrentX and CurrentY properties. The term (x, y) are required. They are to be declared "As Single" indicating the horizontal (x-axis) and vertical (y-axis) coordinates of the point to set. The term [color] is also optional. The R (red) G (green) and B (blue) should be declared "As Long" integer values. You can use the RGB function or QBColor function to specify the color. If omitted, the current ForeColor property setting is used. In order to demonstrate the use of the combination of the "PictureBox" object and the "PSet" method we try to simply put some point on a white background. More complex problems will be solved later in this section. The Draw Points Program 1. Open a new Visual Basic Project by clicking on the "New Project" on the "File" menu, and selecting Standard.EXE from the list of icons. 2. Select "Save As..." from the File menu. A dialog box appears with Form1.frm in the File Name window. Type "Draw Points in place of Form1 and click "O.K." (Make sure you are in the directory that you want). Another dialog box appears with Shahab D. Mohaghegh Chapter THREE - 108

114 Project1.vbp in the File Name window. Type "Draw Points" in place of Project1 and click "O.K." 3. Develop the interface using the following information. Figure 3-4 presents the interface developed for this application. Use the table provided and try to develop an interface similar to that shown in Figure 4-4. Please note that the figure shown below represents the interface after the program has been run and the points been drawn. Originally the "Picture Box" control had a plain white background. Figure 3-4. The Draw Points Program Interface. Shahab D. Mohaghegh Chapter THREE - 109

115 Object Property Value Form Name frmdrawpoints Caption Draw Points Program Picture Box Name picdrawpoints Backcolor White color Command Button Name cmddraw Caption &Draw Points Command Button Name cmdexit Caption &Exit 4. Attach code to the Interface Declarations of variables Click on the "View Code" in the Project Window In the "Object" drop-down list select "General" and in the "Proc:" drop-down list select (declarations) Type the following codes in this window Dim R As Long, G As Long, B As Long Dim x As Single, y As Single Dim Counter As Integer As it was mentioned earlier R, G, and B are to be declared "As Long" and the coordinates "As Single". Double click on the "Draw Points" Command Button Shahab D. Mohaghegh Chapter THREE - 110

116 Visual Basic responds by opening the Code Window Type the following lines in the Code Window For Counter = 1 To Step 1 'Determine point color R = Rnd * 255 G = Rnd * 255 B = Rnd * 255 'Determine point ( x,y ) coordinate x = Rnd * picdrawpoints.scalewidth y = Rnd * picdrawpoints.scaleheight 'Draw the points in the picture control Next picdrawpoints.pset (x, y), RGB(R, G, B) 5. Run the program and test it to see if it works properly. 6. Generate the executable file for this Program by clicking on File in the menu bar and choosing Make EXE File.... The Make EXE File dialog box appears and you will be asked if you would like to save the executable file in Draw Points.exe. Accept by clicking O.K. Code Interpretation After declaring all the necessary variables, a "For Next" loop structure is opened to repeat a set of instructions for 10,000 times. The instructions inside the loop are divided into three sections. First section includes assigning integer values to R, G, and B using Shahab D. Mohaghegh Chapter THREE - 111

117 the Rnd function that is Visual Basic's random number generator. Each of these variables can have a value between 0 and 255. Since the Rnd function provides a value between 0 and 1 it should be multiplied by 255 to get a random values between 0 and 255. In the second section of the code x and y coordinates of the point is chosen randomly. The random number generated for x and y should be multiplied by the "ScaleWidth" and "ScaleHeight" property of the "Picture Box" control. This is to ensure that the point being printed falls inside the control. The "ScaleWidth" and "ScaleHeight" property of the "Picture Box" control are set automatically as you place this control on the form and resize it using your mouse. To check this you can click on the "Picture Box" control on the interface to select it. Once it is selected, click on one of the six handles around it and resize it. Look at the "ScaleWidth" and "ScaleHeight" properties in the property window while resizing the control. The third and last section of the code is to draw the point using the random numbers generated for the color and position of the point in the following manner. Please note that the RGB function is used to generate the color using the R, G, and B values. picdrawpoints.pset (x, y), RGB(R, G, B) Drawing Lines In this section you will learn how to draw lines using the "Picture Box" control. As with the "PSet" method there is another method associated with the "Picture Box" control called the "Line" method. Following line of code draws a line in a picture box. PictureBoxName.Line ( x1, y1 ) ( x2, y2 ), RGB ( 0, 0, 0 ) Shahab D. Mohaghegh Chapter THREE - 112

118 The line starts at coordinates x1 and y1 and continues to coordinates x2 and y2. As for the "PSet" method the RGB function provides the color option for the method. Instead of using the second coordinates x2 and y2 you may choose to use another way of identifying the end point of the line. This can be accomplished by the use of "Step" keyword. The syntax for using the "Step" keyword is as follows: PictureBoxName.Line ( x1, y1 ) Step ( dx, dy ), RGB ( 0, 0, 0 ) In this case the line starts at the same x1 and y1 location and ends at (x1+dx) and (y1+dy). Using the Step keyword in the "Line" method one can draw polygons. Following is an example of using this technique to draw a rectangle. PictureBoxName.Line (10,10) - Step (90,0) PictureBoxName.Line - Step (0,90) PictureBoxName.Line - Step (-90,0) PictureBoxName.Line - Step (0,-90) The above code draws the square in Figure 3-5. Please note that the origins of the coordinates, i.e. x = 0, and y = 0 are at top left corner. Shahab D. Mohaghegh Chapter THREE - 113

119 Figure 3-5. The code draws this square. The first line of code draws a horizontal line from the top left corner to the top right corner. The second line of code draws the vertical line from the top right corner to the bottom right corner. The third line of code draws the horizontal line form the bottom right corner to the bottom left corner and finally the last line of the code completes the square by drawing the vertical line from the bottom left corner to the top left corner. This technique should be used for drawing triangles and other polygons since there is an easier way of drawing squares and rectangles in Visual Basic. The same square could have been drawn using the following single line of code. PictureBoxName.Line (10,10) - (100,100), B In the above code one specifies the top left and bottom right corners and the option "B" instructs Visual Basic to draw a box. Furthermore adding a letter "F" instructs Visual Basic to fill the box with the color specified in RGB Function. Following is an example for drawing a red box. Shahab D. Mohaghegh Chapter THREE - 114

120 PictureBoxName.Line (10,10) - (100,100), RGB (255,0,0), BF We now develop an application that draws a line in the picture box and also draws some random lines. The Draw Lines Program 1. Open a new Visual Basic Project by clicking on the "New Project" on the "File" menu, and selecting Standard.EXE from the list of icons. 2. Select "Save As..." from the File menu. A dialog box appears with Form1.frm in the File Name window. Type "Draw Lines in place of Form1 and click "O.K." (Make sure you are in the directory that you want). Another dialog box appears with Project1.vbp in the File Name window. Type "Draw Lines" in place of Project1 and click "O.K." 3. Develop the interface using the following information. Figure 3-6 presents the interface developed for this application. Use the table provided and develop an interface similar to that shown in Figure 3-6. Object Property Value Form Name frmlines Caption The Lines Program Picture Box Name picdrawlines Backcolor White color Command Button Name cmddraw1 Caption &Draw a Line Command Button Name cmddraw2 Caption &Draw Random Lines Shahab D. Mohaghegh Chapter THREE - 115

121 Command Button Name cmdexit Caption &Exit Figure 3-6. The Draw Lines Program Interface. 4. Attach code to the Interface Declarations of variables Click on the "View Code" in the Project Window In the "Object" drop-down list select "General" and in the "Proc:" drop-down list select (declarations) Type the following codes in this window Declarations of variables Click on the "View Code" in the Project Window Shahab D. Mohaghegh Chapter THREE - 116

122 In the "Object"drop-down list select "General" and in the "Proc:" drop-down list select (declarations) Type the following code in this window Dim Counter As Integer Draw a line that passes through given coordinates in the PictureBox control Double click on the Draw a Line Command Button Visual basic responds by opening the Code Window Write the following code in the cmddraw1_click () event procedure. picdrawlines.line (500, 200)-(4000, 1000), RGB(120, 120, 0) Draw 100 random lines in the Picture Box control Double click on the Draw Random Lines Line Command Button Visual basic responds by opening the Code Window Write the following code in the cmddraw2_click () event procedure For counter = 1 To 100 Step 1 picdrawlines.line -(Rnd * picdrawlines.scalewidth, Rnd *_ picdrawlines.scaleheight) Next 5. Run the program and test it to see if it works properly. 6. Generate the executable file for this Program by clicking on File in the menu bar and choosing Make EXE File.... The Make EXE File dialog box appears and you Shahab D. Mohaghegh Chapter THREE - 117

123 will be asked if you would like to save the executable file in Draw Lines.exe. Accept by clicking O.K. Code Interpretation This code is quite simple. It includes a single line for the first command button and a loop structure for the random lines. The single line of code for drawing a line given a certain coordinates is as follows: picdrawlines.line (500, 200)-(4000, 1000), RGB(120, 120, 0) This line simply identifies the "Line" method for the "picdrawlines" Picture Box control and passes the point (500,200) as the starting point and (4000,1000) as the end point of the line. The RGB function specifies the red, green, and blue values for the color of the line. In the second part the following "For Next" loop structure generates 100 randomly generated lines. picdrawlines.line -(Rnd * picdrawlines.scalewidth, Rnd *_ picdrawlines.scaleheight) The above line of code is very similar to the first line of code. There is one major difference between these two lines of code. Notice that in the previous code, both starting and ending points of the line were specified but in the latter code only one point (randomly generated and scaled to the width and height of the PictureBox control) is specified. This is due to the fact that the PictureBox control has two properties called "Current X" and "Current Y". These properties return or set the horizontal (CurrentX) or Shahab D. Mohaghegh Chapter THREE - 118

124 vertical (CurrentY) coordinates for the next printing or drawing method. So the end point of each line becomes the starting point of the next line and you need only to provide one point. Try It! 1. Modify the "Draw Lines" program such that it will accept user's input for the start and end points of the line. Then draw the line. 2. Modify the above application by checking the user input to see if it fits in the Picture Box control. If it does not, scale it down so it would fit, before drawing it. Graphing Functions In this section you will learn how to graph functions and equations using the PictureBox control and methods. The general idea is to generate an interface that has a PictureBox control and a command button. Start by assigning scale to the PictureBox control and then draw the axes and then put the equation you are trying to graph in a "For Next" loop and draw it using the "Pset" method. Following is a simple example. The Draw Equation Program 1. Open a new Visual Basic Project by clicking on the "New Project" on the "File" menu, and selecting Standard.EXE from the list of icons. 2. Select "Save As..." from the File menu. A dialog box appears with Form1.frm in the File Name window. Type "DrawEquation in place of Form1 and click "O.K." (Make sure you are in the directory that you want). Another dialog box appears with Shahab D. Mohaghegh Chapter THREE - 119

125 Project1.vbp in the File Name window. Type "Draw Equation" in place of Project1 and click "O.K." 3. Develop the interface using the following information. Object Property Value Form Name frmlines Caption Draw Equation Picture Box Name picequation Backcolor White color Command Button Name cmdrun Caption &Calculate Command Button Name cmdexit Caption &Exit Figure 3-7 presents the interface developed for this application. Use the table provided and develop an interface similar to that shown in Figure 3-7. Shahab D. Mohaghegh Chapter THREE - 120

126 4. Attach code to the Interface Figure 3-7. The Draw Equation Program Interface. Draw Y = 0.25 * X 2 equation in the PictureBox control Double click on the Calculate Command Button Visual basic responds by opening the Code Window Write the following code in the cmdcalculate_click () event procedure. Dim x As Single, y As Single picequation.scale (-1, 21)-(11, -1) picequation.line (0, 0)-(10, 0) picequation.line (0, 20)-(0, 0) picequation.currentx = 0 picequation.currenty = 0 picequation.print "0" picequation.currentx = 10 picequation.currenty = 0 picequation.print "10" picequation.currentx = -1 picequation.currenty = 20 picequation.print "20" For x = 0 To 9 Step 0.01 y = 0.25 * x ^ 2 picequation.pset (x, y), QBColor(2) Next Shahab D. Mohaghegh Chapter THREE - 121

127 5. Run the program and test it to see if it works properly. 6. Generate the executable file for this Program by clicking on File in the menu bar and choosing Make EXE File.... The Make EXE File dialog box appears and you will be asked if you would like to save the executable file in Draw Equation.exe. Accept by clicking O.K. Code Interpretation The first step in using a Picture Box control is to assign a scale to it. This is done using the "Scale" method. "Scale" method defines the coordinate system for a Picture Box. picequation.scale (-1, 21)-(11, -1) In the above code, the picture box has been divided into 12 equal segments starting from "-1" to "11" along the x-axis (horizontally) and into 22 equal segments starting from "-1" to "21" along the y-axis (vertically). Again remember that the top left corner is the origin. Next we draw two straight lines that would represent the x and y-axis of the graph. picequation.line (0, 0)-(10, 0) picequation.line (0, 20)-(0, 0) Now using the "Print" method the numbers 0, 10, and 20 are written on the control. Here the CurrentX and CurrentY properties that were covered in the previous example are used to specify the location where the text is printed. picequation.currentx = 0 picequation.currenty = 0 Shahab D. Mohaghegh Chapter THREE - 122

128 picequation.print "0" picequation.currentx = 10 picequation.currenty = 0 picequation.print "10" picequation.currentx = -1 picequation.currenty = 20 picequation.print "20" Now that the coordinate system and the axes are set, it is time to graph the function. Following "For Next" loop structure is written to generate the necessary points. The body of this loop structure includes two statements. The first statement represents the equation being graphed. This statement generates the y coordinates for each x coordinate generated by the loop. The second statement draws a point using the x and y coordinates. For x = 0 To 9 Step 0.01 y = 0.25 * x ^ 2 picequation.pset (x, y), QBColor(2) Next In the above example QBColor is used instead of the RGB function. As you can see the loop structure provides the x value in small enough increments so the points generate the illusion of a line. Shahab D. Mohaghegh Chapter THREE - 123

129 Try It! 1. Use the above example as guide to generate a line representing the following equation. Select control size and x, y ranges such that a clear view of the equation is achieved. Y = 3.5 Sin ( 2x 2 ) Summary In this chapter you learned about Arrays, loops, data access and graphs in Visual Basic. These topics are among important tools for engineers. By now you have learned to use Visual Basic to perform elementary engineering calculations. Keywords Arrays Loop structure Repetition Data access File access Plots Graphs Points Lines Equations Shahab D. Mohaghegh Chapter THREE - 124

130 Exercises 1. Write an application that accesses a predetermined file on the floppy drive. Reads the file content and plots them. 2. Identify two non-linear equations with two unknowns. Write an application that plots the two equations and identify the solution of the equations as the location they meet on the plot. Shahab D. Mohaghegh Chapter THREE - 125

131 4 Visual Basic s Grid Control In this chapter you will be introduced to one of the most important custom controls that Visual Basic provides, the grid control. The use of this control is very helpful in most of the engineering applications. The grid control, which is similar to a spreadsheet, allows you to visualize and manipulate data for your applications. At the end of this chapter you will be able to handle the grid control, its properties and methods. In this chapter array and variable declaration will be revisited and the idea of variable and array scope will be covered. Introduction This chapter is entirely dedicated to the Microsoft grid control. You will see that almost all the operations performed with the grid control somehow involve a loop structure. Visual Basic has two types of controls. The first type is the basic controls that appear regularly in the toolbox and the second type is the custom controls. Custom controls are not initially a part of the toolbox. The programmer should add them when necessary. Since grid control is a custom control first we have to add it to our project before being able to use it. Once added it will appear in the toolbox. Developing an Application with Grid Control In this section of the book we start by developing a very simple application that includes a grid control. The main objective at this point is to see how a custom control is added to a project and how it is used. In this application we add the grid control to the project, Shahab D. Mohaghegh Chapter FOUR - 126

132 place it on a form and talk about its basic properties. In the next application we dive a little deeper into the grid control and use it in a more meaningful fashion. Grid Application 1. Open a new Visual Basic Project by clicking on the "New Project" on the "File" menu, and selecting Standard.EXE from the list of icons. 2. Select "Save As..." from the File menu. A dialog box appears with Form1.frm in the File Name window. Type "Grid Application in place of form1 and click "O.K." (Make sure you are in the directory that you want to be). Another dialog box appears with Project1.vbp in the File Name window. Type " Grid Application " in place of Project1 and click "O.K." 3. Before developing the interface we must first add the grid control to the project. Click on the Project in the Menu bar and Select Components from that menu. This will bring up the Components dialog box. You can bring up the Components dialog box by pressing Control + T. Figure 4-1 shows the Components dialog box. Figure 4-1. Component dialog box. Shahab D. Mohaghegh Chapter FOUR - 127

133 As indicated in Figure 4-1 Visual basic provides many custom controls. We will visit more custom controls in the future chapters of this book. At this point you should check the box beside the Microsoft FelxGrid Control 6.0. Once the box is checked click OK. You will see that the FlexGrid Control is added to your project toolbox. Figure 4-2 is the icon representing this control. Figure 4-2. Microsoft FelxGrid Control 6.0. Now double click on the FlexGrid Control to place it on the form. Use the resize handles to resize the grid control until it looks like the Figure 4-3. Figure 4-3. The grid application interface. As you see in Figure 4-3 the FlexGrid control displays two rows and two columns by default. Select the grid control by clicking on it. Its properties will appear in the property widow. Make the following modifications to the Name, Cols, and Rows properties: Shahab D. Mohaghegh Chapter FOUR - 128

134 Object Property Value FlexGrid Name GrdProduction Cols 5 Rows 10 Command Button Name cmdexit Caption &Exit By default the FlexGrid will display the first row and column in gray, these are called FixedRow and FixedCol, respectively. They are used to display the title of rows and columns respectively. You will see that the grid control displays the number of rows and columns indicated in the properties. Use the handles and resize the grid control to fit the ten rows and five columns. Figure 4-4 shows what your form should look like. Figure 4-4. Modified grid application interface. 4. Attach code to the Interface by adding the end statement to the Exit Command Button. Shahab D. Mohaghegh Chapter FOUR - 129

135 5. Run the program and test it to see if it works properly. 6. Generate the executable file for this Program by clicking on File in the menu bar and choosing Make EXE File...". The Make EXE File dialog box appears and you will be asked if you would like to save the executable file in Grid Application.exe. Accept by clicking O.K. Try It! Go back to application you just developed. In the design mode select the grid control by clicking on it. Now use the handle and resize the control so the ten rows and five columns would not fit in it. What happens? Working with Grid Control Now that we learned how to add a custom control to our project and modify its properties, it is time to write useful programs using the grid control. It is important to note that the content of the grid control can be set at the design time and/or be modified in run time. We will write applications that deal with both situations. First lets get familiar with the grid control lay out. A grid control should be treated as a table or a matrix. It includes rows and columns. Every cell or element of the grid control is addressed by the row and column number it occupies. In order to modify the content of a cell, you must first identify its row and column and then place the statement that modifies the content of the cell. In essence the elements in a grid control are much like a two dimensional array. Following is a table that shows how the cells or elements in a grid control are addressed. Shahab D. Mohaghegh Chapter FOUR - 130

136 Col #1 Col #2 Col #3 Col #4 Row #1 cell (1,1) cell (1,2) cell (1,3) cell (1,4) Row #2 cell (2,1) cell (2,2) cell (2,3) cell (2,4) Row #3 cell (3,1) cell (3,2) cell (3,3) cell (3,4) Row #4 cell (4,1) cell (4,2) cell (4,3) cell (4,4) Row #5 cell (5,1) cell (5,2) cell (5,3) cell (5,4) Lets write a program that calculates the reserve a hydrocarbon reservoir. In the FixedCol we will write the depth interval and in the FixRow the average thickness, average porosity and the average saturation for the corresponding depth interval. The last column will be dedicated to calculation of the average reserve for the depth interval. For this problem the above table will look as follows: Depth Int. Thickness Porosity Saturation Reserve cell (1,1) cell (1,2) cell (1,3) cell (1,4) cell (2,1) cell (2,2) cell (2,3) cell (2,4) cell (3,1) cell (3,2) cell (3,3) cell (3,4) cell (4,1) cell (4,2) cell (4,3) cell (4,4) cell (5,1) cell (5,2) cell (5,3) cell (5,4) Now lets implement the above table in a grid control. Since we want this to appear when the program starts, the code has to be written under the Form_Load procedure. Also note that the FixRow and FixCol are indexed with zero. In other words FixRow and FixCol are the zero row and column respectively. Shahab D. Mohaghegh Chapter FOUR - 131

137 The Reserve Calculation program 1. Open a new Visual Basic Project by clicking on the "New Project" on the "File" menu, and selecting Standard.EXE from the list of icons. 2. Select "Save As..." from the File menu. A dialog box appears with Form1.frm in the File Name window. Type "Reserve in place of form1 and click "O.K." (Make sure you are in the directory that you want to be). Another dialog box appears with Project1.vbp in the File Name window. Type " Reserve Program " in place of Project1 and click "O.K." 3. Using the process covered in the previous example add the grid control to your project. The user interface of this program is very much the same as the previous program. Develop the interface and make the appropriate changes so it would satisfy the requirements of this example. Figure 4-5 provides the necessary information for the number of columns and rows that are needed for this example. 4. Attach code to the Interface by adding the end statement to the Exit Command Button. Also use the following code in the Form_Load procedure. ' specify the column using Col property GrdReserve.Col = 0 ' specify the row using Row property GrdReserve.Row = 0 ' write in the grid using text property GrdReserve.Text = "Depth" ' specify the next row,( as you see the column # remains the same) GrdReserve.Row = 1 GrdReserve.Text = " " GrdReserve.Row = 2 GrdReserve.Text = " " Shahab D. Mohaghegh Chapter FOUR - 132

138 GrdReserve.Row = 3 GrdReserve.Text = " " GrdReserve.Row = 4 GrdReserve.Text = " " GrdReserve.Row = 5 GrdReserve.Text = " " GrdReserve.Row = 6 GrdReserve.Text = "Total" ' same procedure applied to write in rows GrdReserve.Row = 0 GrdReserve.Col = 1 GrdReserve.Text = "Thickness" GrdReserve.Col = 2 GrdReserve.Text = "Porosity" GrdReserve.Col = 3 GrdReserve.Text = "Saturation" GrdReserve.Col = 4 GrdReserve.Text = "Reserve Estimate" Once the above code is written in the Form_Load procedure you can run the program and check the results. The interface now should look like Figure 4-5. Note that the title of the last column has been truncated. Therefore we need to increase the column width in order to accommodate large titles. This can be done using the properties that allows programmers to modify the cell dimensions in a grid control. These properties modify the width of a cell or the height of the cell. The syntax is as follows: Shahab D. Mohaghegh Chapter FOUR - 133

139 ColWidth ( number as Integer ) RowHeight ( number as Integer ) The number in the parentheses specifies the row or column that is to be modified. Figure 4-5. The Reserve calculation program interface. Following code will provide proper width and height for the cells. Add this piece of code to the bottom of the previous code in the Form_Load procedure. ' increase the height of the cells in all rows For i = 0 To 6 Step 1 GrdReserve.RowHeight(i) = 300 Next ' specify the width of the column using Col property GrdReserve.Col = 0 ' increase the width of the cells in Col #4 ( FixCol ) GrdReserve.ColWidth(4) = 1400 Shahab D. Mohaghegh Chapter FOUR - 134

140 Now we add a command button to the form and use it as a means to add the desired values to the grid control and perform the appropriate calculations. After adding the command button (which we will name cmdreserve) the interface will look as Figure 4-6. Remember that we have altered the cell width and height too. Figure 4-6. The Reserve calculation program interface. Add the following code to the cmdreserve_click procedure. Dim h(5) As Single, p(5) As Single, s(5) As Single Dim res(5) As Single, reserve As Single ' First Column is the thickness GrdReserve.Col = 1 For i = 1 To 5 Step 1 GrdReserve.Row = i GrdReserve.Text = 100 h(i) = Val(GrdReserve.Text) Next Shahab D. Mohaghegh Chapter FOUR - 135

141 ' Let's assume that the porosity does not change with depth GrdReserve.Col = 2 For i = 1 To 5 Step 1 GrdReserve.Row = i GrdReserve.Text = 0.35 p(i) = Val(GrdReserve.Text) Next ' Let's assume that saturation increases uniformly with depth GrdReserve.Col = 3 For i = 1 To 5 Step 1 GrdReserve.Row = i GrdReserve.Text = i * 0.15 s(i) = Val(GrdReserve.Text) Next 'Finally calcualte the reserve per depth interval per square feet GrdReserve.Col = 4 For i = 1 To 5 Step 1 GrdReserve.Row = i res(i) = h(i) * p(i) * s(i) GrdReserve.Text = res(i) Next 'Calcualte total reserve reserve = 0 For i = 1 To 5 Step 1 Shahab D. Mohaghegh Chapter FOUR - 136

142 Next reserve = reserve + res(i) 'Print it on the grid GrdReserve.Col = 4 GrdReserve.Row = 6 GrdReserve.Text = reserve 5. Run the program and test it to see if it works properly. 6. Generate the executable file for this Program by clicking on File in the menu bar and choosing Make EXE File...". The Make EXE File dialog box appears and you will be asked if you would like to save the executable file in Reserve Calcualtion.exe. Accept by clicking O.K. Try It! Try to use nested loop structure to accomplish the task in the Reserve Calculation program. What If? How would the code of the Reserve Calculation program change if instead of For Next loop structures, Do While loop structures are used? Shahab D. Mohaghegh Chapter FOUR - 137

143 Filling the Grid Control from a File In the above example the value of each cell in the grid control was set individually during the design time. In most of the engineering problems that you will encounter data is saved in a separate file and you need to import it into your application before manipulating it. In this section we examine a situation that you have the data in a text file. Your goal is to import the data into the application and display it in a grid control to examine its accuracy. Once the accuracy of the data is confirmed, the calculation will take place. We use the previous example and enhance it in order to achieve our goal. The Reserve Table program 1. Open a new Visual Basic Project by clicking on the "New Project" on the "File" menu, and selecting Standard.EXE from the list of icons. 2. Select "Save As..." from the File menu. A dialog box appears with Form1.frm in the File Name window. Type "Reserve in place of form1 and click "O.K." (Make sure you are in the directory that you want to be). Another dialog box appears with Project1.vbp in the File Name window. Type " Reserve Table Program " in place of Project1 and click "O.K." 3. By now you should know how to add the grid control to your projet. Add te grid control to this project. The interface of this example is very much like the one from the last example. There is one minor difference and that is the addition of an other command button. Develop the interface for this example so it would look like Figure 4-7. Shahab D. Mohaghegh Chapter FOUR - 138

144 Figure 4-7. The Reserve table program interface. 4. The code attached to the Form_Load procedure and cmdexit_click procedure will stay the same. We need to attach the code for the Import Data command button and modify the code for the Calculation command Button. First step is to declare variables. Attach the following code to the general declaration section: 'Declaring arrays to be used by all the procedures in this form. Private h(5) As Single, p(5) As Single, s(5) As Single Then add the following code to the Click event of the Import Data command button: 'Open the data file Open "c:\temp\data.txt" For Input As 1 i = 1 For i = 1 To 5 Step 1 Assign data to the arrays Input #1, h(i), p(i), s(i) Shahab D. Mohaghegh Chapter FOUR - 139

145 Print them in the grid control cells GrdReserve.Row = i GrdReserve.Col = 1 GrdReserve.Text = h(i) GrdReserve.Col = 2 GrdReserve.Text = p(i) GrdReserve.Col = 3 GrdReserve.Text = s(i) Next Close #1 Attach the following code to the Click event of the Calculate command button: Dim res(5) As Single, reserve As Single 'Finally calcualte the reserve per depth interval per square feet GrdReserve.Col = 4 For i = 1 To 5 Step 1 GrdReserve.Row = i res(i) = h(i) * p(i) * s(i) GrdReserve.Text = res(i) Next 'Calcualte total reserve reserve = 0 For i = 1 To 5 Step 1 reserve = reserve + res(i) Shahab D. Mohaghegh Chapter FOUR - 140

146 Next 'Print it on the grid GrdReserve.Col = 4 GrdReserve.Row = 6 GrdReserve.Text = reserve Code Interpretation There is couple of important issues that should be discussed at this point. First has to do with the variable declaration. Note that we declared the arrays h(5), p(5), and s(5) using the Private statement in the general declaration segment and not in a specific procedure. Private h(5) As Single, p(5) As Single, s(5) As Single In Visual Basic there are three types of variable or array declaration. They are Dim, Private and Public. These declaration statements differ from on another in scope. By scope we mean the amount of code they serve. For example Dim only serves a procedure or function. In other words, when a variable is declared using the Dim statement in a procedure, it can not be seen or used by other procedures and functions even in the same form. In Visual Basic complete programs or applications are referred to as projects. Each project consists of one or more form and/or module. Each form or module includes one or more procedure and/or function. The scope of variable and array declaration follows the sequence of procedure (function), form (module), and project. As shown in Figure 4-8 the Dim statement s scope is limited to a procedure or a function. The scope of the Private statement is the form or module, which includes many procedures and Shahab D. Mohaghegh Chapter FOUR - 141

147 functions, and finally the scope of the Public statement is the entire project that includes one or more form or module. Therefore in this project the three arrays h(5), p(5), and s(5) are available to all the procedures in the form. Figure 4-8. Scope of declaration statements in visual Basic. It also should be noted that the wider the scope of a declaration statement the more expensive (from a memory standpoint) it is. Therefore it is a good programming practice to use the narrowest possible scope for each array or variable. In other words, if you can get away with using the Dim Statement don t use the Private statement and if you can get away with using the Private statement do not use the Public statement. The file data.txt which is an ASCII file and includes all the data needed for our project resides in the c:\temp directory. Figure 4-9 shows the data.txt file in the Windows NotePad editor. As it was covered in the previous sections, we first open the file using the Open statement. Open "c:\temp\data.txt" For Input As 1 Shahab D. Mohaghegh Chapter FOUR - 142

148 Figure 4-9. The data.txt file used in this application. Once the file is opened, using a For Next loop structure we first assign the data to the h, p, and s arrays: For i = 1 To 5 Step 1 Input #1, h(i), p(i), s(i) Then using the Row and Col properties of the grid control we write the data into the grid control. This is for visual observation of the data. Once the process is completed the loop structure is closed and then the data file is closed. GrdReserve.Row = i GrdReserve.Col = 1 GrdReserve.Text = h(i) GrdReserve.Col = 2 GrdReserve.Text = p(i) GrdReserve.Col = 3 Shahab D. Mohaghegh Chapter FOUR - 143

149 Close #1 Next GrdReserve.Text = s(i) One important issue at this point is that although you can visually inspect the data, there is not much you can do with it. Especially if there is a problem with a data point you have no access to it in order to alter its value. This is the subject of the next section. Next we have to perform the reserve calculations and print the result in the appropriate cells in the grid control. We start by declaring new variables. Since these variable are going to be used only in this procedure there was no need to declare them at the form level. Dim res(5) As Single, reserve As Single The reserves are calculated using the arrays within a loop structure. They are then placed in the appropriate cells in the grid control. GrdReserve.Col = 4 For i = 1 To 5 Step 1 GrdReserve.Row = i res(i) = h(i) * p(i) * s(i) GrdReserve.Text = res(i) reserve = reserve + res(i) Next GrdReserve.Col = 4 GrdReserve.Row = 6 Shahab D. Mohaghegh Chapter FOUR - 144

150 GrdReserve.Text = reserve Manipulating Grid Control at Run-Time So far we have learned a lot about grid control. But almost everything we have learned has to do with working with grid control during the design time. In this section we learn how to change the content of a cell in the grid control when the application is running. We will use what we have developed in the previous examples. The Table Modification program 1. Open a new Visual Basic Project by clicking on the "New Project" on the "File" menu, and selecting Standard.EXE from the list of icons. 2. Select "Save As..." from the File menu. A dialog box appears with Form1.frm in the File Name window. Type "Modify in place of form1 and click "O.K." (Make sure you are in the directory that you want to be). Another dialog box appears with Project1.vbp in the File Name window. Type " Table Modification Program " in place of Project1 and click "O.K." 3. Add the grid control to your projet. The interface of this example is exactly similar to the interface of one of the previous examples as shown in Figure The code written in the Form_Load, the cmdexit_click, and the cmdreserve_click procedures will stay exactly the same as the previous example. The only part of the code that is going to change is the code that has to do with the grid control. Following code is written in the GrdReserve_KeyPress procedure. When you choose the KeyPress event of the grid control you notice that this procedure requires a parameter to be passed to it. This parameter is an integer and appears in the parentheses as Shahab D. Mohaghegh Chapter FOUR - 145

151 KeyAscii. Therefore the first line of the code (which is provided by the Visual Basic and you do not have to write it) is as follows: Private Sub GrdReserve_KeyPress(KeyAscii As Integer) Then add the following code to this procedure. Dim oldrow As Integer, oldcol As Integer ' Make rows lower than 5 and in column 4 inaccessible If GrdReserve.Col <> 4 Then If GrdReserve.Row < 6 Then 'Accept only numbers and decimal points If (KeyAscii < Asc(".")) Or KeyAscii > Asc("9") Then _ KeyAscii = 0 GrdReserve.Text = GrdReserve.Text & Chr$(KeyAscii) End If End If Once you save your application it is ready to be run. Run the application and while it is running click on each cell and enter a number. Once all the cells are full, then click the Calculate Reserves command button and the rest of the cells will be fills with appropriate values. As you can see this application gives the user access to the individual cells in the grid control. This application does two more things. First it does not accept irrelevant user input such as alphabetical values in the cells. Try typing a letter instead of a number in the cell. You will not be able to. Second, it does not let users have access to the cells that are reserved for calculated values. For example you will not be able to write Shahab D. Mohaghegh Chapter FOUR - 146

152 anything in the Reserve Estimate column or the Total row. Let s see how we accomplished these tasks. Code Interpretation Since the code in the Form_Load, the cmdexit_click, and the cmdreserve_click procedures are repetitions, we will not discuss them. Instead we will concentrate on the GrdReserve_KeyPress procedure. The first line that is provided by Visual Basic: Private Sub GrdReserve_KeyPress(KeyAscii As Integer) Indicated that an integer (KeyAscii) must be passed to this procedure. Since this procedure acts on users input (from the keyboard) we have to trap users keystrokes and make sure that the user has pushed right keys. The right keys in this application constitutes numbers 0 to 9 and the decimal point.. This is accomplished by the following IF statement. If (KeyAscii < Asc(".")) Or KeyAscii > Asc("9") Then KeyAscii = 0 In the above statement we check the user s keystroke and let it be passed to the routine if it is the right keystroke. If it is not one of the keys that we consider to be the right key we instead pass the KeyAscii = 0 which is the same as null. This is the reason nothing will appear in the cell if the user pushes any key other than 0 through 9 or the decimal point. Moreover, once one of the right keys is pushed, it is trapped, and changed to an integer using the Visual Basic s Asc() function. This integer is a standard value that can be looked up in the ASCII table. Shahab D. Mohaghegh Chapter FOUR - 147

153 The keystroke at this point satisfies the desired condition but is not in the form that can be shown in the grid control. In order to reflect the user s keystroke in the grid control the integer needs to be changes back to an ASCII character (0 through 9 and the decimal point). This is done using Visual Basic s Chr$() function and then be added to the grid control s Text property. This is achieved using the following line of code. GrdReserve.Text = GrdReserve.Text & Chr$(KeyAscii) In order to make sure that certain rows and column is also off limit to the user for input we use the following nested IF statements: If GrdReserve.Col <> 4 Then If GrdReserve.Row < 6 Then End If End If Try It! Now that you have learned to add values to the grid control during run-time, develop an application that is completely empty and user has to fill all the cells including the title of the rows and columns at run-time. The user should be able to use any keystroke for the title row and column and only numerical keystrokes should be allowed for the rest of the cells. Shahab D. Mohaghegh Chapter FOUR - 148

154 Summary This would be some summary text. Keywords Custom Control Grid Control Column Row Design time Run-time Exercises 1. Develop an application that has two text boxes where user can input two numbers. Use the random number generator function in Visual Basic and generate 100 numbers using the numbers provided by the user as the min. and max. Display the results in a grid control. 2. Take the application in Exercise 1 one step further by providing a picture box control and plot the data in the grid control in the picture box control. 3. Use the concept in Exercise 2 and code a polynomial in your application. Show the form of the polynomial on the main form of your application. Use the min Shahab D. Mohaghegh Chapter FOUR - 149

155 and max provided by the user and the random number generator function to generate data using the polynomial function and then plot the result. Shahab D. Mohaghegh Chapter FOUR - 150

156 5 Functions and Procedures in Visual Basic In this chapter you will be introduced to modular programming in Visual Basic. The structural programming technique brakes the program into small subprograms. These subprograms that are designed to perform specific tasks are called functions and/or procedures. Visual Basic has several native functions and procedures. These are subprograms that have been provided as part of the programming language. A classic example is the Message dialog box. Apart from the native functions and procedures Visual Basic allows the programmer to define her/his own functions and procedures. Introduction User-Defined functions and procedures are also called subprograms. Functions and procedures perform specific tasks that are repeated within a program. They can also be reused in other programs. These subprograms are then called in the main program whenever is needed to perform that specific task. For example once you have written a function that calculates the area of a circle, given the radius, the function can be used in any program that calculation of the area of a circle is needed. The advantages that subprograms (functions and procedures) provide are two folds. First the code is written once and can be called as many times, as it is needed as was mentioned in the example on the area of a circle. Second using the divide and conquer metaphor, dividing the program into smaller, more manageable subprograms makes the debugging process much easier. Shahab D. Mohaghegh Chapter FIVE - 160

157 So far we have been using the words function and procedure as synonyms. They are different. There is a major distinction between a function and a procedure. A function will always return a value, while a procedure does not return a value. In this chapter we will be dealing with both functions and procedures and through examples show you how to implement them in your programs. Discussion of some related topics will become necessary throughout this chapter. We will cover each related topic, as it becomes necessary. Functions A Function is a separate procedure that can take arguments, perform a series of statements, and change the values of its arguments. You can use a Function on the right side of an expression in the same way you use any native function, such as Sqr (square root), Cos (cosine), or Chr (character), when you want to use the value returned by the function. The general form of a Function is as follows: Private Function FunctionName (parameter1 As Type, ) As Type Statements FunctionName= expression [Exit Function] Statements FunctionName= expression End Function Shahab D. Mohaghegh Chapter FIVE - 161

158 The parameter1, parameter2 are the variables (also known as arguments) passed to the Function. Note also that it is possible not to pass any variables to a function and still return a value. Argument1, argument2, are usually declared as a type such as string, integer, single, or double. A Function is called using the function name, followed by the argument list in parentheses, in an expression. The Exit Function statement causes an immediate exit from a Function procedure. Program execution continues with the statement following the statement that called the Function procedure. Any number of Exit Function statements can appear anywhere in a Function procedure. Note that in the Function has started with the keyword Private. This indicates that the Function is accessible to the form or module it has been written in. In order to make the Function accessible to all the forms and modules in the program it should be declared as Public. The scope of a Function follows the same logic as the scope for variables as was explained in the previous chapter. Use the following syntax to call a Function: FunctionName ( argument1, argument2, ) As mentioned before a function can also be called on the right side of an expression. Some functions have arguments passed to them. Functions use these arguments to perform calculations. There are two different ways to pass arguments to a function. The arguments can be passed by reference or by value. We will first provide an example to demonstrate how functions work and then go into detail of passing arguments by reference and by value. The examples provided in this section are based on the Gay- Shahab D. Mohaghegh Chapter FIVE - 162

159 Lussac s law that establishes a relation between pressure and temperature for a constantvolume process. Let s visit this law briefly. The Gay-Lussac s Law The mathematical relation that defines this law can be written as: Or in general P 1 P2 = T1 T 2 P = constant T It must be specified that the temperature in the perfect gas law must be expressed as absolute temperature (degrees Kelvin or Rankin). Any temperature given in degrees Celsius or Fahrenheit must be converted to absolute temperature before being used in the gas-law equations. An experiment was conducted in the laboratory. The volume was kept constant. The initial temperature was 10 o C. The temperature was increased at increments of 10 degrees. For each temperature step the pressure was measured in atmosphere and both temperature and pressure were recorded. You are given a new set of temperatures and are asked to calculate the corresponding pressure for this constant-volume process. In the first application the calculation is made for the data as it is provided through the interface and in later application the input data is provided through an input file. Data is provided in ASCII and has been saved in a file named temperature.dat. You should use Gay_lussac s law to calculate the new pressure. Shahab D. Mohaghegh Chapter FIVE - 163

160 Pressure Function Application 1. Start a new application using the Standard.EXE option in Visual Basic. In this application the user provides the input through the interface. The calculations are made one pressure at a time based on data provided by the user. 2. Develop the interface based on the following information and Figure 5-3. The interface includes three frames, two command buttons and four text boxes. Object Property Value Text Box Name txttemp1 Text Box Name txttemp2 Text Box Name txtpress1 Text Box Name txtpress2 Command Button Name cmdcalculate Command Button Name cmdexit Figure 5-1. Interface for the Pressure Function Program. Shahab D. Mohaghegh Chapter FIVE - 164

161 3. Attach code to the interface. It is highly recommended to use the Option in the Tools item in the menu bar in Visual Basic and check the Require Variable Declaration box. This way you are forced to declare any variable that will be used in the program. Figure 5-4 shows the Option dialog box. Start by declaring variables in the General Declaration area. Option Explicit Private press1 As Single Private temp1 As Single, temp2 As Single Figure 5-2. Option dialog box. Access it using the Tools item in the menu bar. Shahab D. Mohaghegh Chapter FIVE - 165

162 Since we are planning to use a function in this program, we use the Add Procedure in the Tools menu to add the Calculate_Pressure function to our program. This will add the first and last line of the function to the code. Figure 5-3. Add Procedure dialog box. Access it using the Tools item in the menu bar. Add the following code to the Calculate command button. Private Sub cmdcalculate_click() temp1 = Val(txttemp1.Text) press1 = Val(txtpress1.Text) temp2 = Val(txttemp2.Text) txtpress2.text = Calculate_Pressure(temp1, temp2, press1) End Sub As you can see the Text property of txtpress2 Text Box is assigned the outcome of the Calculate_Pressure function. Therefore we shall write the following code for the Calculate_Pressure function. Shahab D. Mohaghegh Chapter FIVE - 166

163 Private Function Calculate_Pressure(t1 As Single, t2 As Single, p1 As Single) As Single Dim p2 As Single ' Transform the temperature in Kelvin degrees t1 = t t2 = t p2 = p1 / t1 * t2 Calculate_Pressure = p2 End Function And of course te following code is written for the Exit command Button. Private Sub cmdexit_click() End Sub End 4. Save the project and make a.exe file using the appropriate item in the File menu. Code Interpretation By using the Private keyword we make the variables temp1, temp2 and press1 available to all the procedures and functions in the form module. The first three lines of cmdcalculate_click() procedure assigns the user inputs to the above three variables that have been declared as single. The last line in this procedure calls the Calculate_Pressure function and passes three arguments to it. These arguments are temp1, temp2, and press1 respectively. txtpress2.text = Calculate_Pressure(temp1, temp2, press1) Shahab D. Mohaghegh Chapter FIVE - 167

164 Looking at the declaration line of the Calculate_Pressure function, we see that the way this function has been written it demands three arguments that are of the type single and it returns a value for Calculate_Pressure that is also a single. Private Function Calculate_Pressure(t1 As Single, t2 As Single, p1 As Single) As Single Once inside the Calculate_Pressure function, the first argument will be assigned to t1, the second to t2 and the third to p1. Please note that the sequence by which the arguments are passed is very important. In this example after the above function declaration line the value of t1 will be the same as the value of temp1 in the cmdcalculate_click() procedure, t2 will be the same as temp2 and p1 will be the same as press1. Job of this Function is first to change the units of the temperature from degrees Celsius to degrees Kelvin for both t1 and t2. Then use the Gay_lussac s law to calculate the new pressure. This is accomplished using the code in the function. Passing Variables By Reference and By Value There are two ways to pass a variable argument to a function or procedure: passing by reference and passing by value. The default in Visual Basic is passing by reference. When an argument variable is passed by reference, the corresponding parameter inside the procedure will change the value of the original argument when the procedure finishes. In other words, it is a way of passing the address (where it resides in the memory) of an argument to a procedure instead of passing the value. This allows the procedure to access the actual variable. As a result, the variable's actual value can be changed by the procedure to which it is passed. Unless otherwise specified, arguments are passed by reference. Figure 5-1 demonstrates the ByRef passing of the variables. Shahab D. Mohaghegh Chapter FIVE - 168

165 Figure 5-4. Passing variables to function By Reference. When passed by value, the argument variable retains its original value after the procedure terminates regardless of what was done to the parameter inside the procedure. In other words, it is a way of passing the value of an argument to a procedure instead of passing the address. This allows the procedure to access a copy of the variable. As a result, the variable's actual value can't be changed by the procedure to which it is passed Arguments to functions and procedures are always passed by reference unless they are accompanied by the ByVal keyword in the front of the argument. It is a good programming practice to use the keyword ByRef in front of the arguments, even if this is not needed, in order to have a clear idea how the variables are passed. Figure 5-2 demonstrates the ByVal passing of the variables. Following example applications show the use of functions in engineering applications as well as the difference between ByRef and ByVal passing of variables. These examples are very similar to the first example. The interface is exactly the same. As it was explained earlier, the default for passing variables to a function is by reference. Since we did not mention how we want the variables to be passed in the first example therefore it should be assumed that they Shahab D. Mohaghegh Chapter FIVE - 169

166 were passed by reference. In the following example we check to see if indeed it was passed by reference. Figure 5-6. Passing variables to function By Value. Pressure Function Application Revisited (1) 1. Start a new application using the Standard.EXE option in Visual Basic. In this application the user provides the input through the interface. The calculations are made one pressure at a time based on data provided by the user. We will check to see what happens to the variables after they are passed to the function. 2. Use the same interface as the previous example. 3. Attach code to the interface. We change the code slightly to reflect the pass by reference explicitly. We also add couple of lines to the code to show that the pass by reference is actually taking place. The new code will look as follows: Shahab D. Mohaghegh Chapter FIVE - 170

167 Private Sub cmdcalculate_click() temp1 = Val(txttemp1.Text) press1 = Val(txtpress1.Text) temp2 = Val(txttemp2.Text) txtpress2.text = Calculate_Pressure_ByRef(temp1, temp2, press1) Cheking the value of variables after they are passed. lbltemp1.caption = "Temperature in Kelvin" lbltemp2.caption = "Temperature in Kelvin" txttemp1.text = temp1 txttemp2.text = temp2 End Sub Private Function Calculate_Pressure_ByRef (ByRef t1 As Single,_ ByRef t2 As Single, ByRef p1 As Single) As Single Dim p2 As Single ' Transform the temperature in Kelvin degrees t1 = t t2 = t p2 = p1 / t1 * t2 Calculate_Pressure_ByRef = p2 End Function Once you run the application enter values as shown Figure 5-1. As you see in this figure first temperature has a value of 10 degrees Celsius and the second temperature has a value of 200 degrees Celsius. Once you click on the Calculate button the interface will look like that of Figure 5-7. Shahab D. Mohaghegh Chapter FIVE - 171

168 Figure 5-7. Program interface after the Calculate button has been pushed once. 4. Save the project and make a.exe file using the appropriate item in the File menu. Code Interpretation First thing to note is that in the name of the cmdcalculate_click() procedure the function has changed to Calculate_Pressure_ByRef to reflect that we are making sure that the variables are being passed by reference. As the process continues the program enters the function at this point. Please note that all the arguments have the ByRef keyword. Within the function the values of the temp1 and temp2 (now represented by t1 and t2) is being altered. They are converted to degrees Kelvin. Then the calculation is completed and the control of the program goes back to the cmdcalculate_click() procedure. Here we have added four lines of code as follows: lbltemp1.caption = "Temperature in Kelvin" lbltemp2.caption = "Temperature in Kelvin" txttemp1.text = temp1 txttemp2.text = temp2 Shahab D. Mohaghegh Chapter FIVE - 172

169 We first change the caption property of the labels lbltemp1 and lbltemp2 to get the user s attention about the change that have taken place. Then we display the current values of temp1 and temp2 variables using the Text properties of the text boxes. As you see in the Figure 5-7 these values are now changed and no longer are the same as the user had input. So the passing by reference had actually taken place since the value of the variables have been altered after they have been accessed and changed in the function. In the next example we see how the passing by value works. Pressure Function Application Revisited (2) 1. Start a new application using the Standard.EXE option in Visual Basic. This application is the same as the previous application with slight changes. We will see what happens to the variables after they are passed to the function by value instead of by reference. 2. Use the same interface as the previous example. 3. Attach code to the interface. We change the code slightly to reflect the pass by value of the variables. We also change couple of lines to show that the pass by value is actually taking place. Showing only the part of the code that has changed, the new code will look as follows: press1) txtpress2.text = Calculate_Pressure_ByVal (temp1, temp2, Shahab D. Mohaghegh Chapter FIVE - 173

170 Cheking the value of variables after they are passed. lbltemp1.caption = "Still in Celsius" lbltemp2.caption = " Still in Celsius " txttemp1.text = temp1 txttemp2.text = temp2 The code for the function will now look like this: Private Function Calculate_Pressure_ByVal (ByVal t1 As Single,_ ByVal t2 As Single, ByVal p1 As Single) As Single Dim p2 As Single ' Transform the temperature in Kelvin degrees t1 = t t2 = t p2 = p1 / t1 * t2 Calculate_Pressure_ByVal = p2 End Function Once you run the application enter values as shown Figure 5-1. As you see in this figure first temperature has a value of 10 degrees Celsius and the second temperature has a value of 200 degrees Celsius. Once you click on the Calculate button the interface will look like that of Figure 5-8. As you note in this Figure the values of temperature remains the same and does not changes although the control of the program has gone to the function and have come back to the command button. Shahab D. Mohaghegh Chapter FIVE - 174

171 Figure 5-8. Program interface after the Calculate button has been pushed. 4. Save the project and make a.exe file using the appropriate item in the File menu. Code Interpretation First thing to note is that in the name of the cmdcalculate_click() procedure the function has changed to Calculate_Pressure_ByVal to reflect that we are making sure that the variables are being passed by value. As the process continues the program enters the function at this point. Please note that all the arguments have the ByVal keyword. Within the function the values of the temp1 and temp2 (now represented by t1 and t2) is being altered. They are converted to degrees Kelvin. Then the calculation is completed and the control of the program goes back to the cmdcalculate_click() procedure. Here we have added four lines of code as follows: lbltemp1.caption = " Still in Celsius " lbltemp2.caption = " Still in Celsius " Shahab D. Mohaghegh Chapter FIVE - 175

172 txttemp1.text = temp1 txttemp2.text = temp2 We first change the caption property of the labels lbltemp1 and lbltemp2 to get the user s attention about the change that have taken place. Then we display the current values of temp1 and temp2 variables using the Text properties of the text boxes. As you see in the Figure 5-8 these values have not changed. So the passing by value had actually taken place since the value of the variables have not been altered after they have been accessed and changed in the function. Working with Functions in Arrays Functions are used very commonly with arrays. There are two important issues to keep in mind when using arrays in functions. First is the only way to pass arrays to a functions is by reference. Arrays can not be passed by value. Second when passing arrays to a function you do not need to specify the arrays dimensions. All you need to do is to make sure that you include the set of parentheses that identifies the variable as an array. Following example uses similar logic as the previous examples but it imports the data from a file instead of having the user to input the data. The data is displayed in a table (grid) and then the new pressures are calculated. Shahab D. Mohaghegh Chapter FIVE - 176

173 Try It! Now that you have learned to add values to the grid control during run-time, develop an application that is completely empty and user has to fill all the cells including the title of the rows and columns at run-time. The user should be able to use any keystroke for the title row and column and only numerical keystrokes should be allowed for the rest of the cells. Summary This would be some summary text. Keywords Custom Control Grid Control Column Row Design time Run-time Exercises 1. Develop an application that has two text boxes where user can input two numbers. Use the random number generator function in Visual Basic and generate 100 numbers Shahab D. Mohaghegh Chapter FIVE - 177

174 using the numbers provided by the user as the min. and max. Display the results in a grid control. 2. Take the application in Exercise 1 one step further by providing a picture box control and plot the data in the grid control in the picture box control. 3. Use the concept in Exercise 2 and code a polynomial in your application. Show the form of the polynomial on the main form of your application. Use the min and max provided by the user and the random number generator function to generate data using the polynomial function and then plot the result. Shahab D. Mohaghegh Chapter FIVE - 178

175 6 Menus and Common Dialogs in Visual Basic In this chapter we cover menus and common dialogs in Visual Basic. We show you how to add menu bar to your application and add menu items and sub-items to the menu bar. Then we show you the process of attaching code to the menu items and sub-items. Another concept that will be covered in this chapter is the interactive file selection dialog boxes that provide information about the file on the computer and allow the user to select the desired file to be open or saved. Introduction In order to give your application the look and feel of a professional Windows program you need to add to it some of the commonly used Windows application features. One of the most common features used in Windows applications is a menu. Menus provide a wealth of functionality to the application and provide access to different segments of the application. They are usually one of the primary ways to access different features that have been built in to the program. Menus have been used so commonly in Windows applications that their presence in most Windows applications are intuitively expected. In this chapter we show you how to build a menu bar for your application and how to add items and sub-items to it. Code will then be added to the menu items and the sub-items in order to make them functional. Figure 6-1 shows an example of a menu. This is the menu in the Visual Basic environment. Up to now in all the examples and applications that we developed in this text book, any time we wanted to access a file from within the application we had to hard code its complete path. Look at the following example from the application in Chapter 4. Shahab D. Mohaghegh Chapter SIX - 179

176 Open "c:\temp\data.txt" For Input As 1 The file data.txt must exist in the temp directory of the c: drive or the application will get a run-time error when it tries to access that file. Figure 6-1. Example of a menu. In this chapter we show you how to generate dialog boxes that provide a snap shot of the user s computer and let him/her search in the computer and find the desired file wherever it might be located. Menus in Visual Basic In this section we cover the inclusion of menus in a Visual Basic application. The following example is very simple. The main intention of presenting this example is to Shahab D. Mohaghegh Chapter SIX - 180

177 show you how to start implementing a menu in your application. We will revisit this example in the future and add new features to it. Therefore, this example should be treated as a first version of a more complex application. We will call it the menu program. The Menu Program 1. Start a new application using the Standard.EXE option in Visual Basic. In this application we just include a menu and will complete the application in the examples that follow. 2. Before we show you the table that you should use to develop the interface, lets see how we start for inclusion of a menu in an application. In order to add a menu to the application you need to use the Menu Editor. There are a total of four ways that one can invoke the Menu Editor. Following Figure shows all of the four ways and has numbered them accordingly. Shahab D. Mohaghegh Chapter SIX - 181

178 Figure 6-2. Four different ways of invoking the Menu Editor. The first way of invoking the Menu Editor is to use the Tools item in the Visual Basic s menu and then select Menu Editor. This is indicated as number 1 in Figure 6-2. As indicated by the number 2 in Figure 6-2, you can also use the <Ctrl> E to invoke the Menu Editor. The third way of invoking the Menu Editor is to use the right mouse button while the cursor is placed on the form. This is indicated as the number 3 in the Figure 6-2. Last but not least is using the Visual Basic s tool bar. Number 4 in Figure 6-2 shows the icon for the Menu Editor. Figure 6-3 shows the Menu Editor. Figure 6-3. The Menu Editor dialog box. As you can see the Menu Editor includes many components and options. We try to briefly talk about the important ones that you will use. The first information that needs to be added to the Menu Editor is the Caption. Caption allows you to enter the menu or Shahab D. Mohaghegh Chapter SIX - 182

179 command name that you want to appear on your menu bar or in a menu. If you want to create a separator bar in your menu, type a single hyphen (-) in the Caption box. Name allows you to enter a control name for the menu item. A control name is an identifier used only to access the menu item in code; it doesn't appear in a menu. Index allows you to assign a numeric value that determines the control's position within a control array. We discussed the control arrays in a previous chapter. They can also be used in a menu structure. This position isn't related to the screen position. Shortcut allows you to select a shortcut key for each command. Checked allows you to have a check mark appear initially at the left of a menu item. It is generally used to indicate whether a toggle option is turned on or off. Items such as HelpContextID, NegotiatePosition, Enabled, Visible, and WindowList are not crucial issues at this point and are not discussed at this point. Right arrow moves the selected menu item down one level each time you click it. You can create up to four levels of submenus. Left arrow moves the selected menu item up one level each time you click it. Up arrow moves the selected menu item up one position within the same menu level each time you click it. Down arrow moves the selected menu item down one position within the same menu level each time you click it. The bottom part of the Menu Editor includes a list box known as the menu list. The menu items that are generated are displayed in this list box. Menu List is a list box that displays a hierarchical list of menu items. Submenu items are indented to indicate their hierarchical position or level. The Next command button moves selection to the next line. The Insert command button inserts a line in the list box above the currently selected line. The Delete command button deletes the currently selected line. Shahab D. Mohaghegh Chapter SIX - 183

180 In order to create a menu item in the form, you should start by providing the item with a name and a caption. The caption is what shows up on the form and the name is used to refer to the item while writing the code. As you provide a caption and a name for the menu item it will appear on the list box on the bottom portion of the dialog box. Once you complete the first item then click on the Next command button. This will save all the information you provided for that item and allows you to put the information for the next item. Use the following table and generate the menu items as they appear in Figure 6-4. Once completed the interface of the program should look like Figure 6-5. Object Property Value Menu Title Caption File Name mnufile Menu Item Caption New Name mnunew Menu Item Caption Open Name mnuopen Menu Title Caption Edit Name mnuedit Menu Item Caption Copy Name mnucopy Menu Item Caption Cut Name mnucut Menu Item Caption Paste Name mnupaste Shahab D. Mohaghegh Chapter SIX - 184

181 Figure 6-4. Menu Editor after the items were added. Figure 6-5. Interface of the Menu program. There are no codes to be attached at this point to this program. The goal of this example was to show you how to invoke the Menu Editor and create a menu for your Shahab D. Mohaghegh Chapter SIX - 185

182 application. In the examples that follow, we cover more issues on this subject and show you how to enhance your program by attaching code to the menu items. The Note Pad Program 1. Start a new application using the Standard.EXE option in Visual Basic. In this application we develop a note pad that lets the user to change the background color and font size using the menu items. 2. Use the following table to develop the interface shown in Figure 6-7. The Menu Editor will look like that of Figure 6-6 when you are done. Object Property Value Form Caption My Notepad Name frmnotepad Text Name txtnotepad Multiline True Font Size 10 Menu Title Caption File Name mnufile Menu Item Caption New Name mnunew Menu Item Caption - Name mnuseparator1 Menu Item Caption Exit Name mnuexit Menu Title Caption BgColors Shahab D. Mohaghegh Chapter SIX - 186

183 Name mnucolors Menu Item Caption Default Colors Name mnudefault Menu Item Caption - Name mnuseparator2 Menu Item Caption Red Name mnured Menu Item Caption Green Name mugreen Menu Item Caption Blue Name mnublue Menu Item Caption - Name mnuseparator3 Menu Item Caption More Colors Name SubMenu Item Caption Maroon Name mnumaroon SubMenu Item Caption Grey Name mnugrey SubMenu Item Caption Light Blue Name mnulightblue Menu Title Caption Font Size Name mnufont Menu Item Caption Normal Name mnunormal Menu Item Caption Small Name mnusmall Shahab D. Mohaghegh Chapter SIX - 187

184 Menu Item Caption Large Name mnularge Figure 6-6. Menu Editor after adding all the items for the Note Pad program. Shahab D. Mohaghegh Chapter SIX - 188

185 Figure 6-7. Interface for the Note Pad program. 3. Attach code to the interface. This application does not need any variables to be declared. We can simply start by writing code for each menu item. To write the code for each item click on the item and the code view window for that item will appear. Note that the click event of the menu item appears by default, which is the event we would like to code for. To start, we write the code for the click event of the New menu item. This is the first item in the File menu title. Private Sub mnunew_click() txtnotepad.text = "" txtnotepad.backcolor = RGB(255, 255, 255) txtnotepad.forecolor = RGB(0, 0, 0) Shahab D. Mohaghegh Chapter SIX - 189

186 End Sub Next item in the File menu title is Exit. You already know how to write the code for the exit routine. The next menu title is the BgColor. The first item in this menu title is Default Color. Write the following code for this menu item. Private Sub mnudefault_click() txtnotepad.backcolor = RGB(255, 255, 255) txtnotepad.forecolor = RGB(0, 0, 0) mnudefault.enabled = False mnured.enabled = True mnublue.enabled = True mnugreen.enabled = True End Sub Write the following code for the Red menu item. Private Sub mnured_click() txtnotepad.backcolor = RGB(255, 0, 0) txtnotepad.forecolor = RGB(255, 255, 255) mnudefault.enabled = True mnured.enabled = False mnublue.enabled = True mnugreen.enabled = True End Sub Write the following code for the Green menu item. Shahab D. Mohaghegh Chapter SIX - 190

187 Private Sub mnugreen_click() txtnotepad.backcolor = RGB(0, 255, 0) txtnotepad.forecolor = RGB(0, 0, 0) mnudefault.enabled = True mnured.enabled = True mnublue.enabled = True mnugreen.enabled = False End Sub Write the following code for the Blue menu item. Private Sub mnublue_click() txtnotepad.backcolor = RGB(0, 0, 255) txtnotepad.forecolor = RGB(255, 255, 255) mnudefault.enabled = True mnured.enabled = True mnublue.enabled = False mnugreen.enabled = True End Sub Write the following code for the Maroon submenu item. Private Sub mnumaroon_click() txtnotepad.backcolor = RGB(150, 50, 50) ' Maroon txtnotepad.forecolor = RGB(255, 255, 255) mnumaroon.checked = True Shahab D. Mohaghegh Chapter SIX - 191

188 mnugrey.checked = False mnulightblue.checked = False mnudefault.enabled = True mnured.enabled = True mnublue.enabled = True mnugreen.enabled = True End Sub Write the following code for the Gray submenu item. Private Sub mnugrey_click() txtnotepad.backcolor = RGB(100, 100, 100) ' Grey txtnotepad.forecolor = RGB(255, 255, 255) mnumaroon.checked = False mnugrey.checked = True mnulightblue.checked = False mnudefault.enabled = True mnured.enabled = True mnublue.enabled = True mnugreen.enabled = True End Sub Write the following code for the Light Blue submenu item. Private Sub mnulightblue_click() txtnotepad.backcolor = RGB(0, 200, 250) 'Light Blue txtnotepad.forecolor = RGB(255, 255, 255) Shahab D. Mohaghegh Chapter SIX - 192

189 mnumaroon.checked = False mnugrey.checked = False mnulightblue.checked = True mnudefault.enabled = True mnured.enabled = True mnublue.enabled = True mnugreen.enabled = True End Sub Write the following code for the Normal menu item in the Font Size menu title. Private Sub mnufontnormal_click() txtnotepad.fontsize = 10 mnufontnormal.enabled = False mnufontsmall.enabled = True mnufontlarge.enabled = True End Sub Write the following code for the Small menu item. Private Sub mnufontsmall_click() txtnotepad.fontsize = 8 mnufontnormal.enabled = True mnufontsmall.enabled = False mnufontlarge.enabled = True End Sub Shahab D. Mohaghegh Chapter SIX - 193

190 Write the following code for the Large menu item. Private Sub mnufontlarge_click() txtnotepad.fontsize = 12 mnufontnormal.enabled = True mnufontsmall.enabled = True mnufontlarge.enabled = False End Sub 4. Save the project and make a.exe file using the appropriate item in the File menu. Code Interpretation The New menu item starts by making sure that nothing is written in the text box. txtnotepad.text = "" The next action is to make sure that the background color (the BackColor property of the text box) is white (the default color) and the font color, which is the same thing as the ForeColor property of the text box is black. txtnotepad.backcolor = RGB(255, 255, 255) txtnotepad.forecolor = RGB(0, 0, 0) The RGB function of Visual Basic is used to assign color. This function uses three integers between values of 0 and 255 (hence 256 color) as the values for Red, Green and Blue respectively. Value 0 means none of that color and value 255 means 100% of that color. Shahab D. Mohaghegh Chapter SIX - 194

191 In the menu item Default Color, first we make sure that the default back and fore colors are assigned as white and black respectively. Then using the Enable property of the menu items make the Default Color item disabled, which sends the message to the user that this item is now being used, and keeps all other options enabled. This sends the message that any of these menu items can now be used. txtnotepad.backcolor = RGB(255, 255, 255) txtnotepad.forecolor = RGB(0, 0, 0) mnudefault.enabled = False mnured.enabled = True mnublue.enabled = True mnugreen.enabled = True This approach is used for all other menu items and submenu items in the BgColor menu title. Each time the back and fore colors are changed to the proper color. Then the enabled property of the menu item is made to be false, which by making it dimmed in the menu list, sends the message to the user that this is the item currently activated and other menu items are enabled by making their enable property to be true. Following codes are used for assigning different colors. Color RGB Function Values White Black Red Green RGB(255,255,255) RGB(0,0,0) RGB(255,0,0) RGB(0,255,0) Shahab D. Mohaghegh Chapter SIX - 195

192 Blue Maroon Gray RGB(0,0,255) RGB(150,50,50) RGB(100,100,100) Light Blue RGB(0, 200, 250) Table 6-1. Some colors using Visual Basic s RGB function. Adding More Features to the Menu Among the common features that are usually added to the menu are access keys and shortcuts. Adding access keys and short cuts to the menu allows the user to manipulate the application using the keyboard rather than the mouse. Access keys make the menu available through keyboard using the combination of the Atl and another key. Shortcuts make the menu available through the function keys, the combination of Ctrl and another key or Shift and another key. Access keys In order to add an access key to a menu item you should add an & in front of the letter Shahab D. Mohaghegh Chapter SIX - 196

193 that should be used in combination with the Alt key. This is done in the Caption box of the Menu Editor and will show up in the list box at the bottom of the Menu Editor. Figures 6-8 and 6-9 show how the access keys are assigned in the Menu Editor and how they would look in the application after they are implemented. Figure 6-8. Menu Editor after adding the access keys. Shortcuts Shortcuts are added to the menu items through the Menu Editor. Unlike the access keys that add a sign (the underline) to the appearance of the menu, shortcuts have no indicators. Their presence should be noted to the user through manuals and help files. There is a combo box in the Menu Editor that allows you to choose a shortcut key or combination of keys for each menu item. Figure 6-10 shows the Menu Editor for the same application (The Notepad Program) when shortcuts are used. Shahab D. Mohaghegh Chapter SIX - 197

194 Figure 6-9. The application after the access keys are implemented. Figure Menu Editor when shortcuts are used. Creating Pop-Up Menus Pop-up menu refers to the block of menu that appears when user clicks on the right mouse button. It is a convenient way of providing access to some of the most important features of your application. In the following example we take the Notepad program and add a pop-up menu to it. The Note Pad Program (Revised) 1. Open the Notepad program to revise it. If you choose not to revise your old program you can rename the new program in a separate directory and start using it. This is due to the fact that we are going to add a new feature to this program and do not intend to change any existing feature. Shahab D. Mohaghegh Chapter SIX - 198

195 In this application we want to make the background color part of the menu available through the right mouse button. 2. There is no need to change any part of the interface in this new application. Since the background color block of the menu is what we are going to make available through the pop-up menu, we just revisit that particular menu item in the following table. Object Property Value Menu Title Caption BgColors Name mnucolors 3. Attach the code to the interface. In order to generate the pop-up menu we need to add the following code to the MouseDown event of the Form. Private Sub Form_MouseDown(Button As Integer, Shift As_ Integer, X As Single, Y As Single) ' Right mouse button clicked If Button = 2 Then PopupMenu mnucolors End If End Sub Once completed, the application will look like Figure 6-11, when the right mouse button is clicked anywhere in the form. It should be noted that in order to activate the pop-up menu the cursor must be located on the form not on the menu or the text box. If you click the right mouse button while the cursor is on the text box you will see that a pop-up menu Shahab D. Mohaghegh Chapter SIX - 199

196 will be displayed that has items like copy, cut, and paste. This is part of the text box and no code needs to be written for it. Figure The Notepad program revised to have a pop-up menu. 4. Save the project and make a.exe file using the appropriate item in the File menu. Code Interpretation The only piece of code that was added to this application was to detect and trap the right mouse button. This is done by adding an If statement with Button=2 as its condition. Button=2 means the second mouse button that is the right one. Since the code is written in the MouseDown event of the form object, whenever any of the mouse buttons are pressed while the cursor is on the form this event is triggered. The If statement checks to see which button is pressed. If it is the left mouse button nothing will happen (since we have written the code for the right mouse button). If it is the right mouse button that is pressed, hence Button=2, then the following statement is executed: Shahab D. Mohaghegh Chapter SIX - 200

197 PopupMenu mnucolors This statement invokes the PopupMenu method. This method displays a pop-up menu at the current mouse location. Pop-up menu can only display one block of menu. In this application we chose the background color block of menu items to be the pop-up menu block. This is accomplished by identifying the mnucolors as the block of the menu to be displayed. File Access Using a Dialog Box In Chapter four you learned how to access data that resides in a file and read it into your application. The problem with that approach is that you have to include the name and location of the data file into your application. Every time you plan to use that application you have to go back to the code and change the data file name and path. This means that you have to have Visual Basic on the computer that is using your application and the compiled version of the application is pretty much useless. The way most of the Windows applications work is as follows. You click on a command button or a menu item to open a particular data file. A dialog box appears that allows you to brows through all the disk drives in your computer and all the directories in each drive and gives you access to all the files in each directory. You go through the search and Shahab D. Mohaghegh Chapter SIX - 201

198 locate the data file that you are interested in and then the program opens the file for you. This way the data file can reside at any location and could be called any names. In this section of this chapter we show you how to develop such a dialog box. In order to accomplish this task we make use of three new controls. They are DriveListBox, DirectoryListBox, and FileListBox. From their names you can see that they are List Boxes. This means that their function is to list the available drive, directories and files, respectively. Figure 6-12 shows their icons in the toolbox. Figure New controls icons in the toolbox. In this section we start by developing an application that uses these controls to give user access to the file that needs to be opened and its content be imported into a grid control. The Open File Dialog Program 1. Start a new application using the Standard.EXE option in Visual Basic. In this application we give access to the user to locate the data file and then we open the data file and import its content into a grid control. 2. There are two forms in this application. One is the main interface and the second form is used to display the Open File dialog box. Use the following table and develop the interface for the main form. Once completed the main form should look like Figure Shahab D. Mohaghegh Chapter SIX - 202

199 Object Property Value Form Caption The Open Menu Program Name frmmain Text Box Name Txtno_rec Flex Grid Name Msfgrddata Rows 50 Cols 6 Menu Title Caption File Name mnufile Menu Item Caption Open File Name mnuopen Menu Item Caption - Name mnuseparator1 Menu Item Caption Exit Name mnuexit Menu Title Caption Import Data Name mnuimport Menu Item Caption Start Import Shahab D. Mohaghegh Chapter SIX - 203

200 Name mnustart Figure Interface for the Open File Dialog Program. We now need to add a second form to this application. This form will play the role of the Open File Dialog box. In order to add a new form to the project you need to click on the Project menu item in Visual Basic. Then select the item Add Form from the drop down menu. The Add Form dialog box will appear. Figure 6-14 shows the Visual Basic s Add Form dialog box. Shahab D. Mohaghegh Chapter SIX - 204

201 Figure The Add Form dialog box. Once the new form has been added to the project, use the following table to develop the Open dialog interface. Figure 6-15 shows the Open File dialog box interface. Object Property Value Form Caption Open File Name frmopenfile FileListBox Name filfind DriveListBox Name drvchange DirListBOx Name dirlook Command Button Name cmdok Caption &OK Shahab D. Mohaghegh Chapter SIX - 205

202 Command Button Name cmdcancel Caption &Cancel Figure Open File dialog box interface. 3. Attach the code to the interface. Following code is added to the frmmain form. Add the following lines to the General Declaration procedure. Option Explicit Private x(50) As Single, y(50) As Single, z(50) As Single Private i As Integer, no_rec As Integer Add the following code to the Form_Load procedure: Shahab D. Mohaghegh Chapter SIX - 206

203 Private Sub Form_Load() Dim k As Integer msfgrddata.row = 0 msfgrddata.col = 0 msfgrddata.text = " No Crt " msfgrddata.col = 1 msfgrddata.text = " X " msfgrddata.col = 2 msfgrddata.text = " Y " msfgrddata.col = 3 msfgrddata.text = " Z " msfgrddata.col = 0 For k = 1 To 28 Step 1 msfgrddata.row = k msfgrddata.text = Format(k, " ##") Next k End Sub Add the following code to the click procedure of the mnuopen menu item. Private Sub mnuopen_click() End Sub frmopenfile.show Add the following code to the click procedure of the mnustart menu item. Shahab D. Mohaghegh Chapter SIX - 207

204 Private Sub mnustart_click() Dim counterf As Integer i = 1 Do While Not EOF(1) Input #1, x(i), y(i), z(i) i = i + 1 Loop Close #1 counterf = i - 1 ' substract 1 because we started from i=1 txtno_rec.text = counterf End Sub Write_data_in_grid x(), y(), z(), counterf As you can see we are addressing a procedure called Write_data_in_grid. Add a procedure to your application and name it Write_data_in_grid. Add the following code to this procedure. Private Sub Write_data_in_grid(ByRef a() As Single, ByRef_ b() As Single, c() As Single, ByVal rec_no As Integer) For i = 1 To rec_no Step 1 msfgrddata.col = 1 msfgrddata.row = i msfgrddata.text = Format(a(i), "##0.#0") msfgrddata.col = 2 msfgrddata.text = Format(b(i), "##0.#0") Shahab D. Mohaghegh Chapter SIX - 208

205 msfgrddata.col = 3 msfgrddata.text = Format(c(i), "##0.#0") Next End Sub At this point the frmmain form is completed and it is time to add code to the controls in the frmopenfile form. Add this code to the Change event of the dirlook Directory List Box control. Private Sub dirlook_change() ' Change to the current or selected path filfind.path = dirlook.path End Sub Add the following code to the Change event of the drvchange Drive List Box control. Private Sub drvchange_change() ' Change to the current or selected drive dirlook.path = drvchange.drive End Sub Add the following code to the Click event of the cmdok command button. Private Sub cmdok_click() Dim File As String 'Initialize an error traping ( in case you hit Esc for example) On Error GoTo FileError Shahab D. Mohaghegh Chapter SIX - 209

206 'Chech if the string of the selected directory If (Right(dirLook.Path, 1) = "\") Then ' ends with "\" 'Builds the entire pathe File = dirlook.path + filfind.filename Else 'Add "\" and builds the entire path File = dirlook.path + "\" + filfind.filename End If 'Open the selected file for reading Open File For Input As #1 FileError: Resume Next Hide the Open File Form frmopenfile.hide End Sub Add the following code to the Click event of the cmdcancel command button. Private Sub cmdcancel_click() Unload cmdcancel.parent 'Unload the form End Sub 4. Save the project and make a.exe file using the appropriate item in the File menu. Code Interpretation The main form includes a handful of routines. Almost all of the code in this form should be familiar to you since they are being repeated from previous examples in this book. In Shahab D. Mohaghegh Chapter SIX - 210

207 the Form_Load procedure the grid control is set up and the numbers are placed on the first column. There are two procedures in the menu. First is the Open File Item in the File menu item. Private Sub mnuopen_click() End Sub frmopenfile.show This procedure simply invokes the form that has the open file dialog box using the show method and passes the control of the program to it. We will visit the frmopenfile form later in this section. The second menu item Import Data includes the Start Import item. The code in this procedure is executed after the frmopenfile form is closed. During the frmopenfile form s operation, the text file where the data resides is identified and the file is assigned a number, in this case 1. The code refers to the file using its number in the Do While loop. Do While Not EOF(1) Input #1, x(i), y(i), z(i) i = i + 1 Loop Close #1 The rest of the code is a repeat of what was presented in the past, including a procedure that writes the data into the grid control. The code for the frmopenfile form is short and simple. The form includes five controls. Two command buttons, Cancel and O.K., and two list boxes and a combo box. But these Shahab D. Mohaghegh Chapter SIX - 211

208 are not simple list and combo boxes. They are special list boxes (even the combo box is called a list box). The first one is called the DriveListBox control. This is the one that actually looks like a combo box. A DriveListBox control enables a user to select a valid disk drive at run-time. This control is used to display a list of all the valid drives in a user's system. The second list box is called the DirListBox. DirListBox control displays directories and paths at run-time. It is used to display a hierarchical list of directories. The third or last list box is the FileListBox. FileListBox control locates and lists files in the directory specified by the Path property at run-time. It is used to display a list of files selected by file type. The sequences by which these list boxes are activated are the natural drive, directory and file sequence. The idea is to generate a path that includes all these information and pass it to the next procedure to open the file. Following code is executed if the user attempts to change the drive. It registers the change in the path property of the DirListBox control named dirlook. Private Sub drvchange_change() End Sub dirlook.path = drvchange.drive The same logic works if the user attempts to change the directory. Here is the code to detect and register that action. Private Sub dirlook_change() End Sub filfind.path = dirlook.path Shahab D. Mohaghegh Chapter SIX - 212

209 The change here is registered in the path property of the FileListBox control named filfind. Rest of the actions takes place in the code written for the O.K command button. It starts by declaring a string variable we have chosen to call File. This variable will hold the path to the file including its name. Dim File As String The next line of code starts an error procedure, On Error GoTo FileError This code is written in order to make sure that in case an error takes place (user hits the Esc button or he/she is unable to find the file needed and decides to leave the form), the program does not produce an error. As you will see later in the code this action lets the user to gracefully leave this form and go back to the form that initiated this dialog box. We will revisit the error trapping later in this procedure. Next we try to make sure that the path has the correct syntax. We do that by checking to make sure if there is a \ (back slash) between the directory name and the file name. If the back slash is not there we insert one. To do this, we use the Right function on the dirlook.path which is a string. The Right function, starting from the right hand side, examines the number of characters we specify (in this case we have specified 1). In the following code the last character (number 1 character from right) of the directory is checked, if it detects a \ it will simply add the file name to it. If the \ is not there it will inserts it. The path is then assigned to the File string variable. Shahab D. Mohaghegh Chapter SIX - 213

210 If (Right(dirLook.Path, 1) = "\") Then ' ends with "\" 'Builds the entire pathe File = dirlook.path + filfind.filename Else 'Add "\" and builds the entire path File = dirlook.path + "\" + filfind.filename End If Next we open the file using the following code and assign a number to it. In this case we assign the number 1 to the file. Open File For Input As #1 From here on we simply refer to the file using its assigned number which is 1. We are finished with the code at this point. All that remains is the continnuation of the error handling process. We had instructed the code to GOTO the FileError if an error occurs. Here is the FileError section. FileError: Resume Next Hide the Open File Form frmopenfile.hide It instructs the code to resume to the next line, which is to hide the frmopenfile form. What we have done in this code may be summarized as follows: 1. We have opened the file that the user has identified 2. We have assigned a number to the file that can be used throughout the program. Shahab D. Mohaghegh Chapter SIX - 214

211 As you remember, we used the file number in the Do While loop to read the content of the file. Using the Visual Basic s Open Dialog Control In the previous section we showed you how to develop a form and write the appropriate code to generate an open File Dialog Box. It was a good practice and revealed some insight into the Visual Basic and its capabilities. In fact, Visual Basic provides an easier way to accomplish the same task (and much more) use a control called the Microsoft Common Dialog Control. This control is not present in the toolbox by default. You have to add it to your project. Just like you did in Chapter 4 with the Grid control. You can add this control to your project using the component item in the project menu of the Visual Basic as shown in the Figure Figure Adding the common dialog control to your project. Shahab D. Mohaghegh Chapter SIX - 215

212 The CommonDialog control provides a standard set of dialog boxes for operations such as opening and saving files, setting print options, and selecting colors and fonts. The control also has the ability to display help by running the Windows Help engine. The CommonDialog control provides an interface between Visual Basic and the routines in the Microsoft Windows dynamic-link library Commdlg.dll. To create a dialog box using this control, Commdlg.dll must be in your Microsoft Windows SYSTEM directory. Following table shows the methods available to the CommonDialog control and their action. Method ShowOpen ShowSave ShowColor ShowFont ShowPrinter ShowHelp Dialog Displayed Show Open Dialog Box Show Save As Dialog Box Show Color Dialog Box Show Font Dialog Box Show Print or Print Option Dialog Box Invokes the Windows Help Engine Table 6-2. Available methods for the CommonDialog control. In this section we just use the ShowOpen method. You can practice with the rest of the methods on your own. In this section we repeat the previous example. This time we substitute the Visual Basic s CommonDialog control for the Open File dialog that we generated. Therefore we will not repeat the entire example and concentrate only on the CommonDialog control. Shahab D. Mohaghegh Chapter SIX - 216

213 The Open File Dialog Program (Revised) 1. Start a new application using the Standard.EXE option in Visual Basic. 2. Use the same interface as you developed for the last example. Do not add the second form, which is the Open File form. Instead use the Components item in the Project menu of the Visual Basic to add the CommonDialog control to the project. The CommonDialog is shown in Figure Figure CommonDialog control. Add this control to the application. It does not matter where you place it. It will be invisible during the run-time. Once you run the program it will look like Figure Figure New application interface. Shahab D. Mohaghegh Chapter SIX - 217

214 In order for the application to show the above dialog box, you need to attach code to the interface. This will require the modification of the code in the Open File menu item. 3. Attach the code to the interface. Following code is added to the Click event of the mnuopen menu item. Private Sub mnuopen_click() 'set the flags and attributes of the common dialog control ' the Filter property selects the Text files, Excel files and All files dlgcommondialog.filter = "Text Files (*.txt) *.txt " + _ "Excel Files (*.xls) *.xls " + _ "All Files (*.*) *.*" dlgcommondialog.showopen ' test if any file from the text box was selected If Len(dlgcommondialog.FileName) = 0 Then Exit Sub: End If Open dlgcommondialog.filename For Input As #1 End Sub This completes the code for invoking the CommonDialog control. When you run the application and use the Open File item in the File menu you will see what is shown in Figure Save the project and make a.exe file using the appropriate item in the File menu. Shahab D. Mohaghegh Chapter SIX - 218

215 Code Interpretation The CommonDialog control has a property called Filter. This property provides the option that only certain types of files (using the file extension as identifier) be displayed in the list box. Please note that the CommonDialog control used in the application has been named dlgcommondialog. dlgcommondialog.filter = "Text Files (*.txt) *.txt " + _ "Excel Files (*.xls) *.xls " + "All Files (*.*) *.*" Above code is responsible for the part of the dialog box that is indicated with an ellipse in Figure Figure Using the Filter property with the CommonDialog control. Using the ShowOpen method invokes the Open File diallog. dlgcommondialog.showopen Shahab D. Mohaghegh Chapter SIX - 219

Start Visual Basic. Session 1. The User Interface Form (I/II) The Visual Basic Programming Environment. The Tool Box (I/II)

Start Visual Basic. Session 1. The User Interface Form (I/II) The Visual Basic Programming Environment. The Tool Box (I/II) Session 1 Start Visual Basic Use the Visual Basic programming environment Understand Essential Visual Basic menu commands and programming procedure Change Property setting Use Online Help and Exit Visual

More information

Computer Science 110. NOTES: module 8

Computer Science 110. NOTES: module 8 Computer Science 110 NAME: NOTES: module 8 Introducing Objects As we have seen, when a Visual Basic application runs, it displays a screen that is similar to the Windows-style screens. When we create a

More information

DOING MORE WITH EXCEL: MICROSOFT OFFICE 2013

DOING MORE WITH EXCEL: MICROSOFT OFFICE 2013 DOING MORE WITH EXCEL: MICROSOFT OFFICE 2013 GETTING STARTED PAGE 02 Prerequisites What You Will Learn MORE TASKS IN MICROSOFT EXCEL PAGE 03 Cutting, Copying, and Pasting Data Basic Formulas Filling Data

More information

WORD XP/2002 USER GUIDE. Task- Formatting a Document in Word 2002

WORD XP/2002 USER GUIDE. Task- Formatting a Document in Word 2002 University of Arizona Information Commons Training Page 1 of 21 WORD XP/2002 USER GUIDE Task- Formatting a Document in Word 2002 OBJECTIVES: At the end of this course students will have a basic understanding

More information

Grade 8 FSA Mathematics Practice Test Guide

Grade 8 FSA Mathematics Practice Test Guide Grade 8 FSA Mathematics Practice Test Guide This guide serves as a walkthrough of the Grade 8 Florida Standards Assessments (FSA) Mathematics practice test. By reviewing the steps listed below, you will

More information

Excel Spreadsheets and Graphs

Excel Spreadsheets and Graphs Excel Spreadsheets and Graphs Spreadsheets are useful for making tables and graphs and for doing repeated calculations on a set of data. A blank spreadsheet consists of a number of cells (just blank spaces

More information

EXCEL 2003 DISCLAIMER:

EXCEL 2003 DISCLAIMER: EXCEL 2003 DISCLAIMER: This reference guide is meant for experienced Microsoft Excel users. It provides a list of quick tips and shortcuts for familiar features. This guide does NOT replace training or

More information

Excel R Tips. is used for multiplication. + is used for addition. is used for subtraction. / is used for division

Excel R Tips. is used for multiplication. + is used for addition. is used for subtraction. / is used for division Excel R Tips EXCEL TIP 1: INPUTTING FORMULAS To input a formula in Excel, click on the cell you want to place your formula in, and begin your formula with an equals sign (=). There are several functions

More information

Corel Ventura 8 Introduction

Corel Ventura 8 Introduction Corel Ventura 8 Introduction Training Manual A! ANZAI 1998 Anzai! Inc. Corel Ventura 8 Introduction Table of Contents Section 1, Introduction...1 What Is Corel Ventura?...2 Course Objectives...3 How to

More information

VBScript: Math Functions

VBScript: Math Functions C h a p t e r 3 VBScript: Math Functions In this chapter, you will learn how to use the following VBScript functions to World Class standards: 1. Writing Math Equations in VBScripts 2. Beginning a New

More information

FSA Geometry EOC Practice Test Guide

FSA Geometry EOC Practice Test Guide FSA Geometry EOC Practice Test Guide This guide serves as a walkthrough of the Florida Standards Assessments (FSA) Geometry End-of- Course (EOC) practice test. By reviewing the steps listed below, you

More information

EXCEL SPREADSHEET TUTORIAL

EXCEL SPREADSHEET TUTORIAL EXCEL SPREADSHEET TUTORIAL Note to all 200 level physics students: You will be expected to properly format data tables and graphs in all lab reports, as described in this tutorial. Therefore, you are responsible

More information

Programming with visual Basic:

Programming with visual Basic: Programming with visual Basic: 1-Introdution to Visual Basics 2-Forms and Control tools. 3-Project explorer, properties and events. 4-make project, save it and its applications. 5- Files projects and exercises.

More information

Name: Dr. Fritz Wilhelm Lab 1, Presentation of lab reports Page # 1 of 7 5/17/2012 Physics 120 Section: ####

Name: Dr. Fritz Wilhelm Lab 1, Presentation of lab reports Page # 1 of 7 5/17/2012 Physics 120 Section: #### Name: Dr. Fritz Wilhelm Lab 1, Presentation of lab reports Page # 1 of 7 Lab partners: Lab#1 Presentation of lab reports The first thing we do is to create page headers. In Word 2007 do the following:

More information

You will have mastered the material in this chapter when you can:

You will have mastered the material in this chapter when you can: CHAPTER 6 Loop Structures OBJECTIVES You will have mastered the material in this chapter when you can: Add a MenuStrip object Use the InputBox function Display data using the ListBox object Understand

More information

Lab1: Use of Word and Excel

Lab1: Use of Word and Excel Dr. Fritz Wilhelm; physics 230 Lab1: Use of Word and Excel Page 1 of 9 Lab partners: Download this page onto your computer. Also download the template file which you can use whenever you start your lab

More information

SUM - This says to add together cells F28 through F35. Notice that it will show your result is

SUM - This says to add together cells F28 through F35. Notice that it will show your result is COUNTA - The COUNTA function will examine a set of cells and tell you how many cells are not empty. In this example, Excel analyzed 19 cells and found that only 18 were not empty. COUNTBLANK - The COUNTBLANK

More information

Introduction to MS Excel Management Information Systems

Introduction to MS Excel Management Information Systems Introduction to MS Excel 2007 Management Information Systems 1 Overview What is MS Excel? Functions. Sorting Data. Filtering Data. Data Form. Data Validation. Create charts in Excel. Formatting Cells.

More information

INTRODUCTION... 1 UNDERSTANDING CELLS... 2 CELL CONTENT... 4

INTRODUCTION... 1 UNDERSTANDING CELLS... 2 CELL CONTENT... 4 Introduction to Microsoft Excel 2016 INTRODUCTION... 1 The Excel 2016 Environment... 1 Worksheet Views... 2 UNDERSTANDING CELLS... 2 Select a Cell Range... 3 CELL CONTENT... 4 Enter and Edit Data... 4

More information

Microsoft Office Excel

Microsoft Office Excel Microsoft Office 2007 - Excel Help Click on the Microsoft Office Excel Help button in the top right corner. Type the desired word in the search box and then press the Enter key. Choose the desired topic

More information

Gloucester County Library System EXCEL 2007

Gloucester County Library System EXCEL 2007 Gloucester County Library System EXCEL 2007 Introduction What is Excel? Microsoft E x c e l is an electronic s preadsheet program. I t is capable o f performing many diff e r e n t t y p e s o f c a l

More information

Gloucester County Library System. Excel 2010

Gloucester County Library System. Excel 2010 Gloucester County Library System Excel 2010 Introduction What is Excel? Microsoft Excel is an electronic spreadsheet program. It is capable of performing many different types of calculations and can organize

More information

Program and Graphical User Interface Design

Program and Graphical User Interface Design CHAPTER 2 Program and Graphical User Interface Design OBJECTIVES You will have mastered the material in this chapter when you can: Open and close Visual Studio 2010 Create a Visual Basic 2010 Windows Application

More information

MatDeck User Manual. Contents

MatDeck User Manual. Contents MatDeck User Manual Contents Table of Pictures... 2 1 Activate license - Help tab... 6 2 MatDeck basics... 7 2.1 Document list area... 7 2.2 Document area... 8 2.2.1 Data types... 8 2.2.2 Variables...

More information

Microsoft Excel 2010 Handout

Microsoft Excel 2010 Handout Microsoft Excel 2010 Handout Excel is an electronic spreadsheet program you can use to enter and organize data, and perform a wide variety of number crunching tasks. Excel helps you organize and track

More information

The Mathcad Workspace 7

The Mathcad Workspace 7 For information on system requirements and how to install Mathcad on your computer, refer to Chapter 1, Welcome to Mathcad. When you start Mathcad, you ll see a window like that shown in Figure 2-1. By

More information

ME 365 EXPERIMENT 3 INTRODUCTION TO LABVIEW

ME 365 EXPERIMENT 3 INTRODUCTION TO LABVIEW ME 365 EXPERIMENT 3 INTRODUCTION TO LABVIEW Objectives: The goal of this exercise is to introduce the Laboratory Virtual Instrument Engineering Workbench, or LabVIEW software. LabVIEW is the primary software

More information

POWERPOINT 2003 OVERVIEW DISCLAIMER:

POWERPOINT 2003 OVERVIEW DISCLAIMER: DISCLAIMER: POWERPOINT 2003 This reference guide is meant for experienced Microsoft Office users. It provides a list of quick tips and shortcuts for familiar features. This guide does NOT replace training

More information

CHAPTER 1 COPYRIGHTED MATERIAL. Getting to Know AutoCAD. Opening a new drawing. Getting familiar with the AutoCAD and AutoCAD LT Graphics windows

CHAPTER 1 COPYRIGHTED MATERIAL. Getting to Know AutoCAD. Opening a new drawing. Getting familiar with the AutoCAD and AutoCAD LT Graphics windows CHAPTER 1 Getting to Know AutoCAD Opening a new drawing Getting familiar with the AutoCAD and AutoCAD LT Graphics windows Modifying the display Displaying and arranging toolbars COPYRIGHTED MATERIAL 2

More information

Start menu. Toggles between All Programs & Back

Start menu. Toggles between All Programs & Back Microsoft Windows Vista Illustrated Introductory Working with Windows Programs Objectives Start a program Open and save a WordPad document Modify text in WordPad Work with a graphic in Paint 2 Objectives

More information

Drawing an Integrated Circuit Chip

Drawing an Integrated Circuit Chip Appendix C Drawing an Integrated Circuit Chip In this chapter, you will learn how to use the following VBA functions to World Class standards: Beginning a New Visual Basic Application Opening the Visual

More information

Budget Exercise for Intermediate Excel

Budget Exercise for Intermediate Excel Budget Exercise for Intermediate Excel Follow the directions below to create a 12 month budget exercise. Read through each individual direction before performing it, like you are following recipe instructions.

More information

Excel 2010: Getting Started with Excel

Excel 2010: Getting Started with Excel Excel 2010: Getting Started with Excel Excel 2010 Getting Started with Excel Introduction Page 1 Excel is a spreadsheet program that allows you to store, organize, and analyze information. In this lesson,

More information

Text box. Command button. 1. Click the tool for the control you choose to draw in this case, the text box.

Text box. Command button. 1. Click the tool for the control you choose to draw in this case, the text box. Visual Basic Concepts Hello, Visual Basic See Also There are three main steps to creating an application in Visual Basic: 1. Create the interface. 2. Set properties. 3. Write code. To see how this is done,

More information

FSA Algebra 1 EOC Practice Test Guide

FSA Algebra 1 EOC Practice Test Guide FSA Algebra 1 EOC Practice Test Guide This guide serves as a walkthrough of the Florida Standards Assessments (FSA) Algebra 1 End-of- Course (EOC) practice test. By reviewing the steps listed below, you

More information

In this section you will learn some simple data entry, editing, formatting techniques and some simple formulae. Contents

In this section you will learn some simple data entry, editing, formatting techniques and some simple formulae. Contents In this section you will learn some simple data entry, editing, formatting techniques and some simple formulae. Contents Section Topic Sub-topic Pages Section 2 Spreadsheets Layout and Design S2: 2 3 Formulae

More information

Type Storage Range of Values

Type Storage Range of Values University of Misan College of Engineering Department of Civil Engineering Course Title: Visual Basic Second Stage Fourth Lecture Visual Basic Data There are many types of data that we come across in our

More information

FSA Algebra 1 EOC Practice Test Guide

FSA Algebra 1 EOC Practice Test Guide FSA Algebra 1 EOC Practice Test Guide This guide serves as a walkthrough of the Algebra 1 EOC practice test. By reviewing the steps listed below, you will have a better understanding of the test functionalities,

More information

Microsoft Word for Report-Writing (2016 Version)

Microsoft Word for Report-Writing (2016 Version) Microsoft Word for Report-Writing (2016 Version) Microsoft Word is a versatile, widely-used tool for producing presentation-quality documents. Most students are well-acquainted with the program for generating

More information

PowerPoint Spring 2002

PowerPoint Spring 2002 PowerPoint 2000 Spring 2002 Table of Contents I. INTRODUCTION... 1 II. GETTING STARTED... 1 A. Opening PowerPoint... 1 B. The Mouse Pointer... 1 C. Working with Text... 2 1. Windows Control Buttons...

More information

A Tutorial for Excel 2002 for Windows

A Tutorial for Excel 2002 for Windows INFORMATION SYSTEMS SERVICES Writing Formulae with Microsoft Excel 2002 A Tutorial for Excel 2002 for Windows AUTHOR: Information Systems Services DATE: August 2004 EDITION: 2.0 TUT 47 UNIVERSITY OF LEEDS

More information

Following a tour is the easiest way to learn Prism.

Following a tour is the easiest way to learn Prism. Page 1 of 25 A tour of Prism Following a tour is the easiest way to learn Prism. View a movie Watch and listen to a ten minute introductory movie from Prism's Welcome dialog. Or view it on the web. Read

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

Creating a Text Frame. Create a Table and Type Text. Pointer Tool Text Tool Table Tool Word Art Tool

Creating a Text Frame. Create a Table and Type Text. Pointer Tool Text Tool Table Tool Word Art Tool Pointer Tool Text Tool Table Tool Word Art Tool Picture Tool Clipart Tool Creating a Text Frame Select the Text Tool with the Pointer Tool. Position the mouse pointer where you want one corner of the text

More information

Full file at https://fratstock.eu Programming in Visual Basic 2010

Full file at https://fratstock.eu Programming in Visual Basic 2010 OBJECTIVES: Chapter 2 User Interface Design Upon completion of this chapter, your students will be able to 1. Use text boxes, masked text boxes, rich text boxes, group boxes, check boxes, radio buttons,

More information

Using Microsoft Excel

Using Microsoft Excel Using Microsoft Excel Formatting a spreadsheet means changing the way it looks to make it neater and more attractive. Formatting changes can include modifying number styles, text size and colours. Many

More information

Visual C# Program: Simple Game 3

Visual C# Program: Simple Game 3 C h a p t e r 6C Visual C# Program: Simple Game 3 In this chapter, you will learn how to use the following Visual C# Application functions to World Class standards: Opening Visual C# Editor Beginning a

More information

GUJARAT TECHNOLOGICAL UNIVERSITY DIPLOMA IN INFORMATION TECHNOLOGY Semester: 4

GUJARAT TECHNOLOGICAL UNIVERSITY DIPLOMA IN INFORMATION TECHNOLOGY Semester: 4 GUJARAT TECHNOLOGICAL UNIVERSITY DIPLOMA IN INFORMATION TECHNOLOGY Semester: 4 Subject Name VISUAL BASIC Sr.No Course content 1. 1. Introduction to Visual Basic 1.1. Programming Languages 1.1.1. Procedural,

More information

Beginning PowerPoint XP for Windows

Beginning PowerPoint XP for Windows Beginning PowerPoint XP for Windows Tutorial Description This course introduces you to the PowerPoint program basics for creating a simple on-screen presentation. Intended Audience Individuals interested

More information

Introduction to Microsoft Word

Introduction to Microsoft Word Chapter Microsoft Word is a powerful word processing program that allows you to enter text, make changes to it, format it, record and print it. You can use it to produce professional business letters,

More information

EXCEL BASICS: MICROSOFT OFFICE 2010

EXCEL BASICS: MICROSOFT OFFICE 2010 EXCEL BASICS: MICROSOFT OFFICE 2010 GETTING STARTED PAGE 02 Prerequisites What You Will Learn USING MICROSOFT EXCEL PAGE 03 Opening Microsoft Excel Microsoft Excel Features Keyboard Review Pointer Shapes

More information

Chapter 4: Single Table Form Lab

Chapter 4: Single Table Form Lab Chapter 4: Single Table Form Lab Learning Objectives This chapter provides practice with creating forms for individual tables in Access 2003. After this chapter, you should have acquired the knowledge

More information

SYLLABUS B.Com (Computer) VI SEM Subject Visual Basic Unit I

SYLLABUS B.Com (Computer) VI SEM Subject Visual Basic Unit I SYLLABUS B.Com (Computer) VI SEM Subject Visual Basic Unit I UNIT I UNIT II UNIT III UNIT IV UNIT V Introduction to Visual Basic: Introduction Graphics User Interface (GUI), Programming Language (Procedural,

More information

Unit 11.Introduction to Form and Report

Unit 11.Introduction to Form and Report Introduction to Form Unit 11.Introduction to Form and Report Introduction: Databases are made to be used. Access provides an easy way to enter data into Access database tables with forms. Forms can also

More information

ECDL Module 6 REFERENCE MANUAL

ECDL Module 6 REFERENCE MANUAL ECDL Module 6 REFERENCE MANUAL Presentation Microsoft PowerPoint XP Edition for ECDL Syllabus Four PAGE 2 - ECDL MODULE 6 (USING POWERPOINT XP) - MANUAL 6.1 GETTING STARTED... 4 6.1.1 FIRST STEPS WITH

More information

Overview About KBasic

Overview About KBasic Overview About KBasic The following chapter has been used from Wikipedia entry about BASIC and is licensed under the GNU Free Documentation License. Table of Contents Object-Oriented...2 Event-Driven...2

More information

Lesson Skill Matrix Skill Exam Objective Objective Number

Lesson Skill Matrix Skill Exam Objective Objective Number Lesson 6 Page 1 Creating Tables Lesson Skill Matrix Skill Exam Objective Objective Number Creating a Table Create a table by specifying rows and columns. 3.1.3 Formatting a Table Apply table styles. 3.1.4

More information

EXCEL 2007 TIP SHEET. Dialog Box Launcher these allow you to access additional features associated with a specific Group of buttons within a Ribbon.

EXCEL 2007 TIP SHEET. Dialog Box Launcher these allow you to access additional features associated with a specific Group of buttons within a Ribbon. EXCEL 2007 TIP SHEET GLOSSARY AutoSum a function in Excel that adds the contents of a specified range of Cells; the AutoSum button appears on the Home ribbon as a. Dialog Box Launcher these allow you to

More information

VISUAL BASIC 6.0 OVERVIEW

VISUAL BASIC 6.0 OVERVIEW VISUAL BASIC 6.0 OVERVIEW GENERAL CONCEPTS Visual Basic is a visual programming language. You create forms and controls by drawing on the screen rather than by coding as in traditional languages. Visual

More information

Laboratory 1. Part 1: Introduction to Spreadsheets

Laboratory 1. Part 1: Introduction to Spreadsheets Laboratory 1 Part 1: Introduction to Spreadsheets By the end of this laboratory session you should be familiar with: Navigating around a worksheet. Naming sheets and cells. Formatting. The use of formulae.

More information

Skill Exam Objective Objective Number

Skill Exam Objective Objective Number Creating Tables 6 LESSON SKILL MATRIX Skill Exam Objective Objective Number Creating a Table Create a table by specifying rows and columns. 3.1.3 Formatting a Table Apply table styles. 3.1.4 Managing Tables

More information

Tutorials. Lesson 3 Work with Text

Tutorials. Lesson 3 Work with Text In this lesson you will learn how to: Add a border and shadow to the title. Add a block of freeform text. Customize freeform text. Tutorials Display dates with symbols. Annotate a symbol using symbol text.

More information

EXCEL BASICS: MICROSOFT OFFICE 2007

EXCEL BASICS: MICROSOFT OFFICE 2007 EXCEL BASICS: MICROSOFT OFFICE 2007 GETTING STARTED PAGE 02 Prerequisites What You Will Learn USING MICROSOFT EXCEL PAGE 03 Opening Microsoft Excel Microsoft Excel Features Keyboard Review Pointer Shapes

More information

An interesting related problem is Buffon s Needle which was first proposed in the mid-1700 s.

An interesting related problem is Buffon s Needle which was first proposed in the mid-1700 s. Using Monte Carlo to Estimate π using Buffon s Needle Problem An interesting related problem is Buffon s Needle which was first proposed in the mid-1700 s. Here s the problem (in a simplified form). Suppose

More information

Vensim PLE Quick Reference and Tutorial

Vensim PLE Quick Reference and Tutorial Vensim PLE Quick Reference and Tutorial Main Toolbar Sketch Tools Menu Title Bar Analysis Tools Build (Sketch)Window Status Bar General Points 1. File operations and cutting/pasting work in the standard

More information

Visual basic tutorial problems, developed by Dr. Clement,

Visual basic tutorial problems, developed by Dr. Clement, EXCEL Visual Basic Tutorial Problems (Version January 20, 2009) Dr. Prabhakar Clement Arthur H. Feagin Distinguished Chair Professor Department of Civil Engineering, Auburn University Home page: http://www.eng.auburn.edu/users/clemept/

More information

Access 2003 Introduction to Report Design

Access 2003 Introduction to Report Design Access 2003 Introduction to Report Design TABLE OF CONTENTS CREATING A REPORT IN DESIGN VIEW... 3 BUILDING THE REPORT LAYOUT... 5 SETTING THE REPORT WIDTH... 5 DISPLAYING THE FIELD LIST... 5 WORKING WITH

More information

DOING MORE WITH EXCEL: MICROSOFT OFFICE 2010

DOING MORE WITH EXCEL: MICROSOFT OFFICE 2010 DOING MORE WITH EXCEL: MICROSOFT OFFICE 2010 GETTING STARTED PAGE 02 Prerequisites What You Will Learn MORE TASKS IN MICROSOFT EXCEL PAGE 03 Cutting, Copying, and Pasting Data Filling Data Across Columns

More information

Welcome Application. Introducing the Visual Studio.NET IDE. Objectives. Outline

Welcome Application. Introducing the Visual Studio.NET IDE. Objectives. Outline 2 T U T O R I A L Objectives In this tutorial, you will learn to: Navigate Visual Studio.NET s Start Page. Create a Visual Basic.NET solution. Use the IDE s menus and toolbars. Manipulate windows in the

More information

Lecture 2 FORTRAN Basics. Lubna Ahmed

Lecture 2 FORTRAN Basics. Lubna Ahmed Lecture 2 FORTRAN Basics Lubna Ahmed 1 Fortran basics Data types Constants Variables Identifiers Arithmetic expression Intrinsic functions Input-output 2 Program layout PROGRAM program name IMPLICIT NONE

More information

variables programming statements

variables programming statements 1 VB PROGRAMMERS GUIDE LESSON 1 File: VbGuideL1.doc Date Started: May 24, 2002 Last Update: Dec 27, 2002 ISBN: 0-9730824-9-6 Version: 0.0 INTRODUCTION TO VB PROGRAMMING VB stands for Visual Basic. Visual

More information

For more info and downloads go to: Gerrit Stols

For more info and downloads go to:   Gerrit Stols For more info and downloads go to: http://school-maths.com Gerrit Stols Acknowledgements GeoGebra is dynamic mathematics open source (free) software for learning and teaching mathematics in schools. It

More information

Introduction to Data Entry and Data Types

Introduction to Data Entry and Data Types 212 Chapter 4 Variables and Arithmetic Operations STEP 1 With the Toolbox visible (see Figure 4-21), click the Toolbox Close button. The Toolbox closes and the work area expands in size.to reshow the Toolbox

More information

Pre-Lab Excel Problem

Pre-Lab Excel Problem Pre-Lab Excel Problem Read and follow the instructions carefully! Below you are given a problem which you are to solve using Excel. If you have not used the Excel spreadsheet a limited tutorial is given

More information

9. Elementary Algebraic and Transcendental Scalar Functions

9. Elementary Algebraic and Transcendental Scalar Functions Scalar Functions Summary. Introduction 2. Constants 2a. Numeric Constants 2b. Character Constants 2c. Symbol Constants 2d. Nested Constants 3. Scalar Functions 4. Arithmetic Scalar Functions 5. Operators

More information

Microsoft Excel Level 1

Microsoft Excel Level 1 Microsoft Excel 2010 Level 1 Copyright 2010 KSU Department of Information Technology Services This document may be downloaded, printed, or copied for educational use without further permission of the Information

More information

C++ Programming: From Problem Analysis to Program Design, Third Edition

C++ Programming: From Problem Analysis to Program Design, Third Edition C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 2: Basic Elements of C++ Objectives (continued) Become familiar with the use of increment and decrement operators Examine

More information

Intermediate Microsoft Excel

Intermediate Microsoft Excel Intermediate Microsoft Excel Class learning objectives By the end of class, students should be able to perform the following tasks in Microsoft Word: 1. Completing a Series 2. Review of Excel Basics Create

More information

Excel 2016 Basics for Windows

Excel 2016 Basics for Windows Excel 2016 Basics for Windows Excel 2016 Basics for Windows Training Objective To learn the tools and features to get started using Excel 2016 more efficiently and effectively. What you can expect to learn

More information

Creating a Basic Chart in Excel 2007

Creating a Basic Chart in Excel 2007 Creating a Basic Chart in Excel 2007 A chart is a pictorial representation of the data you enter in a worksheet. Often, a chart can be a more descriptive way of representing your data. As a result, those

More information

ENV Laboratory 2: Graphing

ENV Laboratory 2: Graphing Name: Date: Introduction It is often said that a picture is worth 1,000 words, or for scientists we might rephrase it to say that a graph is worth 1,000 words. Graphs are most often used to express data

More information

Introduction to Microsoft Excel

Introduction to Microsoft Excel Athens-Clarke County Library Page 1 What is a spreadsheet program? Microsoft Excel is an example of a spreadsheet program that will maintain records for you relating to finances, products, activities,

More information

Chapter 5. Inserting Objects. Highlights

Chapter 5. Inserting Objects. Highlights Chapter 5 Inserting Objects Highlights 5. Inserting AutoShapes, WordArts and ClipArts 5. Changing Object Position, Size and Colour 5. Drawing Lines 5.4 Inserting Pictures and Text Boxes 5.5 Inserting Movies

More information

Glossary. advance: to move forward

Glossary. advance: to move forward Computer Computer Skills Glossary Skills Glossary advance: to move forward alignment tab: the tab in the Format Cells dialog box that allows you to choose how the data in the cells will be aligned (left,

More information

Full file at Excel Chapter 2 - Formulas, Functions, Formatting, and Web Queries

Full file at   Excel Chapter 2 - Formulas, Functions, Formatting, and Web Queries Excel Chapter 2 - Formulas, Functions, Formatting, and Web Queries MULTIPLE CHOICE 1. To start a new line in a cell, press after each line, except for the last line, which is completed by clicking the

More information

HOUR 4 Understanding Events

HOUR 4 Understanding Events HOUR 4 Understanding Events It s fairly easy to produce an attractive interface for an application using Visual Basic.NET s integrated design tools. You can create beautiful forms that have buttons to

More information

Lesson 1 New Presentation

Lesson 1 New Presentation Powerpoint Lesson 1 New Presentation 1. When PowerPoint first opens, there are four choices on how to create a new presentation. You can select AutoContent wizard, Template, Blank presentation or Open

More information

SolidWorks 2½D Parts

SolidWorks 2½D Parts SolidWorks 2½D Parts IDeATe Laser Micro Part 1b Dave Touretzky and Susan Finger 1. Create a new part In this lab, you ll create a CAD model of the 2 ½ D key fob below to make on the laser cutter. Select

More information

SciGraphica. Tutorial Manual - Tutorials 1and 2 Version 0.8.0

SciGraphica. Tutorial Manual - Tutorials 1and 2 Version 0.8.0 SciGraphica Tutorial Manual - Tutorials 1and 2 Version 0.8.0 Copyright (c) 2001 the SciGraphica documentation group Permission is granted to copy, distribute and/or modify this document under the terms

More information

WEEK NO. 12 MICROSOFT EXCEL 2007

WEEK NO. 12 MICROSOFT EXCEL 2007 WEEK NO. 12 MICROSOFT EXCEL 2007 LESSONS OVERVIEW: GOODBYE CALCULATORS, HELLO SPREADSHEET! 1. The Excel Environment 2. Starting A Workbook 3. Modifying Columns, Rows, & Cells 4. Working with Worksheets

More information

Learning Worksheet Fundamentals

Learning Worksheet Fundamentals 1.1 LESSON 1 Learning Worksheet Fundamentals After completing this lesson, you will be able to: Create a workbook. Create a workbook from a template. Understand Microsoft Excel window elements. Select

More information

Microsoft Excel 2010 Tutorial

Microsoft Excel 2010 Tutorial 1 Microsoft Excel 2010 Tutorial Excel is a spreadsheet program in the Microsoft Office system. You can use Excel to create and format workbooks (a collection of spreadsheets) in order to analyze data and

More information

NOTES: Variables & Constants (module 10)

NOTES: Variables & Constants (module 10) Computer Science 110 NAME: NOTES: Variables & Constants (module 10) Introduction to Variables A variable is like a container. Like any other container, its purpose is to temporarily hold or store something.

More information

Chapter 1: Introduction to the Microsoft Excel Spreadsheet

Chapter 1: Introduction to the Microsoft Excel Spreadsheet Chapter 1: Introduction to the Microsoft Excel Spreadsheet Objectives This chapter introduces you to the Microsoft Excel spreadsheet. You should gain an understanding of the following topics: The range

More information

Outline. Midterm Review. Using Excel. Midterm Review: Excel Basics. Using VBA. Sample Exam Question. Midterm Review April 4, 2014

Outline. Midterm Review. Using Excel. Midterm Review: Excel Basics. Using VBA. Sample Exam Question. Midterm Review April 4, 2014 Midterm Review Larry Caretto Mechanical Engineering 209 Computer Programming for Mechanical Engineers April 4, 2017 Outline Excel spreadsheet basics Use of VBA functions and subs Declaring/using variables

More information

Workbooks & Worksheets. Getting Started. Formatting. Formulas & Functions

Workbooks & Worksheets. Getting Started. Formatting. Formulas & Functions 1 Getting Started Cells Workbooks & Worksheets Formatting Formulas & Functions Chart Printing 2 Getting Started Start a spreadsheet program Recognize the spreadsheet screen layout Use the ribbon,quick

More information

Introduction to MS Office Somy Kuriakose Principal Scientist, FRAD, CMFRI

Introduction to MS Office Somy Kuriakose Principal Scientist, FRAD, CMFRI Introduction to MS Office Somy Kuriakose Principal Scientist, FRAD, CMFRI Email: somycmfri@gmail.com 29 Word, Excel and Power Point Microsoft Office is a productivity suite which integrates office tools

More information

PART ONE 1. LAYOUT. A file in Excel is called a Workbook. Each Workbook is made up of Worksheets (usually three but more can be added).

PART ONE 1. LAYOUT. A file in Excel is called a Workbook. Each Workbook is made up of Worksheets (usually three but more can be added). PART ONE 1. LAYOUT A file in Excel is called a Workbook. Each Workbook is made up of Worksheets (usually three but more can be added). The work area is where the data and formulae are entered. The active

More information

Document Editor Basics

Document Editor Basics Document Editor Basics When you use the Document Editor option, either from ZP Toolbox or from the Output option drop-down box, you will be taken to the Report Designer Screen. While in this window, you

More information

Answer: C. 7. In window we can write code A. Immediate window B. Locals window C. Code editor window D. None of these. Answer: C

Answer: C. 7. In window we can write code A. Immediate window B. Locals window C. Code editor window D. None of these. Answer: C 1. Visual Basic is a tool that allows you to develop application in A. Real time B. Graphical User Interface C. Menu Driven D. None Of These 2. IDE stands for.. A. Internet Development Environment B. Integrated

More information