




















































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Lecture notes for university students
Typology: Lecture notes
1 / 92
This page cannot be seen from the preview
Don't miss anything!





















































































Course content
The Visual Basic 6 environment Defining terms Creating a Visual Basic Project Practice project - Building a Football Scoreboard
Improving the VB application Using a step-by-step approach Writing a VB procedure Calling procedures
Using the Visual Basic 6 code editor Adhering to programming standards Data types, variables and constants in Visual Basic Using operators Control structures - IF...THEN, Select Case, DO...LOOP, FOR...NEXT Practice assignment - Upgrading the Scoreboard
DESIGNING VB APPLICATION
Designing the Visual Basic Application Working with users Guiding principles Choosing a Visual Basic interface style
Defining the Visual Basic Form Standard controls: Picture, Frame, CommandButton, Label, TextBox, CheckBox, etc. Visual Basic practice assignment: Creating a Payroll Form
Arrays More controls: ListBox, ComboBox Properties and Methods of objects in Visual Basic Building a file search application: DriveListBox, DirListBox, FileListBox Building a Menu
Debugging Visual Basic code
Learning outcome.
At the end of this topic learner should be able to:
Use basic terms in application development
Understand visual basic 6.0 development environment
Develop a basic application
Application
An application is a collection of objects that work together to accomplish something useful. In Visual Basic(VB) the application is called a Project. A Project could be a the management of student records, banking application, Video store, the calculation of mortgages, a booking service or the Payroll system for employees etc.
Object
An object is a piece of software that has properties and functions that can be manipulated. Whew! You're here so, you must be somewhat familiar with the Windows environment. A window is an object. It has properties : size, color, position on the screen, etc. (The purists among you may want to talk about a class rather than an object but, at this point we just want to keep it simple, and the underlying concept is the same). The window has functions, also called methods , that can be manipulated: change the size, move it around, open it and close it. You do not have to write code to resize a window - you just click and drag. But somebody had to write code at some point. Fortunately for us, when they did they put it all in a nice little package and called it a window object. Now, whenever you need a window in your Project you can make a copy of the window object, change its properties for color or size very easily, and paste it where you want it. Then you can use its built-in methods to open it, close it when you want or resize it whenever necessary. When you create an application using objects and combining them to produce results, you are working in an object-oriented environment.
Event-driven
To produce an application in COBOL, a procedural language, you write COBOL source programs, you compile them into machine code and then you run them via a control interface such as JCL. A program can contain 1000's of lines of source code and could run for hours with no human intervention. In fact, in large installations, a jobstream can consist of a dozen programs, all automatically accepting input from the previous program and producing output for the next. The programmer can be blissfully unaware that the program has run unless something catastrophic happens.
In a VB project, the processes that occur have to be associated with events. An event is something that happens - the user clicks on a button, a form is opened, the result of a calculation is too large. The operation is event-driven because everything that executes does so as the result of some kind of event. The role of the programmer is to anticipate the events and to write the code that will be executed when the event occurs. A VB application is interactive in the sense that the user is constantly interacting with the program. The user inputs a Customer Id, the program checks the Id in the database and immediately brings up the customer's file or displays a message that the particular Id is invalid.
Project description
We want to create a Scoreboard for a football game (there it is already!) between the Giants and the Redskins. To begin with the simplest task we will only count the touchdowns and display appropriate messages.
Please note : although we will create a complete functional Project with controls and code and so on, the purpose of this exercise is to show what can be done. In the following lessons we will be explaining scripts and the use of controls in a lot more detail. If you study this example you should be able to relate it to what you already know of programming and judge whether this tutorial will be easy or hard for you to do.
1.2 Creating the Project
First thing to do is to create a Directory where you will store all your VB Projects. Call it VBApps, for example. Then start VB. The first screen will ask whether you want to open a new project or an existing one - it's obviously a new one and it will be a Standard EXE. Then, maximize all the windows (it's easier to work with - some of the examples in the tutorial had to be reduced for the sake of the presentation). Now, save your project. It will first ask you to save the form - call it Score.frm - and then the Project - call it Scorebrd.vbp. From now on, do File-->Save Project very, very frequently.
Before you start to build-up the form, it will make it easier if you change the color of the form. Otherwise you will be working with grey controls on a grey background. To change the color, just click anywhere on the form, go to the properties window, find the property called BackColor and change it to the standard Window background (teal) or to any color you want in the palette.
In our first example we will need 6 labels and 2 command buttons. Each one of these objects that you put on a Form is called a control. To get a control you go to the Toolbox , click on the control you want, come back to the Form and click and drag the control to the size and position you want. Position the controls somewhat like in the diagram below.
IMPORTANT NOTE : If this is your first experience with VB, don't be afraid to experiment. This is hands-on stuff! Remember that VB is a Microsoft product, therefore it works with the standard Windows interface. All the functions you know from MS-Office work the same way here: Copy, Cut, Paste, (Ctrl)+(Click), (Shift)+(Click), drag the mouse over a group of controls to select them all, etc. The Undo button is a nice one to keep handy - when you modify a control you can always Undo the change - remember this when you get to the part about aligning the controls, making them all the same size and so on. That part can get tricky. If you accidentally end up in the Code window while palying around, go down a few paragraphs and you will see how to get back to the Form. At this point the worst that can happen is that your Form will get all messed up. So what! You can just scrap it and start over again, but you will have learned something.
If you Run the application at this point, you should see your Form appear, just the way you created it. However if you click on any of the controls, absolutely nothing happens! There are events that occur; the form opens, a button is clicked, etc. But, there is nothing that tells the form what to do when it sees an event. That is why we have to write code, also called script.
To switch between the Code window and the Form window, use the buttons just over the Project Explorer window (diagram on the left). Once in the Code window, you have the option of seeing all the code for the Project or the code for one event at a time. Use the buttons in the lower left-hand corner (diagram on the right). To select the object and the event you wish to code, use the two Listboxes at the top of the Code window. The one on the left for the object and the one on the right for the event. Start with General ... Declarations and then Form ... Load , etc.
At this point you might want to download the sample program and study it. In the following lessons we'll add functionality to the exercice and we'll explain what the code means. But for the moment, a good exercice would be to write part of the code and then try to figure out how to improve certain aspects of the program.
Getting to know the interface
Any program can stand to be improved, even mine! But there's a technique to use when building a bigger and better application - you do it step-by-step.
Improving the application
Assuming that you're a beginner with VB, here's the development technique I recommend for you:
write the simplest program that you understand and make it work - even if it doesn't have color or fancy fonts, test it and then save it;
make a copy of your previous working program and code one or two improvements in the copy - if you become stuck and can't recover, destroy the copy, go back to the previous version, make a new copy and start again;
repeat for every improvement you make, using small steps so that if something does go wrong its easier to identify the source of the problem (if you made 12 corrections in a program and then it doesn't work, how will you know which of the changes is causing the problem?)
Avoid repeating code!
In our FootScoreboard example, there is one occasion where there are several lines of code repeated.
OK, so it's only a few lines but, in a large program that can happen a lot and it is very time-consuming both to create the code and the to maintain it.
The way to correct that is to take all the code that repeats and put it into a separate procedure. A procedure is identified by the Private Sub ... End Sub lines.
Then, whenever you have to execute the code, call the procedure simply by writing its name.
But, we'll notice that what we do with the Clear button is in fact the same thing we do when we load the form in the first place. So, we'll use the procedure technique to simplify the code.
1.3 Writing code
The Code Editor
As we saw in the previous lesson, getting to the Code Editor is as simple as hitting the proper button. You may have discovered that you can also call-up the Editor by double-clicking on an object. It is also possible to select "View code" with the right mouse button.
You will note that the Editor has all the functions of a text editor and then some. The most commonly used functions will be Cut ... Copy ... Paste which you can call from the Menu, from the Toolbar or from the right mouse button. You also have access to the usual Find and Replace functions ....
Getting help
There is a lot of documentation available on VB. There is so much, in fact, that it's easy to get lost in it. However, the on-line Help available from the Menu should be used regularly. Very often just doing a search on a word in particular will be sufficient to get you out of a jam. If you want to go into more detail check out the Contents part of MSDN (Microsoft Developers' Network) and surf through it.
Writing code
VB is not very particular about presentation - spaces, indents, lower case or upper case, it doesn't make too much difference to the compiler. But it may make a whole lot of difference to the programmer who has to maintain your code in 2 years, after you've moved up to President.
Apply "Best Programming Practices"
When you work with RAD (Rapid Application Development) tools like VB in a graphical interface environment, you become more than just a programmer, a writer of code. You are a developer. We will cover that in the next lesson.
But at the moment, you are still a Programmer. And unless you are developing an application for your own personal use, that nobody else will see, you have to think of the environment, of the team you are working with.
"No man (or woman) is an island!" Especially when it comes to programming. The code you write may have to be checked by an Analyst. It will have to go through testing. It may have to be modified by other team members and it almost certainly will go through modifications, maybe several times, in the months and years ahead when you probably won't be around to defend yourself. "The evil that men do lives after them...". You do not write code for the VB compiler. You write it for other developers and programmers. What you want others to say behind your back is: "That Jane was blindingly efficient, brilliant, a genius with comments ..."
Chapter 2 Data types and operators
Data types are set of values and permitted/allowable operations on those data.
2.1 VB supports variety of data types.
Data type Storage size Range
Byte 1 byte 0 to 255
Boolean 2 bytes True or False
Integer 2 bytes - 32,768 to 32,
Long (long integer) 4 bytes^ - 2,147,483,648 to 2,147,483,
Single (single- precision floating-point)
4 bytes
Double (double- precision floating-point)
8 bytes - 1.79769313486232E308 to - 4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values
Currency (scaled integer) 8 bytes^ - 922,337,203,685,477.5808 to 922,337,203,685,477.
Decimal 14 bytes +/-79,228,162,514,264,337,593,543,950,335 with no decimal point; +/- 7.9228162514264337593543950335 with 28 places to the right of the decimal; smallest non-zero number is +/- 0.00000 00000000000000000000001
Date 8 bytes January 1, 100 to December 31, 9999
Object 4 bytes Any Object reference
String (variable- length)
10 bytes + string length 0 to approximately 2 billion
String (fixed- length)
Length of string
1 to approximately 65,40 0
Variant (with 16 bytes Any numeric value up to the range of a Double
numbers)
Variant (with characters)
22 bytes + string length
Same range as for variable-length String
User-defined (using Type)
Number required by elements
The range of each element is the same as the range of its data type.
In all probability, in 90% of your applications you will use at most six types: String, Integer, Long, Single, Boolean and Date. The Variant type is often used automatically when type is not important. A Variant-type field can contain text or numbers, depending on the data that is actually entered. It is flexible but it is not very efficient in terms of storage.
2.2 Declaring variables
Declaring a variable means giving it a name, a data type and sometimes an initial value. The declaration can be explicit or implicit.
An explicit declaration: variable is declared in the Declarations Section or at the beginning of a Procedure. An explicit declaration looks like:
Dim MyNumber As Integer
Now the variable MyNumber exists and a 2-byte space has been reserved for it.
An implicit declaration: the variable is declared "on the fly", its data type is deduced from other variables. For example:
Dim Total1 As Integer 'Explicit declaration Dim Total2 As Integer 'Explicit declaration Total3 = Total1 + Total2 'Implicit declaration
Total3 is not formally declared but is implied, it is "arrived at" from the other declarations.
It is never a good idea to have implicit declarations. It goes against the rules for clarity, readability and ease of use of the code. To make sure that this rule is followed, start the Declarations with the Option Explicit clause. This tells the compiler to consider implicit declarations as errors and forces the programmer to declare everything explicitly.
Other examples of declarations: Dim MyName As String Dim StudentDOB As Date Dim Amount5, Amount6, Amount
In the last example the type assigned to each variable will be: Variant. It is the default type when none is