Programming with… Visual Basic Table of Contents Variables................................................................................................................... 3 Variable Data Types ...................................................................................................................3 The Visual Basic opening screen............................................................................ 4 What are Labels? .................................................................................................... 5 What are Text Boxes? ............................................................................................. 6 What are Form Properties? ................................................................................... 7 Project 1 VB is Fun ............................................................................................ 8 How to start a new project ..........................................................................................................8 How to create a Label .................................................................................................................8 How to create a Command Button ..............................................................................................8 How to write code .......................................................................................................................9 Saving a Visual Basic Program ............................................................................ 10 Project The Personal Computer .................................................................... 11 How to create a Label ...............................................................................................................11 How to place graphic images on the form ................................................................................11 How to use Copy to add two more command buttons ..............................................................11 How to write code behind the buttons to move the pointer when you click any of the three buttons. ......................................................................................................................................12 How to run your program to see if it all works .........................................................................12 Structure Diagrams ............................................................................................... 13 Background ...............................................................................................................................13 Sequence ...................................................................................................................................13 Exercises ...................................................................................................................................13 Project Simple Addition ................................................................................. 14 How to create a Label ...............................................................................................................14 How to select the TextBox tool from the tool box. ..................................................................15 Converting Celsius to Fahrenheit .............................................................................................16 Making the conversion program respond to the Enter key rather than the command button ...16 Making the program more versatile ..........................................................................................17 Formatting numbers ..................................................................................................................18 Selections and Decisions ....................................................................................... 19 Loops....................................................................................................................... 20 For… Next loop ........................................................................................................................20 Positive step of one from a given number ................................................................................20 Displays 1 2 3 4 5 6 ..................................................................................................................20 Negative step of minus one from a given number ....................................................................20 Displays 6 5 4 3 2 1 ..................................................................................................................21 Positive step of plus two from a given number ........................................................................21 Displays 0 2 4 6 8 10 ................................................................................................................21 Project … Exploring loops .......................................................................................................21 Problems ...................................................................................................................................22 Strings – String Functions .................................................................................... 23 Simple programs to illustrate string functions ................................................... 24 Page 1 Project …Reversing a string .....................................................................................................24 Project …Joining Strings – Concatenation ...............................................................................26 Project … Splitting Strings .......................................................................................................27 Project …Word Counter ...........................................................................................................28 Visual Basic – Arrays ............................................................................................ 29 General Area .............................................................................................................................29 Printing out data from an array .................................................................................................30 Printing the data in reverse order ..............................................................................................30 Carrying out a simple sequential search ...................................................................................30 Sorting data in an array .............................................................................................................31 Diagram to show Sorting ..........................................................................................................32 Page 2 What is Visual Basic? Visual Basic is a programming language that allows you to create your own software with the look of Windows programmes that you are familiar with. It is the most common and easiest to learn of modern computer languages Visual Basic is also able to add additional features to Microsoft Office applications. When you write a Macro in Excel it is actually created for you using Visual Basic. Definition The word visual in Visual Basic means graphical, easily seen such as pictures and symbols that you can click on and drag. BASIC is short for Beginners All purpose Symbolic Instruction Code. BASIC was originally developed to make it possible for home users to program PCs. BASIC is considered to be a high level language because BASIC code uses a simple set of English words and symbols to give instructions to the computer, not the low level instructions that deal with the zeros and ones that the computer understands. Event Driven Language Visual Basic is also an Event Driven language. Event driven languages allow you to choose what you do rather than have to respond to a series of questions the computer dictates. Event driven languages such as Visual Basic are called Object Oriented Languages or OOLs. There are two parts to creating Visual Basic applications. 1. You firstly place the objects (buttons etc) on a form then 2. Secondly write the code that is hidden behind these buttons. The code makes the buttons respond in the way you want them to. Variables Variables are placeholders used to store values; they have names and data types. The data type of a variable determines how the bits representing those values are stored in the computer's memory. When you declare a variable, you can also supply a data type for it. All variables have a data type that determines what kind of data they can store. You can think of variables as containers, and you choose to put data in the most suitable container. You would not put a small object in a large box or try to stuff a large object into a small box. The following variables are available in visual basic. Variable Data Types Data type Boolean Byte Currency Date (Time) Double Integer Long Single String Prefix bln byt cur dtm dbl int lng sng str Example blnWillgo bytRasterData curMoneyspent dtmStartwork dblTolerance intQuantity lngDistance sngAverage strFName Variant vnt vntCheckSum What the data is used to hold True or False Whole numbers from 0–255 Money values, has a fixed decimal point Date Large decimal numbers more accurately Smaller whole numbers –32,768 to 32,767, Whole numbers that are very large Decimal number Any collection of keyboard characters but usually words Stores all the above data types but is slow and wasteful of memory Bytes 1 8 2 4 4 16 Here is how you would declare a variable Dim curMoneyspent As Currency The cur is the abbreviation for currency. This is a naming convention that helps you by letting you know the type of data that is attached to a particular variable. Page 3 The Visual Basic opening screen Click the Run button to run your application The Form window with our first project The Properties window The Toolbox window The Code window These are some of the most common windows you will see when using Visual Basic To see other windows select the window you want from the View Menu. The Form The blank form is where you will start to design you application. You will place objects on the form, alter their properties and write the code beneath them. The Tool Box The toolbox has controls that you may want to place on your form. These controls can be text boxes, command buttons, check boxes, option buttons etc. You will learn about these as you progress though the exercises. Properties Window This controls how the form and the objects you place on the form will look initially. The code you write can alter these properties when you run your program. Project Explorer This lists all the components such as forms that make up you project. You can click on any item on the project explorer to display it. Form Layout This gives you an initial view of how your form/s will look on the screen. Page 4 What are Labels? Programmers use labels to place titles around the form and to label text boxes so users know what to type into the text box. When you use the Label control, your code can change the label's text so that different messages can appear when needed. When you place labels on a form, you'll almost always set the Label control's Name property and type a new Caption value. In addition, you'll want to change the Font property and possibly the label's color and style. Below are the most common Label control properties that you'll set as you work with the Label control. Common label properties. Property Description Alignment Determines whether the label's caption appears left-justified, centered, or right-justified within the label's boundaries. AutoSize Enlarges the label's size properties, when True, if you assign a caption that is too large to fit in the current label's boundaries at runtime. BackColor Specifies the label's background color. Click the BackColor's palette down arrow to see a list of colors and click Categorized to see a list of common Windows control colors. BackStyle Determines whether the background shows through the label or if the label covers up its background text, graphics, and color. BorderStyle Determines whether a single-line border appears around the label. Caption Holds the text that appears on the label. Enabled Determines whether the label is active. Often, you'll change the Enabled property at runtime with code when a label is no longer needed. Font Produces a Font dialog box in which you can set the caption's font name, style, and size. ForeColor Holds the color of the label's text. Height Holds the height of the label's outline in twips. Left Holds the number of twips from the label's left edge to the Form window's left edge. MousePointer Determines the shape of the mouse cursor when the user moves the mouse over the label. TabIndex Specifies the order of the label in the focus order. Although the label cannot receive the direct focus, the label can be part of the focus order. ToolTipText Holds the text that appears as a tooltip at runtime. Top Holds the number of twips from the label's top edge to the Form window's top edge. Visible Determines whether the label appears or is hidden from the user. Width Holds the width of the label in twips. WordWrap Determines whether the label expands to fit whatever text appears in the caption. Page 5 What are Text Boxes? Text boxes accept user input. Although several other controls accept user input, text boxes are perhaps the easiest to set up and respond to. In addition, a text box is simple to use, and people see text boxes on Windows forms all the time. The table below lists the common properties associated with text boxes. By familiarising yourself with the properties now, you will be able to more quickly produce applications as you learn more about Visual Basic. Common text box properties Property Description Alignment Determines whether the text box's text appears left-justified, centered, or right-justified within the text box's boundaries. BackColor Specifies the text box's background colour. Click the BackColor property's palette down arrow to see a list of colours and click Categorized to see a list of common Windows control colours. BorderStyle Determines whether a single-line border appears around the text box. Enabled Determines whether the text box is active. Often, you'll change the Enabled property at runtime with code when a text box is no longer needed. Font Produces a Font dialog box in which you can set the Text property's font name, style, and size. ForeColor Holds the color of the text box's text. Height Holds the height of the text box's outline in twips. Left Holds the number of twips from the text box's left edge to the Form window's left edge. Locked Determines whether the user can edit the text inside the text box that appears. MaxLength Specifies the number of characters the user can type into the text box. MousePointer Determines the shape of the mouse cursor when the user moves the mouse over the text box. MultiLine Lets the text box hold multiple lines of text or sets the text box to hold only a single line of text. Add scrollbars if you wish to put text in a multiline text box so your users can scroll through the text. PasswordChar Determines the character that appears in the text box when the user enters a password (keeps prying eyes from knowing what the user enters into a text box). ScrollBars Determines whether scrollbars appear on the edges of a multiline text box. TabIndex Specifies the order of the text box in the focus order. TabStop Determines whether the text box can receive the focus. Text Holds the value of the text inside the text box. The Text property changes at runtime as the user types text into the text box. If you set an initial Text property value, that value becomes the default value that appears in the text box when the user first sees the text box. ToolTipText Holds the text that appears as a tooltip at runtime. Top Holds the number of twips from the text box's top edge to the Form window's top edge. Visible Determines whether the text box appears or is hidden from the user. Width Holds the width of the text box in twips. Page 6 What are Form Properties? Forms have properties that you can and should set when you create an application. Being the background of your application, the form's properties help set the stage for the rest of the project. The form supports more property values than the other controls described here, but the list below lists only the most common properties that you'll need. New Term: Pixel stands for picture element and represents the smallest addressable graphic dot on your monitor. Common form properties. Property Description BackColor Specifies the form's background color. Click the BackColor's palette down arrow to see a list of colors and click Categorized to see a list of common Windows control colors. BorderStyle Determines how the Form window appears. The BorderStyle property specifies whether the user can resize the form and also determines the kind of form you wish to display. Caption Displays text on the form's title bar at runtime. ControlBox Determines whether the form appears with the Control menu icon. The Control menu appears when your application's user clicks the Control menu icon. Enabled Determines whether the form is active. Often, you'll change the Enabled property at runtime with code when a form is no longer needed. Generally, only multiform applications, such as MDI applications, need to modify a form's Enabled property. Font Produces a Font dialog box in which you can set the text's font name, style, and size. ForeColor Holds the color of the form's text. Height Holds the height of the form's outline in twips. Icon Describes the icon graphic image displayed on the taskbar when the user minimizes the form. Left Holds the number of twips from the form's left edge to the screen's left edge. MaxButton Specifies whether a maximize window button appears on the form. MinButton Specifies whether a minimize window button appears on the form. MousePointer Determines the shape of the mouse cursor when the user moves the mouse over the form. Moveable Specifies whether the user can move the form at runtime. Picture Determines a graphic image that appears on the form's background at runtime. ScaleMode Determines whether the form's measurements appear in twips, pixels (the smallest graphic dot image possible), inches, centimeters, or other measurements. ShowInTask bar Determines whether the form appears on the Windows taskbar. StartUpPosition Determines the state (centered or default) of the form at application startup. Top Holds the number of twips from the form's top edge to the Form window's top edge. Visible Determines whether the form appears or is hidden from the user. Width Holds the width of the form in twips. WindowState Determines the initial state (minimized, maximized, or normal) in which the window appears at runtime. Page 7 Project 1 VB is Fun To create your first application, follow these steps: How to start a new project 1. Create a new project by going File/New Project and double-clicking the Standard EXE icon 2. Change the form's Name property to frmFirst and change its Caption property to My First Application. The form's Caption property text appears in the title bar when you run the application. How to create a Label 3. Click the Label control and drag a Label on the form 4. Change the label's Name property to lblFirst. Change the label's Caption property to VB is fun. 5. Click the label's Font property value to display the Font dialog box for the label. Set the font to Arial, the size to 24 and set Bold property. 6. Change the fore colour to Orange, or any colour you choose, and change the label's Alignment property to 2-Center. 7. Change the label's BorderStyle property to 1-FixedSingle. This property adds a single-line 3D border around the label. Change the shape of the label to fit the text. How to create a Command Button 8. Add a Command button, but to do so, double-click the command button tool on the Toolbox window. The command button appears in the middle of the form and you can leave it where it is. 9. Change the command button's Name property to cmdExit. 10. Change the command button's Caption property to Exit. Watch the command button as you type the Caption property text. The command button's caption becomes the text you type. 11. The command button will be used to exit the program. When the user clicks the command button, your application should end. When a user clicks a command button a Click event occurs. Therefore, to respond to this event, you must write an event procedure for the command button. Double-click the form's command button and Visual Basic instantly opens the Code window and displays the following wrapper lines for the command button's Click event procedure: Page 8 How to write code The name of the procedure, cmdExit_Click(), describes both the control and the event being processed by the code you only need to fill in the body. Type End for the one-word body of the event procedure and close the Code window. End tells Visual Basic to end the running application. Therefore, the application will end when the user clicks the command button. Press Tab, to insert a space then type End Press the Run button to run the program and watch your creation appear. We are going to make a button that will change the words VB is Fun, in the Label to I love computing. 1. Create another Command Button and set the Name to Cmdchange, and the Caption to Computing. 2. Double click on the button to open the Code window. Type in the following: Lblfirst.Caption = "I love Computing" Remember earlier we set the properties for the label caption as VB is fun. This code says for the caption field of Lblfirst put the words I love computing. The words will be too big for the Label window, so we need to make the font size smaller as well. So lets set the height of the label to 1400 by adding in the following: Lblfirst.Height = 1300 We need to make the Label window wider to fit the words so also add: Lblfirst.Width = 3000 Run the program by clicking on the Run button and see if it works. Exercise Make another Command button to return the Label to the original VB is Fun settings. Page 9 Saving a Visual Basic Program 1 Click Save Project on the tool bar. Click Create New Folder 3 2 4 Type a name for the new folder eg Add and Average Double click on the new folder to open it Check that you have a new named empty folder to save your project in. 5 Click the Save button Type in a new name for the project the 6 Click the Save button 7 You may need to save several files depending on the number of forms used and the objects such as pictures placed on the form. To save your work again just click the Save button. Page 10 Project The Personal Computer Getting Started 1) Start Visual Basic 2) Double click Standard EXE This is how your completed form will look 3) Click on the form and in the Properties window in the Name field change the name of the form to frmComputer, then in the Caption field change the name of the Caption to PC Parts. How to create a Label 4) Drag a label onto the form to make the title Personal Computer. In the properties window change the Name to Lbl1 5) In the Caption field type in The Personal Computer 6) Click in the Font field within the Properties window to display the Font dialog box. Choose Arial Bold 14pt. 7) Click on the Alignment field and choose Center How to place graphic images on the form 8) Select the Image tool from the toolbox and position it in the centre of the form window in the same way you positioned the label, by dragging it from top left corner to the bottom right corner to form a rectangular box. 9) Make sure the image frame is selected (handles showing) 10) In the Properties window click the Picture field, an ellipsis (–) will appear, click on the ellipsis to bring up a File Load dialog box. Load the image of a computer, called _____________ 11) Repeat the above steps to add the pointer image called _____________ How to add a command button 1) Select the Command tool from the tool box and position it at the bottom of the form. Name cmdMonitor Caption Monitor Font 12pt ToolTipText Point at Monitor 2) In the properties window change the following fields to: How to use Copy to add two more command buttons 1) Select the command button you have already made and copy it. (Menu bar Edit Copy then Menu bar Edit Paste, or alternatively CTRL C then CTRL V 2) To the dialog box that asks, “Do you want a Control Array”, click No Page 11 3) Repeat this procedure to make a third button 4) Select the second button and change its properties to Name cmdKeyboard Caption Keyboard ToolTipText Point at Keyboard 5) Select the third button and change its properties to Name cmdMouse Caption Mouse ToolTipText Point at Mouse 6) You are going to record the position of the pointer when it points at the Monitor, Keyboard and Mouse. To do this move the pointer to the position you want then record the two values, Left and Top from the Properties window. Use the table below to record the positions. Pointer pointing at Monitor Keyboard Mouse Left Top How to write code behind the buttons to move the pointer when you click any of the three buttons. 1) Double click the Monitor command button on the form, then enter the position of the pointer as shown below into the Private Sub cmdMonitor_Click() Private Sub cmdMonitor_Click() imgPointer.Left = 2160 imgPointer.Top = 2040 End Sub Hint: To display the form double click Form1 in the Explorer window . 2) Double click the Keyboard command button on the form, then enter the position of the pointer as shown below into the Private Sub cmdKeyboard_Click() Private Sub cmdKeyboard_Click() imgPointer.Left = imgPointer.Top = End Sub 3) Double click the Mouse command button on the form, then enter the position of the pointer as shown below into the Private Sub cmdMouse_Click() Private Sub cmdMouse_Click() imgPointer.Left = imgPointer.Top = End Sub How to run your program to see if it all works 1) Click the Start button on the main (top) toolbar Page 12 2) Click each of your command buttons in turn (Monitor, Keyboard, Mouse) and the graphic pointer image should move to point at each part. 3) Save your work by selecting Save Project As from the file menu. Name the file PC Parts. Structure Diagrams Background In our programs we write lines of code to tell the computer what to do one step at a time. The lines must be written in the correct order and the computer will carry out each one after the other. The code is said to be sequential, i.e. the program is a sequence of steps. When programs become more complicated we need to have a way of planning and designing our code so that the correct steps will be coded in the correct sequence. Structure diagrams are a tool to aid program design. Structure diagrams are made up of boxes which describe a step in the program. These steps might be large or small, large ones can be broken down gradually into smaller ones. We may need to have several levels to a structure diagram. An operation A is shown as a sequence of steps in the diagrams below. What Fig (a) tells us is that A is really done by first doing B, then C and finally D. The chart is read from the top down and from left to right. Fig (b) is diagram with another level in which step B is done by doing steps C and D. Fig (a) B Fig (b) A C D A B E C F D Sequence This is where one step is done after the other. Figs a, b and C are all simple sequences. The diagram Fig (c) below shows the sequence of steps you carry out when you log on to the network. Logging on Fig (c) Enter User ID Type in ID Enter Password Press Tab Exercises Draw Structure Diagrams for the following situations: 1. Saving a newly created file on a floppy disc 2. Cleaning your teeth. Page 13 Type Password Press Enter 3. Starting the car. 4. Changing a car tyre. 5. Recording a TV program on a Video Tape Project Simple Addition Below is a structure diagram showing the steps you will take to add two numbers using VB. Add Two numbers Get the first number Get the second number Add the two numbers Display the result sngNum1 val(txtNum1.text) sngNum2 val(txtNum2.text) sngSum sngNum1 + sngNum2 lblSum.caption sngSum When you write a computer program you have to get data into the computer (Input), process it and then display the results (output). A text box is just one object that can be placed on a form so that you can key in data. Getting Started 1. Start Visual Basic 2. Double click Standard EXE 3. Enlarge the form by dragging its bottom right corner handle so that it size is about width 3500 height 26400 4. In the Properties window double click the Name field and change the name of the form to frmAdder, then double click the Caption field and change the name of the Caption to Adder. How to create a Label 1. Select the label tool from the tool box and position it at the top of the form, by dragging from the top left to the bottom right corner to form a rectangular box. 5. With the label selected double click in the Caption field of the Properties window and type in the new caption ‘Adder’ 6. Click on the Font field within the Properties window to display an ellipses (–) 7. Click on the ellipsis to display the Font dialog box 8. Choose 18 pt from the Font dialog box 9. Click on the Alignment field in the Properties window and from the menu choose Center 10. Create another label to hold the answer 11. Set the following properties Name Border Style Caption Font lblSum Fixed single Remove any text to make it blank 12 pt Page 14 How to select the TextBox tool from the tool box. 1. Create a text box and set the font property to 12pt 2. Copy this text box to make two text boxes. Both will now have the same font size. 3. Position the text boxes as shown in the example above, remove the text from the Text Property and name the boxes: Name txtNum1 txtNum2 4. Select the Command tool from the tool box. 5. Create a command button and set the font property to 12pt 6. Copy this button twice and name the buttons: Name cmdAdd cmdClear Caption &Add &Clear 7. Arrange the buttons as shown in the form above. Private Sub cmdAdd_Click() Dim sngNumone As Single, sngNumtwo As Single, sngSum As Single ‘declares three variables as single precision (sng) sngNumone = Val(txtNum1.text) ‘converts text to a number and assigns it to sngNumone sngNumtwo = Val(txtNum2.text) ‘converts text to a number and assigns it to sngNumtwo sngSum = sngNum1 + sngNum2 ‘adds sngNum1 to sngNum2 and assigns this to sgnSum lblSum.caption = sngSum End Sub Private Sub lblClear_Click() TxtNum1.text = "" TxtNum2.text = "" LblSum.caption = "" End Sub ‘assigns an empty string to txtNum1 ‘assigns an empty string to txtNum2 ‘assigns an empty string to txtNum3 The Val function Converts a string (text) to a number. If the text can not be recognised as a number then the value will be set to zero. If val is not used and no number is entered an error will occur. Dim (Dimension) Declares variables, in this case as single precision numbers. This means they can be decimal numbers taking 4 bytes to store them. This is OK as long as you don’t need to use extremely large numbers. Remarks Any text that starts with a ‘ single quotation mark is ignored. This is part of the documentation that you add to your program to remind you what a piece of code does. Naming Conventions Variables are prefixed with the abbreviation for their data type eg. sng for a single precision number. Giving your command button a key shortcut. In the applications you have used this year you will notice that all command buttons have an underlined letter. Eg Calculate. In this example the C of calculate is underlined. Pressing the key combination Alt C will have the same effect as clicking the Calculate button. To add this feature simply prefix the word calculate with the "&" ampersand character eg. &Calculate Tpo Page 15 Converting Celsius to Fahrenheit The structure diagram below outlines the steps you will carry out to convert a temperature entered in degrees Celsius to degrees Fahrenheit. Convert Celsius to Fahrenheit Get degrees Celsius Calculate degrees Fahrenheit Display Fahrenheit sngCelsius Val(txtCelsius.text sngFahrenheit sngCelsius * 9/5 + 32 lblFahrenheit.caption sngFahrenheit This exercise requires three static labels, one label to display the temperature in Fahrenheit, one text box for input and one command button. 1. Create the form as shown below 2. Add the code to the Convert command button Form properties Name FrmFahrenheit Caption Find Degrees Fahrenheit Text box properties Name txtCelsius Caption Nothing Label properties Name lblFahrenheit Caption Nothing Border Fixed single Command button properties Name cmdConvert Caption &Convert The Code Double Click on the Convert button and then enter the code below: Private Sub cmdConvert_Click() Dim sngCelsius As Single Dim sngFahrenheit As Single sngCelsius = Val(txtCelsius.Text) sngFahrenheit = sngCelsius * 9 / 5 + 32 lblFahrenheit.Caption = sngFahrenheit End Sub 'subroutine that responds to clicking the button cmdConvert 'Declares a decimal number variable called sngCelsius 'Declares a decimal number variable called sngFahrenheit 'Converts text into a number 'Calculates the value for sngFahrenheit 'Displays the value of sngFahrenheit in the label caption. Making the conversion program respond to the Enter key rather than the command button In this example we show you how to Respond to the Enter key being pressed rather than having to click the Convert button. The KeyPress Event. This occurs each time you press any key on the keyboard, however we only want to respond when the Enter Key is pressed. This is easily done as the Enter key returns the ASCII code 13 when pressed, therefore our program must do the calculation only IF KeyAscii = 13 (Enter Key) Page 16 Press Enter When you press the Enter key in a text box it beeps. To prevent this happening KeyAscii is set to zero. 1. Modify the code to that shown below 2. Delete the cmdConvert button Private Sub txtCelsius_KeyPress(KeyAscii As Integer) If KeyAscii = 13 Then KeyAscii = 0 Dim sngCelsius As Single Dim sngFahrenheit As Single sngCelsius = Val(txtCelsius.Text) sngFahrenheit = sngCelsius * 9 / 5 + 32 lblFahrenheit.Caption = sngFahrenheit End If End Sub 'Responds to keypresses returning the keys pressed 'Routine below is only done if the Enter (key 13) is pressed 'Stops the beep when Enter is pressed 'Declares sngCelsius as Single 'Declares sngFahrenheit as Single 'Converts text to a number 'Calculates a value for sngFahrenheit 'Displays sngFahrenheit in the label lblFahrenheit 'End of the If decision 'End of the subroutine Making the program more versatile Now we will make is possible to enter either Celsius or Fahrenheit with keypresses. This will require two routines, one attached to each text box. Convert Celsius to Fahrenheit Get degrees Celsius Calculate degrees Fahrenheit Display Fahrenheit sngCelsius Val(txtCelsius.text sngFahrenheit sngCelsius * 9/5 + 32 txtFahrenheit.text sngFahrenheit Convert Fahrenheit to Celsius Get degrees Fahrenheit Calculate degrees Celsius Display Celsius sngCelsius Val(txtFahrenheit.text sngCelsius (sngFahrenheit - 32) * 5/9 txtCelsius.text sngCelsius The two routines shown above are attached to the two text boxes It is now possible to type into either text box and when you press enter the conversion will occur and appear in the other text box. You will need to: 1. Delete the label used for displaying the temperature in Fahrenheit 2. Add a text box called txtFahrenheit 3. Enter the new code below Private Sub txtFahrenheit_KeyPress(KeyAscii As Integer) 'Responds to keypresses returning the keys pressed If KeyAscii = 13 Then 'Routine is only done if the Enter (key 13) is pressed KeyAscii = 0 'Stops the beep when Enter is pressed Dim sngCelsius As Single 'Declares sngCelsius as Single Dim sngFahrenheit As Single 'Declares sngFahrenheit as Single sngFahrenheit = Val(txtFahrenheit.Text) 'Converts text to a number sngCelsius = (sngFahrenheit - 32) * 5 / 9 'Calculates sngCelsius txtCelsius.Text = sngCelsius 'Displays sngCelsius in txtCelsius text box Page 17 End If End Sub Private Sub txtCelsius_KeyPress(KeyAscii As Integer) If KeyAscii = 13 Then KeyAscii = 0 Dim sngCelsius As Single 'Ends block If 'Ends subroutine 'Responds to keypresses returning keys pressed 'Routine is only done if the Enter (key 13) is pressed 'Stops the beep when Enter is pressed 'Declares sngCelsius as Single Dim sngFahrenheit As Single sngCelsius = Val(txtCelsius.Text) sngFahrenheit = sngCelsius * 9 / 5 + 32 txtFahrenheit.Text = sngFahrenheit End If End Sub 'Declares sngFahrenheit as Single 'Converts text to a number 'Calculates sngFahrenheit 'Displays sngFahrenheit in txtFahrenheit text box 'Ends block If 'Ends subroutine Formatting numbers The most often required format is currency which adds leading "$" dollar sign and formats to two decimal places. Examples: lbltotal.caption = Format(45,"currency") $45.00 or curSum = 45 lblTotal.caption = Format(curSum,"currency") Exercises Write three programs to convert $NZ to $Aus: For each program draw a structure diagram. 1. Write a program that uses a text box for input, a label for output and a command button to Calculation is calculate the result which is to be attached to the click $Au. The conversion rate is $1 event event. NZ = $0.70 AU 2. Write another program similar to the one above except that it uses a keypress rather than a command button. $NZ input here $AU is displayed here Calculation is attached to the keypress event 3. Modify program three so that it converts both ways. ie. $NZ to $Aus and $Aus to $NZ in a similar way to the temperature converter. It must be possible to type into either text box and have the program display the conversion in the other text box. Press Enter Here Or Press Enter Here Extension exercise Create another text box in order that the conversion rate can be entered rather than having it fixed at 7/10 (.7) Page 18 Write a program to calculate the cost of petrol for a trip Start by: 1. drawing up a structure diagram 2. naming each object on the form. Use the table below: Complete the table of named objects that you will need for the form to work. Some of this has been done for you. Object Name Caption/Text Variable Name Variable datatype Form Name frm Caption Text boxes Cost per litre txt cur currency Distance Travelled (km) txt sng single Petrol used (km) txt sng single Labels Total petrol cost lbl cur currency Cost per kilometre lbl cur currency Command buttons Calculate cmd & Reset cmd & 3. Create the objects as shown on the form below, name them and enter their properties. 4. Write the code to that goes behind the two buttons. The Reset button is to clear all the text boxes and labels that hold the results. eg. txtCostPerLitre.text = "" lblTotalCost.Caption = "" Selections and Decisions So far all the programs we have written have been sequential steps which are done is in order 12, 3… etc. IF statements make this possible. A simple decision may be, "Can I Vote?". This will be true if I am 18 or over. Below is a decision tree and a structure diagram to show how this decision can be represented graphically. The decision tree only shows the decision logic whilst the structure diagram shows the complete program. Structure Diagram Can I Vote? Decision Tree Is intAge >= 18 Yes No Can Vote Can't Vote Get intAge Is intAge >=18 Yes Display "Can Vote" Page 19 No Display "Can't Vote" 1. Create the form opposite with the following named objects Type Form Text box Label Label Name FrmAge txtAge LblDecision Caption/Text Can I vote? None Enter Age None Type in age and press Enter 2. Enter the code below under the txtAge text box. Private Sub txtAge_KeyPress(KeyAscii As Integer) If KeyAscii = 13 Then Dim intAge As Integer intAge = Val(txtAge.Text) If intAge >= 18 Then lblDecision.Caption = "Yes you can vote" Else lblDecision.Caption = "No you can't vote" End If End If End Sub 'Only do if the key pressed is 13 "Enter" 'Declare intAge as an integer (whole number) 'Convert txtAge to a number 'Check whether intAge is 18 or over 'Response when intAge is 18 or over 'Response when intAge is under 18 'End of second IF 'End of first IF 'End of subroutine Loops Loops make it possible to repeat a section of code a number of times. This is used for doing calculations, searching and sorting lists etc. Start of Loop Code End of loop For… Next loop This is a loop with an in-built counter. The syntax is: For counter = start To end Step increment Code here Next counter The counter automatically increases or decreases by the value of the increment each time around the loop. The step increment can be omitted, in which case the step will be one. Here some examples of a For…Next loop. Positive step of one from a given number For intCounter = 1 To 6 PicDisplay.Print intCounter; Next intCounter Displays 1 2 3 4 5 6 Negative step of minus one from a given number For intCounter = 6 To 1 Step –1 PicDisplay.Print intCounter; Next intCounter Page 20 Displays 6 5 4 3 2 1 Positive step of plus two from a given number For intCounter = 0 To 10 Step 2 PicDisplay.Print intCounter; Next intCounter Displays 0 2 4 6 8 10 Project … Exploring loops The structure diagram below shows a simple program to demonstrate how a For…Next loop works Loop and display C ounter values. Symbol for a loop Dimension v ariables intC ounter as Integer intStart as I nt eger intFinish as Integer intStep as Integer For intCounter int Start To intFinish Step intStep Get Values intStart Val(txtStart.Text) intFinish Val(txtFinish.Text ) intC ounter Val(txtCounter.Text ) picDisplay .Print intC ounter Text box Named txtStep Text box Named txtStart Picture box named picDisplay Text box Named txtFinish 1. 2. Start button named cmdStart Create the form shown above and name all the objects as shown. Enter the code attached to the Start button as shown below. Option Explicit Private Sub cmdStart_Click() Dim intStart As Integer Dim intFinish As Integer Dim intCounter As Integer 'dimension the starting number 'dimension the finishing number 'dimension the counter Page 21 Dim intStep As Integer picOutput.Cls intStart = Val(txtStart.Text) intFinish = Val(txtFinish.Text) intStep = Val(txtStep.Text) For intCounter = intStart To intFinish Step intStep picDisplay.Print intCounter; Next intCounter End Sub 3. 'dimension the step value 'clear the picture box 'convert text to number 'convert text to number 'convert text to number 'start of loop 'code repeated in the loop 'finish of loop Run the program and enter the values in the table below. Write in the Output column the output you get when each set of values is entered. Start Finish Step 1 6 6 1 -1 0 10 2 12 0 -2 Output Problems a) b) c) d) e) f) g) Enter two integers and add all integers from the first integer to the second. If 1 and 6 were entered the calculation would be 1 + 2 + 3 + 4 + 5 + 6 and the answer would be 21. Enter two integers and add all even integers from the first integer to the second. If 2 and 10 were entered the calculation would be 2 + 4 + 6 + 8 + 10 and the answer would be 30. Find the sum of 1 + ½ + 1/3 + ¼ … 1/100 Produce a table to display the conversion of NZ dollars $ to English pounds £ for 1 to 10 dollars. Have an input box to type in the exchange rate. Display a times table from 1 to 10. Have an input box to enter the table you want printed. Convert Celsius to Fahrenheit as a table ranging from 0 to 40 degrees Celsius in steps of 5. Fahrenheit = Celsius x 9/5 + 32 Create a depreciation calculator to calculate the value of any item after a given period of years. Eg You buy a car for $16,000 and it depreciates at 9.5% each year, then how much will it be worth after 12 years. An example of the layout is shown below. The code for the Calculate button has been done for you. You are to Create the form and objects shown below Draw a structure diagram for the Clear button Write the code for each event (Calculate, Clear, Exit) Page 22 Below is a structure diagram for the Calculate button only. Calculat e Depreciat ion (cmdCalculat e) Dimension Variables Dim sngInit ialValue As Single Dim sngDepreciat ion As Single Dim int Years As Int eger int YearCount As Int eger Loop For int YearCount 1 T o int Years Get Values sngInit ialValue = Val(t xt Init ialValue.T ext ) sngDepreciat ion = Val(t xt Depreciat ion.T ext ) int Years = Val(t xt Years.T ext ) Display New Value lblFinalValue.Capt ion = Format (sngInit ialValue, "currency") sngInit ialValue sngInit ialValue sngInit ialValue * sngDepreciat ion / 100 Strings – String Functions The string data type is any text, which can include any keyboard character. String variables are declared like this: Dim strWord as String where strWord is the variable name. Len Len returns the length of the string in number of characters. See the example below. strName = “Hagley Community College” intLength = Len(strName) intLength’s value would be 24 as this is the number of characters including spaces in the name “Hagley Community College” Right Right returns a specified number of characters from the right side of a string strName = “Hagley Community College” strRightSide = Right(strName, 7) The variable strRightSide would be “College” as College is the 7 rightmost characters. Left Left returns a specified number of characters from the left side of a string strName = “Hagley Community College” strLeftSide = Left(strName, 6) The variable strLeftSide would be “Hagley” as Hagley is the 6 leftmost characters. Mid Mid returns a specified number of characters from a string starting at a given start position and the specified length. strName =”Hagley Community College” strMiddle = Mid(strName, 7, 9) The variable strMiddle would be “Community” as Community is 7 characters from the start of the string and 9 characters in length. Note: With the Mid function you can remove the last parameter. strMiddle = Mid(strName,7) The variable strMiddle would now be “Community College” as no length value has been entered. Page 23 InStr Instr searches for a smaller string within a larger string. strName = ”Hagley Community College” strShort = ”Community” intPosition = InStr(1,strName, strShort,1) The value of intPosition would be 8 as this is the start position of the shorter string “College “ in the larger string “Hagley Community College” If the strShort is not found within strName then the value returned will be zero. Note The first parameter 1, is the position in the string to start searching from. The fourth parameter,1 results in a noncase-sensitive search. UCase UCase converts all lower case letters in the string to upper case. strName = “Hagley Community College” strName = Ucase(strName) The string variable strName would now be equal to “HAGLEY COMMUNITY COLLEGE” LCase LCase converts all upper case letters in a string to lower case. strName = “HAGLEY COMMUNITY COLLEGE” strName =LCase(strName) The string variable strName would now be equal to “hagley community college” Simple programs to illustrate string functions Project …Reversing a string This program uses the following string functions: Len Mid A For… Next loop is used with Mid function to reverse the letters in a string. In this example a single letter is extracted at a time starting with the last letter in the word. Letters are joined together to make a word using the & (joining operator). The code is attached to a Keypress event. The Structure Diagram Reverse a Word Dimension Variables Dim strWord as String Dim strReversedWord as string Dim intCounter as integer Dim intLength as integer Get a word strReversedWord "" intLength Len(strWord) For intCounter intLength To 1 Step -1 strReversedWord strReversedWord & Mid(strWord,intCounter,1) strWord txtWord.text Page 24 lblDisplay.caption strReversedWord The Code Option Explicit Private Sub txtWord_KeyPress(KeyAscii As Integer) If KeyAscii = 13 Then 'only continue if the enter key (13) is pressed KeyAscii = 0 'stop the beep when enter is pressed Dim strWord As String 'variable for word entered Dim strReversedWord As String 'variable for the reversed word Dim intCounter As Integer 'variable for loop counter Dim intLength As Integer 'variable for length of word strWord = txtWord.Text 'get text from text box strReversedWord = "" 'set to null string intLength = Len(strWord) 'find the lenght of the word For intCounter = intLength To 1 Step -1 'start of loop strReversedWord = strReversedWord & Mid(strWord, intCounter, 1) Next intCounter 'end of loop lblDisplay.Caption = strReversedWord 'display the reversed word in the label caption. txtWord.SelStart = 0 'start of highlighted area txtWord.SelLength = intLength 'length of highlighted area End If End Sub Page 25 Project …Joining Strings – Concatenation This program uses the following functions Left Joining of strings is done with the & joining operator. This program illustrates how it is possible to split and recombine strings. The Structure Diagram Enter and combine title initial and Surname Dimension Variables Dim strTitle as String Dim strSurname as String Dim strFirstName as String Dim strCombined as String Get title and names strTitle = txtTitle.text strSurname = txtSurname.text Combine title and names strCombined = strTitle & " " & Left(strFirstName,1) & " " & strSurname Code Option Explicit Private Sub cmdCombine_Click() Dim strTitle, strSurname, strFirstName, strCombined As String strTitle = txtTitle.Text strFirstName = txtFirstName.Text strSurname = txtSurname.Text strCombined = strTitle & " " & Left(strFirstName, 1) & " " & strSurname lblCombined.Caption = strCombined End Sub Page 26 lblCombined.Caption = strCombined Project … Splitting Strings This program uses the following functions. Instr Mid It is more complex than the program to join strings. InStr is used to return the position of the spaces in the string. Mid is used to extract the section of name up to the space. For the last section of the string Mid is used without the last parameter thus only the start point is given for the string. This program will only work if there is one space between each word. A control array is used to display the split name. Structure Diagram Spli t Name into Components Declare Variables Dim Dim Dim Dim strFullName as String strN ame as String int Space as Integer int Next Space as Integer Get Name strFullName txtFullName.text int Next Space InStr(intSpace,strFullname," ",1) int Space 1 strN ame Mid(strFullName, int Space) lblName(2).Caption strN ame For intC ounter 0 to 1 strN ame Mid(FullName, intSpace,int Next Space - intSpace) lblName(intC ounter). Capt ion st rName Code Option Explicit Private Sub txtFullName_KeyPress(KeyAscii As Integer) If KeyAscii = 13 Then KeyAscii = 0 Dim strFullName, strName As String Dim intSpace, intNextSpace, intCounter As Integer strFullName = txtFullName.Text intSpace = 1 For intCounter = 0 To 1 intNextSpace = InStr(intSpace, strFullName, " ", 1) strName = Mid(strFullName, intSpace, intNextSpace - intSpace) lblName(intCounter).Caption = strName intSpace = intNextSpace + 1 Next intCounter strName = Mid(strFullName, intSpace) lblName(2).Caption = strName txtFullName.SelStart = 0 txtFullName.SelLength = Len(strFullName) End If End Sub Page 27 int Space intSpace +1 Project …Word Counter This program uses the following function: InStr This program uses a Do…Loop to find all the occurrences of a word in a sentence or paragraph. The loop repeats until no more occurrences of the word are found, and this is when intStart = 0. Structure Diagram Co un t wo rds i n a sen tence Declare Variables Init ialise Variables int Start InSt r(int Start , strSentence, strWord, 1) Display Number Get Sent ence and Word Do Until inSt art 0 Dim intStart as I nt eger Dim intWordCount As I nt eger Dim strSentence As String strSentence txtSentence. Text lblWordcount .Caption int WordCount End If intWordCount 0 intStart 1 int WordCount intWordCount + 1 strWord txtWord.Text int Start InStr(intSt art + 1, strSent ence, strWord, 1) Code Option Explicit Private Sub txtWord_KeyPress(KeyAscii As Integer) If KeyAscii = 13 Then KeyAscii = 0 Dim intStart, intWordCount As Integer Dim strSentence As String Dim strWord As String strSentence = txtSentence.Text strWord = txtWord.Text intStart = 1 intWordCount = 0 intStart = InStr(intStart, strSentence, strWord, 1) Do Until intStart = 0 intWordCount = intWordCount + 1 intStart = InStr(intStart + 1, strSentence, strWord, 1) Loop lblWordcount.Caption = intWordCount End If End Sub Page 28 ‘stop beep ‘dimension all integer variables ‘dimension string variables ‘get sentence form text box ‘get word from text box ‘set start search position to 1 ‘set words counted to zero ‘find the position of the first occurrence ‘loop until no more words are found ‘check for subsequent words ‘finish of loop ‘display the number of words found Visual Basic – Arrays An Array is a special type of variable that holds more than a single item of data. Before you can use an array you have to tell the computer how large the array (list) is to be. This is done in a Dim statement. e.g. Dim Names(100) would create an array to hold Names(0) to Names(100), in other words this array would hold 101 names. Note that there is a zero element to an array, hence Dim Names(100) will hold 101 names not 100 as you may expect. Arrays, like other variables can be of any of the data types such as Integer, Single, String… etc. Suppose that you wish to store 5 names without using an array. You will need to declare 5 variables. e.g. Dim NameOne as string Dim NameTwo as string Dim NameThree as string Dim NameFour as string Dim NameFive as string To input the names you will need 5 text boxes as well as 5 variables and the code will be: strNameOne = txtNameOne.Text strNameTwo = txtNameTwo.Text strNameThree = txtNameThree.Text strNameFour = txtNameFour.Text strNameFive = txtNameFive.Text Now imagine how clumsy it would be if you need to add a hundred or more names to a hundred variables. To do the same task with an array the code is: Dim strNames(4) as String Dim intCounter as integer Set intCounter to –1 in the Form Load area and then increment(increase) intCounter by 1 and assign the name to the variable each time you increase the counter. IntCounter = intCounter + 1 StrNames(intCounter) = txtNames.Text Here is some code that could be used to enter up to 101 names to an array variable. General Area Dim IntCounter as Integer Dim strNames(100) as String Here is the way the array works Names(100) Private Sub cmdStart_Click() IntCounter = -1 End Sub 0 1 Private Sub txtEnter_Keypress(KeyAscii as Integer) 2 If KeyAscii = 13 And txtEnter.Text <> “” Then 3 IntCounter = intCounter + 1 4 strNames(intCounter) = txtEnter.Text 5 txt.Enter.SetFocus 6 txtEnter.SelStart = 0 7 txtEnter.SelLength = Len(txtEnter.Text) 8 End If … End Sub When the data is in an array it can be.100 Printed out Printed out in Reverse order Searched for matches Sorted into Alphabetic (Ascending or Descending order) Page 29 Fred Mary Lee Tania Jack Tahu … Printing out data from an array To make it simple the contents of the array are printed out to a picture box. The routine uses a For…Next loop where the start value is 0 and the finish value is the number of names in the array which is stored in the global variable called intCounter. A Step value is not given as the default step is + 1. Here is the routine to print out an array. Private Sub cmdForward_Click() Dim intIndex As Integer picDisplay.Cls For intIndex = 0 To intCounter picDisplay.Print intIndex; " "; strNames(intIndex) Next intIndex End Sub Disp layi ng an array For intIndex 0 To intC ounter picDisplay .Print intI ndex; " "; strNames(intI ndex) Printing the data in reverse order 0 1 2 3 4 5 6 7 8 9 10 Fred Charlie Zane Mary Paul Tahu Mohammad Lee Tania Tina Rick This Procedure is almost the same as the procedure to print out the names in a forward direction, the only differences are the start and finish values are reversed and a negative Step value of –1 is added. Private Sub cmdReverse_Click() Only this line of code differs Dim intIndex As Integer from the Sub cmdForward picDisplay.Cls For intIndex = intCounter To 0 Step -1 picDisplay.Print intIndex; " "; strNames(intIndex) Next intIndex End Sub Carrying out a simple sequential search Searching is done by typing in a search string and then comparing the search string with each element in the array and printing it out if it matches. The Left function is used so that a “Begins with” search is implemented. A For…Next loop is used to step through each element of the array to check if it matches the search string. Searching strSearchString txtEnter.Text intLength Len(strSearchString) intIndex -1 For intIndex 0 To intCounter Is strSearchString = Left(strNames(intIndex), intLength) Yes picDisplay.Print strNames(intIndex) Private Sub cmdSearch_Click() Dim intIndex As Integer Dim intLength As Integer Page 30 End Sub Dim strSearchString As String Len Finds the strSearchString = txtEnter.Text length of the intLength = Len(strSearchString) search string intIndex = -1 picDisplay.Cls For intIndex = 0 To intCounter If strSearchString = Left(strNames(intIndex), intLength) Then picDisplay.Print strNames(intIndex) End If Next intIndex The search string is looked for in each element of the array. A more complex search could be setup using the string functions, Left, Right and Instr. Sorting data in an array There are many ways of sorting data in an array. The bubble sort is not the most efficient but is by far the simplest to follow. Sorting is done by: 1. Comparing the first element in the array with each other element and swapping if first is greater than the second. 2. Comparing the second element in the array with each other element and swapping if it is greater than the other 3. This is repeated until the second to last element has been compared with the last element. Sorting is done using two nested For…Next loops. The Pseudocode below shows simply how this is done. For intInner = 0 To intCounter –1 For intOuter = intInner + 1 To intCounter Compare the strNames(intInner) with strNames(intOuter) If StrNames(intInner) > StrNames(intOuter) Then Swap them Next intInner Next intOuter Visual Basic is able to make comparisons between strings using simple relational operators. Eg strNames(0) > strNames(1) will compare the strings using the value of the Ascii code that makes up each letter of the word. Note that upper case letters all have smaller Ascii Codes than lower case letters. An ascending sort will put Upper case letters first. To carry out a case independent sort the function UCase or LCase can be used. The diagram below shows how the comparisons are made for the First 3 passes of the Outer loop. StrNames(0) is compared with strNames(1) and swapped if the first name is larger than the second. strNames(0) is compared with strNames(2) strNames(0) is compared with strNames(3) strNames(0) is compared with strNames(5) strNames(0) is compared with strNames(6) strNames(0) is compared with strNames(7) strNames(0) is compared with strNames(8) strNames(0) is compared with strNames(9) strNames(0) is compared with strNames(10) strNames(1) is compared with strNames(2) strNames(1) is compared with strNames(3) strNames(1) is compared with strNames(4) … strNames(9) is compared with strNames(10) Page 31 Diagram to show Sorting Third Pass Second Pass 0 1 2 3 4 5 6 7 8 9 10 First Pass Right is a structure diagram for a sort routine. Zane Charlie Mary Jane Paul Fred Andrea Tahu Rick Andrew Michael BubbleSort For intOuter 0 To intCounter - 1 For intInner intOuter + 1 To intCounter Is strNames(intOuter) > strNames(intInner) Yes strTemp strNames(intInner) strNames(intInner) strNames(intOuter) strNames(intOuter) strTemp Below is the code for a Bubble sort routine. StrTemp Swapping array elements Private Sub cmdSort_Click() Dim intInner As Integer Dim intOuter As Integer Dim intIndex As Integer Dim strTemp As String For intOuter = 0 To intCounter - 1 For intInner = intOuter + 1 To intCounter If strNames(intOuter) > strNames(intInner) Then strTemp = strNames(intInner) strNames(intInner) = strNames(intOuter) strNames(intOuter) = strTemp End If Next intInner Next intOuter End Sub Before StrNames(intOuter) StrNames(intInner) Step 1 B A A B Step 2 Step 3 A A B B A Page 32 A B