Professional Documents
Culture Documents
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
Structure Diagrams...............................................................................................13
Background...............................................................................................................................13 Sequence...................................................................................................................................13 Exercises...................................................................................................................................13
Project
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
Page 2
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.
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 Form window with our first project The Properties 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
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
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
Page 6
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
application.
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
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.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
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.
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.
Project
Getting Started
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
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
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
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 )
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
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
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
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
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
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
2. Write another program similar to the one above except that it uses a keypress rather than a command button.
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.
Extension exercise
Create another text box in order that the conversion rate can be entered rather having it fixed at 7/10 (.7)
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 = ""
C a n I V o te ?
Structure Diagram
I s in t A g e > = 1 8
Y es D is p la y " C a n V o te "
Page 19
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
Dimension variables
Get Values
picDisplay.Print intCounter
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
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
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
Reverse a Word
Dimension Variables
Get a word
strReversedWord
""
intLength Len(strWord)
lblDisplay.caption strReversedWord
Dim strWord as String Dim strReversedWord as string Dim intCounter as integer Dim intLength as integer
strWord txtWord.text
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
Dimension Variables
lblCombined.Caption = strCombined
Dim strTitle as String Dim strSurname as String Dim strFirstName as String Dim strCombined as String
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
Declare Variables
Get Name
intSpace 1
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
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
Structure Diagram
Count words in a sentence
Declare Variables
Initialise Variables
Display Number
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
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
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
0 1 2 3 4 5 6 7 8 9 10
Fred Charlie Zane Mary Paul Tahu Mohammad Lee Tania Tina Rick
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
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
A more complex search could be setup using the string functions, Left, Right and Instr.
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)
Third Pass
Second Pass
First Pass
BubbleSort
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