Visual Basic

28
It is easier to read, understand and manage things if they are broken down into sections. Books are divided into chapters, essays are written in paragraphs, school subjects are split into units, school years are split into register classes. All of these things have been broken down into manageable ‘chunks’. Each ‘chunk’ has something in common. The chapter in a book is one part of the story. The unit at school is all on one topic. One register class all have the same guidance teacher, may all take German or all play in the school wind band. There is usually a list at the start of things to show what each of the ‘chunks’ are. The contents page at the beginning of a book, a course description of a subject at school or a list of register classes. Procedures & Parameters b-programs make your program more readable, maintainable, modular and robu The same applies to programming. It is much easier to read, understand and manage a program if it is broken down into sections. Each section should perform a main step from your design. These sections are often known as procedures. In Visual Basic a procedure is called a sub-program When you write out the pseudocode for your program design then the main steps listed will each become sub-programs. At the beginning of your program, after you have listed the variables you will use, you will have to list the sub-programs you will use as well.

description

 

Transcript of Visual Basic

Page 1: Visual Basic

It is easier to read, understand and manage things if they are broken down into sections. Books are divided into chapters, essays are written in paragraphs, school subjects are split into units, school years are split into register classes. All of these things have been broken down into manageable ‘chunks’. Each ‘chunk’ has something in common. The chapter in a book is one part of the story. The unit at school is all on one topic. One register class all have the same guidance teacher, may all take German or all play in the school wind band.

There is usually a list at the start of things to show what each of the ‘chunks’ are. The contents page at the beginning of a book, a course description of a subject at school or a list of register classes.

Procedures & Parameters

Sub-programs make your program more readable, maintainable, modular and robust.

The same applies to programming.

It is much easier to read, understand and manage a program if it is broken down into sections. Each section should perform a main step from your design. These sections are often known as procedures.

In Visual Basic a procedure is called a sub-program

When you write out the pseudocode for your program design then the main steps listed will each become sub-programs. At the beginning of your program, after you have listed the variables you will use, you will have to list the sub-programs you will use as well.

Page 2: Visual Basic

For Example…

This would be written in code as:

Private Sub cmdCalculate_click()

DIM number1 as integerDIM number2 as integerDIM answer as integer

Call get_numbersCall calculateCall display_result

END Sub

Variable statements

Sub-program statements

It’s worth remembering that the order you list the sub-programs in is the order they will run in.

Pseudocode Sub-program nameMain Steps

1. Get two numbers get_numbers2. Calculate the sum calculate3. Display the answer in message box Display_result

Page 3: Visual Basic

Private Sub cmdCalculate_click()

DIM number1 as integerDIM number2 as integerDIM answer as integer

Call get_numbers( )Call calculate( )Call Display_result( )

END Sub

Sub get_numbers ( )Number1 = InputBox(“Enter the first number”)Number2 = InputBox(“Enter the second number”)

End Sub

Sub calculate ( )Answer = number1+number2

End Sub

Sub Display_result( )txtAnswer.text = answer

End Sub

So a whole program written with sub-programs would look something like this:

Variable statements

Sub-program get_numbers

Sub-program calculate

Sub-program display_result

Sub-program statements

Page 4: Visual Basic

Private Sub cmdCalculate_click( )

DIM number1 as integerDIM number2 as integerDIM answer as integer

Sub Display_result( )txtAnswer.text = answer

End Sub

Sub calculate ( )Answer = number1+number2

End Sub

Sub get_numbers ( )Number1 = InputBox(“Enter the first number”)Number2 = InputBox(“Enter the second number”)

End Sub

END SubCall Display_result( )Call calculate( )Call get_numbers( )

Running order of a program which uses sub-programs

Page 5: Visual Basic

There are two different ways you can use variables within your program. Global Variables and Local Variables

Variables

Global Variables

Global variables are variables whose value is available throughout your program for use by different sub programs. Global variables are declared right at the beginning of your program, before you call any sub programs.

It is NOT good programming practise to make all your variables global. Global variables are more likely to be altered by mistake and produce errors in your code. Where possible, Local variables should be used.

It will always be necessary to have some global variables as you will normally want to move some data between different sub programs, for example a value taken in in one sub program might be used in a calculation in another and displayed in a third.

Page 6: Visual Basic

Local Variables

Local variables are variables which are used in only one sub program. They are not declared at the beginning of your code – instead the dimensioning takes place within the sub program.

The value stored in a local variable can only be changed, used and viewed in the sub routine it was declared in.

You should try to use Local variables whenever possible as it reduces the chances of values being changed by accident elsewhere in your code and makes the program easier to maintain and update. It is also considered good programming practise to use Local variables where possible.

Page 7: Visual Basic

Global Variable number

Dimensioned at the start of the program

Used in different sub programs –

the value from one is passed into and used in the other

Local variables counter and answer

dimensioned within the sub program and used only in that sub program

Local and Global variables

Page 8: Visual Basic

Sub-Programs & Parameters

You can’t use sub-programs in Visual Basic without also using parameters.

Parameters handle the flow of data within your program for all global variables. A parameter can be either a variable or a value. Parameters can be passed into and out of a sub-program.

Parameters improve the reliability and robustness of your program

You must list all the parameters you intend to use in each sub- program. This list must be included as part of the CALL statement and as part of the actual sub-program.

Page 9: Visual Basic

There are two different ways to pass parameters between sub-programs.

You can pass parameters by VALUE or you can pass parameters by REFERENCE

Passing Parameters

Passing Parameters by Value

Parameter Passing by VALUE is when a value is passed into a subprogram for use by the subprogram, but the changed value is not passed out.

Parameters passed by Value are indicated by putting brackets around the parameter name.

Passing Parameters by ReferenceParameter Passing by REFERENCE is when a value is passed into a subprogram for use by the subprogram, and then the changed value is passed out to be used by other sub-programs.

Parameters are passed by Reference by default and are simply listed in the parameter list.

Page 10: Visual Basic

Private Sub cmdBegin_Click()

Dim number1 As IntegerDim number2 As IntegerDim answer As Integer

Call get_numbers(number1, number2)Call calculate((number1), (number2), answer)Call display_answer((answer))

End Sub

Sub get_numbers(number1, number2)number1 = InputBox("Enter number 1")number2 = InputBox("Enter number 2")

End Sub

Sub calculate(number1, number2, answer)answer = number1 + number2

End Sub

Sub display_answer(answer)txtAnswer.Text = answer

End Sub

Example Comments

The parameters are shown in blue

number1 and number2 are changed in the get_numbers sub-program and the changed data needs to be used elsewhere so are passed by reference.

The same parameters are listed here in the exact same order they are listed in the main program.

number1 and number2 are simply passed into the calculate sub-program but are not changed and so are passed by value,

answer is changed and needs to be passed by reference.

answer is passed into the display_answer sub-program but is not changed and so is passed by value.

Page 11: Visual Basic

Sub-programs and parameters make designing your program even more crucial.You need to indicate in your design where and how parameters will be used.

This could be by adding data flows to structure diagrams

Or by indicating data flow in pseudocode.

Calculate Displayanswer

Get Numbers

Main

number1number2

number1number2 answer answer

1. Set up variables2. Get numbers OUT: number1, number23. Calculate answer IN: number1, number2. OUT: answer4. Display answer IN: answer5. End

Design

Page 12: Visual Basic

Try this program out in Visual Basic.

Page 13: Visual Basic

IF register_class = “4A” OR register_teacher = “4I” OR register_teacher = “5A” THEN

guidance_teacher = “Ms Graham”

Else IF register_teacher = “4B” OR register_teacher = “4G” OR register_teacher = “5C” THEN

guidance_teacher = “Miss Stott”

Else IF register_teacher = “4C” OR register_teacher = “4K” OR register_teacher = “5E” THEN

guidance teacher = “Mrs Skellern”

… (and so on)

END IF

IF register_class = “4A” THEN

guidance_teacher = “Ms Graham”

Else IF register_teacher = “4B” THEN

guidance_teacher = “Miss Stott”

Else IF register_teacher = “4C” THEN

guidance teacher = “Mrs Skellern”

… (and so on)

END IF

Using the CASE statementA CASE statement is a more efficient way of performing a multiple choice in programming. You could use the IF… THEN… ELSE IF… ELSE IF… ELSE IF … but it gets quite messy and you have to repeat the condition of the choice each time.

For Example:

The IF method gets even more messy if you have multiple possibilities giving the same result.

For Example:

Page 14: Visual Basic

SELECT CASE register_ classCASE IS “4A”,”4I”,”5A”

guidance_teacher = “Ms Graham”CASE IS “4B”, ”4G”,”5C”

guidance_teacher = “Miss Stott”CASE IS “4C”, “4K”, “5E”

guidance_teacher = “Mrs Skellern”END SELECT

The CASE statement will perform this same task much more neatly and efficiently.

SELECT CASE register_ class

Case Is “4A”,”4I”,”5A”

guidance_teacher = “Ms Graham”

Case Is “4B”, ”4G”,”5C”

guidance_teacher = “Miss Stott”

Case Is “4C”, “4K”, “5E”

guidance_teacher = “Mrs Skellern”

End Select

This is the variable you are checking

This is the first condition (or conditions) to check if it meets. The comma means OR.This is what happens if the condition is met. There can be more than one line of code here.

Page 15: Visual Basic

The CASE statement treats number ranges differently from other Visual Basic structures.

The default for a CASE condition is CASE IS. So CASE IS can be exactly something or more or less than one number. You cannot have a number range – CASE IS >20 AND <40.

If you need a number range you need to use CASE…..TO – CASE 20 TO 40

Page 16: Visual Basic

When using random numbers you need to use the RND command.

Randomize is the word used to mix up a list of numbers each time a program is run. It is a pre-defined function.

The value of the random number is between 0 and 1 (a real number or a fraction). If we want a bigger number we have to multiply the random number by the biggest amount we want. To see how random numbers work, look at the following program:

Create random number

Display random numberOutput

Random Numbers

Page 17: Visual Basic

As you can see, the RND function produces random numbers between 0 and 1

To produce whole random numbers between 1 and 10 we would have to do three things to the line number = RND.

• We would need to multiply by 10 to get a random fraction between 0 and 10

• We would need to chop off the fraction part using the function INT (changes a number to the nearest whole number)

• Lastly, we need to add 1 because the highest number would always be 9 as it would be rounded down by the INT function.

So, Number = RND will become

Number = INT (RND * 10) + 1

Output

Inserting the word RANDOMIZE gives truly random results

Page 18: Visual Basic

Validation and Conditional Loops

You need to remember to validate the input to any program. This will greatly reduce run-time errors caused by unexpected data and will also assist the users to enter the right data and be clear what they are doing. It will also help the testing phase.

A simple validation could be something like entering a price which is less than £10.

Private Sub cmdBegin_Click()DIM cost as Integer

Cost = INPUTBOX(“Please enter the cost”)txtCost.text = cost

END SUB

Private Sub cmdBegin_Click()DIM cost as Integer

DOCost = INPUTBOX (“Please enter the cost”)

LOOP UNTIL cost < 10txtCost.text = cost

END SUBNo validation – you can enter what you like Simple validation

Keeps asking until you enter a valid number – no error message

If you wanted to make sure the cost of an item was less that £10 you would need to keep asking the user to enter the cost UNTIL it was less than £10. They might enter it correctly the first time, in which case they don’t need to be asked again or they might get it wrong one hundred times in which case the program will loop until they enter a cost that is less than £10.

The problem here is that there is no message to tell the user why they keep getting asked for the same thing.

You can add a condition which will check if the input is ok and print a helpful error message if it is not.

This program will ask the user to enter the cost of an item and will display it in a text box. However, there is no way to check whether the cost is less than £10. To check this (this is called VALIDATION) you will need to use a conditional loop.

A conditional loop is where some lines of code in your program will repeat until a certain condition is met.

Page 19: Visual Basic

Private Sub cmdBegin_Click()DIM cost as Integer

DOCost = INPUTBOX (“Please enter the cost”)IF cost >=10 THEN

MSGBOX(“The cost must be less than £10”)END IF

LOOP UNTIL cost < 10txtCost.text = cost

END SUB

Private Sub cmdBegin_Click()DIM cost as Integer

DOCost = INPUTBOX (“Please enter the cost”)IF cost >=10 THEN

MSGBOX(“The cost must be less than £10”)END IF

LOOP UNTIL cost > 0 AND cost < 10txtCost.text = cost

END SUB

This is better, every time an invalid cost is entered a message is displayed stating why and asking for the data again.

This is correct – as it is a cost it also checks the number is greater than 0. The error message is still displayed and there is no chance the data entered will be inappropriate.

It is much more difficult to validate text input, you can help eliminate problems by converting all text input to either upper or lower case, as Visual Basic considers them as different in a comparison - “john” would be considered as different from “John”. It is not always appropriate to convert all text to upper or lowercase.

You can also count the number of characters entered – this can help with things like postcodes which are a fixed length.

Page 20: Visual Basic

So far all the variables you have used have been single item variables. As you write more complex programs you will find you need many similar variables in one program.

If you were going to read in 10 pupils marks you could have 10 individual variables.

Dim mark1 as integer

Dim mark2 as integer

Dim mark3 as integer

Dim mark4 as integer

Dim mark5 as integer

Dim mark6 as integer

Dim mark7 as integer

Dim mark8 as integer

Dim mark9 as integer

Dim mark10 as integer

This would also require 10 input statements

Mark1 = inputbox(“Please enter Mark 1”)

Mark2 = inputbox(“Please enter Mark 2”)

Mark3 = inputbox(“Please enter Mark 3”)

Mark4 = inputbox(“Please enter Mark 4”)

Mark5 = inputbox(“Please enter Mark 5”)

Mark6 = inputbox(“Please enter Mark 6”)

Mark7 = inputbox(“Please enter Mark 7”)

Mark8 = inputbox(“Please enter Mark 8”)

Mark9 = inputbox(“Please enter Mark 9”)

Mark10 = inputbox(“Please enter Mark 10”)

This would require 10 variables

txtMark1.text = mark1

txtMark2.text = mark2

txtMark3.text = mark3

txtMark4.text = mark4

txtMark5.text = mark5

txtMark6.text = mark6

txtMark7.text = mark7

txtMark8.text = mark8

txtMark9.text = mark9

txtMark10.text = mark10

And 10 output statements

This is obviously an awful lot of repetitive code. There is a much better way of storing and using data which is related. This is using an array.

Using Arrays

Page 21: Visual Basic

An array stores a number of variables in a special data structure. If you wanted to store a large amount of one type of data then you could use an array. An array to holds them all together and treats them as one thing. The program can then refer to the whole array or any single element of the array.

You would declare an array like this:

Array name The number of elements in the array

Array data type

DIM mark(10) as Integer

The memory sets aside an area divided into elements

Mark

1 2 3 4 5 6 7 8 9 10

So this element is referred to as Mark(6) and this one is Mark (8)

An input statement would look like this: Mark(3) = Inputbox(“Please enter mark 3)

The data entered would be placed in the third element of the array.

Page 22: Visual Basic

To eliminate the need for multiple INPUT and OUTPUT statements you would use a FOR loop for array operations.

FOR counter = 1 TO 10

Mark(counter) = Inputbox(“Please enter the mark “)

NEXT counter

FOR giraffe = 1 TO 10

lstResults.additem Mark(giraffe)

NEXT counter

Whatever variable is used in the FOR loop is also used for the element position in the Array. As the loop goes round, the loop variable (counter or giraffe above) is incremented (goes up by one) so first time round counter = 1 and the input goes in Mark(1), next time round counter = 2 so the input goes in Mark(2) and so on. Instead of 10 input statements or 10 output statements, those three lines of code will input or output all 10 data items.

Page 23: Visual Basic

You can also use FOR loops and arrays to take in more than one set of related data. For example if you wanted to read in 6 student names and their marks. You need to keep the names and marks separate because you might want to use the numeric data for comparisons or calculations.You will need to declare 2 arrays one for names and one for marks. You will only need one FOR loop.

Name Mark

Jim 37

Bob 26

Sue 52

Jan 86

John 17

Peter 79

37 26 52 86 17 79

Jim Bob Sue Jan John

PeterName

Mark

(1) (2) (3) (4) (5) (6)

(1) (2) (3) (4) (5) (6)

So this dataWould be stored like this

This means that the name and mark are stored in different arrays but in the same position, so could be accessed at the same time using one FOR loop

Page 24: Visual Basic

DIM name(6) as StringDIM mark(6) as IntegerDIM pupil as IntegerDIM result as Integer

FOR pupil = 1 TO 6name(pupil) = Inputbox(“Please enter the name”)mark(pupil) = Inputbox (“please enter the mark”)

NEXT pupil

FOR result = 1 TO 6lstClassResults.additem name(result) & “ “ & mark(result)

NEXT result

This code uses one FOR loop to read in both the name and the mark.

A different FOR loop is used to display the data in a list box.

Page 25: Visual Basic

String Operations

Visual Basic considers upper and lower case text to be different, so if you had a quiz program where the answer should be true and the user entered TRUE, when you perform the comparison to see if they got the answer right the program would say they got it wrong. You can convert string data to upper and lower case to help prevent problems like this.

To convert test to upper case or lower case you would use the UCase or LCase functions.

lowercase_string = LCase(string_variable)

uppercase_string = UCase(string_variable)

Where string_variable is the original data and lowercase_string and uppercase_string is where the converted data is stored.

You can use the Len function to find out how many characters are in a string variable. It counts spaces as well as characters. You will need to store the length as a numeric variable.

Numeric_variable = Len(string_variable)

Ifstring_variable = “John Smith” then numeric_variable = 10

Ifstring_variable = “Hello” then numeric_variable = 5

Page 26: Visual Basic

One of the operations you can do with string variables is string concatenation – this is adding the two strings together. It is as simple as this:

Newstring = string1+string2

DIM initial as StringDIM surname as StringDIM userID as String

initial = Inputbox(“Please enter your initial”)surname = Inputbox(“Please enter your surname”)userID = surname+initial

INPUT : initial = V surname = Mackenzie

OUTPUT : MackenzieV

String Operations - Concatenation

Page 27: Visual Basic

String Operations – Sub String

A Sub string operation is where you separate part of the string value. You can take the first character, the middle three characters, the last two, the first seven. Basically you can separate whatever number of characters you want from wherever you want in the string.

You need to use the Mid$ function for this:

String_output = Mid$(string_input, start position, number or characters)String_out = Mid$(string_input, 2, 3 )

So if string_input = “Greetings”

Then

String_out = “ree”

If string_input = “Computing is Fun”

Then

String_out = “omp”

Character to start at How many characters to extract

Page 28: Visual Basic