Unit 2 - Variables 2.1 Introduction We are definitely becoming a society of vast amounts of information. However this information needs to be stored where it can be used and accessed. Our mail gets stored in a mailbox, our E-mail gets stored in our in boxes and our personal items hopefully get stored neatly in our rooms. Programming requires information to be stored. The information is stored in what are called variables. Variables are like the mailboxes of our computers. Each variable contains information, just as a mailbox contains envelopes/letters. Each variable has an address, just as each mailbox is assigned a street address. Each variable will have a specific name, similarly each mailbox is labeled with the name of a family or business. A variable in programming is information or a value that is expected to change. Days of the year change, the temperature in our Canadian climate changes and whether we like it or not our age changes. In programming we use variables to store information or values that are expected to change during the course of the program. Variables in Visual Basic hold information or values. When a variable is used or declared the Visual Basic sets up a storage space, such as a named memory box, in the computers memory. When needed in a program visual basic can access this variable and its value as long as it has been declared. Definition Declared means when a variable is given a name. Required Skills 1. From design. 2. Command controls, text boxes and label boxes. 3. Comments New Skills 1. 2. 3. 4. 5. Variables and Variable Data Types Constants Message Box Color Multiple Forms Outcomes In order to work through this unit you should be able to: 9. 10. 11. 12. 13. 1. Declare a variable using a data type. 2. Declare a variable using all eleven data types. 3. Declare a variable and assign the variable to an object. 4. Know where to declare a variable (local, global or modular). 5. Declare more than one variable of the same data type. 6. Know the scope of variables. 7. Know the difference between a variable and a constant. 8. Declare a constant and use it in a program. Know the order of operations (PEDMAS/BEDMAS). Use mathematical operations in a program. Use the message box where appropriate in a program. Use of multiple forms in a project. Know how to refer to object values or information from form to form. Key Words For the explanations and definitions of the key words see Appendix B Variable Description A variables is a named storage place in a computers memory. Variables are used in a code statements to store temporary values used by other code statements. Code statements are lines of programming code inside an object. For the most part variables are declared as Option Explicit in the General Declarations area of the program (see frmVariableDeclaration) . Variables in Visual Basic all have a name, that the programmer creates, and a data type that Visual Basic pre-defines. of The contents a variable determine what data type a variable will be. A data type is whether the contents of a variable is numbers, letters or special numbers. Data types will be discussed below. The following is an example of a variable declaration using Option Explicit in the General Declarations section of a program. Notice that the Object is General and the Proc is declarations. Variable Data Types The contents of a variable is a determining factor as to what data type the variable will be. Visual Basic holds 11 standard data types for variables. It is also possible to define your own variable types. For our purposes we will be using the standard data types. The most often used data types include string and integer. For example: Dim Num1 as Integer Variable Type Storage Size (in bytes) Range String length 1 to 65,535 characters 1 of string Byte Description 0 to 255 Boolean 2 True or False Integer 2 -32,768 to 32,767 Long Integers 4 -2,147,483,647 to 2,147,483,647 Single Precision 4 -3.402823E38 to string variables hold characters. one of the most common uses of strings variables is to pick up the information contained in a text box. hold relatively small integer values. it is a no type-declaration characters are no type_ declaration characters. used when there are logical tests to be performed. hold relatively small integer values. used when integers require no decimal point. it is a no type-declaration character use whenever a number is larger than an integer. eg. the cost of a new house, $150,000 hold relatively small integer values. it is a no type-declaration -1.401298E-45 for negative numbers -1.401298E-45 to character. usually numbers that contain decimal places. use when you do not want integers to be rounded off. eg. 23.45 -3.402823E38 for positive numbers Double Precision Currency 8 8 -1.79769313486232E308 to 4.94065645841247E324 for negative numbers 4.94065645841247E-324 to 1.79769313486232E308 for positive numbers -922,337,203,685,477. 5808 to 2,337,203,685,477.5807 hold relatively small integer values. it is a no type-declaration character. needs greater storage. use when you need very small or very large numbers that require great precision. hold relatively small integer values. it is a no type-declaration character. used when accuracy is important. Date 8 Jan. 1, 100 to Dec. 31, 9999 used to find days between two dates. Variant 16 for negative numbers Any numeric value up to the range of a Double hold relatively small integer values. it is a no type-declaration character 22 + string length Variable Declaration 2.2 Variable Names Variable names are given depending on the information the variable will store. For example the variable name FirstName will be given to a variable that will hold a persons first name. Again The variable name is declared or named in the general declarations area of a program as show in the Variable Description section. Rules for Declaring Variables There are certain standards that we must follow when declaring variables. They include: 1. The variable name must begin with a character. For variables that are declared in an event the first character must be a letter. The first character for variables declared in the form or module the first letter must indicate whether the variable is declared in the form's (f_) or module's (m_) general declarations area followed by an underscore and the variable name. eg. f_Age as Integer The concepts of declaring variables in events, forms or modules will be discussed in the Scope of Variables section. NOTE: for smaller programs we will be declaring variables in forms or in objects programs. For larger programs with multiple forms we will declare variables in modules. 1. All memory variables will be declared in the most appropriate location and appear in lower case. 2. The name cannot be more than 40 characters long. 3. The name cannot contain punctuations or blank spaces 4. All variables must have a data type that is suitable to the variable use in the program. 5. The name cannot be a reserved word (such as Print, Name, Hour), because reserved words have special meaning in Visual Basic. See Appendix A for a list of Reserved Words. Examples of Proper Variable Declarations Valid Invalid Reason for Invalidity Variable Name Variable Name f_Hourswkd Hours hours is a reserved word f_Salary97 97Salary name must not begin with a number c_Discount_Price Discount Price name cannot contain a space c_FirstName Name reserved word m_FireDepartment Fire.Department name cannot contain punctuation The Dim Statement for Data Types Before a variables is declared programmers must include the Dim syntax. This indicates to the program that the variables value could change as the program runs. Syntax Variable Declaration in an Event: Dim <NameYouCreate> as Data Type Variable Declaration in a form's General Declarations: Dim <f_NameYouCreate> as Data Type Variable Declaration in a module's General Declarations: Dim <m_NameYouCreate> as Data Type Examples Dim CanadianDollar as Currency Dim f_ Year as Integer Dim m_FirstName as String Dim CorrectAnswer as Boolean Dim f_Temperature as Long Dim m_FractionCalc as Single Dim f_TheCalculation ' this makes f_TheCalculation have the variant data type. The variant data type takes up a lot of space in memory. It is not good programming practice to declare variables with the variant data type. You can also declare variables on the same line. It is good programming practice to keep all the same variables of the same data type on the same line. Dim NumberofDays as Integer, HoursWorked as Integer Dim m_FirstName as String, m_MiddleName as String, m_LastName as String Dim f_TaxRate as Integer, f_Subtotal as Integer, f_Total As Integer The Scope of Variables Variables may be declared in the following levels in Visual Basic: Variable Type variable name = expression Event Dim Fname as Type ReDim Fname as Type Description Static Fname as Type Form Dim f_Fname as Type Module Public m_Fname as Type (for VB 4.0) Global m_Fname as Type (for VB 3.0) Variable Assignment Statements declared in any procedure. available only in the procedure or object in which it is called. ReDim is used to change the size of an array, only in a procedure. Static is when the programmer wishes to have a procedure retain a variable's values for the duration of the application. also known as local to the event, local to the object or control or procedure in any procedure. in the declaration section of a form. available to all procedures in that module, but not to any other form or code module. in declaration section of a module, cannot be declared anywhere. available in every procedure in all forms and code modules in the application. The easiest way to create a variable is to assign a value to the variable's name in a code statement. An assignment statement assigns a value to the property of an control/object. After the period is the property of the object followed by the equal sign and the value. The value could be a variable or a piece of information. <Object.Property> = <value property > EXAMPLE CHANGES THE... txtLname.Text = "Jones" the text displayed in the text box to Jones HourlyIncome = 10.55 f_FirstName = "John" g_PresentAge = 16 Variables can either hold numbers called numeric data or characters called string data. String data must be placed in quotation marks. Numeric data need not be in quotation marks. Variables can also be assigned to the value of another variable, the value of an object/control or the value of a mathematical expression. txtHourlyIncome.Text = f_HourlyIncome If you prefer output to be tested you can print any output on the form. All you need to do is separate the variables or anything as text with a semi-colon. Remember that variables need not have quotes around them, but the programmers setup must. For example: print "The "; f_Chlorine ; "is too high and the"; f_AlgaeCount ; "is normal." Visual Basic Variable Declaration Exercises Activity 2.2.1 1. Complete the following table. PLEASE DO NOT WRITE ON THIS HANDOUT. Variable Declaration Explanation Or Assignments Why Correct or Incorrect? Correction or Better Choice Dim Name as Integer Dim m_FirstName as Integer Dim m_Money Earned as Integer Dim f_Currency as String Dim f_ Person as String Dim m_Name as String Dim GoldbachNo as Integer Dim m_PizzaOrder Dim !Factorial as Double Dim m_Chemicalppms as Double Dim x, y, z as Integer Dim m_Num1 as Integer, m_Num2 as Integer txtCarPayment.txt = m_CarPayment TextOrderNum.Text = m_OrderNum txtCarPayment.txt = m_CarPayment Distance = txtDistance print "Show me the $ "; m_Money "!!!" m_FibonacciNum = "45" Activity 2.2.2 TOPICS: Variable Text Boxes, Label Boxes, Command Boxes and the Message Box. PART A You need to create the following: 1. 5 Label Objects 2. 4 Text Boxes 3. 3 Command Boxes 1. Change the form NAME to THE PERSONAL INFORMATION PROGRAM. Your form should appear similar to the following form: The following will help you create your program: Label1 CHANGE THE NAME TO: lblTPersonal CHANGE THE CAPTION TO: MY PERSONAL INFORMATION Change the FontSize to 18 point. Label2 CHANGE THE NAME TO:lblFirst CHANGE THE CAPTION TO: First Name Label3 CHANGE THE NAME TO: lblLast CHANGE THE CAPTION TO: Last Name Label4 CHANGE THE NAME TO: lblHeight CHANGE THE CAPTION TO: Height Label5 CHANGE THE NAME TO: lblHair Please use American spelling of color, since this is American software. CHANGE THE CAPTION TO: Hair Colour Text1 Diagram #1 CHANGE THE NAME TO: txtFirstName CHANGE THE TEXT TO: null, delete text1 As see in Diagram #1 Text2 CHANGE THE NAME TO: txtLastName CHANGE THE TEXT TO: delete Text2 Text3 CHANGE THE NAME TO: txtHeight CHANGE THE TEXT TO: delete Text3 Text4 CHANGE THE NAME TO: txtHairColor CHANGE THE TEXT TO: delete Text4 Command1 CHANGE THE NAME TO: cmdDisplay CHANGE THE TEXT TO: DISPLAY Double Click on Command2 CHANGE THE NAME TO: cmdClear CHANGE THE TEXT TO: CLEAR Double Click on Command3 CHANGE THE NAME TO: cmdExit CHANGE THE TEXT TO: E&XIT Double click on the command button, type in End between the sub and end sub. 1. Assignment Statements 2. In the general declarations area declare the following variables. REMEMBER!!! Accessing the general declarations area: double click on the form, beside Object click on the arrow down choose (General), beside Proc click on the arrow down choose (Declarations). You are using f_ because your variables are declared at the form level. This will allow you to use the variables anywhere else in the program. f_FirstName - string f_LastName - string f_Height - integer 1. Double Click on cmdDisplay. 2. Assign the 3 text boxes to the 3 appropriate variables f_FirstName = txtFirstName.Text f_LastName = txtLastName.Text f_Height = txtHeight.Text 1. Using the MSGBOX Statement The MessageBox displays one of Visual Basic's predefined dialog boxes. Example #1 MsgBox txtFirstName.Text or MsgBox f_FirstName This will display your first name in the message box. For string expressions, you must enclose them in quotations Example #2 MsgBox "Hello" Syntax <ReturnValue> = MsgBox (prompt [,buttons][,title][helpfile][,context] You can also omit the return value and the equal sign. If you want to display more than one item in the message box it is possible using the ampersand sign (&) . You can use quotes to type in text and for blank spaces between you name. Example #3 MsgBox f_FirstName & " " & f_LastName & ". " & "Your height is " & f_Height 1. Add in a text box for hair colour and declare a variable for hair colour. 2. Double Click on cmdDisplay. Type in the following code below your assignment statements: NOTE: Make sure that you type the line below in one line. The ampersand (&) sign does not need to be bold and large. MsgBox f_FirstName & " "& f_LastName & " your height is " & f_Height & " and your hair color is " & f_HairColor & ". " THE KEY FOR UNDERSTANDING: " " = a space ". " = a period and a space " and your hair color is" = a space and your hair color is Double Click on the cmdClear. Assign all the variables to a null string to clear the text boxes. txtFirstName.Text = " " txtLastName.Text = " " txtHeight.Text = " " Remember to add in your hair colour text box. Run the program use F5. Save the Form File as: vars1.frm Save the project as: vars1.vbp 1. Enter in your first name, last name, height in centimeters and your hair color. 2. Click on Display. What is the output? Note the output word for word and space for space. If you have syntax errors check cmdDisplay. Make sure you have all the quotes and ampersand signs. Ask a friend in the class for help. Here is what your output could look like: Activity 2.2.3 Part B ENHANCEMENTS: Add some color to your form by changing the properties of the objects. Change the color of the text boxes and label boxes as well as the text. See is you can add a label box and a text box for your favorite food. Don't forget to declare the variable for your favorite food and assign it to the text box. Label6 NAME: lblFood CAPTION: Favorite Food Text5 NAME: txtFood TEXT: delete Text5 Assign the food text box to the variable f_Food. Using the ampersand sign add in f_Food to the code in cmdDisplay. For example: MsgBox f_FirstName & " "& f_LastName & " your height is " & f_Height & " and your hair color is " & f_HairColor & ". " & "Your favorite food is " & f_Food " ." Note the output in your computer science binders. Constants 2.3 Constants are useful when the programmer declares a variable and it's value never changes. It is best to declare constants in the general declarations area. Constants are declared because it is easier to change a constant's value in one area. It is time consuming to search for a variable and change its value in the locations where the variable has been used. The same rules for declaring variables also applies for constants. (See the Variable Declaration section above.) Syntax Const <areadeclared_ConstantName> = <Value> Example Const f_CdnTax = 0.15 Const f_UserName = "Grade 11 Students" Visual Basic also declare constants for your file properties in a module. eg. Global Const Left_Justify = 0 The tax constant could be used in many of your programs dealing with currency. Activity 2.3.1 Name and 5 instances where constants are necessary. Use the proper syntax to declare the constants. The Format Function 2.4 Functions in Visual Basic are predefined procedures that perform a specific task. The Format Function The format is used to improve the appearance of numbers in your application. The Format Function formats any expression according to a set of string instructions you specify. If your application included using currency for millions of dollars you could specify how the dollar value should appear or you could use the predefined format function to display the dollar value. When using the format function it is not necessary to code with the format function until the formatted expressions are displayed. Note: # is a place holder for a digit. Pre-defined Formats Format Explanation Currency Displays a number with a dollar sign and two decimal places; if appropriate displays a number with a thousand separator; negative numbers are enclosed in parenthesis Fixed Displays a number with at least one digit to the left and two digits to the right of the decimal point. Standard Displays a number with two decimal places; if appropriate, displays a number with a thousand separator; negative numbers are enclosed in parenthesis Percent Multiplies a number by 100 and displays the number with a percent sign(%); displays two digits to the right of the decimal point. Scientific Displays a value as a decimal number between 0 and 10 time the appropriate power of 10. Syntax Format$(NumericExpression, FormatString$) The $ sign is to distinguish that the format output will become a string. When a variable is a variant the $ is not needed. Note: the date function will be discussed below. Examples 1. 2. 3. 4. 5. 6. Format$(99, "Percent") Format$(123000, "Currency") txtNetPay.Text = Format$(m_NetPay, "Currency") txtPlanetMass.Text = Format$(Mass, "Scientific") txtTermMark.Text = Format$(FinalMark, "Percent") lblPrice.Caption = Format(lblTotalPrice.Caption *100 *1.05, "Currency") Activity 2.4.1 Write the code in a program for the examples above and note their output. For example: On a blank form create a label box and Name it cmdDisplay with a caption Display. Type in: Print Format$(99, "Percent") Run the program and click on Display. Activity 2.4.2 The expressions below are manually/user defined. For the following expressions note the output in your computer science binders. What is the output???? Print Format$(987.654321, "###.##") Print "The interest rate is " ; Format$(Payment, "####.##). Assume: Dim Payment as Integer Payment = 4532.1 Print Format$(543.210, "###.###") Print Format$(543.210, "000.000") Print Format$(123456789.91, "#.#.##") Print Format$(500000000, "#00,,"):"million yen" Print Format$(81.234, "###.##%") Print Format$(Amount, "$###.##"). Assume: Dim f_Amount as Integer Amount =12.3 Print Format$(456.120,"###.###") Print Format$(1000000000000,"#.#.#.##") Calendar Functions 2.5 A. The Date Function Date$ returns a string for the Month-Day-Year (mm-dd-yyyy). The month and day always use two digits. The year uses four eg. 01-01-1992 for 1 January 1992 Syntax Date$= "mm-dd-yyyy" Date$="mm/dd/yyyy" mm = numbers between 01 and 12 dd = days between 01 and 31 yyyy= are years between 1980 and 2099 Remember that if your computer has a built-in clock calendar to permanently reset the clock you may have to use to setup program that came with the computer. Example lblDate.Caption = Date$ What will happen to computers in the year 2000? B. The Time Function The time function runs on a 24-clock. The eight character string is returned as hh:mm:ss. You can also set the time to show only the hours, hours and minutes or the full string. Syntax Time$(string) Example lblTime.Caption = Format(Time$, "Medium Time") C. The DateValue Function The DateValue(string) function accepts any date entered in by the user mm-dd-yyyy The returned valued of a numeric calendar function is represented as a serial-number. For example December 31, 1599 would be 1.000000 and January 1, 1600 would be 2.000000. The digits to the left of the decimal point is the date and to the right is the time. This is called a double-precision number. Syntax DateValue$("Month-Day-Year") DateValue$("Day-Month-Year") The user can enter in the date the following ways: DateValue $("12-30-1599") DateValue$("December 30, 1599") DateValue$("Dec 30, 1599") DateValue$("30 December 1599") DateValue$("30-Dec-1599") Before using the DateValue function, you need to know the current serial date or the date NOW. Visual Basic uses a pre-defined function, Now to determine the current date. Syntax txtDateNow = Now Example txtDateNow = "Today's date is"; Format$(Now, "hh:mm:ss AM/PM mm/dd/yy") txtDateNow = "Today's date is"; Format$(Now, Medium Date") You can also have different types of formats to display the dates. Instead of having the user define the dates with hh:mm etc... By using medium date, general date, long date or short date. Medium date will be discussed in Activity 2.5.1 . For Other Numeric Calendar Functions see Appendix C Activity 2.5.1 Time Zones, Dates and Introduction to Functions Save as: Zone In this project you will be determining the time of day in various international locations around the world. You will need 1. 2. 3. 4. 4 label boxes 2 text boxes 11 command boxes 1 picture (for now) The text boxes are titled txtDate and txtTime. Coding The following code below will provide you with enough code to complete the rest of the program. Make sure you use comments for each command button and you assign all variables appropriately to the text boxes. You will be getting practice using the now and date function. Declare the variables f_Time and f_Date as strings in the general declarations area under the word Option Explicit. Assign them to the appropriate text boxes in their respective command boxes. Example for the Mississauga Time Zone Private Sub cmdMississauga_Click() ' the present time is now in Mississauga where we are located. txtTime = f_Time f_Time = Format(Time$, "Medium Time") End Sub Example for the Iceland Time Zone Private Sub cmdIceland ' the time in Iceland is determined by the time now and 4 hours away. txtTime = f_TIme f_TIme = Format$(TimeSerial(Hour(Now)+ 4, Minute(Now), Second(Now)), "Medium Time") End Sub You will now have to determine the time difference in hours for the other locations. Use the same code as you have for cmdIceland but make sure you change the + 4 to the appropriate number of hours away Auckland, France etc... are __ number of hours away. The Date Function Double click on the Date command button. Type in the following code: Private Sub cmdDate_Click() txtDate.Text = f_Date f_Date.Caption = Date$ End Sub How does the TimeSerial, Hour, Minute and Now function operate in this example? See if you can add In flags for each location. Place the picture beside the name of the city. Perhaps you can copy the code from the command box into the picture and make it a click event. Activity 2.5.4 Enhancement The date function must be modified so that the date appears properly for each time zone. Expressions 2.6 Expressions are used to calculate values. To create expression you need variables and the operators. The operators in Visual Basic include: Addition + Subtraction Multiplication * Division / Exponents ^ Mathematical Operations Mathematical expressions many times involve multiple uses of different operators. When an equation includes many operators the order of operations supercedes any order in the expression. The order of operations works in Visual Basic the same way as it does in your math class. The order of operations is also known as the order of precedence. This means that certain mathematical functions will always be calculated before any other calculation. The Order of Operations/Precedence could be best remembered by PEDMAS or BEDMAS. Activity 2.5 Name the 6 orders of operation for arithmetics. If there are two of the same operators in an expression/equation the all have equal precedence, however they are evaluated from left to right in which they appear. f_Calculation = Num1*Num2*Num3*Num4+Num6 Therefore Num1*Num2 would be calculated first. In programming many times there are comparison or logical operators used along with the in the arithmetic expressions. The order in this case is arithmetic, comparison and then logical operators. Comparison operators all have equal precedence; that is, they are evaluated in the left to right order in which they appear. (VB help file) Arithmetic and logical operators are evaluated in the following order of precedence: Arithmetic Comparison Logical Exponents ^ Equality = Not Negation - Inequality <> And Multiplication Less than < Or Integer Division \ Greater than > Xor Modular arithmetic Mod Less than or Equal to <= Eqv Addition and subtraction +,- Greater than or Equal to >= Imp String concatenation & Like and Division *, / Is The string concatenation operator (&) is not an arithmetic operator, but in precedence it does fall after all arithmetic operators and before all comparison operators (see Unit 6). Similarly, the Like operator, while equal in precedence to all comparison operators, is actually a pattern-matching operator. The Is operator is an object reference comparison operator. It does not compare objects or their values; it checks only to determine if two object references refer to the same object. Activity 2.6.1 Using Mathematical Functions You will now create a small program that allows a user to enter in their name and income. Allow the program to display taxes once the user clicks on the command button. The taxes are multiplied by 40% since that is the average amount that most people working full time would pay to the government. Change the form's Caption to The Tax Man. You will need the following 1. 4 labels 2. 3 text boxes 3. 3 command boxes Label1 CAPTION: "Visual Basic is Fun" NAME: lblTitle Command1 Double click on command1 CAPTION: EXIT NAME: cmdExit Label2 Change the following: CAPTION: Name NAME: lblName Text1 Change the following: CAPTION: not available in for the text tool NAME: txtName TEXT: none Label3 Change the following: CAPTION: Income NAME: lblIncome Text2 Change the following: CAPTION: not available in for the text tool NAME: txtIncome TEXT: none Label4 Change the following: CAPTION: Taxes NAME:lblTaxes Text3 Change the following: CAPTION: not available for the text tool NAME: txtTaxes TEXT: none Command2 Change the following: CAPTION: "CALCULATE YOUR TAXES" NAME: cmdCalcTaxes Double Click on the command button and type in the following code. Private Sub cmdCalcTax_Click() ' these variables are control variables Dim Income As Integer, Taxes As Integer Income = txtIncome.Text Taxes = Int(Income *0.4) txtTaxes.Text = taxes End Sub Int is a common mathematical function used in visual basic. Int() will return an integer value of the number entered as the argument. With a negative number it returns the first integer less than or equal to the number. Command3 Change the following: CAPTION: CLEAR NAME: cmdClear Sub cmdClear_Click() txtTaxes.Text="" txtIncome.Text = "" EndSub Activity 2.6.2 ADDING IN COLOUR See appendix E for Lesson on Colour Create a new label and place it anywhere on the form. Change the following: CAPTION: "Click Here for Fun" NAME: lblResponse Type in the following code: Private Sub lblResponse_Click Sample1.BackColor = QBColor(2) lblReponse.BackColor=QBColor(13) lblResponse.Caption = "Very Much Fun!" End Sub Run the program and click on CLICK HERE FOR FUN Note what happens. Sample1 is the name of the form and BackColor is one of its properties. Try using QBColor(10) and then QBColor(7) in place of Sample1.BackColor in lblResponse. Describe what happens in your computer science binders. 1. 2. 3. 4. What does QBColor change? What does Sample1.BackColor change? What does lblResponse.BackColor change? For Commonly Used Mathematical Functions See Appendix D Review and New Code Statements Code Statement Explanation m_TicketCost = 10.50 numeric data Movie = "Batman" string data f_TipTotal = m_SubTotal value of another variable m_FinalCost = m_Price * m_Tax value of an expression Interest = m_Principal * 4.25 * Time value of an expression Val 2.7 The Val Funciton tells Visual Basic to treat the a character or string as a numeric function. Val is used when the user enters in information, such as a number, into a text box that will be used in a mathematical expression. The string expression is to be interpreted by Visual Basic as a numeric value thus a dollar sign, comma or percent sign cannot be used in the expression. Val is executed from left to right. If it encounters any alphabetical characters it returns a value of 0. For example: Val(2001Olympics), the output would be 2001. It is good practice to use val when creating large mathematical expressions. Syntax Val(String Expression) Examples Val("2001") The output would be 2001 as numeric. m_PresentAge = Val(txtEnteredAge.Text) Length = Val(txtLength.Text) f_Area = Val(txtLength.Text) * Val(txtWidth.Text) * Val(txtHeight.Text) lblTotalAmount.Caption = Val(txtTotal.Text) + Val(txtTax.Text) + Val(txtTip.Text) Val will be used in the preceding Units as well as the exercises. Using Multiple Forms 2.8 Before starting this activity you need to write a short action adventure story. Make sure the story has at least two story lines at the beginning and two for each subsequent story. The story you will see below is an example how to create an action adventure story using multiple forms. It is by no means creative so it does need your talents. HANDLING MULTIPLE FORMS AT RUN TIME: Project Options - what form to start on right away. Start up form - specify what form begins the program. The Action Adventure Story Action adventure stories include many different plots and story directions. When reading you start with one story line and then you are given a choice of two story lines. From this story line you are given two more choices and so on. Visual Basic does not restrict you to one form. As your programs become more complicated you will need to use multiple forms. You can include many forms in your program provided you use the proper syntax and coding. . multiple forms add power and flexibility to your application. you will always see the list of projects on the form. make sure that you always name the properties of the form with something meaningful. Creating multiple forms is very simple process. On the menu bar choose insert and then form. On the menu bar you can also click on Activity 2.8.1 The Action Adventure Story Your teacher will provide you with the a sample action adventure story. MAIN STORY FORM On the first form (the Main Story) you will need the following objects: 3 labels 2 text boxes 5 command boxes 1 oval shape 1 picture Create a new program. The form properties are as follows: CAPTION: Main Story TITLE : frmMainStory. MAXIMIZING YOUR FORM DURING RUN TIME To make the form appear on the entire screen you need to change the properties of the form. Go the Properties, find WindowState and change the state from 0-Normal to 2-Maximized. You form will appear as large as your computer screen. Using the specifications in the table below create the frmMainStory. Object Name Property Label for Title of the Action Adventure lblTitle Text Property Caption Property The Action Adventure Story of ... Variable Name Label - prompt the user to enter their Name lblEntireName ENTER YOUR FULL NAME: Label for Choice of Stories lblAB CLICK STORY A or B Shape around Choice of Stories shpAB Text Box for Entire Name txtEntireName Empty Text Box for Story txtPart1 Story type in your own story. Command for StoryA cmdStoryA STORY A Command for Story B cmdStoryB STORY B Command for Help and Hints cmdHelpHints HELP and HINTS Command for Clear cmdClear CLEAR Command for Exit cmdExit E&XIT Click on the New Form icon twice. You should have two more forms appearing on top of the MainStory form. On the menu bar click on View and then Projects. You will see all the forms listed. Click on form2. Press F4 to show the properties. CAPTION FOR FORM2: Story Line A NAME: frmStoryA. Click on form3. Press F4 to show the properties. CAPTION FOR FORM3: Story Line B NAME: frmStoryB. Create 4 more forms and change the properties as indicated. NOTE: You may change the form Captions and Names as to the story lines of your stories. You may want to keep the names of the forms to keep track of which forms are being used. Form 4 - CAPTION: Story Line A1 NAME: frmStoryA1 Form 5 - CAPTION: Story Line A2 NAME: frmStoryA2 Form 6 - CAPTION: Story Line B1 NAME: frmStoryB1 Form 7 - CAPTION: Story Line B2 NAME: frmStoryB2 You can add more forms as your story progresses. 1. Go to frmMainStory 2. Now you are going to program the first form so that subsequent story lines can be accessed by the user of your action adventure story. The code that you will be using to execute these functions include: Load, Show, Hide and Unload. Later on in the help section of the program you will be learning the properties of a form. Double Click on the command button STORY A. Type in the following code: 'Story Line A will display the next form and part of the action adventure story Load frmStoryA frmStoryA.Show Double click on the command button STORY B. Type in the following code: 'Story Line B will display the next form and part of the action adventure story Load frmStoryB frmStoryB.Show The meaning of the code.... Load - places the form into memory but it does now show the form. The properties and controls in code also get loaded into the computers memory. Although load uses up computer memory your program will respond faster to the user. Syntax Load <FormName> Show - shows the form on the screen. Before the form can be shown Visual Basic must check that the form is loaded into memory. Syntax <FormName>.Show Hide In this program you will also need to hide the forms when you are accessing help. You will be using <FormName>.Hide For our purposes we will be needing the users Entire Name and possibly other information throughout the program. Therefore we will not be using the command Unload. Unload - removes the form from the computers memory. Any information that is in current form being used is unloaded or lost. Syntax Unload <FormName> Colouring the background of a form. Double Click on the command box (cmdStoryA) "STORY A". Add in the following code. 'This will change the background color of Story Line A frmStoryA.BackColor = RGB(10, 20, 100) If the programmer would like to change any properties of an object from form to form the GENERAL SYNTAX is: FormName.ControlName.Property = Value you can use . periods or exclamation marks to separate the form names from the control. why? periods are generally used by older versions of VB . !exclamations are generally used by newer versions of VB. Other examples will be discussed later in this exercise. It is now time to Run the program. Choose either STORY . If you choose STORY A you should see the form Story Line A1 appear with a blue color. STORY LINE A FORM Re-create the Story Line A form as shown below. Object Name Property Label for Welcome Title lblStoryA Welcom.e... Label for the Title lblStoryAA to Story Line A Text Box for the Story txtStoryA Label for Choice of Stories lblAB CLICK STORY A1 or A2 Shape around Choice of Stories shpAB Make the shape oval Label for the Entire Name lblTheName *In properties change the size of the label box to Autosize. Picture of the Earth picEarth Command for StoryA1 cmdStoryA1 STORY A1 Command for StoryA2 cmdStoryA2 STORY A2 Command for Main Screen cmdMain BACK TO THE MAIN SCREEN Command for Help cmdHelpHints HELP and HINTS Command for Clear cmdClear CLEAR Command for Exit cmdExit E&XIT Referring to Objects in Other Forms Text Property Caption Property Type in Story A Variable Name In the Main Story form a text box called txtEntireName allows the user to enter in their full name. The idea is for the name to appear on the second form and throughout the program in other forms. In order to do this you require the general syntax described above. Double click on the Story Line A form. Type in the following code in the Sub Form Load: ' the name entered in the Main Story form will appear in the label box in Story Line A lblTheName.Caption = frmMainStory.txtEntireName.Text Explanation: lblTheName.Caption - is a label on the form of Story Line A where the name will appear. = - assigns the caption to the main form's textbox frmMainStory.txtEntireName.Text - refers to the Main Story's text box where the name was originally entered. STORY LINE B Created a form similar to Story Line A's form. See if you can design the form differently. Don't forget to add color and pictures. The same coding can be used but make sure to change the names of the story lines to B1 and B2. THE HELP and HINTS FORM The help file will assist the user in keeping track of the program. Create a help form. Below is a simple example. You can use any captions, labels or commands as needed. SIZE OF THE FORM Having the help form appear half the size of the screen during run time. Go to the Main Form and double click on the help command. Type in the following code: frmHelp.Height = Screen.Height / 2 Screen.Height/2 cuts the default height of the form in ½ The default for forms are as they appear when you run the program. This allows the user to stay in the Action Adventure story and see part of the main form while getting some help and hints about the story. A help command could be added to each form. With the code above you are now ready to complete the story with as many forms as your story requires. Have fun and good luck! EXERCISES Save all programs as per your teachers instructions or use handbook convention and the file names below. or Save the file (.frm and .vbp) as: The first three characters of the file name and then the first five characters of your last name. Programmers Last Name is: Golds File Name: ArtPrices. Save As: ArtGolds My Favorite Month Write a program that accepts what month of the year the user enjoys the most. Have the user enter in their full name and display their favorite month. Use the following Program Specifications: 1. Make a sketch of the interface before you begin the program. (5 points) 2. Complete the interface with the following properties table: (10 points) Object Name Property Text Property Caption Property Variable Name First Name Label lblFName First Name Middle Name Label lblMName Middle Name Last Name Label lblLName Last Name Title of the Program lblTitle Welcome to my first Visual Basic Program ..... First Name txtFName empty Please Enter your First Name f_FName Middle Name txtMName empty Middle Name f_MName Last Name txtLName empty Last Name f_LName Favorite Month txtFMonth empty Favorite Month f_Month Process Display Button cmdDisplay DISPLAY THE MONTH Clear Button cmdClear CLEAR Exit Button cmdExit E&XIT 1. In order to display the information you should use the message box. Make sure that when you display the users information that it has the proper spacing. 2. Change the form colour and title the form. 3. Change the text boxes to the same colour. 4. Declare the variables in general declarations. 5. Assign the text boxes to the proper variable names. (2 points each = 10 points) 6. The program runs correctly (5 points) TOTAL = 30 points File Name: Month the Pet Purchasing Program INDEPENDANT RESEARCH: Find out the cost of your favorite pet, the vetrinary bills per month, food costs and accessories. Make a list of at least 5 accessories and their costs. Write a program that allows the user to enter in the type of pet, name of the pet, cost of a pet, veterinary costs per month, food costs and accessory costs for the pet (minimum 5 accesories). The tax must be calculated on each item spent. Sketch the interface of your pet purchasing program. Program Specifications:Use val and constants, declare the appropriate variables and assign them to any text boxes. Use the format currency function to display the final cost a pet. Properties Table Object Name Property Text Property Caption Property Variable Name Title of the Program lblTitle THE PET ORDER FORM Type of Pet Label lblPetType Type of Pet Name of Pet Label lblPetName Pet Name Enter Information Label lblName Enter the information below. Type of Pet Text Box txtPetType empty Pet Type f_PetType Name of Pet Text Box txtPetName empty Pet Name f_PetName Price of Pet Text Box txtPrice empty Price of Pet f_Price Veterinary Cost Text Box txtVetCost empty Veterinary Cost f_VetCost Food Cost Text Box txtFoodCost empty Food Cost Per Month f_FoodCost Accessory 1 Text Box txtAccess1 empty Accesory Group 1 f_Access1 Accessory 2 Text Box txtAccess2 empty Acessory Group 2 f_Access2 Accessory 3 or more programmers decision Text Boxes Subtotal Text Box txtSubTotal empty SubTotal f_SubTotal Tax Text Box txtTax empty Tax f_Tax Total Text Box txtTotal empty Total f_Total Process Display Button cmdDisplay THE GRAND TOTAL Clear Button cmdClear CLEAR Exit Button cmdExit E&XIT Happy Birthday Write a program that asks for a person's Birthdat as month-day-year. Your program should output the number of days that they have been alive. The current year represents the year that you are writing this program in. Program Specifications: variable declaration, calculations and correct age output. File Name: Birthday I Love Mathematics Most of us enjoy a good challenge from calculations in math. Write a program that accepts 4 numbers from a user and performs calculations written below. Make a Sketch of the interface. Complete the program using the Properties Table below. Object Name Property Text Property Caption Property Variable Name First Number Label lblNum1 First Number Second Number Label lblNum2 Second Number Third Number Label lblNum3 Third Number Fourth Number Label lblNum4 Fourth Number Answer Label lblAnswer Answer First Number Text Box txtNum1 empty f_Num1 Second Number Text Box txtNum2 empty f_Num2 Third Number Text Box txtNum3 empty f_Num3 Fourth Number Text Box txtNum34 empty f_Num4 Answer Text Box txtAnswer empty f_Answer Display Button cmdProcess PROCESS THE EQUATION Clear Button cmdClear CLEAR Exit Button cmdExit E&XIT The code to sum all four numbers entered in the text boxes would be attached to the PROCESS THE EQUATION button. The code would appear as follows. Private Sub cmdProcess_Click() Dim f_Num1 as Integer, f_Num2 as Integer, f_Num3 as Integer, f_Num4 as Integer Dim f_Answer as Integer f_num1 = Val(txtNum1.Text) f_num2 = Val(txtNum2.Text) f_num3 = Val(txtNum3.Text) f_num4 = Val(txtNum4.Text) txtAnswer.Text = f_Num1 + f_Num2 +f_Num3 + f_Num4 End Sub Why is Val used in the assignment statements? Write the expression in your notebooks for the following equations. Then write the code for the following equations. You may need to have 9 more command buttons. Description Expressions 1 the sum of the first two numbers times the sum of the last two numbers (num1+num2) *(num3 +num4) 2 the product of all the numbers 3 the average of all the numbers 4 the sum of the squares of the numbers 5 four times the first number minus two times the last number 6 the first number minus the second number then times the third number 7 the sum of the halves of each number 8 the average of the cubes of each number 9 the sum of the square root of each number