You are on page 1of 34

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 Lblfirst.Caption = "I love Computing".......................................................................................9 Lblfirst.Height = 1300................................................................................................................9 Lblfirst.Width = 3000.................................................................................................................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
Page 1

Strings String Functions....................................................................................23 Simple programs to illustrate string functions...................................................24


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 Visual Basic is also an Event Driven language. Event driven languages allow you to choose what you do Language 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 Variant Prefix bln byt cur dtm dbl int lng sng str vnt Example blnWillgo bytRasterData curMoneyspent dtmStartwork dblTolerance intQuantity lngDistance sngAverage strFName vntCheckSum What the data is used to hold True or False Whole numbers from 0255 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
Alignment AutoSize BackColor BackStyle BorderStyle Caption Enabled Font ForeColor Height Left MousePointer TabIndex ToolTipText Top Visible Width WordWrap

Description
Determines whether the label's caption appears left-justified, centered, or right-justified within the label's boundaries. 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. 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. Determines whether the background shows through the label or if the label covers up its background text, graphics, and color. Determines whether a single-line border appears around the label. Holds the text that appears on the label. Determines whether the label is active. Often, you'll change the Enabled property at runtime with code when a label is no longer needed. Produces a Font dialog box in which you can set the caption's font name, style, and size. Holds the color of the label's text. Holds the height of the label's outline in twips. Holds the number of twips from the label's left edge to the Form window's left edge. Determines the shape of the mouse cursor when the user moves the mouse over the label. 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. Holds the text that appears as a tooltip at runtime. Holds the number of twips from the label's top edge to the Form window's top edge. Determines whether the label appears or is hidden from the user. Holds the width of the label in twips. 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
Alignment BackColor

Description
Determines whether the text box's text appears left-justified, centered, or right-justified within the text box's boundaries. 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. Determines whether a single-line border appears around the text box. 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. Produces a Font dialog box in which you can set the Text property's font name, style, and size. Holds the color of the text box's text. Holds the height of the text box's outline in twips. Holds the number of twips from the text box's left edge to the Form window's left edge. Determines whether the user can edit the text inside the text box that appears. Specifies the number of characters the user can type into the text box. Determines the shape of the mouse cursor when the user moves the mouse over the text box. 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. 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). Determines whether scrollbars appear on the edges of a multiline text box. Specifies the order of the text box in the focus order. Determines whether the text box can receive the focus. 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. Holds the text that appears as a tooltip at runtime. Holds the number of twips from the text box's top edge to the Form window's top edge. Determines whether the text box appears or is hidden from the user. Holds the width of the text box in twips.

BorderStyle Enabled Font ForeColor Height Left Locked MaxLength MousePointer MultiLine

PasswordChar ScrollBars TabIndex TabStop Text

ToolTipText Top Visible Width

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
BackColor BorderStyle Caption ControlBox Enabled

Description
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. 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. Displays text on the form's title bar at runtime. Determines whether the form appears with the Control menu icon. The Control menu appears when your application's user clicks the Control menu icon. 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. Produces a Font dialog box in which you can set the text's font name, style, and size. Holds the color of the form's text. Holds the height of the form's outline in twips. Describes the icon graphic image displayed on the taskbar when the user minimizes the form. Holds the number of twips from the form's left edge to the screen's left edge. Specifies whether a maximize window button appears on the form. Specifies whether a minimize window button appears on the form. Determines the shape of the mouse cursor when the user moves the mouse over the form. Specifies whether the user can move the form at runtime. Determines a graphic image that appears on the form's background at runtime. Determines whether the form's measurements appear in twips, pixels (the smallest graphic dot image possible), inches, centimeters, or other measurements. Determines whether the form appears on the Windows taskbar. Determines the state (centered or default) of the form at application startup. Holds the number of twips from the form's top edge to the Form window's top edge. Determines whether the form appears or is hidden from the user. Holds the width of the form in twips. Determines the initial state (minimized, maximized, or normal) in which the window appears at runtime.

Font ForeColor Height Icon Left MaxButton MinButton MousePointer Moveable Picture ScaleMode ShowInTask bar StartUpPosition Top Visible Width WindowState

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
Type a name for the new folder eg Add and Average

4
Double click on the new folder to open it

Check that you have a new named empty folder to save your project in.

Click the Save button

Type in a new name for the project the

6
Click the Save button

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


This is how your completed form will look

Getting Started

1) Start Visual Basic 2) Double click Standard EXE

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 _____________
Name cmdMonitor Caption Monitor Font 12pt ToolTipText Point at Monitor

How to add a command button


1) Select the Command tool from the tool box and position it at the bottom of the form.

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 Name cmdMouse Caption Mouse ToolTipText Point at Mouse

5) Select the third button and change its properties to

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)

Fig (b)

C
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.

Fig (c)

Logging on
Enter User ID Enter Password

Type in ID

Press Tab

Type Password

Press Enter

Exercises Draw Structure Diagrams for the following situations: 1. Saving a newly created file on a floppy disc 2. Cleaning your teeth. 3. Starting the car. 4. Changing a car tyre. Page 13

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 T w o n um b ers

G e t t h e f ir s t num ber

G e t th e s e c o n d num ber

A d d th e tw o nu m b ers

D is p l a y t h e r e s u lt

sngN um 1 v a l( t x t N u m 1 . t e x t )

sngN um 2 v a l( t x t N u m 2 . t e x t )

sngSum sngN um 1 + sngN um 2

l b lS u m . c a p t i o n 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 Borde Captio Font lblSum Fixed single Remove any text to make it 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 dont 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.

C o n v e r t C e ls iu s t o F a h r e n h e it

G et d eg rees C e ls iu s

C a lc u la t e d e g r e e s F a h r e n h e it

D is p la y F a h r e n h e it lb lF a h r e n h e it . c a p t io n s n g F a h r e n h e it

s n g C e ls iu s V a l( t x t C e ls iu s . t e x t

s n g F a h r e n h e it s n g C e ls iu s * 9 / 5 + 3 2

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

Command button properties Name cmdConvert Caption &Convert

Label properties Name lblFahrenheit Caption Nothing Border Fixed single

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 Press Enter 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

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.
C o n v e r t C e ls iu s t o F a h r e n h e it

G et d eg rees C e ls iu s

C a lc u la t e d e g r e e s F a h r e n h e it

D is p la y F a h r e n h e it

s n g C e ls iu s V a l( t x t C e ls iu s . t e x t

s n g F a h r e n h e it s n g C e ls iu s * 9 / 5 + 3 2

t x t F a h r e n h e it . t e x t s n g F a h r e n h e it

C o n v e r t F a h r e n h e it t o C e ls iu s

G et d eg rees F a h r e n h e it

C a lc u la t e d e g r e e s C e l s iu s

D is p la y C e ls iu s

s n g C e ls iu s V a l( t x t F a h r e n h e it . t e x t

s n g C e ls iu s ( s n g F a h r e n h e it - 3 2 ) * 5 /9

t x t C e ls i u s . t e x t s n g C e ls iu s

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 End If 'Ends block If End Sub 'Ends subroutine Private Sub txtCelsius_KeyPress(KeyAscii As Integer) 'Responds to keypresses returning keys pressed Page 17

If KeyAscii = 13 Then KeyAscii = 0 Dim sngCelsius As Single Dim sngFahrenheit As Single sngCelsius = Val(txtCelsius.Text) sngFahrenheit = sngCelsius * 9 / 5 + 32 txtFahrenheit.Text = sngFahrenheit End If End Sub

'Routine 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 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 $NZ input here

$AU is displayed here

2. Write another program similar to the one above except that it uses a keypress rather than a command button.

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

Extension exercise
Create another text box in order that the conversion rate can be entered rather having it fixed at 7/10 (.7)

Or Press Enter Here

than

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.

C a n I V o te ?

Structure Diagram

Decision Tree Y es N o C a n V o te C a n 't V o te


G e t in t A g e I s in t A g e >=18

I s in t A g e > = 1 8

Y es D is p la y " C a n V o te "

N o D is p la y " C a n ' t V o te "

Page 19

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 ForNext 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 ForNext loop works

Loop and display Counter values.

Symbol for a loop

Dimension variables

Get Values

For intCounter intStart To intFinish Step intStep

intCounter as Integer intStart as Integer intFinish as Integer intStep as Integer

intStart Val(txtStart.Text) intFinish Val(txtFinish.Text) intCounter Val(txtCounter.Text)

picDisplay.Print intCounter

Text box Named txtStart

Text box Named txtStep

Text box Named txtFinish

Picture box named picDisplay Start button named cmdStart

1. 2.

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
Page 21

'dimension the starting number 'dimension the finishing number 'dimension the counter

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. Start 1 6 0 12

'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. Finish 6 1 10 0 -1 2 -2 Step 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.


C a lc u la t e D e p r e c ia t io n ( c m d C a lc u la t e )

D im e n s io n V a r ia b le s

G e t V a lu e s

L oop F o r in t Y e a r C o u n t 1 T o in t Y e a r s

D is p la y N e w V a lu e

D im D im D im in t Y

s n g I n it ia lV a lu e A s S in g le s n g D e p r e c ia t io n A s S in g le in t Y e a r s A s I n t e g e r earC o un t A s In teger

s n g I n it ia lV a lu e = V a l( t x t I n it ia lV a lu e .T e x t ) sn g D e p r e c ia t io n = V a l( t x t D e p r e c ia t io n .T e x t ) in t Y e a r s = V a l( t x t Y e a r s .T e x t )

lb lF in a lV a lu e .C a p t io n = F o r m a t ( s n g I n it ia lV a lu e , " c u r r e n c y " )

sn g I n it ia lV a lu e sn g I n it ia lV a lu e s n g I n it ia lV a lu e * s n g D e p r e c ia t io n / 1 0 0

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) intLengths 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

Get a word

strReversedWord

""

intLength Len(strWord)

For intCounter intLength To 1 Step -1

lblDisplay.caption strReversedWord

Dim strWord as String Dim strReversedWord as string Dim intCounter as integer Dim intLength as integer

strWord txtWord.text

strReversedWord strReversedWord & Mid(strWord,intCounter,1)

Page 24

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

Get title and names

Combine title and names

lblCombined.Caption = strCombined

Dim strTitle as String Dim strSurname as String Dim strFirstName as String Dim strCombined as String

strTitle = txtTitle.text strSurname = txtSurname.text

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

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
Split Name into Components

Declare Variables

Get Name

intSpace 1

strName Mid(strFullName, intSpace)

lblName(2).Caption strName

Dim strFullName as String Dim strName as String Dim intSpace as Integer Dim intNextSpace as Integer

strFullName txtFullName.text

For intCounter 0 to 1

intNextSpace InStr(intSpace,strFullname," ",1)

strName Mid(FullName, intSpace,intNextSpace - intSpace)

lblName(intCounter).Caption strName

intSpace intSpace +1

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

Project Word Counter


This program uses the following function: InStr This program uses a DoLoop 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
Count words in a sentence

Declare Variables

Initialise Variables

intStart InStr(intStart, strSentence, strWord, 1)

Display Number

Get Sentence and Word

Do Until inStart 0 Dim intStart as Integer Dim intWordCount As Integer Dim strSentence As String intWordCount 0 intStart 1 lblWordcount.Caption intWordCount End If

strSentence txtSentence.Text

strWord txtWord.Text

intWordCount intWordCount + 1

intStart InStr(intStart + 1, strSentence, 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 Private Sub cmdStart_Click() IntCounter = -1 End Sub Here is the way the array works Names(100) Fred Mary Lee Tania Jack Tahu

0 1 2 Private Sub txtEnter_Keypress(KeyAscii as Integer) 3 If KeyAscii = 13 And txtEnter.Text <> Then 4 IntCounter = intCounter + 1 5 strNames(intCounter) = txtEnter.Text 6 txt.Enter.SetFocus 7 txtEnter.SelStart = 0 8 txtEnter.SelLength = Len(txtEnter.Text) End If 100 End Sub When the data is in an array it can be. Printed out Printed out in Reverse order Searched for matches
Page 29

Sorted into Alphabetic (Ascending or Descending order)

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 ForNext 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
Displaying an array

For intIndex 0 To intCounter

picDisplay.Print intIndex; " "; strNames(intIndex)

0 1 2 3 4 5 6 7 8 9 10

Fred Charlie Zane Mary Paul Tahu Mohammad Lee Tania Tina Rick

Printing the data in reverse order


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.

Page 30

A ForNext 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 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 End Sub

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 ForNext 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
Page 31

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)

Diagram to show Sorting


0 1 2 3 4 5 6 7 8 9 10 Zane Charlie Mary Jane Paul Fred Andrea Tahu Rick Andrew Michael

Third Pass

Second Pass

First Pass

Right is a structure diagram for a sort routine.

BubbleSort

For intOuter 0 To intCounter - 1

For intInner intOuter + 1 To intCounter

Is strNames(intOuter) > strNames(intInner)

Yes

Page 32
strTemp strNames(intInner) strNames(intInner) strNames(intOuter) strNames(intOuter) strTemp

Below is the code for a Bubble sort routine. Swapping array Private Sub cmdSort_Click() elements 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

StrTemp

StrNames(intOuter) StrNames(intInner)

Step 1

B A B

A A

Step 2 B

Step 3

B A

Page 33

You might also like