Ads 468x60px

Visual Basic - Part- I


INTRODUCTION TO VISUAL BASIC 6.0
 1.1 A brief description of Visual Basic
            Visual Basic is a high level programming language evolved from the earlier DOS version called BASIC. BASIC means Beginner’s All-purpose Symbolic Instruction Code. It is a fairy easy programming language to learn. The codes look a bit like English language. Different software companies produced different version of BASIC, such as Microsoft QBASIC, QUICKBASIC, GWBASIC, IBM BASIC and so on.
                Visual Basic is a Visual and events driven Programming language. Theses are the main divergence from the old BASIC. In BASIC, programming is done in a text-only environment and the program is executed sequentially. In Visual Basic, programming is done in a graphical environment. Because users may click on a certain object randomly, so each object has to be programmed independently to be able to response to those actions (events). Therefore, a Visual Basic program in made up of many subprograms, each has its own program codes, and each can be executed independently and at the same time each can be linked together in one way or another.
A Brief History of Basic
  • Language developed in early 1960's at Dartmouth College
(Beginner's)
(All-Purpose)
(Symbolic)
(Instruction)
(Code)
  • Answer to complicated programming languages (FORTRAN, Algol, Cobol ...). First timeshare language.
  • In the mid-1970's, two college students write first Basic for a microcomputer (Altair) - cost $350 on cassette tape. You may have heard of them: Bill Gates and Paul Allen!
  • Every Basic since then essentially based on that early version. Examples include: GW-Basic, QBasic, QuickBasic.
  • Visual Basic was introduced in 1991.

1.2 The Visual Basic Environment
                On start up, Visual Basic 6.0 will display the following dialog box as shown in figure 1.1. You can choose to start a new project, open an existing project or select a list of recently opened programs. A project is a collection of files that make up your application. There are various types of applications we could create, however, we shall concentrate on creating standard EXE programs (EXE means executable program). Now, click on the Standard EXE icon to go into the actual Visual Basic programming environment.

What is Visual Basic?
  • Visual Basic is a tool that allows you to develop Windows (Graphic User Interface - GUI) applications. The applications have a familiar appearance to the user.
  • Visual Basic is event-driven, meaning code remains idle until called upon to respond to some event (button pressing, menu selection, ...). Visual Basic is governed by an event processor. Nothing happens until an event is detected. Once an event is detected, the code corresponding to that event (event procedure) is executed. Program control is then returned to the event processor.
Some Features of Visual Basic
·         Full set of objects - you 'draw' the application
·         Lots of icons and pictures for your use
·         Response to mouse and keyboard actions
·         Clipboard and printer access
·         Full array of mathematical, string handling, and graphics functions
·         Can handle fixed and dynamic variable and control arrays
·         Sequential and random access file support
·         Useful debugger and error-handling facilities
·         Powerful database access tools
·         ActiveX support
·         Package & Deployment Wizard makes distributing your applications simple
Visual Basic 6.0 versus Other Versions of Visual Basic
  • The original Visual Basic for DOS and Visual Basic For Windows were introduced in 1991.
  • Visual Basic 3.0 (a vast improvement over previous versions) was released in 1993.
  • Visual Basic 4.0 released in late 1995 (added 32 bit application support).
  • Visual Basic 5.0 released in late 1996. New environment, supported creation of ActiveX controls, deleted 16 bit application support.
  • And, now Visual Basic 6.0 - some identified new features of Visual Basic 6.0:

·         Faster compiler
·         New ActiveX data control object
·         Allows database integration with wide variety of applications
·         New data report designer
·         New Package & Deployment Wizard
·         Additional internet capabilities
16 Bits versus 32 Bits
  • Applications built using the Visual Basic 3.0 and the 16 bit version of Visual Basic 4.0 will run under Windows 3.1,      Windows for Workgroups, Windows NT, or Windows 95
  • Applications built using the 32 bit version of Visual Basic 4.0, Visual Basic 5.0 and Visual Basic 6.0 will only run with Windows 95 or Windows NT (Version 3.5.1 or higher).
  • In this class, we will use Visual Basic 6.0 under Windows 95, recognizing such applications will not operate in 16 bit environments.
Structure of a Visual Basic Application
Project (.VBP, .MAK)
Application (Project) is made up of:
Ø  Forms - Windows that you create for user interface
Ø  Controls - Graphical features drawn on forms to allow user interaction (text boxes, labels, scroll bars, command buttons, etc.) (Forms and Controls are objects.)
Ø  Properties - Every characteristic of a form or control is specified by a property. Example properties include names, captions, size, color, position, and contents. Visual Basic applies default properties. You can change properties at design time or run time.
Ø  Methods - Built-in procedure that can be invoked to impart some action to a particular object.
Ø  Event Procedures - Code related to some object. This is the code that is exe cuted when a certain event occurs.
Ø  General Procedures - Code not related to objects. This code must be invoked by the application.
Ø  Modules - Collection of general procedures, variable declarations, and constant definitions used by application.

Steps in Developing Application
·         There are three primary steps involved in building a Visual Basic application:
1.       Draw the user interface
2.       Assign properties to controls
3.       Attach code to controls

We’ll look at each step.
The Visual Basic Start-up Dialog box

Drawing the User Interface and Setting Properties
Visual Basic operates in three modes.
  • Design mode - used to build application
  • Run mode - used to run the application
  • Break mode - application halted and debugger is available We focus here on the design mode.

Six windows appear when you start Visual Basic.
  • The Main Window consists of the title bar, menu bar, and toolbar. The title bar indicates the project name, the current Visual Basic operating mode, and the current form. The menu bar has dropdown menus from which you control the operation of the Visual Basic environment. The toolbar has buttons that provide shortcuts to some of the menu options. The main window also shows the location of the current form relative to the upper left corner of the screen (measured in twips) and the width and length of the current form.

The Form Window is central to developing Visual Basic applications. It is where you draw your application.

Ø  The Toolbox is the selection menu for controls used in your application.
Ø  The Properties Window is used to establish initial property values for objects. The drop-down box at the top of the window lists all objects in the current form. Two views are available: Alphabetic and Categorized. Under this box are the available properties for the currently selected object.
Ø  The Form Layout Window shows where (upon program execution) your form will be displayed relative to your monitor’s screen:
Ø  The Project Window displays a list of all forms and modules making up your application. You can also obtain a view of the Form or Code windows (window containing the actual Basic coding) from the Project window.
As mentioned, the user interface is ‘drawn’ in the form window. There are two ways to place controls on a form:
  1. Double-click the tool in the toolbox and it is created with a default size on the form. You can then move it or resize      it.
  2. Click the tool in the toolbox, then move the mouse pointer to the form window. The cursor changes to a crosshair. Place the crosshair at the upper left corner of where you want the control to be, press the left mouse button and hold it down while dragging the cursor toward the lower right corner. When you release the mouse button, the control is drawn.
    • To move a control you have drawn, click the object in the form window and drag it to the new location. Release the mouse button.
    • To resize a control, click the object so that it is select and sizing handles appear. Use these handles to resize the object.
In figure 1.2, the Visual Basic Environment consists of the:
¥  A Blank Form for you to design your application’s interface.
¥  The Project window which displays the files that are created in your application.
¥  The Properties window which displays the properties of various controls and objects that are created in your applications.
It also includes a Toolbox that consists of all controls essential for developing a VB Application. Controls are tools such as text box, command button, label, combo box, picture box, timer and other objects that can be dragged and drawn on a form to perform certain tasks according to the events associated with them. Additional objects can be added by clicking on the project item on the menu and click on components on the drop-down list, then select those controls you need to use in your program.
Figure 1.2 – The Visual Basic Environment


BUILDING A VISUAL BASIC APPLICATION
2.1 Creating Your First Application
        In this section, we are not going into the technical aspects of VB programming; just have a feel of it. Now, you can try out the examples below.
Example 2.1.1 is a simple program. First of all, you have to launch Microsoft Visual Basic. Normally, a default form Form1 will be available for you to start your new project. Now, double click on Form1, the source code window for from1 as shown in figure 2.1 will appear. The top of the source code window consists of a list of objects and their associated events or procedures. In figure 2.1, the object displayed is Form and the associated procedure is Load.
Figure 2.1 - Source Code Window

When you click on the object box, the drop-down list will display a list of objects you have inserted into your form as shown in figure 2.2. Here, you can see a form, command button with the name Command1, a Label with the name Label1 and a Picture Box with the name Picture1. Similarly, when you click on the procedure box, a list of procedure associated with the object will be displayed as shown in figure 2.3. Some of the procedures associated with the object Form are Activate, Click, DblClick (which means Double Click), DragDrop, KeyPress and etc. Each object has its own set of procedures. You can always select an object and write codes for any of its procedure in order to perform certain tasks.
Figure 2.2 – List of Objects
Figure 2.3 – List of Procedures

You do not have to worry about the beginning and the end statements (i.e. Private Sub Form_Load……….End Sub.); Just key in the lines in between the above two statements exactly as are shown here. When you run the program, you will be surprise that nothing shown up. In order to display the output of the program, you have to add the Form1.show statement like in Example 2.1.1 or you can just use Form_Activate( ) event procedure as shown in example 2.1.2. The command Print does not mean printing using a printer but it means displaying the output on the computer screen. Now, press F5 or click on the run button to run the program and you will get the output as shown in figure 2.4.
Example 2.1.1
                Private Sub Form_Load( )
                        Form1.show
                        Print “Welcome To Emmess Information Technology”
        End Sub
Figure 2.4 – The output of Example 2.1.1

You can also perform simple arithmetic calculations as shown in example 2.1.2. Visual Basic uses * to denote the multiplication operator and / to denote the division operator. The output is shown is figure 2.3, where the result are arranged vertically.
Example 2.1.2
        Private Sub Form_Activate( )
                        Print 50 + 20
                        Print 50 – 20
                        Print 50 * 20
                        Print 50 / 20
        End Sub
Figure 2.5 – The output of Example 2.1.2

Example 2.1.2 can also be written as
        Private Sub Form_Activate( )
                        Print 50 + 20, 50 – 20, 50 * 20, 50 / 20
        End Sub
The numbers will be arranged in a horizontal line separated by spaces as shown in figure 2.6
Figure 2.6 – Output in a horizontal line

        Example 2.1.3 is an improved version of example 2.1.2 as it employs two variables x and y and assigned initial values of 20 and 10 to them respectively. When you need to change the values of x and y, just change the initial values rather than changing every individual value which is more time consuming.
Example 2.1.3
Private Sub Form_Activate ( )
                        x = 20
                        y = 10
                        Print x + y
                        Print x – y
                        Print x * y
                        Print x / y
        End Sub
        Besides, you can also use the + or the & operator to join two or more texts (string together like in example 2.1.4 (a) and (b)
Example 2.1.4 (a)
        Private Sub Form_Activate( )
                        A = “KuppuSwamy”
                        B = “ likes”
                        C = “ to”
                        D = “ eat”
                        E = “ Murukku"
                        Print A + B + C + D + E
        End Sub
The output is as shown in figure 2.7
Figure 2.7 – The output of Example 2.1.4 (a) & (b)

2.2 Steps in Building a Visual Basic Application
        Generally, there are three basic steps in building a VB application. The steps are as follows:
Step 1 : Design the interface
Step 2 : Set Properties of the controls (Objects)
Step 3 : Write the events procedures
Example 2.2.1
The program is a simple program that calculates the volume of a cylinder. Let design the interface:
Figure 2.8 -  A Program to calculate the Volume of a Cylinder

First of all, go to the properties window and change the form caption to Volume Of Cylinder, then drag and insert three labels into the form and change their captions to Base Radius, Height and Volume respectively. After that, insert three Text Boxes and clear its text contents so that you get three empty boxes. Named the text boxes as radius, hght (we cannot use height as it is the built-in control name of VB) and volume respectively. Lastly, insert a command button and change its caption to OK and its name to OK. Now save the project as cylinder.vbp and the form as cylinder.vbp as well. We shall leave out the codes at the moment which you shall learn it in lesson3.
Example 2.2.2
Designing an attractive and user friendly interface should be the first step in construction a VB program. To illustrate, let’s look at the calculator program.
Figure 2.9 – calculator

Now, follow the steps below to design the calculator interface.
ª  Resize the form until you get the size are satisfied with.
ª  Go to the properties window and change the default caption you want, such as 32 bit Calculator.
ª  If you want, Change other properties of the form, such as background color, foreground color, border style. I recommend you set the following properties for Form1 for the calculator program:
Border Style
Fixed Single
MaxButton
False
minButton
True
These properties will ensure that the users cannot resize or maximize your calculator window, but able to minimize the window.
ª  Draw the Display Panel by clicking on the Command button and place your mouse on the form. Start drawing by pressing down your mouse button and drag it along.
ª  Click on the panel and the corresponding properties window will appear. Clear the default label so that the caption is blank (because the display panel is supposed to show the number as we click on the number button). It is better to set the background color to a bright color while the foreground color should be something like black (for easy viewing). Change the name to display as I am going to use it later to write codes for the calculator.
ª  Now draw the command buttons that are necessary to operate a calculator. I suggest you follow exactly what is shown in the image above.
Now run the project by pressing F5. If you are satisfied with the appearance, go ahead to save the project. At the same time, you should also save the file that contains your form.

WORKING WITH CONTROLS
3.1 The Control Properties
                Before writing an event procedure for the control to response to a user’s input, you have to set certain properties for the control to determine its appearance and how it will work with the event procedure. You can set the properties of the controls in the properties window or at runtime.
Figure 3.1 on the right is a  typical properties
window for a form. You can rename the form caption to any name that you like best. In the properties window, the item appears at the top part is the object currently selected (in Figure 3.1, the object selected id Form1). At the bottom part, the items listed in the left column represent the names of various properties associated with the selected object while the items listed in the right column represent the states of the properties. Properties can be set by highlighting the items in the right column then change them by typing or selecting the options available. For example, in order to change the caption. Just highlight Form1 under the name Caption and change it to other names. You may also try to alter the appearance of the form by setting it to 3D or flat. Other things you can do are to change its foreground and background color, change the font type and font size, enable or disable minimize and maximize buttons and etc.
                You can also change the properties at runtime to give special effects such as change of color, shape, animation effect and so on. For example the following code will change the form color to red every time the form is loaded. VB uses hexadecimal system to represent the color, You can check the color codes in the properties windows which are showed up under ForeColor and BackColor.
Private Sun Form_Load( )
Form1.Show
Form1.BackColor = &H000000FF&
End Sub
Another example is to change the control Shape to a particular shape at runtime by writing the following code. This code will change the shape to a circle at runtime. Later you will learn how to change the shape randomly by using the RND function.
Private Sun Form_Load( )
Shape1.Shape = 3
End Sub
I would like to stress that knowing how and when to set the object’s properties is very important as it can help you to write a good program or you may fail to write a good program. So, I advice you to spend a lot of time playing with the objects properties.
I would like to stress a few important points about setting up the properties.
4  You should set the Caption Property of a control clearly so that a user knows what to do with that command. For example, in the calculator program, all the captions of the command buttons such as +, - , MC, MR are commonly found in an ordinary calculator, a user should have no problem in manipulating the buttons.
4  A lot of programmers like to use a meaningful name for the Name Property may be because it is easier for them to write and read the event procedure and easier to debug or modify the programs later. However, it is not a must to do that as long as you label your objects clearly and use comments in the program.
4  One more important property is whether the control is enabled or not.
4  Finally, you must also considering making the control visible or invisible at runtime, or when should it become visible or invisible.
3.2 Handling some of the common Controls
3.2.1 The Text Box
                The text box is the standard control that is used to receive input from the user as well as to display the output. It can handle string (text) and numeric data but not images or pictures. String in a text box can be converted to a numeric data by using the function Val(text). The following example illustrates a simple program that processes the inputs from the user.
Example 3.1
          In this program, two text boxes are inserted into the form together with a few labels. The two text boxes are used to accept inputs from the user and on of the labels will be used to display the sum of two numbers that are entered into the two text boxes. Besides, a command button is also programmed to calculate the sum of the two numbers using the plus operator. The program use creates a variable sum to accept the summation of values from text box 1 and text box 2. The procedure to calculate and to display the output on the label is shown below. The output is shown in Figure 3.1.
Private Sub Command1_Click( )
‘To add the values in text box 1 and text box 2
Sum = Val(Text1.Text) + Val(Text2.Text)
‘To display the answer on label1
Label1.Caption = Sum
End Sub
Figure 3.1

3.2.2 The Label Box 
                The Label is a very useful control for Visual Basic, as it is not only used to provide instructions and guides to the users, it can also be used to display outputs. One of its most important properties is Caption. Using the syntax label.Caption, it can display text numeric data. You can change its caption in the properties window and also at runtime. Refer to Example 3.1 and Figure 3.1 for the usage of label.
3.2.3 The Command Button
                The command button is a very important control as it is used to execute commands. It display an illusion that the button is pressed when the user click on it. The most common event associated with the command button is the Click event, and the syntax for the procedure is
                Private Sub Command1_Click( )
                                Statements
                End Sub
3.2.4 The Picture Box 
            The Picture Box is one of the controls that used to handle graphics. You can load a picture at design phase by clicking on the picture item in the properties window and select the picture from the selected folder. You can also load the picture at runtime using the LoadPicture method. For example, the statement will load the picture graph.gif into the picture box.
                Picture1.Picture= LoadPicture(“C:\VB program\Image\graph.gif”)
You will learn more about the picture box in future lessons. The image in the picture box is not resizable.
3.2.5 The Image Box
                The image Box is another control that handles images and pictures. It functions almost identically to the picture box. However, there is one major difference, the image in an Image Box is stretchable, which means it can be resized. This feature is not available in the Picture Box. Similar to the Picture Box, it can also use the LoadPicture method to load the picture. For example, the statement loads the picture grape.gif into the image box.
                Image1.Picture= LoadPicture(“C:\VB program\Image\graph.gif”)
3.2.6 The List Box 
                The function of the List Box is to present a list of items where the user can click and select the items from the list. In order to add items to the list, we can use the AddItem method. For example, is you wish to add a number of items to list box 1, you can key in the following statements
Example 3.2
                Private Sub Form_Load( )
                                List1.AddItem”MS-Office”
                                List1.AddItem”FoxPro”
                                List1.AddItem”VisualBasic”
                                List1.AddItem”C&C++”
                                List1.AddItem”Oracle&SQL”
                                List1.AddItem”Dot Net”
                End Sub
Figure 3.2 – Output of the List Box program

The items in the list box can be identified by the ListIndex property, the value of the ListIndex for the first item is 0, the second item has a ListIndex 1, and the third item has a ListIndex 2 and so on.
3.2.7 The Combo Box
                The function of the Combo Box is also to present a list of items where the user can click and select the items from the list, However, the user needs to click on the small arrowed on the right of the combo box to see the items which are presented in a drop-down list. In order to add items to the list, you can also use the AddItem method. For example, if you wish to add a number of items to Combo box 1, you can key in the following statements
Example 3.3
                Private Sub form_Load( )
                                Combo1.Clear
                                Combo1.AddItem “HTML”
                                Combo1.AddItem “XML”
                                Combo1.AddItem “PHP&MySQL”
                                Combo1.AddItem “CSS”
                                Combo1.AddItem “ASP”
                                Combo1.AddItem “JSP”
                End Sub
Figure 3.3 – Output of the Combo Box program

3.2.8 The Check Box
                The Check Box control lets the user to select or unselect an option. When the Check Box is checked, its value is set to 1 and when it is unchecked, the value is set to 0. You can include the statements Check1.Value=1 to mark the Check Box and Check1.Value=0 unmark the Check Box, and use them to initiate certain actions. For example, the program will change the background color of the form to red when the check box is unchecked and it will change to blue when the check box is checked. You will learn about the conditional statement If….Then….Elseif in later lesson. VbRed and VbBlue are color constants and BackColor is the background color property of the form.
Example 3.4
                Private Sub Check1_Click( )
                                If Check1.Value = 0 Then
                                Form1.BackColor = vbRed
                                ElseIf Check1.Value = 1 Then
                                Form1.BackColor = vbBlue
                                End If
                End Sub
Figure 3.4 – Output of the Check Box program

3.2.9 The Option Box
                The Option Box control also lets the user selects one of the choices. However, two or more Option Boxes must work together because as one of the Option Boxes is selected, the other Option Boxes will be unselected. In fact, only one Option Box can be selected at one time. When an option box is selected, its value is set to “True” and when it is unselected, its value is set to “False”. In the following example, the shape control is placed in the form together with six Option Boxes. When the user clicks on different option boxes, different shapes will appear. The values of the shape control are 0, 1, and 2, 2, 4, 5 which will make it appear as a rectangle, a square, an oval shape, a rounded rectangle and a rounded square respectively.
Example 3.5
                Private Sub Option1_Click( )
                                Shape1.Shape = 0
                End Sub
                Private Sub Option2_Click( )
                                Shape1.Shape = 1
                End Sub
                Private Sub Option3_Click( )
                                Shape1.Shape = 2
                End Sub
                Private Sub Option4_Click( )
                                Shape1.Shape = 3
                End Sub
                Private Sub Option5_Click( )
                                Shape1.Shape = 4
                End Sub
                Private Sub Option6_Click( )
                                Shape1.Shape = 5
                End Sub
Figure 3.5 – Output of the Option Box program

3.2.9 The Drive List
                The Drive ListBox is used to display a list of drives available in your computer. When you place this control into the form and run the program, you will be able to select different drives from your computer as shown in Figure 3.6
Figure 3.6 – Output of the Drive List Box

3.2.10 The Directory List Box 
            The Directory List Box is used to display the list of directories of folders in a selected drive. When you place this control into the form and run the program, you will be able to select different directories from a selected drive in your computer as shown in figure 3.7
Figure 3.7 – Output of the Directory List Box

3.2.11 The File List Box
                The File List Box is used to display the list of files in a selected directory or folder. When you place this control into the form and run the program, you will be able to a list of files in a selected directory as shown in Figure 3.8
Figure 3.8 – Output of the Directory List Box

You can coordinate the Drive List Box, the Directory List Box and the File List Box to search for the files you want.

WRITING THE CODES
            In lesson 2, you have learned how to enter the program code and run the sample Visual Basic program but without much understanding about the logics of VB programming. Now, let’s get down learning a few basic rules about writing the VB program code.
                Each control or object in VB can usually run many kinds of events or procedures, these events are listed in the dropdown list in the code window that is displayed when you double-click on an object and click on the procedure box (refer to Figure 2.3). Among the events are loading a form, clicking of a command button, pressing a key on the keyboard or dragging an object and etc. For each event, you need to write an event procedure will appear as shown in Figure 2.1. It takes the following format:
Private Sub Command1_Click( )
(Key in your program code here)
End Sub
                You then need to key-in the procedure in the space between Private Sub Command1_Click ………………….End Sub. Sub actually stands for sub procedure that made up a part of all procedure in a program. The program code is made up of a number of statements that set certain properties or trigger some actions. The syntax of Visual Basic’s program code is almost like the normal English language though not exactly the same, so it is very easy to learn.
The syntax to set the property of an object or to pass certain value to it is:
                Obeject.Property
where Object and Property is separated by a period (or dot). For example, Form1.Show means to show the form with the name Form1, Label1.Visisble = True means label1 is set to be visible, Text1.Text = “VB” is to assign the text VB to the text box with the name Text1, Text2.Text = 100 is to pass a value of 100 to the text box with the name Text2. Timer1.Enabled=False is to disable the timer with the name Timer1 and so on. Let’s examine a few examples below.
 Example 4.1
                Private Sub Command1_Click( )
                                Label1.Visible = False
                                Label2.Visible = True
                                Text1.Text = “You are Correct”
                End Sub
Example 4.2
Private Sub Command1_Click( )
                                Label1.Caption = “Welcome”
                                Image1.Visible = True
                End Sub
Example 4.3
                Private Sub Command1_Click( )
                                Picture1.Show = True
                                Timer1.Enabled = True
                                Label1.Caption = “Start Counting”
                End Sub
In example 4.1, clicking on the command button will make label1 become invisible and label 2 become visible and the text “You are Correct” will appear in TextBox1. In example 4.2, clicking on the command button will make the caption label1 change to “Welcome” and Image1 will become visible. Example 4.3, clicking on the command button will make Picture1 show up, timer starts running the caption of label1 change to “Start Counting”.
Syntaxes that do not involve setting of properties are also English-like, some of the commands are Print, If…Then…Else…End If, For…Next, Select Case…End Select, End and Exit Sub. For example, Print “Visual Basic” is to display the text Visual Basic on screen and End is to end the program. Other commands will be explained in details in the coming lessons.
Program code that involve calculations is very easy to write, you need to write them almost like what you do in mathematics. However, in order to write an event procedure that involves calculations, you need to know the basic arithmetic operators in VB as they are not exactly the same as the normal operator we use, except for + and -. For multiplication, we use *, for division we use /, for raising a number x to the power of n, we use x^n and for square root, we use sqr(x). More advanced mathematical functions such as Sin, Cos, Tan, Log and etc. There are also two important functions that are related to arithmetic operations, i.e. the functions Val and Str$, where Val is to convert text entered into a textbox to numerical value and Str$ is to display a numerical value in a textbox as a string (text). While the function Str$ is as important as VB can display a numeric values as string implicitly, failure to use Val will results in wrong calculation. Let’s examine example 4.4 and example 4.5.
Example 4.4
                Private Sub Form_Activate( )
                                Text3.Text = Text1.Text + Text2.Text
                End Sub
Example 4.5
Private Sub Form_Activate( )
                                Text3.Text = Val(Text1.Text) + Val(Text2.Text)
                End Sub
When you run the program in example 4.4 and enter 12 in textbox1 and 3 in textbox2 will give you a result of 123, which is wrong. It is because VB treat the numbers as string and so it just joins up the two strings. On the other hand, running exampled 4.5 will give you the correct result, i.e., 15.
We shall now look at more examples in mathematics.
Now we shall attempt to write the codes for the cylinder program where the interface is shown in Figure 2.8. First of all, name the textbox as radius, hght, and volume. To get the values of the various textboxes, use Val(radius.Text), Val(hght.Text) and assign them to the variables r and h. In addition, assign the value 22/7 to the variable pi. After that, write the equation v = pi*(r^s)*h to compute the value of volume of cylinder and then assign it to the variable v. Finally, display the value in the volume textbox using the functions Str$
                Private Sub OK_Click( )
                                r = Val(radius.Text)
                                h = Val(hght.Text)
                                pi = 22/7
                                v = pi*(r^2)*h
                                volume.Text = Str$(v)
                End Sub
When you run the program, you should be able to see the interface as shown in Figure 2.8. If you enter a value each in the radius box and the height box, then click OK, the value of the Volume will be displayed in the volume box.
I shall attempt to explain the above source program to newcomers in Visual Basic (If you are a veteran, you can skip this part). The program could be explained using pseudo codes as follows:
o   Procedure for clicking the OK button to calculate the volume of cylinder
o   Get the value of r from the radius text box
o   Get the value of h from the height text box
o   Assign a constant value 22/7 to pi
o   Calculate the volume using formula
o   Output the result to the Volume text box
o   End of Procedure

MANAGING VISUAL BASIC DATA
There are many types of data we come across in our daily life. For example, we need to handle data such as names, addresses, money, date, stock quotes, statistics and etc everyday. Similarly in Visual Basic, we are also going to deal with these kinds of data. However, to be more systematic, VB divides data into different types.
5.1 Types of Visual Basic Data
5.1.1 Numeric Data
Numeric data are data that consists of numbers, which can be computed mathematically with various standard operators such as, add, minus, multiply, divide and so on. In VB, the numeric data are divided into 7 types, they are summarized in Table 5.1
Table 5.1 – Numeric Data Types
Type
Storage
Range of Values
Byte
1 byte
0 to 255
Integer
2 bytes
-32,768 to 32,767
Long
4 bytes
-2,147,483,648 to 2,147,483,648
Single
4 bytes
-3.402823E+38 to -1.401298E-45 for negative values
1.401298E-45 to 3.402823E+38 for positive values
Double
8 bytes
-1.79769313486232e+308 to -4.94065645841247E-324 for negative
4.94065645841247E-324 to 1.79769313486232e+308 for positive
Currency
8 bytes
-922,337,203,685,477.5808 to 922,337,203,685,477.5807
Decimal
12 bytes
+/- 79,228,162,514,264,337,593,543,950,335 if no decimal is use
+/- 7.9228162514264337593543950335 (28 decimal places)

5.1.2 Non – Numeric Data Types
The non-numeric data types are summarized in Table 5.2
Table 5.2 – Non Numeric Data Types
Type
Storage
Range of Values
String (fixed length
Length of String
1 to 65,400 characters
String (variable length)
Length + 10 bytes
0 to 2 billion characters
Date
8 bytes
January 1, 1000 to December 31, 9999
Boolean
2 bytes
True or False
Object
4 bytes
Any embedded object
Variant (Numeric)
16 bytes
Any value as large as Double
Variant (Text)
Length + 22 bytes
Same as variable – length String

5.1.3 Suffixes for Literals
Literals are values that you assign to a data. In some cases, we need to add a suffix behind a literal so that VB can handle the calculation more accurately. For example, we can use num = 1.3089# for a Double type data.
Some of the suffixes are displayed
Data Type                            Suffix
Boolean                                 None
Integer                   %
Long (Integer)      &
Single (Floating) !
Double (Floating)                #
Currency                               @
Date                                       None
Object                    None
String                                     $
Variant                   None
                In addition, we need to enclose string literals within two quotations and date and time literals within two # sign. String can contain any characters, including numbers. The following are few examples:
                memberName      =              “Bencihar, John”
                TelNumber                           =              “04651-900-222-111”
                LastDay                 =              #31-Dec-00#
                ExpTime                                =              #12:00#
Variables
4     We’re now ready to attach code to our application. As objects are added to the form, Visual Basic automatically builds a framework of all event procedures. We simply add code to the event procedures we want our application to respond to. But before we do this, we need to discuss variables.
4     Variables are used by Visual Basic to hold information needed by your application. Rules used in naming variables:
No more than 40 characters
They may include letters, numbers, and underscore (_)
The first character must be a letter
You cannot use a reserved word (word needed by Visual Basic)
5.2 Managing Variables
                Variables are like mail boxes in the post office. The contents of the variables changes every now and then, just like the mail boxes. In term of VB, variable are areas allocated by the computer memory to hold data. Like the mail boxes, each variable must be given a name. To name a variable in Visual Basic, you have to follow a set of rules.
5.2.1 Variable Names
                The following are the rules when naming the variables in Visual Basic
4  It must be less than 255 characters
4  No space is allowed
4  It must not begin with a number
4  Period is not permitted
Examples of valid and invalid variable names are displayed in Table 5.4
Valid and Invalid variable names Table 5.4
Valid Name
Invalid Name
My_No
My.No
ThisTime
1NewTime
Long_Name_Can_BeUse
She&HerMother
Number_10
*&

Variable Declaration
In VB, one needs to declare the variables before using them by assigning names and data types. They are normally declared in the general section of the codes windows using the Dim statement.
                The format is as follows:
                Dim variableName as DataType
  • There are three ways for a variable to be typed (declared):
1. Default
2. Implicit
3. Explicit
  • If variables are not implicitly or explicitly typed, they are assigned the variant type by default. The variant data type is a special type used by Visual Basic that can contain numeric, string, or date data.
  • To implicitly type a variable, use the corresponding suffix shown above in the data type table. For example,
TextValue$ = "This is a string"
creates a string variable, while
Amount% = 300
creates an integer variable.
  • There are many advantages to explicitly typing variables. Primarily, we insure all computations are properly done, mistyped variable names are easily spotted, and Visual Basic will take care of insuring consistency in upper and lower case letters used in variable names. Because of these advantages, and because it is good programming practice, we will explicitly type all variables.
  • To explicitly type a variable, you must first determine its scope. There are four levels of scope:
Procedure level
Procedure level, static
Form and module level
Global level
  • Within a procedure, variables are declared using the Dim statement:
Dim MyInt as Integer
Dim MyDouble as Double
Dim MyString, YourString as String
Procedure level variables declared in this manner do not retain their value once a procedure terminates.
  • To make a procedure level variable retain its value upon exiting the procedure, replace the Dim keyword with Static :
Static MyInt as Integer
Static MyDouble as Double
  • Form (module) level variables retain their value and are available to all procedures within that form (module). Form (module) level variables are declared in the declarations part of the general object in the form's (module's) code window. The Dim keyword is used:
Dim MyInt as Integer
Dim MyDate as Date
  • Global level variables retain their value and are available to all procedures within an application. Module level variables are declared in the declarations part of the general object of a module's code window. (It is advisable to keep all global variables in one module.) Use the Global keyword:
Global MyInt as Integer
Global MyDate as Date
  • What happens if you declare a variable with the same name in two or more places? More local variables shadow (are accessed in preference to) less local variables. For example, if a variable MyInt is defined as Global in a module and declared local in a routine MyRoutine, while in MyRoutine, the local value of MyInt is accessed. Outside MyRoutine, the global value of MyInt is accessed.
Example of Variable Scope:
Procedure Routine1 has access to X, Y, and A (loses value upon termination)
Procedure Routine2 has access to X, Y, and B (retains value)
Procedure Routine3 has access to X, Z, and C (loses value)
Example
Stopwatch Application - Attaching Code
All that’s left to do is attach code to the application. We write code for every event a response is needed for. In this application, there are three such events:
clicking on each of the command buttons.
  1. Double-click anywhere on the form to open the code window. Or, select ‘View Code’ from the project window.
  2. Click the down arrow in the Object box and select the object named (general). The Procedure box will show (declarations). Here, you declare three form level variables:
Option Explicit
Dim StartTime As Variant
Dim EndTime As Variant
Dim ElapsedTime As Variant
The Option Explicit statement forces us to declare all variables. The other lines establish StartTime, EndTime, and ElapsedTime as variables global within the form.
  1. Select the cmdStart object in the Object box. If the procedure that appears is not the Click procedure, choose Click from the procedure box. Type the following code which begins the timing procedure. Note the Sub and End Sub statements are provided for you:
Sub cmdStart_Click ()
‘Establish and print starting time
StartTime = Now
lblStart.Caption = Format(StartTime, "hh:mm:ss")
lblEnd.Caption = ""
lblElapsed.Caption = ""
End Sub
In this procedure, once the Start Timing button is clicked, we read the current time and print it in a label box. We also blank out the other label boxes. In the code above (and in all code in these notes), any line beginning with a single quote ( ) is a comment. You decide whether you want to type these lines or not. They are not needed for proper application operation.
  1. Now, code the cmdEnd button.
Sub cmdEnd_Click ()
‘Find the ending time, compute the elapsed time
‘Put both values in label boxes
EndTime = Now
ElapsedTime = EndTime - StartTime
lblEnd.Caption = Format(EndTime, "hh:mm:ss")
lblElapsed.Caption = Format(ElapsedTime, "hh:mm:ss")
End Sub
Here, when the End Timing button is clicked, we read the current time (End Time), compute the elapsed time, and put both values in their corresponding label boxes.
  1. And, finally the cmdExit button.
Sub cmdExit_Click ()
End
End Sub
This routine simply ends the application once the Exit button is clicked.
6. Did you  notice that  as you typed in  the code, Visual Basic  does automatic syntax checking on what you type (if you made any mistakes, that is)?
7.  Run your application by clicking the Run   button on   the toolbar, or by pressing <f5>. Pretty easy, wasn’t it?
8.  Save your application - see the Primer on the next page. Use the Save Project As option under the File menu. Make sure you save both the form and the project files.
9.  If you have the time, some other things you may try with the Stopwatch Application:
A.  Try changing the form color and the fonts used in the label boxes and command buttons.
B.  Notice you can press the ‘End Timing’ button before the ‘Start Timing’ button. This shouldn’t be so. Change the application soyou can’t do this. And make it such that you can’t press the ‘Start Timing’ until ‘End Timing’ has been pressed. Hint: Look at the command button Enabled property.
C.  Can you think of how you can continuously display the ‘End Time’ and ‘Elapsed Time’? This is a little tricky because of the eventdriven nature of Visual Basic. Look at the Timer tool. Ask me for help on this one.
Exercise 1
Calendar/Time Display
Design a window that displays the current month, day, and year. Also, display the current time, updating it every second (look into the Timer control). Make the window look something like a calendar page. Play with object properties to make it pretty.
Form:
Properties:
Form frmCalendar:
Caption = My Calendar
BorderStyle = 1 - Fixed Single
Timer timDisplay:
Interval = 1000
Label lblDay:
Caption = Sunday
FontName = Times New Roman
FontBold = True
FontSize = 24
Label lblTime:
Caption = 00:00:00 PM
FontName = Times New Roman
FontBold = True
FontSize = 24
Label lblYear:
Alignment = 2 - Center
Caption = 2010
FontName = Times New Roman
FontBold = True
FontSize = 24
Label lblNumber:
Alignment = 2 - Center
Caption = 31
FontName = Arial
FontBold = True
FontSize = 72
Label lblMonth:
Alignment = 2 - Center
Caption = March
FontName = Times New Roman
FontBold = True
FontSize = 24
Code:
General Declarations:
Option Explicit
timDisplay Timer Event:
Private Sub timDisplay_Timer()
Dim Today As Variant
Today = Now
lblDay.Caption = Format(Today, "dddd")
lblMonth.Caption = Format(Today, "mmmm")
lblYear.Caption = Format(Today, "yyyy")
lblnumber.Caption = Format(Today, "d")
lblTime.Caption = Format(Today, "h:mm:ss ampm")
End Sub
Example 5.1
       Dim password As String
                Dim yourname As String
                Dim firstnum As Integer
                Dim secondnum As Integer
                Dim total As Integer
                Dim doDate As Date
You may also combine them in one line , separating each variable with a comma, as follows:
Dim password As String, yourname As String, firstname As Integer, ……………………….
If data type is not specified, VB will automatically declare the variable as a Variant.
For String declaration, there are two possible formats, one for the variable-length string and another for the fixed-length string. For the variable-length string, just use the same format as example 5.1 above. However, for the fixed-length string, you have to use the format as shown below:
Dim VariableName As String * n, where n defines the number of characters the string can hold.
Example 5.2
                Dim yourName As String * 10
yourName can holds no more than 10 Characters.
         
WORKING WITH VARIABLES
6.1 Assigning Values to Variables
                After declaring various variables using the Dim statement, we can assign values to those variables. The general format of an assignment is
                Variable = Expression
The variable can be a declared variable or a control property value. The expression could be a mathematical expression, a number, a string, a Boolean value (True or False) and etc. The following are some examples:
                firstNumber = 100
                secondNumber = firstNumber – 99
                username = “John George”
                userpass.Text = password
                Label1.Visible = True
                Command1.Visisble = False
                Label4.Caption = TextBox1.Text
                thirdNumber = Val(usernum1.Text)
                total = firstNumber + secondnumber + thirdNumber
6.2 Operators in Visual Basic
                In order to compute inputs from users and to generate results, we need to use various mathematical operators. In Visual Basic, except for + and -, the symbols for the operators are different from normal mathematical operators, as shown in Table 6.1
Table 6.1 – Arithmetic Operators
Operator
Mathematical Function
Example
^
Exponential
2^4=16
*
Multiplication
4*3=12
/
Division
12/4=3
Mod
Modulus (Return the remainder from an integer division)
15 Mod 4=3
\
Integer Division (discards the decimal places)
19\4=4
+ or &
String concatenation
“Visual”&” Basic” = “Visual Basic”

Visual Basic Functions
Visual Basic offers a rich assortment of built-in functions. The on-line help utility will give you information on any or all of these functions and their use. Some examples are:
Function Value  Returned
Abs                                         Absolute value of a number
Asc                                         ASCII or ANSI code of a character
Chr                                         Character corresponding to a given ASCII or ANSI code
Cos                                         Cosine of an angle
Date                                       Current date as a text string
Format                                   Date or number converted to a text string
Left                                         Selected left side of a text string
Len                                         Number of characters in a text string
Mid                                         Selected portion of a text stri ng
Now                                        Current time and date
Right                                      Selected right end of a text string
Rnd                                        Random number
Sin                                          Sine of an angle
Sqr                                          Square root of a number
Str                                           Number converted to a text string
Time                                       Current time as a text string
Timer                                     Number of seconds elapsed since midnight
Val                                          Numeric value of a given text string

Example 6.1
                Dim firstname As String
                Dim secondname As String
                Dim yourName As String
                Private Sub Command1_Click()
                                firstName = Text1.Text
                                secondName = Text2.Text
                                yourName = secondName +” “ + firstName
                                Label1.Caption = yourName
                End Sub
Figure 6.1 - Output of Example 6.1

In this example, three variables are declared as string. For variables firstName and secondName will receives their data from the user’s input into textbox1 and textbox2, and the variable yourName will be assigned the data by combining the first two variables. Finally, yourName is displayed on Label1.
Example 6.2
                Dim number1, number2, number3 As Integer
                Dim total, average As Variant
                Private Sub Form_Click()
                                number1 = Val(Text1.Text)
                                number2 = Val(Text2.Text)
                                number3 = Val(Text3.Text)
                                total = number1 + number2 + number3
                                average = total/5
                                Label1.Caption = total
                                Label2.Caption = average
                End Sub
Figure 6.2 - Output of Example 6.2

In the example above, three variables are declared as Integer and two variables are declared as variant. Variant means the variable can hold any numeric data type. The program computes the total and average of the three numbers that are entered into three text boxes. In the coming lessons, we will see how to write more complex Visual Basic programs using mathematical operators and equations.
Example 2
Savings Account
1.             Start a new project. The idea of this project is to determine how much you save by making monthly deposits into a savings account. For those interested, the mathematical formula used is:

where
F - Final amount
D - Monthly deposit amount
I - Monthly interest rate
M - Number of months
2.             Place 4 label boxes, 4 text boxes, and 2 command buttons on the form. It should look something like this:

3.             Set the properties of the form and each object.
Form1:
BorderStyle 1-Fixed Single
Caption Savings Account
Name frmSavings
Label1:
Caption Monthly Deposit
Label2:
Caption Yearly Interest
Label3:
Caption Number of Months
Label4:
Caption Final Balance
Text1:
Text [Blank]
Name txtDeposit
Text2:
Text [Blank]
Name txtInterest
Text3:
Text [Blank]
Name txtMonths
Text4:
Text [Blank]
Name txtFinal
Command1:
Caption &Calculate
Name cmdCalculate
Command2:
Caption E&xit
Name cmdExit
Now, your form should look like this:
4.             Declare four variables in the general declarations area of your form. This makes them available to all the form procedures:
Option Explicit
Dim Deposit As Single
Dim Interest As Single
Dim Months As Single
Dim Final As Single
The Option Explicit statement forces us to declare all variables.
5.             Attach code to the cmdCalculate command button Click event.
Private Sub cmdCalculate_Click ()
Dim IntRate As Single
‘Read values from text boxes
Deposit = Val(txtDeposit.Text)
Interest = Val(txtInterest.Text)
IntRate = Interest / 1200
Months = Val(txtMonths.Text)
‘Compute final value and put in text box
Final = Deposit * ((1 + IntRate) ^ Months - 1) / IntRate
txtFinal.Text = Format(Final, "#####0.00")
End Sub
This code reads the three input values (monthly deposit, interest rate, number of months) from the text boxes, computes the final balance using the provided formula, and puts that result in a text box.
6.             Attach code to the cmdExit command button Click event.
Private Sub cmdExit_Click ()
End
End Sub
7.             Play with the program. Make sure it works properly. Save the project.

CONTROLLING PROGRAM FLOW
7.1 Conditional Operators
                To control the VB program flow, we can use various conditional operators. Basically, they resemble mathematical operators. Conditional operators are very powerful tools, they let the VB program compare data values and then decide what action to take, whether to execute a program or terminate the program and etc.
These operators are shown in Table 7.1
Table 7.1 – Conditional Operators
Operator
Meaning
=
Equal to
> 
More than
< 
Less than
>=
More than or equal
<=
Less than or equal
<> 
Not Equal to

You can also compare strings with the above operators. However, there are certain rules to follows: Upper case letters are less than lowercase letters, “A”<”B”<”C”<”D”…………..<”Z” and number are less than letters.
7.2 Logical Operators
                In addition to conditional operators, there are a few logical which offer added power to the Visual Basic programs. There are shown in Table 7.2
Table 7.2
Operator
Meaning
And
Both sides must be true
Or
One side or other must be True
Xor
One side or other must be true but not both
Not
Negates Truth

7.3 Using If…..Then….Else Statements with Operators
                To effectively control the VB program flow, we shall use If…Then…Else statement together with the conditional operators and logical operators.
The general format for the If…Then…Else statement is
                If conditions Then
                                VB expressions
                Else
                                VB expressions
                End If
* Any If…Then…Else statement must end with End If. Sometime it is not necessary to use Else.
Example 7.1
                Private Sub OK1_Click()
                                firstnum = Val(usernum1.Text)
                                secondnum = Val(usernum2.Text)
                                total = Val(sum.Text)
                                If total = firstnum + secondnum And Val(sum.Text)<>0 Then
                                                correct.Visible = True
                                                wrong.Visible = False
                                Else
                                                correct.Visible = False
                                                wrong.Visible = True
                                End If
                End Sub
Example 7.2 – Find the big number
                Private Sub Text3_Click()
                                Dim a,b As Integer
                                a = Val(Text1)
                                b = Val(Text2)
                                If (a>b) Then
                                                Text3 = “A is Big”
                                Else
                                                Text3 = “B is Big”
                                End If
                End Sub
Output

Example 7.3 – Give number is odd or even
            Private Sub Text2_Click()
                                Dim a As Integer
                                a = Val(Text1)
                                If (a mod 2) = 0 Then
                                                Text2 = “Number is Even”
                                Else
                                                Text2 = “Number is Odd”
                                End If
                End Sub
Output

Example 7.4 – Given number isPositive, Negative or Zero
Private Sub Text2_Click()
                                Dim a As Integer
                                a = Val(Text1)
                                If (a >0) Then
                                                Text2 = “Number is Positive”
                                ElseIf (a<0) Then
                                                Text2 = “Number is Negative”
                                Else
                                                Text2 = “Number is Zero”
                                End If
                End Sub
Output

The GoTo Statement
  • Another statement, and perhaps the most hated statement in programming, is the GoTo statement. However, we will need this to do Run- Time error trapping. The format is GoTo Label, where Label is a labeled line. Labeled lines are formed by typing the Label followed by a colon.
  • GoTo Example:


When the code reaches the GoTo statement, program control transfers to the line labeled Line10.

MORE ON PROGRAM CONTROL
8.1 Select Case
                If you have a lot of conditional statements, using If…Then…Else could be very messy. For multiple conditional statements, it is better to use Select Case
The format is:
                Select Case expression
                                Case value1
                                Block of one or more VB statements
Case value2
                                Block of one or more VB statements
                                Case value3
                                Block of one or more VB statements
                                Case value4
                                ---
                                ---
                                ---
                                Case Else
                                Block of one or more VB statements
                End Select
* The data type specified in expression must match that of Case values.

8.2 Examples
Example 8.1
                ‘Examination Grades
                                Dim grade As String
                                Private Sub Compute_Click()
                                                Grade = txtgrade.Text
                                                Select Case grade
                                                Case “A”
                                                                result.Caption = “High Distinction”
                                                Case “A-”
                                                                result.Caption = “Distinction”
                                                Case “B”
                                                                result.Caption = “Credit”
                                                Case “C”
                                                                result.Caption = “Pass”
                                                Case Else
                                                                result.Caption = “Fail”
                                                End Select
                                End Sub
*Please note that grade is a string, so all the case values such as “A” are of String data type.
Figure 8.1 – Output of Example 8.1

Example 8.2
          Dim mark As Single
                Private Sub Compute_Click()
                ‘Examination Marks
                mark = mrk.Text
                                Select Case mark
                                Case Is>=85
                                                comment.Caption = “Excellence”
                                Case Is>=70
                                                comment.Caption = “Good”
                                Case Is>=60
                                                comment.Caption = “Above Average”
                                Case Is>=50
                                                comment.Caption = “Average”
                                Case Else
                                                comment.Caption = “Need to work Harder”
                                End Select
                End Sub
* Note we use the keyword Is here to impose the conditions. This is generally used for numeric data.
Figure 8.2 – Output of Example 8.2

Example 8.3
Example 8.2 could be rewritten as follows:
Dim mark As Single
                Private Sub Compute_Click()
                ‘Examination Marks
                mark = mrk.Text
                                Select Case mark
                                Case 0 to 49
                                                comment.Caption = “Need to work Harder”
                                Case 50 to 59
                                                comment.Caption = “Average”
                                Case 60 to 69
                                                comment.Caption = “Above Average”
                                Case 70 to 84
                                                comment.Caption = “Good”
                                Case Else
                                                comment.Caption = “Excellence”
                                End Select
                End Sub
Example 8.4        Circle – Area, Circumference
                Private Sub Text3_Click()
                                Dim c As Integer
                                c=Val(Text1)
                                                Select Case c
                                                Case 1
                                                Text3 = 3.14 * Val(Text2) * Val(Text2)
                                                Label4.Caption =”Area”
                               
                                                Case 2
                                                Text3 = 2 * 3.14 * Val(Text2)                                                                                                            
Label4.Caption =”Circumference”
                                                Case 3
                                                End
                                                Case Else
                                                Label4.Caption =”Your No is Wrong”
                                                End
                                                End Select
                                End Sub
Output


LOOPING
Visual Basic allows a procedure to be repeated as many times as long as the processor could support. This is generally called looping.
Visual Basic Looping
Looping is done with the Do/Loop format. Loops are used for operations are to be repeated some number of times. The loop repeats until some specified condition at the beginning or end of the loop is met.
9.1 Do Loop
                The formats are
a)            Do While condition
                                Block of one or more VB statements
                Loop
b)            Do
                                Block of one or more VB statements
                Loop While condition
c)             Do Until condition
                                Block of one or more VB statements
                Loop
g)            Do
Block of one or more VB statements
                Loop Until condition
Example 9.1
Do While counter <=1000
num.text = counter
counter = counter+1
Loop
* The above example will keep on adding until counter >1000
The above example can be rewritten as
Do
                num.Text = counter
                counter = counter+1
Loop until counter>1000
9.2 For….Next Loop
The format is:
                For counter = startNumber to endNumber (Step increment)
                                One or more VB statements
                Next
Example:
                (a)           For counter = 1 to 10
                                                display.Text = counter
                                Next
                (b)           For counter = 1 to 1000 step 10
                                                counter = counter + 1
                                Next
                (c)           For counter = 1000 to 5 step -5
                                                counter = counter - 10
                                Next
Example 9.2 – Given number is Prime or Not (Using Do..While)
                Private Sub Command1_Click()
                                Dim n, i, x, m As Integer
                                n = Val(Text1)
                                x = 0
                                i = 2
                                                Do While (i<n)
                                                m = n mod i
                                                If m =  0 Then
                                                x = 1
                                                Exit Do
                                                End If
                                                i = i+1
                                                Loop
                                If x = 0 Then
                                Print n, “ is Prime”
                                Else
                                Print n, “ is Not Prime”
                                End If
                End Sub
Output

Example 9.3 – Armstrong or Not (Using For… Next)
                Private Sub Command1_Click()
Dim n, s, a, m As Integer
                                                For n = 100 To 500
                                                 s = 0
                                                 a = n
                                                 Do While (a <> 0)
                                m = a Mod 10
                                s = s + m ^ 3
                                a = Int(a / 10)
                                Loop
                If n = s Then
                                Print n, " is Armstrong"
                                End If
                                                Next n
End Sub
Output

Example 9.4 – Polindrome or Not (Using For… Next)
Private Sub Command1_Click()
Dim n, s, a, m As Integer
                                                For n = 1000 To 1500
                                                 s = 0
                                                 a = n
                                                 Do While (a <> 0)
                                m = a Mod 10
                                s = s * 10 + m
                                a = Int(a / 10)
                                Loop
                If n = s Then
                                Print n, “ is Polindrome”
                                End If
                                                Next n
End Sub
Output

Example 9.5 – (Using For… Next)
                Private Sub Form_Click()
                                Dim i As Integer
                                For i = 1 to 10
                                                Print i; “*”; 10;m “=”; i*10
                                Next i
                End Sub

Example 9.6 – Fibonacci Number
                Private Sub Form_Click()
                                Dim n, a, b, c, t As Integer
                                                a = 0
                                                b = 1
                                                Print a
                                                Print b
                                                t = 3
                                                Do While (t<=10)
                                                c = a+b
                                                Print c
                                                a = b
                                                b = c
                                                t = t+1
                                                Loop
                End Sub
Output

Example 9.7 –  Sum of following series
i)                     1+2+3+……………….+n
ii)                   12+22+32+………….+n2
iii)                  13+23+33+………….+n3
iv)                  1+3+5+………………+n
v)                   2+4+6+………………+n
Private Sub Form_Click()
Dim n, s, sq, cu, e, o, i As Integer
                n = Val(Text1)
                s = 0
                sq = 0
                cu = 0
                e = 0
                o = 0
                i = 1
Do While (i<=n)
                s = s+i
                sq = sq+i^2
                cu = cu+i^3
If (i mod 2) = 0 Then
                e = e+i
Else
                o = o+i
End If
                i = i+1
Loop
Print “Sum of Numbers:”, s
Print “Sum of Sq Numbers:”, sq
Print “Sum of Cu Numbers:”, cu
Print “Sum of Even Numbers:”, e
Print “Sum of Odd Numbers:”, o
End Sub
Output

Example 9.8 –  1+1/2+1/3+1/4+………..1/n
                Private Sub Form_Click()
                                Dim n, i, s As Integer
                                                s = 0
                                                i = 1
                                                n = Val(Text1)
                                Do While (i<=n)
                                s = s+1 mod i
                                i = i+1
                                Loop
                Print “Sum of Series:”, s
                End Sub

Example 9.8 –  1/1!+1/2!+1/3!+1/4!+………..1/n!
                Private Sub Form_Click()
                                Dim n, i, f, j, s As Single
                                                s = 0
                                                n = Val(Text1)
                                For i = 1 to n
                                f = 1
                                For j = 1 to i
                                f = f*j
                                Next j
                                s = s+1/f
                                Next i
                Print “Sum of Series:”, s
                End Sub
Output

Example 9.9
                Private Sub Form_Click()
                                Dim i, j As Integer
                                For i = 1 to 5
                                                For j = 1 to i
                                                Print “*”;
                                                Next j
                                Print
                                Next i
                End Sub
Output

Example 9.10
                Private Sub Form_Click()
                                Dim i, j As Integer
                                For i = 1 to 5
                                                For j = 1 to i
                                                Print j; “ ”;
                                                Next j
                                Print
                                Next i
                End Sub
Output

Example 9.11
                Private Sub Form_Click()
Dim i, j, l As Integer
Dim s As String
                s = “EMMESS”
                l = Len(s)
For i = 1 to l
For j = 1 to i
Print Mid(s, j, 1); “ “;
Next j
Print
Next i
End Sub
Output

Example 9.12  - String Alphabetic Order
                Private Sub Form_Click()
                                Dim s, t As String
                                Dim i, j, l As Integer
                                s = “KANYAKUMARI”
                                l = Len(s)
                                                For i = 1 to l-1
                                                For j = i+1 to l
                                If Mid(s, i, 1)>Mid(s, j, 1) Then
                                t = Mid(s, i, 1)
                                Mid(s, i, 1) = Mid(s, j, 1)
                                Mid(s, j, 1) = t
                                End If
                                                Next j
                                                Next i
                                Print s
                End Sub
Output

Example 9.13  

Private Sub Add_Click()
                                List1.AddItem Text1
                                Text1 = “ “
                                Text1.SetFocus
                End Sub
                Private Sub Remove_Click()
                                Dim n as Integer
                                n = List1.ListIndex
                                List1.RemoveItem n
                End Sub
                Private Sub Clear_Click()
                                List1.Clear
                End Sub
                Private Sub Command1_Click()
                                List2.AddItem List1.List(List1.ListIndex)
                End Sub
                Private Sub Command2_Click()
                                Dim i As Integer
                                                For i = 1 to List1.ListCount
                                                List2.AddItem List1.List(i)
                                                Next i
                End Sub

Example 9.14 
                Private Sub Combo1_Click()
Label8.Font = Combo1.Text
End Sub
Private Sub Combo2_Click()
Select Case Combo2.Text
Case "Bold"
Label8.FontItalic = False
Label8.FontBold = True
Case "Italic"
Label8.FontBold = False
Label8.FontItalic = True
End Select
End Sub
Private Sub Combo3_Click()
Label8.FontSize = Combo3.Text
End Sub
Private Sub Combo4_Click()
Select Case Combo4.Text
Case "Green"
Label8.ForeColor = vbGreen
Case "Red"
Label8.ForeColor = vbRed
End Select
End Sub
Private Sub Command1_Click()
Label8.Caption = Text1.Text
End Sub

Private Sub Command2_Click()
End
End Sub
Private Sub Form_Load()
Combo1.AddItem "Arial"
Combo1.AddItem "Times New Roman"
Combo2.AddItem "Bold"
Combo2.AddItem "Italic"
Combo3.AddItem "10"
Combo3.AddItem "14"
Combo4.AddItem "Green"
Combo4.AddItem "Red"
End Sub
Private Sub Option1_Click()
Label8.FontUnderline = True
Label8.FontStrikethru = False
End Sub
Private Sub Option2_Click()
Label8.FontUnderline = False
Label8.FontStrikethru = True
End Sub
Output

Example 9.15
Private Sub Command1_Click()
End
End Sub
Private Sub Form_Load()
With List1
.AddItem "C++"
.AddItem "Visual Basic"
.AddItem "FoxPro"
.AddItem "Oracle"
.AddItem "Java"
End With
Text1 = ""
End Sub
Private Sub List1_Click()
Dim n As Integer
n = List1.ListIndex
Text1 = List1.List(n)
End Sub               
Output

Example 9.20
Private Sub Option1_Click()
Text6 = Val(Text5) * 0.6
End Sub
Private Sub Option2_Click()
Text6 = Val(Text5) * 0.5
End Sub
Private Sub Option3_Click()
Text6 = Val(Text5) * 0.8
End Sub
Private Sub Option4_Click()
Text6 = Val(Text5) * 1
End Sub
Private Sub Text5_Click()
Text5 = Val(Text4) - Val(Text3)
End Sub
Output

Example 9.21
Private Sub HScroll1_Change()
Text2 = HScroll1.Value
HScroll1.Max = 100
HScroll1.SmallChange = 1
HScroll1.LargeChange = 5
End Sub
Private Sub HScroll2_Change()
Text3 = HScroll2.Value
HScroll2.Max = 100
HScroll2.SmallChange = 1
HScroll2.LargeChange = 5
End Sub
Private Sub HScroll3_Change()
Text4 = HScroll3.Value
HScroll3.Max = 100
HScroll3.SmallChange = 1
HScroll3.LargeChange = 5
End Sub
Private Sub HScroll4_Change()
Text5 = HScroll4.Value
HScroll4.Max = 100
HScroll4.SmallChange = 1
HScroll4.LargeChange = 5
End Sub
Private Sub Text5_Change()
Text6 = Val(Text2) + Val(Text3) + Val(Text4) + Val(Text5)
End Sub
Output

Example 9.22
Private Sub Command1_Click()
If Val(Text1) > 0 Then
List1.AddItem Text1
Text2 = List1.ListCount
ElseIf Val(Text1) < 0 Then
List3.AddItem Text1
Text4 = List3.ListCount
Else
List2.AddItem Text1
Text3 = List2.ListCount
End If
End Sub
Output

Example 9.23
Private Sub Command1_Click()
Dim i, l As Integer
Dim a, s As String
a = ""
l = Len(Text1)
For i = 1 To l
s = Mid(Text1, i, 1)
If Asc(s) >= 67 And Asc(s) <= 80 Then
a = a + Chr(Asc(s) + 32)
ElseIf Asc(s) >= 97 And Asc(s) <= 122 Then
a = a + Chr(Asc(s) - 32)
End If
Next i
Text2 = a
End Sub
Output


Exercise 2
Flash Card Addition Problems
Write an application that generates random addition problems. Provide some kind of feedback and scoring system as the problems are answered.
Form:


Properties:
Form frmAdd:
BorderStyle = 1 - Fixed Single
Caption = Flash Card Addition
CommandButton cmdNext:
Caption = &Next Problem
Enabled = False
CommandButton cmdExit:
Caption = E&xit
TextBox txtAnswer:
FontName = Arial
FontSize = 48
MaxLength = 2
                Label lblMessage:
Alignment = 2 - Center
BackColor = &H00FFFF00& (Cyan)
BorderStyle = 1 - Fixed Single
FontName = MS Sans Serif
FontBold = True
FontSize = 24
FontItalic = True
Label lblScore:
Alignment = 2 - Center
BackColor = &H0000FFFF& (Yellow)
BorderStyle = 1 - Fixed Single
Caption = 0
FontName = Times New Roman
FontBold = True
FontSize = 36
Label Label1:
Alignment = 2 - Center
Caption = Score:
FontName = MS Sans Serif
FontSize = 18
Label Label4:
Alignment = 2 - Center
Caption = =
FontName = Arial
FontSize = 48
Label lblNum2:
Alignment = 2 - Center
FontName = Arial
FontSize = 48
Label Label2:
Alignment = 2 - Center
Caption = +
FontName = Arial
FontSize = 48
Label lblNum1:
Alignment = 2 - Center
FontName = Arial
FontSize = 48
Code:
General Declarations:
Option Explicit
Dim Sum As Integer
Dim NumProb As Integer, NumRight As Integer
cmdExit Click Event:
Private Sub cmdExit_Click()
End
End Sub
cmdNext Click Event:
Private Sub cmdNext_Click()
'Generate next addition problem
Dim Number1 As Integer
Dim Number2 As Integer
txtAnswer.Text = ""
lblMessage.Caption = ""
NumProb = NumProb + 1
'Generate random numbers for addends
Number1 = Int(Rnd * 21)
Number2 = Int(Rnd * 21)
lblNum1.Caption = Format(Number1, "#0")
lblNum2.Caption = Format(Number2, "#0")
'Find sum
Sum = Number1 + Number2
cmdNext.Enabled = False
txtAnswer.SetFocus
End Sub
Form Activate Event:
Private Sub Form_Activate()
Call cmdNext_Click
End Sub
Form Load Event:
Private Sub Form_Load()
Randomize Timer
NumProb = 0
NumRight = 0
End Sub
txtAnswer KeyPress Event:
Private Sub txtAnswer_KeyPress(KeyAscii As Integer)
Dim Ans As Integer
'Check for number only input and for return key
If (KeyAscii >= vbKey0 And KeyAscii <= vbKey9) Or KeyAscii
= vbKeyBack Then
Exit Sub
ElseIf KeyAscii = vbKeyReturn Then
'Check answer
Ans = Val(txtAnswer.Text)
If Ans = Sum Then
NumRight = NumRight + 1
lblMessage.Caption = "That's correct!"
Else
lblMessage.Caption = "Answer is " + Format(Sum, "#0")
End If
lblScore.Caption = Format(100 * NumRight / NumProb,
"##0")
cmdNext.Enabled = True
cmdNext.SetFocus
Else
KeyAscii = 0
End If
End Sub

INTRODUCTION TO VISUAL BASIC FUNCTIONS – PART I
            Functions are similar to normal procedures but the main purpose of the functions is to accept certain inputs and pass them on to main program to finish the execution. They are two types of function, the built-in functions (or internal functions) and the functions created by the programmers.
                The general formats of a function is
                                functionName (arguments)
                where arguments are values that are passed on to the functions.
In the lesson, we are going to learn two very basic useful internal functions, i.e. the MsgBox() and InputBox() functions.
10.1 MsgBox ( ) Function
                The objective of MsgBox is to produce a pop-up message box and prompt the user to click on a command button before we can continue. This message box format is as follows:
                yourMsg = MsgBox(Prompt, Style Value, Title)
The first argument, Prompt, will display the message in the message box. The Style Value will determine what type of command buttons appear on the message box, please refer Table 10.1 for type of command button displayed. The Title argument will display the title of the message board.

Table 10.1 – Style Values
Style Value                          Named Constant                               Button Displayed
                0                              vbOkOnly                                              Ok buyyon
                1                              vbOkCancel                                         Ok and Cancel buttons
                2                              vbAbortRetryIgnore                             Abort, Retry and Ignore buttons
                3                              vbYesNoCancel                  Yes, No and Cancel buttons
                4                              vbYesNo                                               Yes and No buttons
                5                              vbRetryCancel                     Retry and Cancel buttons
We can use named constant in place of integers for the second argument to make the programs more readable. In fact, Visual Basic automatically shows up a list of names constant where you can select one of them.
Example:
                yourMsg = MsgBox(“Click OK to Proceed”, 1, “Startup Menu”)
                and
                yourMsg = MsgBox(“Click OK to Proceed”, vbOkCancel, “Startup Menu”)
are the same.
Figure 10.1- output of Message Box

yourMsg is a variable that holds values that are returned by the MsgBox() function. The values are determined by the type of buttons being clicked by the users. It has to be declared as Integer data type in the procedure or in the general declaration section. Table 10.2 shows the values, the corresponding named constant and buttons.
Table 10.2 – Return Values and Command Buttons
Value                     Named Constant                               Button Clicked
                                1              vbOk                                                      Ok button
                                2              vbCancel                                               Cancel button
                                3              vbAbort                                                  Abort button
                                4              vbRetry                                                  Retry button
                                5              vbIgnore                                                Ignore button
                                6              vbYes                                                     Yes button
                                7              vbNo                                                      No button
Example 10.1
(i)            The Interface:
                You draw three command buttons and a label as shows in Figure 10.2
Figure 10.2


(ii)           The Procedure for the test button:
                Private Sub Test_Click()
                                Dim testmsg As Integer
                                testmsg = MsgBox(“Click to test”, 1, “Test Message”)
                                If testmsg = 1 Then
                                display.Caption = “Testing Successful”
                                Else
                                display.Caption = “Testing Fail”
                                End If
                End Sub
Private Sub  End_Click()
                                display.Caption = “ “
                End Sub
when a user click on the test button, the image like the one shown in Figure 10.3 will appear. As the user click on the OK button, the message “Testing Successful” will be displayed and when we clicks on the Cancel button, the message “Testing Fail” will be displayed.
Figure 10.3


Figure 10.4

To make the message box looks more complicated, you can add an icon besides the message. There are four types of icons available in VB as shows in Table 10.3
Table 10.3


Example 10.2
In this example, the following message box will be displayed:
Figure 10.5

You could draw the same interface as in example 10.1 but modify the codes as follows:
Private Sub Test_Click()
                                Dim testmsg As Integer
                                testmsg = MsgBox(“Click to test”, vbYesNoCancel +
vbExclamation, “Test Message”)
                                If testmsg = 6 Then
                                display.Caption = “Testing Successful”
                                ElseIf testmsg = 7 Then
                                display.Caption = “Are you sure?”
                                Else
                                display.Caption = “Testing Fail”
                                End If
                End Sub
10.2 The InputBox ( ) Function
                An InputBox() function will display a message box where the user can enter a value or a message in the form of text. The format is
                myMessage=InputBox(Prompt, Title, default_text, x-position, y-position)
myMessage is a variant data type but typically it is declared as string, which accept the message input by the users. The arguments are explained as follows:
§    Prompt                       - The message displayed normally as a question asked.
§    Title                            - The title of the Input Box.
§    default-text                - The default text that appears in the input field where users can use it as his intended input or we may change to the message we wish to key in.
§    x-position and y-position        - The position or the coordinate of the input box.

Example 10.3
i. The interface
Figure 10.6

ii. The procedure for the OK button
                Private Sub OK_Click()
                                Dim userMsg As String
                                userMsg = InputBox(“What is your message?”, “Message
                                                                Entry Form”, “Enter your message here”,
                                                                                                500,700)
                                If userMsg <> “” Then
                                Text1.Text = userMsg
                                Else
                                Text1.Text = “No Message”
                                End If
                End Sub
When a user click the OK button, the input box as shown in Figure 10.7 will appear. After user entering the message and click OK, the message will be displayed on the caption, if we click Cancel, “No message” will be displayed
Figure 10.7
Figure 10.8
Figure 10.9 – Enter the message box
Figure 10.10 – Output message
Example 10.4
Private Sub Command1_Click()
Dim s, r As String
Dim i, l As Integer
s = InputBox("Enter the String")
l = Len(s)
r = ""
For i = 1 To l Step -1
r = r + Mid(s, i, 1)
Next i
If s = r Then
MsgBox "The String is Polindrome"
Else
MsgBox "The String is not Polindrome"
End If
End Sub

INTRODUCTION TO VISUAL BASIC FUNCTIONS – PART II
12.1 Create your own Functions
The general format of a function is as follows:
Public Function functionName (Arg As dataType, …….) as dataType
Or
Private Function functionName (Arg As dataType, …….) as dataType
* Public indicates that the function is applicable to the whole program and
Private indicates that the function is only applicable to a certain or procedure.
Example 12.1
                In this example, a user can calculate future value of a certain amount of money we have today based on the interest rate and the number of years from now supposing we shall invest this amount of money somewhere. The calculation is based on the compound interest rate.
Figure 12.1

Public Function FV(PV As Variant, i As Variant, n As Variant) As Variant
‘Formula to calculate Future Value(FV)
‘PV denotes Present Value
FV = PV * (1+i/100)^n
End Function

Private Sub compute_Click()
                ‘This procedure will calculate Future Value
                Dim FutureVal As Variant
                Dim PresentVal As Variant
                Dim interest As Variant
                Dim period As Variant
                PresentVal = PV.Text
                interest = rate.Text
                period = years.Text

                FutureVal = FV(PresentVal, interest, period)
                MsgBox(“The Future Value is “ & FutureVal)

End Sub

Example 12.2
The following program will automatically compute examination grades based on the marks that a student obtained.
                Public Function grade(mark As Variant) As String
                                mark = Text1.Text
                                Select Case mark
                                Case Is >= 80
                                                grade = “A”
                                Case Is >= 70
                                                grade = “B”
                                Case Is >= 60
                                                grade = “C”
                                Case Is >= 50
                                                grade = “D”
                                Case Is >= 40
                                                grade = “E”
                                Case Else
                                                grade = “F”
                                End Select
                End Function
Private Sub compute_Click()
                grading.Caption = grade(mark)
End Sub
Private Sub end_Click()
                End
End Sub
Figure 12.2 – Output of Example 12.2


ARRAYS
14.1 Introduction to Array
                By definition, an array is a list of variables, all with the same data type and name. When we work with a single item, we only need to use one variable. However, if we have a list of items which are of similar type to deal with, we need to declare an array of variables instead of using a variable for each item. For example, if we need to enter one hundred names, instead of declaring one hundred different variables, we need to declare only one array. We differentiate each item in the array by using subscript, the index value of each item, for example name(1), name(2), name(3),……….etc.
14.2 Declaring Arrays
                We could use Public or Dim statement to declare an array just as the way we declare a single variable. The Public statement declare an array that can be used throughout an application while the Dim statement declare an array that could be used only in a local procedure.
The general format to declare an array is as follow:
Dim arrayName(subs) as dataType
where subs indicates the last subscript in the array.
Example 14.2
                Dim Count(100 to 500) As Integer
declares an array that consists of the first element starting from Count(100) and ends at Count(500)
14.3 Sample Programs
(i)                   The Interface
Figure 14.1


(ii) The Codes
                Dim studentName(10) As String
                Dim num As Integer
                Private Sub Form_click()
                                For num = 1 to 10
                                studentName(num) = InputBox(“Enter the Student Name”,
                                                                                                “Enter Name”, “”, 1500, 4500)
                                If studentName(num) <> “ “ Then
                                Form1.Print studentName(num)
                                Else
                                End
                                End If
                                Next
                                End Sub
                                Private Sub Start_Click()
                                                Form1.Cls
                                End Sub
                                Private Sub Exit_Click()
                                                End
                                End Sub
The above program accepts data entry through an input box and displays the entries in the form itself. As you can see, this program will only allows a user to enter 10 names each time he click on the start button.
(iii) Output
Figure 14.2


Example 14.2
(i) The Interface
Figure 14.3


(ii) The Codes
                Dim studentName(10) As String
                Dim num As Integer
                Private Sub Form_click()
                                For num = 1 to 10
                                studentName(num) = InputBox(“Enter the Student Name”,
                                                                                                “Enter Name”, “”, 1500, 4500)
                                List1.AddItem studentName(num)
                                Next
                                End Sub
                                Private Sub Start_Click()
                                                Form1.Cls
                                End Sub
                                Private Sub Exit_Click()
                                                End
                                End Sub
(iii) Output
Figure 14.4

The above program accepts data entries through an InputBox and displays the items in a list box.

Example 14.3
Dim m, i As Integer
Private Sub Command1_Click()
Label1.Caption = "Who is President of our Nation?"
For i = 1 To 4
Option1(0).Caption = "1.Karuna Nithi"
Option1(1).Caption = "2.Sonia Gandhi"
Option1(2).Caption = "3.Meera Kumari"
Option1(3).Caption = "4. Pradheepa Patil"
Next i
End Sub
Private Sub Option1_Click(Index As Integer)
If Option1(3).Value = True Then
m = 100
Else
m = 0
End If
Text1 = m
End Sub
Output

Example 14.4
                Private Sub Form_Click()
Dim a(10), i, s As Integer
s = 0
For i = 1 To 10
a(i) = Val(InputBox("Enter the any 10 nos:"))
Print a(i)
s = s + a(i)
Next i
Print "Sum of Numbbers:", s
End Sub
Output

Example 14.5Numbers in Ascending order
                Dim i, n, a(10), t As Integer
Private Sub Form_click()
n = Val(InputBox("Enter any Values"))
For i = 1 To n
a(i) = Val(InputBox("Enet the Numbers"))
Next i
For i = 1 To n - 1
For j = i + 1 To n
If a(i) > a(j) Then
t = a(i)
a(i) = a(j)
a(j) = t
End If
Next j
Next i
Print "Sorting Numbers are "
For i = 1 To n
Print a(i)
Next i
End Sub
Output

Example 14.6 - Names in Ascending order
Private Sub Form_click()
Dim i, j, n, t As String
Dim a(50) As String
n = InputBox("Enter any Names")
For i = 1 To n
a(i) = InputBox("Enter the Names")
Next i
For i = 1 To n - 1
For j = i + 1 To n
If a(i) > a(j) Then
t = a(i)
a(i) = a(j)
a(j) = t
End If
Next j
Next i
Print "Names is ascending order"
For i = 1 To n
Print a(i)
Next i
End Sub
Output

Example 14.7 – Find the biggest number
                Private Sub Form_click()
Dim a(5), i, big As Integer
For i = 1 To 5
a(i) = InputBox("Enet the Numbers")
Print a(i)
Next i
big = a(1)
For i = 1 To 5
If a(i) > big Then
big = a(i)
End If
Next i
Print "Biggest number is ", big
End Sub
Output

Example 14.8 – 3x3 Matrix, before and after transposing
Private Sub Form_click()
Dim a(3, 3), i, j As Integer
For i = 1 To 3
For j = 1 To 3
a(i, j) = Val(InputBox("Enter the Numbers"))
Next j
Next i
Print "Before transposing Matrix is..."
For i = 1 To 3
For j = 1 To 3
Print a(i, j); "";
Next j
Print
Next i
Print "Aftertransposing Matrix is..."
For i = 1 To 3
For j = 1 To 3
Print a(j, i); "";
Next j
Print
Next i
End Sub
Output

Example 14.9
Dim d, d1 As Date
Private Sub Command1_Click()
d = Text1
d1 = Now()
y = Year(d)
Y1 = Year(d1)
age = (Y1 - y)
MsgBox "Your age is " & age
End Sub
Output

Character, Mathematics and Date & Time Functions
Example 14.10
Private Sub Form_Click()
Print Len("emmess")
Print InStr("emmess Computer Center", "c")
Print Left("emmess", 2)
Print Right("emmess", 2)
Print Mid("emmess", 2, 3)
Print LTrim("   emmess")
Print RTrim("emmess  ")
Print String(10, "#")
Print LCase("EMMESS")
Print UCase("emmess")
Print Asc("emmess")
Print Chr(10)
Print Now()
Print Date
Print Month(Date)
Print Year(Date)
Print Time()
Print DateValue("25/07/2012")
Print Day(Date)
Print Hour(Time)
Print Minute(Time)
Print Second(Time)
Print Abs(-4)
Print Exp(4)
Print Sqr(4)
Print Sin(2)
Print Log(2)
Print Cos(3)
Print Tan(5)
Print Sgn(25)
Print Fix(17.5)
Print StrComp("emmess", "ms")
Print StrReverse("emmess")
End Sub
Output

Example 14.11
a) The Interface
b) The Codes
Private Sub Form_Load()
Label1.Caption = "Emmess Info Tech "
Label1.FontSize = 20
Label1.FontName = "Arial Rounded MT Bold"
Timer1.Interval = 200
End Sub
Private Sub Timer1_Timer()
Label1.Caption = Mid(Label1.Caption, 2, Trim(Len(Label1.Caption))) + Mid(Label1, 1, 1)
Label1.ForeColor = RGB(Rnd * 255, Rnd * 255, Rnd * 255)
End Sub
c) Output
Example 14.12
Dim d, d1 As Date
Private Sub Form_Click()
d = InputBox("Enter Your date of Birth")
y = Year(d)
Y1 = Year(Now())
Y2 = Y1 - y + 1
d1 = DateAdd("yyyy", Y2, d)
w = Weekday(d1)
Select Case w
Case 1
MsgBox "Your Birthday is Sunday"
Case 2
MsgBox "Your Birthday is Monday"
Case 3
MsgBox "Your Birthday is Tuesday"
Case 4
MsgBox "Your Birthday is Wednesday"
Case 5
MsgBox "Your Birthday is Thursday"
Case 6
MsgBox "Your Birthday is Friday"
Case 7
MsgBox "Your Birthday is Saterday"
End Select
End Sub
Output