microsoft visual basic 3.0 - institute of technology,...

43
Visual Basic Programming Introduction In the early days of programming, it was usually the highly educated computer programmers using complex languages. In 1964 a new language Beginner's All-purpose Symbolic Instruction Code (or BASIC) was introduced. Using common English to perform processor tasks, BASIC quickly became popular. Visual Basic is a programming environment, which is based on the programming language ‘Basic’, which allows applications with the ‘Look and Feel’ of windows to be created. Visual basic provides all the components necessary to such as textboxes, buttons etc. to build a windows application, leaving the programmer time to concentrate on programming. When writing programs in the original Basic language, the program is written line by line and when run it starts running from the beginning to end, with goto or gosub statements included to alter the flow of the program. Visual basic is event driven . The part of the program which runs is determined by the occurrence of an event. A visual basic program is written by assembling a range of object (buttons, textboxes etc.) on a form to form the user interface. Sections of code are then attached to the object so that they are activated by an event such as a mouse click. Therefore, it is the actions of the user which governs the sequence of operations. Controls are the components which are put together on the form to construct an application. These include buttons, text box etc. Most controls are visible and together form the visible user interface. Double clicking on an object brings up a code window allowing code to be written for that object. Such code is associated with a particular action. Such code is called a subroutine and begins with Sub and ends with End sub. VBA S Dalton 2010 1

Upload: nguyenmien

Post on 29-Jun-2018

214 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: microsoft Visual Basic 3.0 - Institute Of Technology, Sligostaffweb.itsligo.ie/staff/sdalton/VB/VB2010.doc  · Web viewVisual Basic Programming ... which is based on the programming

Visual Basic ProgrammingIntroductionIn the early days of programming, it was usually the highly educated computer programmers using complex languages. In 1964 a new language Beginner's All-purpose Symbolic Instruction Code (or BASIC) was introduced. Using common English to perform processor tasks, BASIC quickly became popular.

Visual Basic is a programming environment, which is based on the programming language ‘Basic’, which allows applications with the ‘Look and Feel’ of windows to be created. Visual basic provides all the components necessary to such as textboxes, buttons etc. to build a windows application, leaving the programmer time to concentrate on programming.

When writing programs in the original Basic language, the program is written line by line and when run it starts running from the beginning to end, with goto or gosub statements included to alter the flow of the program.

Visual basic is event driven. The part of the program which runs is determined by the occurrence of an event. A visual basic program is written by assembling a range of object (buttons, textboxes etc.) on a form to form the user interface. Sections of code are then attached to the object so that they are activated by an event such as a mouse click. Therefore, it is the actions of the user which governs the sequence of operations.

Controls are the components which are put together on the form to construct an application. These include buttons, text box etc. Most controls are visible and together form the visible user interface.Double clicking on an object brings up a code window allowing code to be written for that object. Such code is associated with a particular action. Such code is called a subroutine and begins with Sub and ends with End sub.

Modules are used to write code which is not associated with a particular form or object.

A project holds the menu forms and modules together which make up a program.

VBA S Dalton 2010 1

Page 2: microsoft Visual Basic 3.0 - Institute Of Technology, Sligostaffweb.itsligo.ie/staff/sdalton/VB/VB2010.doc  · Web viewVisual Basic Programming ... which is based on the programming

Visual Basic objects (the toolbox)The toolbox contains the building blocks necessary to assemble a visual basic program.

The pointer (not an object itself) is used to move and resize controls once inserted on the form.

Command buttons allow a user to select one of a limited number of options, e.g. OK and cancel.

A picture box is used to insert images (BMP etc) like a company logo.

Labels are used for headings only i.e. does not change during the running of a program.

Text boxes are capable of receiving input from and displaying information to the user while the program is running.

Check boxes provide a means to toggle settings on/off. (object snaps)

Option boxes allow selection of only one option (e.g units display in AutoCAD, )

Frames provide a means of grouping controls logically. Where option boxes are in frames, one option can be selected in each.

List boxes display a list of items from which the user can make a selection. (a file list in an open files dialogue box).

Combo boxes provides a combination of a data entry box with a drop downlist (e.g. drives section of file open dialogue).

Scroll bars may be used to provide a visual means of adjusting a parameter where the actual value doesn’t realy matter (e.g. aperture size in AutoCAD). Scroll bars may also be used in conjunction with a picture image to provide the effect of panning or zooming.

Timers (invisible during runtime) may be used where the user is allowed a limited time to make a selection. (Assessment software)

Objects can be placed on forms by: Selecting the object, clicking the left mouse button at one point on the

form, dragging the mouse and releasing the mouse button. Double clicking the control (again Control appears at centre of form). It

may then be repositioned by the user.

VBA S Dalton 2010 2

Page 3: microsoft Visual Basic 3.0 - Institute Of Technology, Sligostaffweb.itsligo.ie/staff/sdalton/VB/VB2010.doc  · Web viewVisual Basic Programming ... which is based on the programming

Object PropertiesAll controls have a wide range of properties. The properties available depend on the control type selected. An objects properties can be displayed by simply selecting the object. This will cause the properties to be displayed on the bottom left.

Changing and objects propertiesProperties may be changed at ‘design time’ or ‘run time’.

At design time properties are set using the properties dialogue box. Some properties are only on or off while other may have several values. Where properties are off the property can be specified as either true/false or 1/0.

Properties may also be changed at run time, (while the program is running). Properties are change at run time by specifying:

The object name, The property and The value

e.g. textbox1.text = "Hello"Typical properties include:

Caption the name displayed on a button Name the name by which the object is referred to in

programming Enabled determines if the usable or greyed out

EventsVisual Basic Programs are driven by event. Typical events include.

Click the pressing and releasing of the mouse button mousedown the pressing down of the mouse button mousemove the moving of the mouse button over the object. Change When the contents of a text box change.

When any of these events occur then the code associated with this event (if there is any) will be executed.

To program a particular event.Double click on the object concerned.From the procedure list select the required event to which the code is required to respond. Write the necessary code between sub and end sub.

The first line of a particular procedure looks something like this.

The first word represents the name of the object. The second word represents the event which causes the code to run.

Getting input and presenting output

VBA S Dalton 2010 3

Page 4: microsoft Visual Basic 3.0 - Institute Of Technology, Sligostaffweb.itsligo.ie/staff/sdalton/VB/VB2010.doc  · Web viewVisual Basic Programming ... which is based on the programming

In order to perform calculations the computers must receive input from the user. When these calculations are complete the computer must present the results of these calculations back to the user.

Consider a simple example of calculating the area of a circle. The radius value is obtained from the user. The value is assigned to a variable. The variable is used to perform the calculation. The answer is presented to the user.

Methods of setting the radius value are as follows:-1. r = 2002. r = val(textbox1.text)3. r = inputbox("Please enter Radius")

Method 1: This is an example of an assignment statement however because this is written into the program it does not allow the user to change the at run time.Method 2: The program obtains the radius value by accessing the contents of a text box on the form.Method 3: If alternately the program developer my wish to prompt the user to enter a value, this can be done by presenting the user a dialog box requesting the information required.

Now that the computer knows the radius value it can perform the calculation. a = 3.14 * r ^ 2

Now that the answer is known it can be presented to the user. Again this can be done in a number of ways as follows.

textbox2.text = a msgbox = a

Method 1: puts the result into a textbox on the formMethod 2: presents the result in a message-box.

VBA S Dalton 2010 4

Page 5: microsoft Visual Basic 3.0 - Institute Of Technology, Sligostaffweb.itsligo.ie/staff/sdalton/VB/VB2010.doc  · Web viewVisual Basic Programming ... which is based on the programming

StatementsThese are words that perform simple actions. e.g. Let, For, while, next.Msgbox etc.

Msgbox “Hello”

FunctionsThese take, number, text and other data, perform an operation and returns a value which can in turn be used by the program. For example to obtain input from the user:

name = Inputbox (“Please enter your name”)The response to this command generates an output, which is assigned to a variable.

MethodsMethods perform actions on particular objects:-

text1.Text = "ABC" add text to a textbox ‘text1’Picture1.Circle (500, 500), 250 draws a circle in ‘picture1’

Attaching code to objectsCode is attached to objects by double clicking on them. This brings up a code window for that object. All lines of code are entered between the lines Sub and End sub. The subroutine name has two part separated by an underscore.

The first part is the name of the object (e.g. Command1)The second part is the procedure (or action) which causes it to execute.

Code can be written for any procedure (or action) available in the list.

The syntaxVisual basic commands must be written according a predefined syntax.

[object.]Line [[Step](x1, y1)] - [Step](x2, y2) [,[color][,B[F]]]VB help can be used to find more information on command syntax.

Items in square brackets are optional.

As you type Visual Basic will also prompt you with a list of available options.

The visual basic editor checks each line as you type. This is called Syntax Checking. Words that are recognized as visual basic commands turn ‘Blue’.

Variables

VBA S Dalton 2010 5

Page 6: microsoft Visual Basic 3.0 - Institute Of Technology, Sligostaffweb.itsligo.ie/staff/sdalton/VB/VB2010.doc  · Web viewVisual Basic Programming ... which is based on the programming

A variable is a combination of letters (and numbers used to store values). Different variable types are used depending on the type of data to be stored.

Variable may be declared (optional) using the Dim statement follow by followed by variable name and type.

Dim value as integerThis has the effect of allocating a particular amount of memory to that variable.Integer 2 bytes -32,768 to +32,767 216 = 65,538Long (long integer)

4 bytes -2,147,483,648 to 2,147,483,647

232 = 4,294,967,296+- 2 billion

Single (prec. floating-point)

4 bytes FP Number with 7 digit accuracy

Double (prec floating-point)

8 bytes FP Number with 15 digit accuracy

String 1 byte per char.

256 possibilities(see ascii table)

text up to 65,000 characters

A variant is a type of variable, which adapts to any data type

CommentsComments are added to a program to make it easier to follow. Comments are preceded by Rem or a “ ’ “. These lines are ignored by the syntax checker.

Developing simple applicationsThe simplest objects available to the user are. Command buttons allow a user to select one of a limited number of

options, e.g. OK and cancel. Labels are used for headings only i.e. something which does not change

during the running of a program. Text boxes are capable of receiving input from and displaying information

to the user while the program is running.

Presenting information to the userThere are a number of methods of presenting information to the user e.g. print, textbox, msgbox. Write a simple program called greeting.

In the program you will create a button called greeting then after double clicking on the button enter Print “Hello” between Sub and End sub and run the program. This causes the message to be printed in the form background.

A better way to get the users attention is the users’ attention is for the message to appear in a message box. Replace print with

Msgbox “Hello”This causes a message box to appear into which the user must enter a value.

It is also possible to direct information to a textbox buy changing its text property. Place a text box in the form and change the command to.

text1.text = “Hello”

VBA S Dalton 2010 6

Page 7: microsoft Visual Basic 3.0 - Institute Of Technology, Sligostaffweb.itsligo.ie/staff/sdalton/VB/VB2010.doc  · Web viewVisual Basic Programming ... which is based on the programming

To make the greeting more polite you could add the persons name to the greeting. It is first necessary to obtain the persons name.

person = inputbox(“Please enter your name”)text2.text = “Hello” + person

The value extracted from a text box is a string variable and therefore cannot be used in mathematical operations. To convert the output of a text box to a numeric value use a = val(text1.text)

The if statementBased on the results of a comparison a program can be directed to process different sections of code. Below is syntax for a single response if statement.

If test then statement(s) if trueIf result >= 40 then print "Pass"

N.B. If “print” does not work just direct the outcome to a text box.Textbox1.text = “Pass”

If two possible outcomes must yield a response the syntax is:If test then statement(s) if true else statement(s) if false

If result >= 40 then print "Pass" else print "Fail"

If there are multiple actions then spread over many lines and end with endif. If test then statement(s) if true else statement(s) if false endif

If result >= 40 then print "Pass" print "Congratulations"

else print "Fail"print "Enrol for Repeat"

Endif

If and initial comparison, is followed by another than another etc. elseif is used.

If test then st. if true elseif test then st. if true elseif …else…endifIf result < 40 then

print "Fail" elseif result <55 then

print "Pass"elseif result <70 then

print "Merit"else print "Distinction"

Endif

The outcome of first question can determine the next i.e. Nested if statementsIf gender = "M" then

if age < 18 then title = "Boy" else title = "Man"elseif gender = "F" then

if age < 18 then title = "Girl" else title = "Woman"else title = "Unknown"

VBA S Dalton 2010 7

Page 8: microsoft Visual Basic 3.0 - Institute Of Technology, Sligostaffweb.itsligo.ie/staff/sdalton/VB/VB2010.doc  · Web viewVisual Basic Programming ... which is based on the programming

Program flow control Although the user generally determines what happens by virtue of its event driven mode of operation, all programming languages have facilities to enable them to make decisions of their own which effect the program operation.

Comparision operatorsComparision operators compare two values.

= Equal to< Less than<= Less than or equal to<> Less than or greater than but not equal to>= Greater than or equal to> Greater than

Having made the comparison the program makes a decision based on whether of result of the comparison is true(1) or False(0).

Logical operatorsLogical operators can be used to test a number of conditions then based on the combined result govern the program flow. If A and B are the results of two comparison operations then if conditions A and B are required to be satisfied then AND operation is used. If it is sufficient that either A or B is satisfied then the OR operation is used.

AND True if both are trueOR True if either is trueNOT Reverses the resultXOR True if one or other is true but not bothEQU True if both are true of both are false

ExampleA B A AND B A OR B A XOR B0 0 0 0 00 1 0 1 11 0 0 1 11 1 1 1 0

Examplesif gender = "M" or gender = "m" then gender = "Male"if gender = "M" and age > 16 then agebracket = "Adult"

VBA S Dalton 2010 8

Page 9: microsoft Visual Basic 3.0 - Institute Of Technology, Sligostaffweb.itsligo.ie/staff/sdalton/VB/VB2010.doc  · Web viewVisual Basic Programming ... which is based on the programming

Branching using Select Case statementSelect Case provides a convenient alternative to multiple if statement

Percentage = [user input]Select case percent

Case Is < 40result = "Fail"

Case Is < 55result = "Pass"

Case Is < 70result = "Merit"

Case Elseresult = "Distinction"

End select[output] = result

Optype = [user input]Select case optype

Case "+"Z = X + Y

Case "-"Z = X - Y

Case "*"Z = X * Y

Case "/"Z = X / Y

End selectprint Z

Strings Vs Numerical ValuesYou must be careful distinguish between string data and numeric data. For example, the string "25" is not equivalent to the value, 13. If a number is to be used in a sentence it must be converted into a string. The double quotations are used to show that the "25" is a string. Adding strings simple joint to portions of a sentence. “My age is”+”25” = “My age is 25” or “20”+”10” = “2010”.

Where it required to extract the numerical value from a string, the Val command is used: e.g. To change "13" into 13 as in Val("13") = 13. Similarly, the numerical value, 14, can be change to a string by Str(14) = "14". This is useful for inserting a persons age into a sentence where the age was initially a numeric value "Pat Murphy is " + str(age) + "years old."

Mathematical OperationsVisual basic has all the usual mathematical functions Addition +Subtraction -Multiplication *Division /To the power of ^ 2 ^ 3 = 8

Sin of an angle Sin(angle in radians) Sin(1) = 0.84Cos of an angle Cos(angle in radians) Cos(1) = 0.54Tan of an angle Tan(angle in radians) Tan(1) = 1.56Inverse tan Atn(number) Atn(1) = .79Random number Generates a random number Rnd Square root of a number Sqr(number) sqr(4) = 2Absolute value of a number Abs(n) removes minus Abs(-5.6) = 5.6Integer portion of a number int(n) (removes decimal part) int(52.47) = 52

a = 10 / 5 * 2 is the referred to as an expressions the / and * are referred to as operatorsthe 10, 5 and 2 are called operands (the numbers being operated on)

Order of precedence

VBA S Dalton 2010 9

Page 10: microsoft Visual Basic 3.0 - Institute Of Technology, Sligostaffweb.itsligo.ie/staff/sdalton/VB/VB2010.doc  · Web viewVisual Basic Programming ... which is based on the programming

In mathematical operations certain operations are performed before others. e.g. a = 5 + 2 ^ 3 * (5 - 3) = 21In the above expression the order of operations is:

() Parenthesis ^ To the power of (exponent) operator*/ Multiplication and division operators+- Additions and subtraction

To alter the natural sequence, parenthesis or brackets should be used. 24 / 6 * 2 = 8 (not 2) 24 / (6 * 2) = 2

Use of Mod, \ operatorIf we divide 15 by 4 we get 3.75. Occasionally it is desirable to determine how may times the 4 will go completely in 15 (i.e. 3) and then find the remainder (3).

To determine if one number divides evenly into another it is useful to check if the calculation produces a remainder or not. The Mod operator (sometimes called “the remainder function”) is used to test this. To determine how many times one number divides into another completely we use the \ operator. This returns the integer portion of a division.Examples:

15 / 4 = 3.75 15 \ 4 = 3 4 goes into 15 completely 3 times. 15 Mod 4 = 3    i.e. 15 divided by 4 leaves a remainder of 3

To test for even and odd numbers "any even number" Mod 2 = 0    because any even number

divided by 2 leaves a remainder of 0 "any odd number" Mod 2 = 1    because any odd number

divided by 2 leaves a remainder of 1

Repeating program sectionsBASIC has several ways of repeating program sections. The FOR-NEXT loop, WHILE-WEND loop and the DO-LOOP (DO WHILE and DO UNTIL)

The FOR-NEXT loop is a convenient way to repeat a block of statements a specified number of times. The number of times is determined by a counter which increments each time the section is repeated.

For variable = start_value to end_value [step size]statements…next [variable]

For n = 1 to 4 Print “This is repeat number”, nNext n

The loop repeats the section until the “loop variable” equals the upper limit 4.

Sample outputThis is repeat number 1This is repeat number 2This is repeat number 3 This is repeat number 4

VBA S Dalton 2010 10

Page 11: microsoft Visual Basic 3.0 - Institute Of Technology, Sligostaffweb.itsligo.ie/staff/sdalton/VB/VB2010.doc  · Web viewVisual Basic Programming ... which is based on the programming

If it is required to count in increments other than 1, or to count downward the step modifier is used. E.g.

For n = 1 to 10 step 2: Next n counts 1,3,5,7,9For n = 20 to 15 step –1: Next n counts 20,19,18,17,16,15

WHILE…WEND loopWhere it is not known how many times to repeat a loop but the conditions required to stop the loop is known the while…wend may be used.

While teststatements

Wend

Sample codex = 10While x >= 0 rootx = x ^ .5 Print x, rootx x = x - 1Wend

The while-wend loop will continue to work while the test is true.

DO-LOOP By using a DO LOOP a program can be made to repeat a section indefinitely. E.g.

DOn = n + 1text1.text = n

LOOPThe only way to stop this program is by pressing the CTRL and BREAK keys together or by addition of the EXIT DO the user can exit a DO LOOP at an appropriate time.

DOn = n + 1

if n > 1000 then exit dotext1.text = n

LOOP

DO WHILE or UNTILThe following variations on the DO-LOOP provide better controlWith these the DO-LOOP allows a section of program to be repeated:WHILE a particular condition is true orUNTIL a particular condition is trueThis allows you to exit a loop when you choose.

The DO WHILE loop repeats a program section while a particular condition is true.

A = 0; B = 20DO WHILE A < B

Print A, BA = A + 1B = B – 1.5

LOOP

The DO UNTIL loop repeats a program section until a particular condition becomes true.

A = 0; B = 20DO WHILE A > B

Print A, BA = A + 1B = B – 1.5

LOOP

Arrays An ordinary variable can only store a single value. If it is required to store several values, which have something in common, then an array may be used. An array is essentially a variable, which has several compartments,

VBA S Dalton 2010 11

Page 12: microsoft Visual Basic 3.0 - Institute Of Technology, Sligostaffweb.itsligo.ie/staff/sdalton/VB/VB2010.doc  · Web viewVisual Basic Programming ... which is based on the programming

each of which is referred to by an index number. Arrays must be declared in the general declarations section e.g.

1 2 3 4 545 32 75 48 52

a(5) is an array which can store 5 values. To store a value in ‘compartment’ 3 use: a(3) = 75

Example In the following example the user is requested to enter 5 numbers. As they are entered each is assigned to array location n.

For n = 1 To 5 results(n) = InputBox("Enter result" + Str(n))Next nFor n = 1 To 5 Print results(n)Next n

Strings and string functionsVisual basic has a variety of tools for working with string variables. A string is a variable, which can store characters. E.g. letters, numbers, or symbols. Numbers stored in string variables cannot be used in calculations unless converted to a ‘value’. To use numbers in a sentence they must be converted to a string.To convert a string to a value Val("13") 13To convert a value to a string Str(14) "14"

ASCII codesInternally, computers work using numbers. It is therefore necessary to know the relationship between the numbers used by the computer and the characters seen on screen. Each symbol or character used in the computer is assigned a code called an ASCII code. It is through the use of this code converted into binary that the computer manipulates it data.

ASCII (American standard code for information interchange) is a special code, which allows 256 letters, numbers and special symbols to be represented in binary. Full ASCII table next page.

VBA S Dalton 2010 12

Page 13: microsoft Visual Basic 3.0 - Institute Of Technology, Sligostaffweb.itsligo.ie/staff/sdalton/VB/VB2010.doc  · Web viewVisual Basic Programming ... which is based on the programming

Standard ASCII Chart

VBA S Dalton 2010 13

Page 14: microsoft Visual Basic 3.0 - Institute Of Technology, Sligostaffweb.itsligo.ie/staff/sdalton/VB/VB2010.doc  · Web viewVisual Basic Programming ... which is based on the programming

Extended ASCII Chart

To determine the ASCII code for a character Print ASC(“A”)Print ASC("a")

6597

To determine the character for an ASCII code Print CHR$(77) MTo determine the length of a string LEN("ABCDE") 5To convert a string to uppercase UCASE("Abc") "ABC"To convert a string to lowercase LCASE("Abc" "abc"

VBA S Dalton 2010 14

Page 15: microsoft Visual Basic 3.0 - Institute Of Technology, Sligostaffweb.itsligo.ie/staff/sdalton/VB/VB2010.doc  · Web viewVisual Basic Programming ... which is based on the programming

String manipulationStrings can contain a large number of characters. It is often required to locate or extract portions of a string to assign to another variable. A$ = “ABCEFGHIGJKLMNOPQRSTUVWXYZ”

To determine the length of a string LEN(A$) 26To determine the first 4 characters of a string LEFT$(A$, 4) "ABCD"To determine the last 3 characters of a string RIGHT$(A$,3) "XYZ"To extract characters 10 to 15. MID$(A$, 10, 5) "JKLMN"To determine the location of a character INSTR(1, A$, “M”) 13

Any of the results of the above queries can be printed or assigned to a variable for subsequent manipulation.

print LEFT$(A$, 6): B$ = LEFT$(A$, 6)

Concatenation There is often requirement to join strings together. e.g.

a$ = "ABC" b$ = "DEF"To concatenate (join) strings c$ = A$ + B$ "ABCDEF"To insert spaces to joined strings

c$ = A$ + space$(3)+ B$ "ABC DEF"

To insert a number into a string c$ = A$ + str$(5)+ B$ "ABC5DEF"

String processingWhen data is transmitted by computers, it is transmitted as a long series of ASCII characters. As far as the computer is concerned it sees no difference between letters of the alphabet, numbers or symbols. For example a measuring device may return the following coordinates:

X56.345Y35.345

In order to extract the numeric value of the two coordinates you would need to: Write a loop to analyze each character one by one. Distinguish between letters and numbers (depending on ascii value) Group the number characters together as a string Converting number string into mathematical value

VBA S Dalton 2010 15

Page 16: microsoft Visual Basic 3.0 - Institute Of Technology, Sligostaffweb.itsligo.ie/staff/sdalton/VB/VB2010.doc  · Web viewVisual Basic Programming ... which is based on the programming

Programming checkboxes and option boxes Option boxes are programmed to respond to the click event. This event occurs where the check box is ticked on or off it is therefore necessary to determine the status of the checkbox to determine what action to take. The status of the checkbox is indicated by its value property. E.g.

Sub Check1_Click ()If check1.Value = 1 Then textbox1.text = “on”Else Textbox1.text = “off”End If

End Sub Option boxes works in a similar manner. However while multiple checkboxes can be selected at any one time, only one option box can be active.However where there are groups of option boxes have total independent functions. These can be isolated from each other by enclosing them in frames. This would allow the user to be presented with 2 sets of options e.g. Option A and B & Option X, Y and Z

Scroll barsScroll bars are a convenient method of adjusting a parameter where the precise value is not critical. e.g. a radio volume. To provide a convenient way of adjusting a parameter between two defined limits scroll bars may be used. Scroll bar properties are as follows:Min: The value when the slider is at the top or leftMax: The value when the slider is at the bottom or rightSmall change: Change caused by clicking the arrowLarge change: Change caused by clicking in space beside slider.

The position of the slide determines its value property Value property. The slider setting is obtained by querying its value property e.g.

a = hscroll1.value.

VBA S Dalton 2010 16

Page 17: microsoft Visual Basic 3.0 - Institute Of Technology, Sligostaffweb.itsligo.ie/staff/sdalton/VB/VB2010.doc  · Web viewVisual Basic Programming ... which is based on the programming

Data Storage and retrievalWhile data can be entered into text boxes or input boxes. This is not practical where large amounts of data need to be processed. Where such data is contained in a text file, this can be imported into the program from the text file.Likewise where large amount of data are generated by a program, this can be saved to a text file.Visual basic can handle both sequential and random access files. In a sequential file data is stored sequentially in the order in which it is

written to disc. When reading this data it is also read sequentially. Spreadsheets and word processors use sequential files.

Random access files hold a set of records each of which has and identical structure. If a records position is known it can be read from the file edited and returned to the same place. This eliminates the need to read the entire file. Database applications (Access) use these files.

Opening and closing filesThe open statement is used to access files on disc. When opening files each file, which is opened is assigned a unique number (e.g. #1). The format of the open statement is as follows:

Open filename for mode as #filenumberExample: Open “data.txt” for input as #1

The filename is a string expression or variable: The modes are:

Input, to read from an existing file Output, to create a new file (replaces any file with the same name) Append, to add data to the end of an existing file.

All actions refer to the filenumber rather than the filename. Each file open has a unique number assigned to it. E.g. #1, #2, etc

When work on the file is completed, it must be closed using.Close #filename e.g.: close #1

Reading and writing dataOnce a file has been opened data can be written to or read from it using the following commands. Print #, write #, input #Any number of items can be written to a file in a single print or write statement. Commas are used to separate each item.

Write #: The write statement writes data in a standard comma separated format. This is sometimes referred to as comma deliminated format.

write #1, A,B,C produces 32,24,57Print #: The print statement allows greater control over the file layout by allowing a number of spaces or tabs between each item. This allows better control of the layout of the file content making it more presentable for printing. Files containing numbers separated by spaces are spaces are sometimes referred to as space deliminated.

print #1, tab(2), A, tab(3), B, tab(4), C gives 32 24 57

Input #

VBA S Dalton 2010 17

Page 18: microsoft Visual Basic 3.0 - Institute Of Technology, Sligostaffweb.itsligo.ie/staff/sdalton/VB/VB2010.doc  · Web viewVisual Basic Programming ... which is based on the programming

Data can be read back for the file using: Input #filenumber, variables

The variables must be of the right type and in the right order to match the data file, and the data items in the file must be separated by commas (i.e. it is easier to read numbers from a comma deliminated file). E.g.

Input #1, X, Y, Zwould assign the first three numbers in a file to variables X, Y and Z:

X= 32, Y = 24, Z=57

Deleting filesTo delete files from within a Visual basic program use the kill instruction

Kill 'data.txt'This permanently deletes the file and does not add it to the recycle bin.

Data Storage and retrieval TutorialThe following program demonstrates the sequence of writing numbers too and then reading numbers from a file. Finally the file is deleted. First create 3 buttons: Write, Read and Delete

Code for write button The following code generates a number sequence and saves it to textfile called ‘data.txt’

Sub Write_Click ()Open "d:\data.txt" For Output As #1For n = 1 To 100 Step 5 Print #1, nNext nClose #1

End Sub

Code for read button The following codes read the number from the text file

Sub Read_Click ()Open "d:\data.txt" For Input As #1Do While Not EOF(1) Input #1, x Text1.text = xLoopClose #1

End Sub

N.B. The do-while loop is convenient for reading the file, as it is not possible to know the length of the file. Instead the computer continues to read each line in the file until the EOF (end of file character) is reached and then stops.

Code for Remove button The following code deletes the selected fileSub Remove_Click ()

Kill "d:\data.txt" End Sub

VBA S Dalton 2010 18

Page 19: microsoft Visual Basic 3.0 - Institute Of Technology, Sligostaffweb.itsligo.ie/staff/sdalton/VB/VB2010.doc  · Web viewVisual Basic Programming ... which is based on the programming

Errors and Error DetectionThere are two categories of error Syntax errors are mistakes in the use of the language such as misspelling

the command or a missing bracket, or supplying the wrong type of data. Logical errors are errors in the how a program is structured. Although a

program may run it does not produce the desired results because the logic in the program does not correctly reflect what it is required to do.

Errors may be detected at design time, compile time or run time.At design time each line is checked when the user presses return. If the syntax is wrong an error is reported. If correct, reserved words turn blue.Some errors are not identifiable by looking at a single line. Some structures cover a number of lines e.g. For-Next, If-then-else. When running a program VB performs a process called compiling in which it checks the validity of the program as a whole. Run time errors occur while the program is running causing it to crash unexpectedly during normal operation.

Tips on debuggingDebugging is the process of solving problems in a program. The standard approach to running a program is

Run Start (F5)

A program also be run one line at a time using Debug Single step (F8)

It is possible to run (F5) a program up to a certain point, then to step though line by line (F8) from that point onwards. This is achieved by adding a break point

Debug Toggle breakpoint (F9)Simply place the cursor on the line of interest then select F9 causing the line to turn dark red. The program stops automatically at this line.

When debugging, it is possible to find the values of variables as the program progresses. This is achieved by activating the debug window.

Window Debug (Ctrl+B)

There are two methods of checking the value of a variable in the debug window. i.e. by using the immediate window or by adding watches.

To check the value of a variable once; simply type print and the variable name in the immediate or lower portion of the debug window. e.g. Print a. Will show you the current value of variable a.

To monitor a variable continuously; a ‘watch’ may be added to display of a particular variable continuously. Debug Add watch. This will cause the value of a variable to be displayed continuously in the debug window.

VBA S Dalton 2010 19

Page 20: microsoft Visual Basic 3.0 - Institute Of Technology, Sligostaffweb.itsligo.ie/staff/sdalton/VB/VB2010.doc  · Web viewVisual Basic Programming ... which is based on the programming

Sample debug windows

Dialog Box OptionsExpression: The variable to be monitored. Context:

Procedure: Variable is only monitor while in the selected procedure. Form/Module or Global: The variable is monitored constantly.

Error trapping There are situations where a program can crash by attempting to perform an invalid operation. Typical examples are: Trying to perform a calculation on a string variable. Dividing by Zero: Computers cannot handle infinity as an answer. Trying to access files which do not exist, 'file not found', 'drive not ready' etc.

The following are typical errors.a = "Hello"b = 2 * a

Division by Zero

a = 5: b = 0c = a / b

Error trapping allows us to detect such errors and take appropriate action.

We can identify errors by using ‘On Error’ program we can begin to trap the error by adding the following lines: On error goto label: at the beginning of the

procedure Exit sub: after the section of regular

programming label: The heading for the section where the

error handling takes place.

Sub Command1_Click () On Error GoTo errortrap a = 10 b = 0 c = a / bExit Sub

errortrap:Print Err, ErrorResume NextEnd Sub

In this simple example above line 1 instructs the program that should an error occur, to proceed to the section called errortrap. In this case the program simply prints the error, (Print err prints the error code while print error prints the error message.) then returns to the next line using Resume next. Resume returns to the same line having taken corrective action resume next returns to the next line bypassing the error altogether N.B. Select Case is useful for processing trapped errors of different types

VBA S Dalton 2010 20

Page 21: microsoft Visual Basic 3.0 - Institute Of Technology, Sligostaffweb.itsligo.ie/staff/sdalton/VB/VB2010.doc  · Web viewVisual Basic Programming ... which is based on the programming

Data representationIn order to be able to process information or data, or to communicate with external devices, all types of computer data must be represented in binary form. Generally we work to the base 10. This means that we have 10 digits with which we can use to represent a number. i.e. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9In decimal we interpret the following number 3256 as

3 2 5 6103 102 101 10 Number base1000s 100s 10s Units Position value3000 200 50 6 3256

A computer can only work with 1s and 0s. For this reason internally the computer works in binary. The binary system uses only 2 digits, 0 and 1. The binary number 101011 in decimal is.

1 0 1 0 1 125 24 23 22 21 20 Number base32 16 8 4 2 1 Position value32 0 8 0 2 1 43

i.e. (1 x 32) + (1 x 8) + (1 x 2) + (1 x 1) = 43

Each digit in a binary number is referred to as a Bit (i.e. Binary DigIT). A byte is a collection of 8 binary bits. A byte is the amount of storage space necessary to store a single letter or number (ascii character).

Converting from decimal to binary is achieved as shown opposite: e.g. 163 becomes 10100011.

A kilobyte is 1,000 bytes. A megabyte is 1,000,000 bytes. A Gigabyte is 1,000,000,000 bytes.

Answer: 10100011

Binary coded decimalRather than representing a decimal number by a single binary number, an alternative approach is to represent each character by a binary number.In the binary coded decimal system (BCD) each digit in a decimal number is given its own binary number. For example the number 943 can be represented as:

1110101111by converting the entire number into a single binary number.Alternatively using the BCD system it can be represented by representing each character using 4 bits each.

9 4 31001 0100 0011

If however only 4 bits are used to represent each character then only 16 possible characters may be represented. If however 8 bits are used per character then 256 possible characters may be represented. This allows letters numbers and special characters to be represented.

Serial/Parallel data transmission

VBA S Dalton 2010 21

Page 22: microsoft Visual Basic 3.0 - Institute Of Technology, Sligostaffweb.itsligo.ie/staff/sdalton/VB/VB2010.doc  · Web viewVisual Basic Programming ... which is based on the programming

Data transmission can take place using either serial or parallel transmission.

Parallel data transmission occurs through the parallel port and through a parallel cable (like a printer cable). A parallel cable uses 8 wires, one for each bit. This achieves very fast communication speeds.

Serial communication achieves data communication using a single wire by sending one bit at a time. Although slower this form of data transmission can take place over longer distances and through existing telephone networks.

RS232 An american standard known as RS232 defines the parameters for serial data transmission.For successful communication a number of parameters must be specified. The baud rate determines the transmission speed in bits per second. Typical baud rates are:- 1200, 2400, 4800, 9600, 19200 etcThe parity type During data communication only seven bits are used to represent the character. The 8th bit is used as a parity bit. The parity bit is a checking device, which is used to determine whether or not the character has been transmitted correctly. The parity bit is set to 1 or 0 so that the total number of 1’s in a transmitted byte of data is even in even parity or odd in odd parity. If the receiving device detects break from the parity type expected it interprets this as an error in communication.The parity type may be odd (O), even (E) or none (N) where no parity checking is performed.

Reading Data from Serial PortUsing older forms of Basic sending data to and reading data from the communications port was achieved using a command similar to the open file command for reading from and sending data too the port: I.e.

OPEN “Com1:9600,E,7,1” FOR RANDOM AS #1Where the filename is replaced with the communications port and the communications parameters.

Port number = Com1 Baud rate = 9600 Parity = even Bits transmitted = 7

Random is used to allow two-way communication.

Reading Data from the Serial Port using Visual BasicTo read data from or send data to the communications port, Visual Basic uses a dedicated ‘object’ called MScomm. MScomm is a communications control tool, which provides serial communications for an application by allowing transmission and reception of data through the serial communications port of the computer. When data is received the ‘Oncomm’ event is generated. The occurrence of this even causes the software to process the data it has received.

A number of properties must be set for the object to ensure reliable communication. These properties are set during start up of the software. Typical settings are shown below:-

VBA S Dalton 2010 22

Page 23: microsoft Visual Basic 3.0 - Institute Of Technology, Sligostaffweb.itsligo.ie/staff/sdalton/VB/VB2010.doc  · Web viewVisual Basic Programming ... which is based on the programming

comm.CommPort = 1comm.Settings = "1200,N,8,1"comm.InputLen = 0comm.PortOpen = Truecomm.RThreshold = 26

Commport identifies which communications port to use. Settings sets the baud rate, parity, parameters, for the communication. Portopen is used to open the communications port for the receipt of data. Rthreshold indicates how many characters must be received at the input buffer before the ‘oncomm’ event is generated. InputLen indicates how many characters to read from the input buffer at a time. If set to zero, all characters in the buffer are read.

The following command is used to take the data received and assign it to a variable.

i = comm2.InputIf the position of the data required within the string of characters received is known (extraction of X and Y coordinates from a measuring device) then these can be extracted from the string of input data as follows.

X$ = Mid$(I$, 4, 9)Y$ = Mid$(I$, 17, 9)

Alternately the characters must be analysed 1 by 1. as in the recent exercise.

VBA S Dalton 2010 23

Page 24: microsoft Visual Basic 3.0 - Institute Of Technology, Sligostaffweb.itsligo.ie/staff/sdalton/VB/VB2010.doc  · Web viewVisual Basic Programming ... which is based on the programming

Menu Design (seems not to be available in VBA) The menu design tool is accessed by selecting Window Menu Design

Or Ctrl + MThe ‘caption’ governs the word, which will actually appear in the menu. ‘Name’ determines the name of the associated sub routine. This may not necessarily be the same as the caption. To distinguish the object from other objects it is usual to letter MNU to distinguish menu options from other objects.

Shortcuts may be used for commonly used commands. E.g. Ctrl+S to save.

Each additional item is added by selecting:- ‘Next’ if is to follow the currently select item ‘Insert’ if it is to precede the selected item.

Items may be removed by selecting ‘delete’.

Having created the menu options they can be rearranged as required using the arrow buttons. The Up/Down arrows allow the selected item to be moved up and down through the menu. The left right buttons allow an item to be moved from menu to sub menu level.

There are two methods of accessing a menu opting quickly without using the mouse. This is by: Alt + the underlined letter. e.g. File Exit is Alt + F + xTo place an underscore under a particular place '&' symbol before it. The second method is to define a short cut. Ctrl + C for Copy.

Adding Code to a menu itemCode can be added to a menu option in the exact same way as to a button. Simply choose the menu option at design time (while your program is not running) and you will be presented with a code window beginning and ending with the usual Sub and End Sub. The object name is determined by what was entered in the name box during menu design time.

VBA S Dalton 2010 24

Page 25: microsoft Visual Basic 3.0 - Institute Of Technology, Sligostaffweb.itsligo.ie/staff/sdalton/VB/VB2010.doc  · Web viewVisual Basic Programming ... which is based on the programming

Computer Graphics There two are fundamental methods for representing graphics images.

Raster and Vector

Raster FormatsA raster format breaks an image into a grid of equally sized pieces, called "pixels", and records colour information for each pixel. The number of colours that the file can contain is determined by the bits-per-pixel: the more information that is recorded for each pixel, the more shades or colours that the image file can contain. E.g Microsoft paint files. Vector FormatsVector image formats contain vector information. Vector information is a collection of geometric shapes that combine to make an image. The information is recorded as mathematical formulas. Vector data cannot reproduce photo-realistic images, but have the advantage that the lines can be manipulated and modified easily. E.g. An AutoCAD drawing.

Displaying Computer Grahpics The graphics capability of your computer depends on the amount of graphics memory on your graphics card. Two issues effect the amount of graphics memory required.

Resolution (Grahics mode) Colour depth

ResolutionResolution is term used to describe how many dots or ‘pixels’ are used on your display. If your image has a resolution of 1000x500 then there are 1000 pixels across and 500 pixels down. Higher resolution images have more pixels along the horizontal and vertical axis and can show more detail than a "low-resolution" image. Most screens on IBM compatible PC's have displays of 640x480 pixels, while at the upper end screens can display images as large as 1600x1280. The following are typical resolutions available.

640 x 480, 800 x 600, 1024 x 768, 1280 x 1024, 1600 x 1200

Colour depthColour depth refers to the variety of colours, which can be displayed.

Greyscale, 16 colour, 256 colour, 65,536 colour (high colour)16.7 million colour (true colour)

The level of colour available depends on the amount of graphics memory allocated to each screen pixel or dot. The number of combinations of 1’s and 0’s for the amount of memory allocated to a pixel determines the number of colours, which a pixel can represent. e.g. 1 byte per pixel (or 8 bits) allows 256 possible compinations of 1’s and 0’s and therefore 256 possible colours.

Number of combinations = 28 = 256 i.e. 256 colours/shades

It follows therefore that

VBA S Dalton 2010 25

Page 26: microsoft Visual Basic 3.0 - Institute Of Technology, Sligostaffweb.itsligo.ie/staff/sdalton/VB/VB2010.doc  · Web viewVisual Basic Programming ... which is based on the programming

1/2 a byte per pixel produces 24 = 16 colours 16 colour mode1 byte per pixel produces 28 = 256 colours 256 colour mode2 bytes per pixel produces 216 = 65,536 colours 65,536 colour mode3 bytes per pixel produces 224 = 16,777,216 colours true colour mode

The total amount of graphics memory required in each mode at 1024*768 is:Color mode Bytes Bits Width Height Num.

PixelRAM

16 0.5 4 1024 768 786432 393216256 1 8 1024 768 786432 786432

65536 2 16 1024 768 786432 157286416777216 3 24 1024 768 786432 2359296

Procedure: Determine the resolution Determine the colour level required. Determine the number of bytes per pixel for the required colour level. Multiply the number of bytes per pixel by the total number of pixels.

ExampleDetermine the amount of graphics memory required to display a 640 by 480 image at 256 colours. Resolution 640 x 480 Colour depth 256 Bytes per pixel needed 1 Total memory (640 x 480) x 1 = 307200 or 307K

Graphics in Visual BasicGraphics in Visual basic can be of two sorts. Images inserted from files Images drawing using graphical shapes.

(Does not apply to VBA as it does not have the Picturebox object)

Loading images form files1. picture1.picture = LoadPicture("d:\image.bmp")2. picture1.picture = LoadPicture()The first instruction loads an image and places it in a picture box. The second instruction is used to clear the image.

Drawing using graphical shapesPset, line and circle commands may be used to draw graphical shapes in a variety of colours, thicknesses etc. You can only draw on a form, a picture box or a printer object.

The scale property

VBA S Dalton 2010 26

Page 27: microsoft Visual Basic 3.0 - Institute Of Technology, Sligostaffweb.itsligo.ie/staff/sdalton/VB/VB2010.doc  · Web viewVisual Basic Programming ... which is based on the programming

When drawing in a picture box you will notice that the 0,0 point is at the top left hand corner, with the Yaxis pointing downwards. This can be rectified by using the scale command. The scale command operates by setting the co-ordinate represented by the top left corner and the lower right. The scale command allows the axis lengths and directions to be defined.

Picture1.scale (0,0)-(400,300)This command calibrates the picturebox so that the 0,0 position is in the top-left corner and the horizontal and vertical edges represent 400 and 300 units respectively.

Picture1.scale (0,300)-(400,0). This command set the axis direction to point in the more conventional direction.

Picture1.scale (-200,-150)-(200,150)This allows the origin to relocated: i.e. to the centre of the picturebox.

The scale is independent of the actual dimensions of the picturebox. When representing geometry it is important to calibrate the picturebox so that the horizontal and vertical units are the same (this is to avoid distorting the images).

The picturebox can be calibrated at either design time or at run time. If the scale is to remain fixed then it can be set at design time using the properties box and the properties:

ScaleLeft, Scaletop, ScaleHeight, Scale WidthIf however it is required to change these parameters during the operation of the program (e.g. if you were writing a CAD program and you wanted to zoom pan and zoom) then you would need to incorporate the instruction into your programs so that you can change the scale during program operation.

Drawing methodsThere are 3 main drawing methods, pset, line, circle. These can be used in a variety of ways to produce different results.

Pset Method [object].pset (x,y),[colour]The pset method plots a single point at a location (x,y). [Object] is the name of the VB object on which the points are plotted. This is limited to the form, a picture box or a printer object. Colour (optional determines the colour of the dot (default black). The follow generates a single random dot in a picture box each time the command is executed.

picture1.PSet (Rnd * 100, Rnd * 80)A spray of dots can be created by containing it within a For next loop.

Line Method Draws a line on the designated object. [object].Line [step] [(xstart, ystart)] - [step] (xend,yend), [colour],BF

VBA S Dalton 2010 27

Page 28: microsoft Visual Basic 3.0 - Institute Of Technology, Sligostaffweb.itsligo.ie/staff/sdalton/VB/VB2010.doc  · Web viewVisual Basic Programming ... which is based on the programming

The step option causes points to be relative to the previous point. Otherwise co-ordinates will be absolute. The colour option determines the colour of the line and can be defined using the Qbcolour option or the RGB optoin.B stands for block and will produce a rectangle.F stands for fill and will cause the rectangle be shaded in.

Circle Method[object].Circle (x, y), radius, [colour, start, end, aspect]Only (x, y), radius are essential. Start and end are used to create and arc and refer to the angles expressed in radians. Aspect is used to create an ellipse.

Visual Basic ColourTwo method are available to determine the colour of abject in Visual Basic. Qbcolor(x): This allow select one of 16 colours using a number from 0 to

15. RGB(x,y,z): Allows the colour to be set by determining the values of the

RGB components. each of which can be adjusted between 0 and 255. This gives total of 16.7 million colours.

Shown below are the 15 main colour and their equivalent RGB values

QBcolor Colour Red, Green, Blue0 Black 0,0,01 Blue 128,0,02 Green 0,128,03 Cyan 128,128,04 Red 0,0,1285 Magenta 128,0,1286 Brown 0,128,1287 White 128,128,1288 Grey 128,128,1289 Light Blue 255,0,010 Light Green 0,255,011 Light Cyan 255,255,012 Light Red 0,0,25513 Light Magenta 255,0,25514 Yellow 0,255,25515 Bright White 255,255,255

VBA S Dalton 2010 28