Visual Basic Advanced Lessons
-
Upload
krystallane-manansala -
Category
Documents
-
view
226 -
download
0
Transcript of Visual Basic Advanced Lessons
-
7/29/2019 Visual Basic Advanced Lessons
1/34
Programming with
Visual Basic
-
7/29/2019 Visual Basic Advanced Lessons
2/34
Table of Contents
Variables...................................................................................................................3Variable Data Types....................................................................................................................3
The Visual Basic opening screen............................................................................4
What are Labels?.....................................................................................................5What are Text Boxes?.............................................................................................6
What are Form Properties?....................................................................................7
Project 1 VB is Fun.............................................................................................8How to start a new project..........................................................................................................8How to create a Label ................................................................................................................8How to create a Command Button .............................................................................................8How to write code.......................................................................................................................9Lblfirst.Caption = "I love Computing".......................................................................................9
Lblfirst.Height = 1300................................................................................................................9Lblfirst.Width = 3000.................................................................................................................9
Saving a Visual Basic Program............................................................................10
Project The Personal Computer.....................................................................11How to create a Label...............................................................................................................11How to place graphic images on the form................................................................................11How to use Copy to add two more command buttons..............................................................11How to write code behind the buttons to move the pointer when you click any of the three
buttons.......................................................................................................................................12How to run your program to see if it all works.........................................................................12
Structure Diagrams...............................................................................................13Background...............................................................................................................................13Sequence...................................................................................................................................13Exercises...................................................................................................................................13
Project Simple Addition .................................................................................14How to create a Label...............................................................................................................14How to select the TextBox tool from the tool box....................................................................15Converting Celsius to Fahrenheit..............................................................................................16Making the conversion program respond to the Enter key rather than the command button...16
Making the program more versatile..........................................................................................17Formatting numbers..................................................................................................................18
Selections and Decisions........................................................................................19
Loops.......................................................................................................................20For Next loop........................................................................................................................20Positive step of one from a given number.................................................................................20Displays 1 2 3 4 5 6...................................................................................................................20
Negative step of minus one from a given number....................................................................20Displays 6 5 4 3 2 1...................................................................................................................21Positive step of plus two from a given number.........................................................................21
Displays 0 2 4 6 8 10.................................................................................................................21Project Exploring loops........................................................................................................21Problems....................................................................................................................................22
Page 1
-
7/29/2019 Visual Basic Advanced Lessons
3/34
Strings String Functions....................................................................................23
Simple programs to illustrate string functions...................................................24Project Reversing a string.....................................................................................................24Project Joining Strings Concatenation...............................................................................26Project Splitting Strings.......................................................................................................27Project Word Counter...........................................................................................................28
Visual Basic Arrays............................................................................................29General Area.............................................................................................................................29Printing out data from an array.................................................................................................30Printing the data in reverse order..............................................................................................30Carrying out a simple sequential search...................................................................................30Sorting data in an array.............................................................................................................31Diagram to show Sorting..........................................................................................................32
Page 2
-
7/29/2019 Visual Basic Advanced Lessons
4/34
What is Visual Basic?
Visual Basic is a programming language that allows you to create your ownsoftware with the look of Windows programmes that you are familiar with. It isthe 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 Macroin Excel it is actually created for you using Visual Basic.
The word visual in Visual Basic means graphical, easily seen such as pictures and symbols that you can clickon and drag.BASIC is short forBeginners All purpose Symbolic Instruction Code. BASIC was originally developed tomake 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 andsymbols to give instructions to the computer, not the low level instructions that deal with the zeros and onesthat the computer understands.
Visual Basic is also an Event Driven language. Event driven languages allow you to choose what you dorather than have to respond to a series of questions the computer dictates. Event driven languages such asVisual 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 then2. 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 avariable, you can also supply a data type for it. All variables have a data type that determines what kind of datathey can store.You can think of variables as containers, and you choose to put data in the most suitable container. You wouldnot 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 TypesData type Prefix Example What the data is used to hold Bytes
Boolean bln blnWillgo True or False
Byte byt bytRasterData Whole numbers from 0255 1
Currency cur curMoneyspent Money values, has a fixed decimal point
Date (Time) dtm dtmStartwork DateDouble dbl dblTolerance Large decimal numbers more accurately 8
Integer int intQuantity Smaller whole numbers 32,768 to 32,767, 2
Long lng lngDistance Whole numbers that are very large 4
Single sng sngAverage Decimal number 4
String str strFName Any collection of keyboard characters but usuallywords
Variant vnt vntCheckSum Stores all the above data types but is slow andwasteful of memory
16
Here is how you would declare a variableDim curMoneyspent As Currency
The cur is the abbreviation for currency. This is a naming convention that helps you by letting you know thetype of data that is attached to a particular variable.
Page 3
Definition
Event DrivenLanguage
-
7/29/2019 Visual Basic Advanced Lessons
5/34
The Visual Basicopening screen
These are some of the most common windows you will see when using Visual BasicTo 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 theirproperties 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, commandbuttons, 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 canalter 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 projectexplorer to display it.
Form Layout
This gives you an initial view of how your form/s will look on the screen.
Page 4
The Formwindowwith ourfirstproject
The Code
window
The Toolbox
window
ThePropertieswindow
Click the Run button to run your application
-
7/29/2019 Visual Basic Advanced Lessons
6/34
What are Labels?
Programmers use labels to place titles around the form and to label text boxes so users know what to type intothe text box. When you use the Label control, your code can change the label's text so that different messagescan appear when needed.
When you place labels on a form, you'll almost always set the Label control's Name property and type a newCaption 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 DescriptionAlignment Determines whether the label's caption appears left-justified, centered, or right-justified within
the label's boundaries.
AutoSize Enlarges the label's size properties, when True, if you assign a caption that is too large to fit inthe current label's boundaries at runtime.
BackColor Specifies the label's background color. Click the BackColor's palette down arrow to see a listof colors and click Categorized to see a list of common Windows control colors.
BackStyle Determines whether the background shows through the label or if the label covers up itsbackground text, graphics, and color.
BorderStyle Determines whether a single-line border appears around the label.
Caption Holds the text that appears on the label.
Enabled Determines whether the label is active. Often, you'll change the Enabled property at runtimewith code when a label is no longer needed.
Font Produces a Font dialog box in which you can set the caption's font name, style, and size.
ForeColor Holds the color of the label's text.
Height Holds the height of the label's outline in twips.
Left Holds the number of twips from the label's left edge to the Form window's left edge.
MousePointer Determines the shape of the mouse cursor when the user moves the mouse over the label.
TabIndex Specifies the order of the label in the focus order. Although the label cannot receive the directfocus, the label can be part of the focus order.
ToolTipText Holds the text that appears as a tooltip at runtime.
Top Holds the number of twips from the label's top edge to the Form window's top edge.
Visible Determines whether the label appears or is hidden from the user.
Width Holds the width of the label in twips.
WordWrap Determines whether the label expands to fit whatever text appears in the caption.
Page 5
-
7/29/2019 Visual Basic Advanced Lessons
7/34
What are Text Boxes?
Text boxes accept user input. Although several other controls accept user input, text boxes are perhaps theeasiest to set up and respond to. In addition, a text box is simple to use, and people see text boxes on Windowsforms all the time.
The table below lists the common properties associated with text boxes. By familiarising yourself with theproperties now, you will be able to more quickly produce applications as you learn more about Visual Basic.
Common text box properties
Property DescriptionAlignment Determines whether the text box's text appears left-justified, centered, or right-justified
within the text box's boundaries.
BackColor Specifies the text box's background colour. Click the BackColor property's palette downarrow to see a list of colours and click Categorized to see a list of common Windows controlcolours.
BorderStyle Determines whether a single-line border appears around the text box.Enabled Determines whether the text box is active. Often, you'll change the Enabled property at
runtime with code when a text box is no longer needed.
Font Produces a Font dialog box in which you can set the Text property's font name, style, andsize.
ForeColor Holds the color of the text box's text.
Height Holds the height of the text box's outline in twips.
Left Holds the number of twips from the text box's left edge to the Form window's left edge.
Locked Determines whether the user can edit the text inside the text box that appears.
MaxLength Specifies the number of characters the user can type into the text box.MousePointer Determines the shape of the mouse cursor when the user moves the mouse over the text box.
MultiLine Lets the text box hold multiple lines of text or sets the text box to hold only a single line oftext. Add scrollbars if you wish to put text in a multiline text box so your users can scrollthrough the text.
PasswordChar Determines the character that appears in the text box when the user enters a password (keepsprying eyes from knowing what the user enters into a text box).
ScrollBars Determines whether scrollbars appear on the edges of a multiline text box.
TabIndex Specifies the order of the text box in the focus order.
TabStop Determines whether the text box can receive the focus.
Text Holds the value of the text inside the text box. The Text property changes at runtime as theuser types text into the text box. If you set an initial Text property value, that value becomesthe default value that appears in the text box when the user first sees the text box.
ToolTipText Holds the text that appears as a tooltip at runtime.
Top Holds the number of twips from the text box's top edge to the Form window's top edge.
Visible Determines whether the text box appears or is hidden from the user.
Width Holds the width of the text box in twips.
Page 6
-
7/29/2019 Visual Basic Advanced Lessons
8/34
What are Form Properties?
Forms have properties that you can and should set when you create an application. Being the background ofyour application, the form's properties help set the stage for the rest of the project. The form supports moreproperty values than the other controls described here, but the list below lists only the most common propertiesthat you'll need.
New Term:Pixel stands for picture element and represents the smallest addressable graphic dot on yourmonitor.
Common form properties.
Property DescriptionBackColor Specifies the form's background color. Click the BackColor's palette down arrow to see a
list of colors and click Categorized to see a list of common Windows control colors.
BorderStyle Determines how the Form window appears. The BorderStyle property specifies whetherthe user can resize the form and also determines the kind of form you wish to display.
Caption Displays text on the form's title bar at runtime.
ControlBox Determines whether the form appears with the Control menu icon. The Control menuappears when your application's user clicks the Control menu icon.
Enabled Determines whether the form is active. Often, you'll change the Enabled property atruntime with code when a form is no longer needed. Generally, only multiformapplications, such as MDI applications, need to modify a form's Enabled property.
Font Produces a Font dialog box in which you can set the text's font name, style, and size.
ForeColor Holds the color of the form's text.
Height Holds the height of the form's outline in twips.
Icon Describes the icon graphic image displayed on the taskbar when the user minimizes theform.
Left Holds the number of twips from the form's left edge to the screen's left edge.
MaxButton Specifies whether a maximize window button appears on the form.
MinButton Specifies whether a minimize window button appears on the form.
MousePointer Determines the shape of the mouse cursor when the user moves the mouse over the form.
Moveable Specifies whether the user can move the form at runtime.
Picture Determines a graphic image that appears on the form's background at runtime.
ScaleMode Determines whether the form's measurements appear in twips, pixels (the smallest graphicdot image possible), inches, centimeters, or other measurements.
ShowInTask bar Determines whether the form appears on the Windows taskbar.
StartUpPosition Determines the state (centered or default) of the form at application startup.
Top Holds the number of twips from the form's top edge to the Form window's top edge.
Visible Determines whether the form appears or is hidden from the user.
Width Holds the width of the form in twips.
WindowState Determines the initial state (minimized, maximized, or normal) in which the windowappears at runtime.
Page 7
-
7/29/2019 Visual Basic Advanced Lessons
9/34
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-clickingthe Standard EXE icon
2. Change the form's Name property to frmFirst and change itsCaption property toMy 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'sName property to
lblFirst. Change the
label's Caption
property toVB is
fun.
5. Click the label's Fontproperty value todisplay the Font dialogbox for the label. Set thefont to Arial, the size to24 and set Bold
property.
6. Change the forecolour to Orange,
or any colour youchoose, and changethe label'sAlignment 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 theshape of the label to fit the text.
How to create a Command Button
8. Add a Command button, but to do so, double-clickthe 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'sName property to cmdExit.
10. Change the command button's Caption property to Exit. Watch the command button as you type theCaption 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 Clickevent occurs. Therefore, torespond to this event, you must write an event procedure for the command button. Double-clickthe form'scommand button and Visual Basic instantly opens the Code window and displays the following wrapperlines for the command button's Click event procedure:
Page 8
-
7/29/2019 Visual Basic Advanced Lessons
10/34
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 Endfor 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 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 Labelto I love computing.
1. Create anotherCommand Button and set the Name to Cmdchange, and theCaption 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. Thiscode says for the caption field of Lblfirst put the words I love computing.
The words will be too big for the Label window, so weneed to make the font size smaller as well. So lets setthe height of the label to 1400 by adding in thefollowing:
Lblfirst.Height = 1300
We need to make the Label window wider to fit thewords so also add:
Lblfirst.Width = 3000
Run the program by clicking on the Run
button and see if it works.
Page 9
Press Tab, to insert a space then type End
Exercise
Make another Command button to returnthe Label to the original VB is Funsettings.
-
7/29/2019 Visual Basic Advanced Lessons
11/34
Saving a Visual Basic Program
Page 10
You may need to save several files depending on the number of forms used and theobjects such as pictures placed on the form.
To save your work again just click the Save button.
ClickSave Projecton the tool bar.
1ClickCreate NewFolder 2
Type a name for the newfolder eg Add andAverage
3
Double click on the newfolder to open it
4
5
Check that you have anew named empty folderto save your project in.
Click the Savebutton
Type in a new namefor the projectthe
Click the Savebutton
6
7
-
7/29/2019 Visual Basic Advanced Lessons
12/34
Name cmdMonitorCaption Monitor
Font 12ptToolTipText Point at Monitor
Project The Personal Computer
Getting Started
1) Start Visual Basic
2) Double clickStandard
EXE3) Click on the form and in the Properties
window in the Name field change the nameof the form to frmComputer, then in theCaption field change the name of theCaption to PC Parts.
How to create a Label
4) Drag a label onto the form to make the titlePersonal Computer. In the properties
window change the Name to Lbl15) In the Caption field type in The Personal Computer
6) Click in the Font field within the Properties window todisplay 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 inthe centre of the form window in the same way you
positioned the label, by dragging it from top left cornerto 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 theellipsis to bring up a File Load dialog box. Load the image of a computer, called
_____________
11) Repeat the above steps to add the pointer image called _____________
How to add a commandbutton1) 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
This is how yourcompleted formwill look
-
7/29/2019 Visual Basic Advanced Lessons
13/34
3) Repeat this procedure to make a third button
4) Select the second button and change its properties to
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, Keyboardand 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 Left Top
Monitor
Keyboard
Mouse
How to write code behind the buttons to move the pointer when you click any ofthe three buttons.
1) Double click the Monitor command button on the form, then enter the position of the pointer asshown below into the Private Sub cmdMonitor_Click()
.
2) Double click the Keyboard command button on the form, then enter the position of the pointer asshown below into the Private Sub cmdKeyboard_Click()
3) Double click the Mouse command button on the form, then enter the position of the pointer asshown below into the Private Sub cmdMouse_Click()
How to run your program to see if it all works
1) Click the Start button on the main (top) toolbar
Page 12
Private Sub cmdMonitor_Click()imgPointer.Left = 2160imgPointer.Top = 2040
End Sub
Private Sub cmdMouse_Click()imgPointer.Left =imgPointer.Top =
End Sub
Private Sub cmdKeyboard_Click()imgPointer.Left =imgPointer.Top =
End Sub
Name cmdKeyboardCaption KeyboardToolTipText Point atKeyboard
Name cmdMouseCaption MouseToolTipText Point at Mouse
Hint: To display the formdouble clickForm1 in theExplorer window
-
7/29/2019 Visual Basic Advanced Lessons
14/34
2) Click each of your command buttons in turn (Monitor, Keyboard, Mouse) and the graphic pointerimage 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 bewritten in the correct order and the computer will carry out each one after the other. The code is said to besequential, 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 thatthe 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 orsmall, large ones can be broken down gradually into smaller ones. We may need to have several levels to astructure 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 thetop down and from left to right. Fig (b) is diagram with another level in which step B is done by doing steps Cand D.
Sequence
This is where one step is done after the other. Figs a, b and C are all simple sequences.The diagram Fig (c) below shows the sequence of steps you carry out when you log on to the network.
Exercises
Draw Structure Diagrams for the following situations:
1. Saving a newly created file on a floppy disc2. Cleaning your teeth.3. Starting the car.4. Changing a car tyre.
Page 13
A
B C D
A
B E F
C D
Fig (a) Fig (b)
Logging
on
Enter UserID
EnterPassword
Type in ID Press Tab TypePassword
Press Enter
Fig (c)
-
7/29/2019 Visual Basic Advanced Lessons
15/34
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.
When you write a computer program you have to get data into the computer (Input), process it and then displaythe 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 cornerhandle so that it size is about width 3500 height26400
4. In the Properties window double click the Name field
and change the name of the form to frmAdder, thendouble click the Caption field and change the name ofthe 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 thetop 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 thenew 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 lblSumBorde Fixed sin leCa tio Remove an text to make itFont 12 t
Page 14
A d d t h e t w o
n u m b e r s
G e t t h e f i r s t
n u m b e r
G e t t h e s e c o n d
n u m b e r
D i s p l a y t h e
r e s u l t
A d d T w o
n u m b e r s
s n g N u m 1 v a l ( t x t N u m 1 . t e x t )
s n g N u m 2
v a l ( t x t N u m 2 . t e x t )
s n g S u m
s n g N u m 1 + s n g N u m 2
l b l S u m . c a p t io n
s n g S u m
-
7/29/2019 Visual Basic Advanced Lessons
16/34
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 Propertyand 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 CaptioncmdAdd &AddcmdClear &Clear
7. Arrange the buttons as shown in the form above.
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 tozero. 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 4bytes to store them. This is OK as long as you dont need to use extremely large numbers.
RemarksAny text that starts with a single quotation mark is ignored. This is part of the documentation that you add toyour 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 havethe 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
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 sngNumonesngNumtwo = Val(txtNum2.text) converts text to a number and assigns it to sngNumtwosngSum = sngNum1 + sngNum2 adds sngNum1 to sngNum2 and assigns this to sgnSumlblSum.caption = sngSum
End Sub
Private Sub lblClear_Click()TxtNum1.text = "" assigns an empty string to txtNum1
TxtNum2.text = "" assigns an empty string to txtNum2LblSum.caption = "" assigns an empty string to txtNum3
End Sub
-
7/29/2019 Visual Basic Advanced Lessons
17/34
Press Enter
Converting Celsius to Fahrenheit
The structure diagram below outlines the steps you will carry out to convert a temperature entered in degreesCelsius to degrees Fahrenheit.
This exercise requires three static labels, one label to display the temperature in Fahrenheit, one text box forinput and one command button.
1. Create the form as shown below2. Add the code to the Convert command button
The Code
Double Click on the Convert button and then enter the code below:
Private Sub cmdConvert_Click() 'subroutine that responds to clicking the button cmdConvertDim sngCelsius As Single 'Declares a decimal number variable called sngCelsius
Dim sngFahrenheit As Single 'Declares a decimal number variable called sngFahrenheitsngCelsius = Val(txtCelsius.Text) 'Converts text into a numbersngFahrenheit = sngCelsius * 9 / 5 + 32 'Calculates the value for sngFahrenheitlblFahrenheit.Caption = sngFahrenheit 'Displays the value of sngFahrenheit in the label caption.
End Sub
Making the conversion program respond to the Enter key rather than thecommand button
In this example we show you how to Respond to the Enter key beingpressed 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 ispressed. This is easily done as the Enter key returns the ASCIIcode 13 when pressed, therefore our program must do the calculationonly IF KeyAscii = 13 (Enter Key)
Page 16
C a l c u l a t e d e g r e e s
F a h r e n h e i t
G e t d e g r e e s
C e l s i u s
D i s p l a y
F a h r e n h e i t
C o n v e r t C e l s i u s
t o F a h r e n h e i t
s n g C e l s i u s V a l ( t x t C e l s i u s . t e x t
s n g F a h r e n h e i t
s n g C e l s i u s * 9 / 5 + 3 2
l b l F a h r e n h e i t . c a p t i o n
s n g F a h r e n h e i t
Form propertiesName FrmFahrenheitCaption Find Degrees
Fahrenheit
Text box propertiesName txtCelsiusCaption Nothing
Label propertiesName lblFahrenheitCaption NothingBorder Fixed single
Command button propertiesName cmdConvertCaption &Convert
-
7/29/2019 Visual Basic Advanced Lessons
18/34
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 below2. Delete the cmdConvert button
Private Sub txtCelsius_KeyPress(KeyAscii As Integer) 'Responds to keypresses returning the keys pressedIf KeyAscii = 13 Then 'Routine below is only done if the Enter (key 13) is pressedKeyAscii = 0 'Stops the beep when Enter is pressed
Dim sngCelsius As Single 'Declares sngCelsius as SingleDim sngFahrenheit As Single 'Declares sngFahrenheit as Single
sngCelsius = Val(txtCelsius.Text) 'Converts text to a numbersngFahrenheit = sngCelsius * 9 / 5 + 32 'Calculates a value for sngFahrenheitlblFahrenheit.Caption = sngFahrenheit 'Displays sngFahrenheit in the label lblFahrenheit
End If 'End of the If decisionEnd Sub '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.
The two routines shown above are attached to the two text boxesIt 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 Fahrenheit2. Add a text box called txtFahrenheit3. Enter the new code belowPrivate Sub txtFahrenheit_KeyPress(KeyAscii As Integer) 'Responds to keypresses returning the keys pressedIf KeyAscii = 13 Then 'Routine is only done if the Enter (key 13) is pressedKeyAscii = 0 'Stops the beep when Enter is pressed
Dim sngCelsius As Single 'Declares sngCelsius as SingleDim sngFahrenheit As Single 'Declares sngFahrenheit as Single
sngFahrenheit = Val(txtFahrenheit.Text) 'Converts text to a number
sngCelsius = (sngFahrenheit - 32) * 5 / 9 'Calculates sngCelsiustxtCelsius.Text = sngCelsius 'Displays sngCelsius in txtCelsius text boxEnd If 'Ends block If
End Sub 'Ends subroutinePrivate Sub txtCelsius_KeyPress(KeyAscii As Integer) 'Responds to keypresses returning keys pressed
Page 17
C a l c u l a t e d e g r e e s
F a h r e n h e i t
G e t d e g r e e s
C e l s i u s
D i s p l a y
F a h r e n h e i t
C o n v e r t C e l s i u s
t o F a h r e n h e i t
s n g C e l s i u s V a l ( t x t C e l s i u s . t e x t
s n g F a h r e n h e i t
s n g C e l s i u s * 9 / 5 + 3 2
t x t F a h r e n h e i t . t e x t
s n g F a h r e n h e i t
C a l c u l a t e
d e g r e e s C e l s i u s
G e t d e g r e e s
F a h r e n h e i t
D i s p l a y
C e l s i u s
C o n v e r t F a h r e n h e i t
t o C e l s i u s
s n g C e l s i u s V a l ( t x t F a h r e n h e i t . t e x t
s n g C e l s i u s
( s n g F a h r e n h e i t - 3 2 ) * 5 / 9
t x t C e l s i u s . t e x t
s n g C e l s i u s
-
7/29/2019 Visual Basic Advanced Lessons
19/34
Calculation isattached to the clickevent event.
Calculation isattached to thekeypress event
If KeyAscii = 13 Then 'Routine is only done if the Enter (key 13) is pressedKeyAscii = 0 'Stops the beep when Enter is pressed
Dim sngCelsius As Single 'Declares sngCelsius as Single
Dim sngFahrenheit As Single 'Declares sngFahrenheit as SinglesngCelsius = Val(txtCelsius.Text) 'Converts text to a numbersngFahrenheit = sngCelsius * 9 / 5 + 32 'Calculates sngFahrenheittxtFahrenheit.Text = sngFahrenheit 'Displays sngFahrenheit in txtFahrenheit text box
End If 'Ends block IfEnd Sub 'Ends subroutine
Formatting numbers
The most often required format is currency which adds leading "$" dollar sign and formats to two decimalplaces.Examples:lbltotal.caption = Format(45,"currency")$45.00orcurSum = 45lblTotal.caption = Format(curSum,"currency")
Exercises
Write three programs to convert $NZ to $Aus: For eachprogram draw a structure diagram.1. Write a program that uses a text box for input, a label for
output and a command button tocalculate the result which is to be$Au. The conversion rate is $1NZ = $0.70 AU
2. Write another program similar tothe one above except that it uses akeypress rather than a commandbutton.
3. Modify program three so that it converts both ways. ie. $NZto $Aus and $Aus to $NZ in a similar way to thetemperature converter. It must be possible to type into either
text box and have the program display the conversion in theother text box.
Extension exerciseCreate another text box in order that the conversion rate can be entered rather thanhaving it fixed at 7/10 (.7)
Page 18
Or Press EnterHere
Press EnterHere
$NZ inputhere
$AU is
displayedhere
-
7/29/2019 Visual Basic Advanced Lessons
20/34
Write a program to calculate the cost of petrol for a trip
Start by:1. drawing up a structure diagram2. 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 foryou.
Object Name Caption/Text Variable Name Variable datatypeForm
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 twobuttons. The Reset button is to clear all the textboxes 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 astructure diagram to show how this decision can be represented graphically. The decision tree only shows thedecision logic whilst the structure diagram shows the complete program.
Page 19
C a n I V o t e ?
G e t i n t A g e
I s i n t A g e
> = 1 8
D i s p l a y " C a n
V o t e "
D i s p l a y " C a n ' t
V o t e "
Y e s N o
Y e s
N oI s i n t A g e > = 1 8
C a n V o t e
C a n ' t V o t e
Decision Tree
StructureDiagram
-
7/29/2019 Visual Basic Advanced Lessons
21/34
1. Create the form opposite with the following named objects
2. Enter the code below under the txtAge text box.
Private Sub txtAge_KeyPress(KeyAscii As Integer)If KeyAscii = 13 Then 'Only do if the key pressed is 13 "Enter"
Dim intAge As Integer 'Declare intAge as an integer (whole number)intAge = Val(txtAge.Text) 'Convert txtAge to a numberIf intAge >= 18 Then 'Check whether intAge is 18 or over
lblDecision.Caption = "Yes you can vote" 'Response when intAge is 18 or overElse
lblDecision.Caption = "No you can't vote" 'Response when intAge is under 18End If 'End of second IF
End If 'End of first IFEnd Sub '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 LoopCode
End of loop
For Next loop
This is a loop with an in-built counter. The syntax is:Forcounter=startTo 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 6PicDisplay.Print intCounter;
Next intCounterDisplays 1 2 3 4 5 6
Negative step of minus one from a given numberFor intCounter = 6 To 1 Step 1
PicDisplay.Print intCounter;Next intCounter
Page 20
Type Name Caption/Text
Form FrmAge Can I vote?
Text box txtAge None
Label Enter Age
Label LblDecision None
Type inage andpress Enter
-
7/29/2019 Visual Basic Advanced Lessons
22/34
Displays 6 5 4 3 2 1
Positive step of plus two from a given number
For intCounter = 0 To 10 Step 2PicDisplay.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
1. Create the form shown above and name all the objects as shown.2. Enter the code attached to the Start button as shown below.
Option ExplicitPrivate Sub cmdStart_Click()
Dim intStart As Integer 'dimension the starting number Dim intFinish As Integer 'dimension the finishing number Dim intCounter As Integer 'dimension the counter
Page 21
Loop and display Countervalues.
Get ValuesDimension variables
intCounter as IntegerintStart as IntegerintFinish as IntegerintStep as Integer
intStart Val(txtStart.Text)intFinish Val(txtFinish.Text)intCounter Val(txtCounter.Text)
For intCounter intStart TointFinish Step intStep
picDisplay.PrintintCounter
Picture boxnamed
picDisplay
StartbuttonnamedcmdStart
Text boxNamedtxtStart
Text boxNamedtxtFinish
Text boxNamedtxtStep
Symbol
for a loop
-
7/29/2019 Visual Basic Advanced Lessons
23/34
Dim intStep As Integer 'dimension the step valuepicOutput.Cls 'clear the picture boxintStart = Val(txtStart.Text) 'convert text to numberintFinish = Val(txtFinish.Text) 'convert text to number intStep = Val(txtStep.Text) 'convert text to number For intCounter = intStart To intFinish Step intStep 'start of loop
picDisplay.Print intCounter; 'code repeated in the loop
Next intCounter 'finish of loopEnd Sub
3. Run the program and enter the values in the table below. Write in the Output column the output youget when each set of values is entered.
Start Finish Step Output
1 6
6 1 -1
0 10 2
12 0 -2
Problems
a) Enter two integers and add all integers from the first integer to the second. If 1 and 6 wereentered the calculation would be 1 + 2 + 3 + 4 + 5 + 6 and the answer would be 21.
b) Enter two integers and add all even integers from the first integer to the second. If 2 and 10were entered the calculation would be 2 + 4 + 6 + 8 + 10 and the answer would be 30.
c) Find the sum of 1 + + 1/3 + 1/100
d) Produce a table to display the conversion of NZ dollars $ to English pounds for 1 to 10dollars. Have an input box to type in the exchange rate.
e) Display a times table from 1 to 10. Have an input box to enter the table you want printed.f) Convert Celsius to Fahrenheit as a table ranging from 0 to 40 degrees Celsius in steps of 5.
Fahrenheit = Celsius x 9/5 + 32g) 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 beworth 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
-
7/29/2019 Visual Basic Advanced Lessons
24/34
Below is a structure diagram for the Calculate button only.
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.
LenLenreturns the length of the string in number of characters. See the example below.
strName = Hagley Community CollegeintLength = Len(strName)intLengths value would be 24 as this is the number of characters including spaces in the name HagleyCommunity College
RightRight returns a specified number of characters from the right side of a stringstrName = Hagley Community CollegestrRightSide = 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 stringstrName = Hagley Community CollegestrLeftSide = Left(strName, 6)The variable strLeftSide would be Hagley as Hagley is the 6 leftmost characters.
MidMid returns a specified number of characters from a string starting at a given start position and thespecified length.strName =Hagley Community CollegestrMiddle = Mid(strName, 7, 9)The variable strMiddle would be Community as Community is 7 characters from the start of the stringand 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
C a l c u l a t e
D e p r e c i a t i o n
( c m d C a l c u l a t e )
D i m e n s i o n V a r i a b l e s
D i m s n g I n i t i a l V a l u e A s S i n g l e
D i m s n g D e p r e c i a t i o n A s S i n g l e
D i m i n t Y e a r s A s I n t e g e r
i n t Y e a r C o u n t A s I n t e g e r
G e t V a l u e s
s n g I n i t i a l V a l u e = V a l ( t x t I n i t i a l V a l u e . T e x t )
s n g D e p r e c i a t i o n =
V a l ( t x t D e p r e c i a t i o n . T e x t )
i n t Y e a r s = V a l ( t x t Y e a r s . T e x t )
L o o p
F o r i n t Y e a r C o u n t 1
T o i n t Y e a r s
s n g I n i t i a l V a l u e s n g I n i t i a l V a l u e -
s n g I n i t i a l V a l u e * s n g D e p r e c i a t i o n / 1 0 0
l b l F i n a l V a l u e . C a p t i o n =
F o r m a t ( s n g I n i t i a l V a l u e , " c u r r e n c y " )
D i s p l a y N e w V a l u e
-
7/29/2019 Visual Basic Advanced Lessons
25/34
InStrInstr searches for a smaller string within a larger string.strName = Hagley Community CollegestrShort = CommunityintPosition = InStr(1,strName, strShort,1)The value of intPosition would be 8 as this is the start position of the shorter string College in thelarger string Hagley Community College
If the strShort is not found within strName then the value returned will be zero.NoteThe first parameter 1, is the position in the string to start searching from.The fourth parameter,1 results in a noncase-sensitive search.
UCaseUCase converts all lower case letters in the string to upper case.strName = Hagley Community CollegestrName = 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 COLLEGEstrName =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 theletters in a string. In this example a single letter is extracted ata time starting with the last letter in the word. Letters are
joined together to make a word using the & (joiningoperator).
The code is attached to a Keypress event.
The Structure Diagram
Page 24
Reverse a Word
Get a word
strWord txtWord.text
strReversedWord ""intLength
Len(strWord)For intCounter
intLength To 1 Step -1
strReversedWord strReversedWord &Mid(strWord,intCounter,1)
lblDisplay.caption
strReversedWordDimension Variables
Dim strWord as StringDim strReversedWord as stringDim intCounter as integerDim intLength as integer
-
7/29/2019 Visual Basic Advanced Lessons
26/34
The Code
Option ExplicitPrivate Sub txtWord_KeyPress(KeyAscii As Integer)
If KeyAscii = 13 Then 'only continue if the enter key (13) is pressedKeyAscii = 0 'stop the beep when enter is pressed
Dim strWord As String 'variable for word enteredDim strReversedWord As String 'variable for the reversed wordDim intCounter As Integer 'variable for loop counter Dim intLength As Integer 'variable for length of wordstrWord = txtWord.Text 'get text from text boxstrReversedWord = "" 'set to null stringintLength = Len(strWord) 'find the lenght of the wordFor intCounter = intLength To 1 Step -1 'start of loop
strReversedWord = strReversedWord & Mid(strWord, intCounter, 1)Next intCounter 'end of looplblDisplay.Caption = strReversedWord 'display the reversed word in the label caption.txtWord.SelStart = 0 'start of highlighted area
txtWord.SelLength = intLength 'length of highlighted areaEnd If
End Sub
Page 25
-
7/29/2019 Visual Basic Advanced Lessons
27/34
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 andrecombine strings.
The Structure Diagram
Code
Option ExplicitPrivate Sub cmdCombine_Click()
Dim strTitle, strSurname, strFirstName, strCombined As StringstrTitle = txtTitle.TextstrFirstName = txtFirstName.TextstrSurname = txtSurname.TextstrCombined = strTitle & " " & Left(strFirstName, 1) & " " & strSurnamelblCombined.Caption = strCombined
End Sub
Page 26
Enter and combine title initial
and Surname
Get title and names
strTitle = txtTitle.textstrSurname = txtSurname.text
Combine title andnames
lblCombined.Caption =strCombinedDimension Variables
Dim strTitle as StrinDim strSurname as StrinDim strFirstName as StringDim strCombined as String
strCombined = strTitle & " " &Left(strFirstName,1) & " " & strSurname
-
7/29/2019 Visual Basic Advanced Lessons
28/34
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 inthe string.Mid is used to extract the section of name up to thespace. For the last section of the string Mid is usedwithout the last parameter thus only the start point isgiven 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
CodeOption ExplicitPrivate Sub txtFullName_KeyPress(KeyAscii As Integer)
If KeyAscii = 13 ThenKeyAscii = 0Dim strFullName, strName As StringDim intSpace, intNextSpace, intCounter As IntegerstrFullName = txtFullName.TextintSpace = 1For intCounter = 0 To 1
intNextSpace = InStr(intSpace, strFullName, " ", 1)strName = Mid(strFullName, intSpace, intNextSpace - intSpace)lblName(intCounter).Caption = strNameintSpace = intNextSpace + 1
Next intCounterstrName = Mid(strFullName, intSpace)lblName(2).Caption = strName
txtFullName.SelStart = 0txtFullName.SelLength = Len(strFullName)
End IfEnd Sub
Page 27
Split Name intoComponents
Declare Variables
Dim strFullName as StringDim strName as StringDim intSpace as IntegerDim intNextSpace as Integer
Get Name
strFullName txtFullName.text
intSpace 1
For intCounter 0 to 1
intNextSpace InStr(intSpace,strFullname," ",1) lblName(intCounter).Caption strNamestrName Mid(FullName, intSpace,intNextSpace - intSpace) intSpace intSpace +1
strName Mid(strFullName, i ntSpace)lblName(2).Caption strName
-
7/29/2019 Visual Basic Advanced Lessons
29/34
-
7/29/2019 Visual Basic Advanced Lessons
30/34
Visual Basic Arrays
An Array is a special type of variable that holds more than a single item of data. Before you can use anarray 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 arraywould hold 101 names. Note that there is a zero element to an array, hence Dim Names(100) will hold101 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 stringDim NameTwo as stringDim NameThree as stringDim NameFour as stringDim 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.TextstrNameTwo = txtNameTwo.Text
strNameThree = txtNameThree.TextstrNameFour = txtNameFour.TextstrNameFive = txtNameFive.Text
Now imagine how clumsy it would be if you need to add a hundred or more names to a hundredvariables.To do the same task with an array the code is:
Dim strNames(4) as StringDim intCounter as integer
Set intCounter to 1 in the Form Load area and then increment(increase) intCounter by 1 and assign thename to the variable each time you increase the counter.
IntCounter = intCounter + 1StrNames(intCounter) = txtNames.Text
Here is some code that could be used to enter up to 101 names to an array variable.
General AreaDim IntCounter as IntegerDim strNames(100) as String
Private Sub cmdStart_Click()
IntCounter = -1End Sub
Private Sub txtEnter_Keypress(KeyAscii as Integer)If KeyAscii = 13 And txtEnter.Text Then
IntCounter = intCounter + 1strNames(intCounter) = txtEnter.Texttxt.Enter.SetFocustxtEnter.SelStart = 0txtEnter.SelLength = Len(txtEnter.Text)
End IfEnd Sub
When the data is in an array it can be. Printed out
Printed out in Reverse order
Searched for matches
Page 29
Here is the way the array worksNames(100)
0 Fred1 Mary
2 Lee
3 Tania
4 Jack
5 Tahu
6
7
8
100
-
7/29/2019 Visual Basic Advanced Lessons
31/34
Sorted into Alphabetic (Ascending or Descending order)
Printing out data from an arrayTo make it simple the contents of the array are printed out to a picture box. The routine uses a ForNextloop where the start value is 0 and the finish value is the number of names in the array which is stored inthe 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 IntegerpicDisplay.ClsFor intIndex = 0 To intCounter
picDisplay.Print intIndex; " ";strNames(intIndex)
Next intIndexEnd Sub
Printing the data in reverse orderThis 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()Dim intIndex As IntegerpicDisplay.ClsFor intIndex = intCounter To 0 Step -1
picDisplay.Print intIndex; " "; strNames(intIndex)Next intIndex
End Sub
Carrying out a simple sequential searchSearching is done by typing in a search string and then comparing the search string with each element inthe array and printing it out if it matches.The Left function is used so that a Begins with search is implemented.
Page 30
Only this line of code differsfrom the Sub cmdForward
Displaying
an array
For intIndex 0 TointCounter
picDisplay.PrintintIndex; " ";strNames(intIndex)
0 Fred
1 Charlie2 Zane3 Mary4 Paul5 Tahu6 Mohammad7 Lee8 Tania9 Tina10 Rick
-
7/29/2019 Visual Basic Advanced Lessons
32/34
A ForNext loop is used to step through each element of the array to check if it matches the searchstring.
Private Sub cmdSearch_Click()Dim intIndex As IntegerDim intLength As IntegerDim strSearchString As StringstrSearchString = txtEnter.TextintLength = Len(strSearchString)intIndex = -1picDisplay.Cls
For intIndex = 0 To intCounterIf strSearchString = Left(strNames(intIndex), intLength) Then
picDisplay.Print strNames(intIndex)End If
Next intIndexEnd Sub
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 thesimplest 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 other3. 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 isdone.
For intInner = 0 To intCounter 1
For intOuter = intInner + 1 To intCounterCompare the strNames(intInner) with strNames(intOuter)If StrNames(intInner) > StrNames(intOuter) Then Swap them
Next intInner
Page 31
Len Finds thelength of thesearch string The search string
is looked for in
each element ofthe array.
Yes
Searching
strSearchStrin
xtEnter.TextintLen th
Len(strSearchString) intIndex -1
For intIndex
0 To intCounter
picDisplay.PrintstrNames(intIndex)
IsstrSearchStrin =
Left(strNames(intIndex),intLength)
-
7/29/2019 Visual Basic Advanced Lessons
33/34
Yes
BubbleSort
For intOuter 0 TointCounter - 1
For intInner intOuter+ 1 To intCounter
IsstrNames(intOuter) >strNames(intInner)
strTemp
strNames(intInner)strNames(intInner)
strNames(intOuter)
strNames(intOuter)
strTemp
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 upeach letter of the word.
Note that upper case letters all have smaller Ascii Codes than lower case letters. An ascending sort willput 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
Page 32
0 Zane
1 Charlie
2 Mary
3 Jane
4 Paul5 Fred
6 Andrea
7 Tahu
8 Rick
9 Andrew
10 MichaelSecond Pass FirstPass
Third Pass
Right is a structure diagram for a sortroutine.
-
7/29/2019 Visual Basic Advanced Lessons
34/34
Below is the code for a Bubble sort routine.
Private Sub cmdSort_Click()Dim intInner As IntegerDim intOuter As IntegerDim intIndex As IntegerDim strTemp As StringFor intOuter = 0 To intCounter - 1
For intInner = intOuter + 1 To intCounterIf strNames(intOuter) > strNames(intInner) Then
strTemp = strNames(intInner)strNames(intInner) = strNames(intOuter)
strNames(intOuter) = strTempEnd If
Next intInnerNext intOuter
End Sub
B A
A
B B
A
A B
A
B A
StrTemp
StrNames(intInner)StrNames(intOuter)
Swapping array
elements Before
Step 1
Step 2
Step 3