Microsoft Visual Basic 3.0
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.
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.
Visual Basic objects (the toolbox)
The toolbox contains the building blocks necessary to assemble a visual basic program.
[pic] The pointer (not an object itself) is used to move and resize controls once inserted on the form.
[pic] Command buttons allow a user to select one of a limited number of options, e.g. OK and cancel.
[pic] A picture box is used to insert images (BMP etc) like a company logo.
[pic] Labels are used for headings only i.e. does not change during the running of a program.
[pic] Text boxes are capable of receiving input from and displaying information to the user while the program is running.
[pic] Check boxes provide a means to toggle settings on/off. (object snaps)
[pic] Option boxes allow selection of only one option (e.g units display in AutoCAD, )
[pic] Frames provide a means of grouping controls logically. Where option boxes are in frames, one option can be selected in each.
[pic] List boxes display a list of items from which the user can make a selection. (a file list in an open files dialogue box).
[pic] Combo boxes provides a combination of a data entry box with a drop downlist (e.g. drives section of file open dialogue).
[pic] 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.
[pic] 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.
|Object Properties |[pic] |
|All 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 properties
Properties 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
Events
Visual 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. |[pic] |
|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. | |
|[pic] | |
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
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 = 200
2. 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 form
Method 2: presents the result in a message-box.
Statements
These are words that perform simple actions. e.g. Let, For, while, next.
Msgbox etc.
Msgbox “Hello”
Functions
These 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.
Methods
Methods 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 objects
Code 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 syntax
Visual 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.
[pic]
Items in square brackets are optional.
| |[pic] |
|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
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 integer
This has the effect of allocating a particular amount of memory to that variable.
|Integer |2 bytes |-32,768 to +32,767 |216 = 65,538 |
|Long |4 bytes |-2,147,483,648 to 2,147,483,647 |232 = 4,294,967,296 |
|(long integer) | | |+- 2 billion |
|Single (prec. |4 bytes | |FP Number with |
|floating-point) | | |7 digit accuracy |
|Double (prec |8 bytes | |FP Number with |
|floating-point) | | |15 digit accuracy |
|String |1 byte |256 possibilities |text up to 65,000 characters |
| |per char. |(see ascii table) | |
A variant is a type of variable, which adapts to any data type
Comments
Comments 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 applications
The 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 user
There 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”
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 statement
Based 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 true
If 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…endif
If result < 40 then
print "Fail"
elseif result 16 then agebracket = "Adult"
Branching using Select Case statement
Select Case provides a convenient alternative to multiple if statement
|Percentage = [user input] |Optype = [user input] |
|Select case percent |Select case optype |
|Case Is < 40 |Case "+" |
|result = "Fail" |Z = X + Y |
|Case Is < 55 |Case "-" |
|result = "Pass" |Z = X - Y |
|Case Is < 70 |Case "*" |
|result = "Merit" |Z = X * Y |
|Case Else |Case "/" |
|result = "Distinction" |Z = X / Y |
|End select |End select |
|[output] = result |print Z |
Strings Vs Numerical Values
You 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 Operations
Visual 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.84 |
|Cos of an angle |Cos(angle in radians) |Cos(1) = 0.54 |
|Tan of an angle |Tan(angle in radians) |Tan(1) = 1.56 |
|Inverse tan |Atn(number) |Atn(1) = .79 |
|Random number |Generates a random number |Rnd |
|Square root of a number |Sqr(number) |sqr(4) = 2 |
|Absolute value of a number |Abs(n) removes minus |Abs(-5.6) = 5.6 |
|Integer 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 operators
the 10, 5 and 2 are called operands (the numbers being operated on)
Order of precedence
In mathematical operations certain operations are performed before others. e.g. a = 5 + 2 ^ 3 * (5 - 3) = 21
In 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, \ operator
If 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 sections
BASIC 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 |Sample output |
|Print “This is repeat number”, n |This is repeat number 1 |
|Next n |This is repeat number 2 |
|The loop repeats the section until the “loop variable” equals the upper limit 4. |This is repeat number 3 |
| |This is repeat number 4 |
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,9
For n = 20 to 15 step –1: Next n counts 20,19,18,17,16,15
WHILE…WEND loop
|Where it is not known how many times to repeat a loop but the conditions required to stop the |Sample code |
|loop is known the while…wend may be used. |x = 10 |
|While test |While x >= 0 |
|statements |rootx = x ^ .5 |
|Wend |Print x, rootx |
| |x = x - 1 |
| |Wend |
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.
DO
n = n + 1
text1.text = n
LOOP
The 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.
DO
n = n + 1
if n > 1000 then exit do
text1.text = n
LOOP
DO WHILE or UNTIL
The following variations on the DO-LOOP provide better control
With these the DO-LOOP allows a section of program to be repeated:
WHILE a particular condition is true or
UNTIL a particular condition is true
This allows you to exit a loop when you choose.
|The DO WHILE loop repeats a program section while a |The DO UNTIL loop repeats a program section until a particular |
|particular condition is true. |condition becomes true. |
|A = 0; B = 20 |A = 0; B = 20 |
|DO WHILE A < B |DO WHILE A > B |
|Print A, B |Print A, B |
|A = A + 1 |A = A + 1 |
|B = B – 1.5 |B = B – 1.5 |
|LOOP |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, each of which is referred to by an index number. Arrays must be declared in the general declarations section e.g.
|[pic] |[pic] |
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|For n = 1 To 5 |
|5 numbers. As they are entered each is assigned to array |results(n) = InputBox("Enter result" + Str(n)) |
|location n. |Next n |
| |For n = 1 To 5 |
| |Print results(n) |
| |Next n |
Strings and string functions
Visual 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") |13 |
|To convert a value to a string |Str(14) |"14" |
ASCII codes
|Internally, computers work using numbers. It is therefore |[pic] |
|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.
Standard ASCII Chart
[pic]
Extended ASCII Chart
[pic]
|To determine the ASCII code for a character |Print ASC(“A”) |65 |
| |Print ASC("a") |97 |
|To determine the character for an ASCII code |Print CHR$(77) |M |
|To determine the length of a string |LEN("ABCDE") |5 |
|To convert a string to uppercase |UCASE("Abc") |"ABC" |
|To convert a string to lowercase |LCASE("Abc" |"abc" |
String manipulation
Strings 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$) |26 |
|To 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 processing
When 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
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 () |[pic] |
|If check1.Value = 1 Then | |
|textbox1.text = “on” |[pic] |
|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|[pic] |
|time, only one option box can be active. | |
|However where there are groups of option boxes have total independent functions. These can be |[pic] |
|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 bars
|Scroll bars are a convenient method of adjusting a parameter where the precise value is not critical. e.g. a |[pic] |
|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 left | |
|Max: The value when the slider is at the bottom or right | |
|Small change: Change caused by clicking the arrow | |
|Large 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.
Data Storage and retrieval
While 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.
1. 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.
2. 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 files
The 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 #filenumber
Example: 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 data
Once 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,57
Print #: 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 #
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, Z
would assign the first three numbers in a file to variables X, Y and Z:
X= 32, Y = 24, Z=57
Deleting files
To 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 Tutorial
The 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 |Code for read button The following codes read the number from |
|sequence and saves it to textfile called ‘data.txt’ |the text file |
| |Sub Read_Click () |
|Sub Write_Click () |Open "d:\data.txt" For Input As #1 |
|Open "d:\data.txt" For Output As #1 |Do While Not EOF(1) |
|For n = 1 To 100 Step 5 |Input #1, x |
|Print #1, n |Text1.text = x |
|Next n |Loop |
|Close #1 |Close #1 |
|End Sub |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 file
Sub Remove_Click ()
Kill "d:\data.txt"
End Sub
Errors and Error Detection
There 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 debugging
Debugging 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.
Sample debug windows
|[pic] |[pic] |
Dialog Box Options
Expression: 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. |[pic] |
|a = "Hello" | |
|b = 2 * a | |
|Division by Zero | |
|a = 5: b = 0 |[pic] |
|c = a / b | |
|Error trapping allows us to detect such errors and take appropriate action.| |
|We can identify errors by using ‘On Error’ |Sub Command1_Click () |
|program we can begin to trap the error by adding the following lines: |On Error GoTo errortrap |
|On error goto label: at the beginning of the procedure |a = 10 |
|Exit sub: after the section of regular programming |b = 0 |
|label: The heading for the section where the error handling takes place. |c = a / b |
| |Exit Sub |
| | |
| |errortrap: |
| |Print Err, Error |
| |Resume Next |
| |End 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
Data representation
In 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, 9
In decimal we interpret the following number 3256 as
|3 |2 |5 |6 | |
|103 |102 |101 |10 |Number base |
|1000s |100s |10s |Units |Position value |
|3000 |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 |1 | |
|25 |24 |23 |22 |21 |20 |Number base |
|32 |16 |8 |4 |2 |1 |Position value |
|32 |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 |[pic] |
|collection of 8 binary bits. A byte is the amount of storage space necessary to store |Answer: 10100011 |
|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. | |
Binary coded decimal
Rather 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:
1110101111
by 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 3
1001 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
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 etc
The 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 Port
Using 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 #1
Where 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 Basic
To 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:-
mPort = 1
comm.Settings = "1200,N,8,1"
comm.InputLen = 0
comm.PortOpen = True
comm.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.Input
If 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.
Menu Design (seems not to be available in VBA)
|The menu design tool is accessed by selecting |[pic] |
|Window Menu Design | |
|Or Ctrl + M | |
|The ‘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 + x
To 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 item
Code 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.
[pic]
Computer Graphics
There two are fundamental methods for representing graphics images.
Raster and Vector
Raster Formats
A 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 Formats
Vector 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
Resolution
Resolution 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 depth
Colour 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
1/2 a byte per pixel produces 24 = 16 colours 16 colour mode
1 byte per pixel produces 28 = 256 colours 256 colour mode
2 bytes per pixel produces 216 = 65,536 colours 65,536 colour mode
3 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. Pixel |RAM |
|16 |0.5 |4 |1024 |768 |786432 |393216 |
|256 |1 |8 |1024 |768 |786432 |786432 |
|65536 |2 |16 |1024 |768 |786432 |1572864 |
|16777216 |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.
Example
Determine 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 Basic
Graphics 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 files
1. 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 shapes
Pset, 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
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 Width
If 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 methods
There 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
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 Colour
Two 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, Blue |
|0 |Black |0,0,0 |
|1 |Blue |128,0,0 |
|2 |Green |0,128,0 |
|3 |Cyan |128,128,0 |
|4 |Red |0,0,128 |
|5 |Magenta |128,0,128 |
|6 |Brown |0,128,128 |
|7 |White |128,128,128 |
|8 |Grey |128,128,128 |
|9 |Light Blue |255,0,0 |
|10 |Light Green |0,255,0 |
|11 |Light Cyan |255,255,0 |
|12 |Light Red |0,0,255 |
|13 |Light Magenta |255,0,255 |
|14 |Yellow |0,255,255 |
|15 |Bright White |255,255,255 |
-----------------------
1 2 3 4 5
|45 |32 |75 |48 |52 |
[pic]
[pic]
[pic]
[pic]
[pic]
................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.
Related download
Related searches
- visual basic codes for excel
- visual basic for excel examples
- visual basic for beginners excel
- excel visual basic programming examples
- visual basic examples for beginners
- microsoft visual basic for excel
- excel visual basic tutorial pdf
- visual basic for beginners pdf
- microsoft visual basic tutorial pdf
- visual basic programs with codes
- visual basic book pdf download
- visual basic programming for beginners