INTRODUCTION TO VISUAL BASIC Visual Basic is an ideal programming language for developing sophisticated professional applications for Windows.
It makes use of Graphical User Interface (GUI) for creating robust and powerful applications. The Graphical user Interface as the name suggests, uses illustrations for text, which enables user to interact with an application. This feature makes it easier to comprehend things in a quicker and easier way. In a GUI environment, the number of options open to the user are much greater, allowing more freedom to the user and developer. Features such as easier comprehension, user-friendliness, faster application development (RAD) and many other aspects such as introduction to ActiveX technology and Internet features make visual basic an interesting tool to work with. HISTORY Visual Basic was developed from the programming language-BASIC in the 1970s, Microsoft started developing ROM-based interpreted BASIC for the early microprocessor based computers. In 1982, Microsoft QuickBasic revolutionized BASIC and was legitimized as a serious development language for MS-DOS environment. Later on, Microsoft Corporation created the enhanced version of BASIC called Visual Basic for Windows. THE INTEGRATED DEVELOPMENT ENVIRONMENT (IDE) One of the most significant changes in Visual Basic 6.0 is the Integrated Development Environment (IDE). IDE is a term commonly used in the programming world to describe the interface and environment that a programmer can use to create applications. It is called integrated because a programmer can access virtually all of the development tools that he/she need from one screen called an interface. The IDE is also commonly referred to as the design environment, or the program. The Visual Basic IDE is made up of a number of components: Menu Bar Tool Bar Project Explorer Properties window Form Layout Window Toolbox Form Designer Object Browser Menu Bar The Menu Bar displays the commands that are required to build an application. The main menu items have sub menu items that can be chosen when needed. The toolbars in the menu bar provide quick access to the commonly used commands and a button in the toolbar is clicked once to carry out the action represented by it. Toolbox The Toolbox contains a set of controls that are used to place on a Form at design time thereby creating the user interface area. Additional controls can be included in the toolbox by using the Components menu item on the Project menu.
Control Description Pointer PictureBox Label TextBox Frame CommandButton CheckBox OptionButton ListBox ComboBox HScrollBar and VScrollBar DriveListBox DirListBox FileListBox Shape Line Image Data OLE Provides a way to move and resize the controls form Displays icons/bitmaps and metafiles. It displays text or acts as a visual container for other controls. Displays a text that the user cannot modify or interact with. Used to display message and enter text. Serves as a visual and functional container for controls Used to carry out the specified action when the user chooses it. Displays a True/False or Yes/No option. This control which is a part of an option group allows the user to select only one option even it displays mulitiple choices. Displays a list of items from which a user can select one. Contains a TextBox and a ListBox. This allows the user to select an ietm from the dropdown ListBox, or to type in a selection in the TextBox. These controls allow the user to select a value within the specified range of values Timer Executes the timer events at specified intervals of time Displays the valid disk drives and allows the user to select one of them. Allows the user to select the directories and paths, which are displayed. Displays a set of files from which a user can select the desired one. Used to add shape (rectangle, square or circle) to a Form Used to draw straight line to the Form Used to display images such as icons, bitmaps and metafiles. Enables the use to connect to an existing database and display information from it. Used to link or embed an object, display and manipulate data from other windows based applications.
Project Explorer Docked on the right-side of the screen, just under the toolbar, is the Project Explorer window. The Project Explorer serves as a quick reference to the various elements of a project namely form, classes and modules. All of the object that makes up the application are packed in a project. A simple project will typically contain one form, which is a window that is designed as part of a program's interface. It is possible to develop any number of forms for use in a program, although a program may consist of a single form or more than one form. In addition to forms, the Project Explorer window also lists code modules and classes. Properties Window The Properties Window is docked under the Project Explorer window. The Properties Window exposes the various characteristics of selected objects. Each and every form in an application is considered an object. Each object in Visual Basic has characteristics such as color and size. Other characteristics affect not just the appearance of the object but the way it behaves too. All these characteristics of an object are called its properties. Thus, a form has properties and any controls placed on it will have properties too. All of these properties are displayed in the Properties Window. Object Browser The Object Browser allows us to browse through the various properties, events and methods that are made available to us. It is accessed by selecting Object Browser from the View menu or pressing the key F2. The left column of the Object Browser lists the objects and classes that are available in the projects that are opened and the controls that have been referenced in them. It is possible to scroll through the list and select the desired object or class to inspect. After an object is picked up from the Classes list, its members (properties, methods and events) can be seen in the right column. A property is represented by a small icon that has a hand holding a piece of paper. Methods are denoted by little green blocks, while events are denoted by yellow lightning bolt icon. VB TERMINOLOGY
Term Design time Run time Forms Controls Objects Properties Methods Events Event-driven programming Description When the application is still being developed in the Visual Basic environment. When the application is executed. At run time, the programmer interacts with the application as the user would. Windows that can be customized to serve as the interface for an application or as dialog boxes used to gather information from the user. Graphic representations of objects, such as buttons, list boxes, and edit boxes, that users manipulate to provide information to the application. A general term used to describe all the forms and controls that make up a program. The characteristics of an object such as size, caption, or color. The actions that an object can perform or that can be performed on the object. Actions recognized by a form or control. Events occur as the user, operating system, or application interacts with the objects of a program.
Event-driven programming or event-based programming is a programming paradigm in which the flow of the program is determined by events. When user performs an action on a graphical component, an event generated. The program responds to events that the user generates in interacting with GUI components.
The order of events is controlled by the user. MODULES in Visual Basic Code in Visual Basic is stored in modules. There are three kinds of modules: form, standard, and class. Simple applications can consist of just a single form, and all of the code in the application resides in that form module. As the applications get larger and more sophisticated, additional forms needed. Eventually their might be some common code that can be used in several forms. Instead of duplicating the code in both forms, a separate module containing a procedure that implements the common code can be created. This separate module should be a standard module. Each standard, class, and form module can contain: Declarations. A constant, type, variable, and dynamic-link library (DLL) procedure can be declared at the module level of form, class or standard modules. Procedures. A Sub, Function, or Property procedure contains pieces of code that can be executed as a unit. Form Modules Form modules (.FRM file name extension) are the foundation of most Visual Basic applications. They can contain procedures that handle events, general procedures, and form-level declarations of variables, constants, types, and external procedures. Standard Modules Standard modules (.BAS file name extension) are containers for procedures and declarations commonly accessed by other modules within the application. They can contain global (available to the whole application) or module-level declarations of variables, constants, types, external procedures, and global procedures. Class Modules Class modules (.CLS file name extension) are the foundation of object-oriented programming in Visual Basic. Class modules can be used to create new objects. These new objects can include customized properties and methods. Actually, forms are just class modules that can have controls placed on them and can display form windows.
PROCEDURES in Visual Basic Visual Basic programs can be broken into smaller logical components called Procedures. Procedures are useful for condensing repeated operations such as the frequently used calculations, text and control manipulation etc. The benefits of using procedures in programming are: It is easier to debug a program a program with procedures, which breaks a program into discrete logical limits. Procedures used in one program can act as building blocks for other programs with slight modifications. A Procedure can be Sub, Function or Property Procedure. Sub Procedures A sub procedure can be placed in standard, class and form modules. Each time the procedure is called, the statements between Sub and End Sub are executed. The syntax for a sub procedure is as follows:
[Private | Public] [Static] Sub Procedurename [( arglist)] [ statements] End Sub arglist is a list of argument names separated by commas. Each argument acts like a variable in the procedure. There are two types of Sub Procedures namely general procedures and event procedures. Event Procedures An event procedure is a procedure block that contains the control's actual name, an underscore(_), and the event name. The following syntax represents the event procedure for a Form_Load event. Private Sub Form_Load() ....statement block.. End Sub Event Procedures acquire the declarations as Private by default. General Procedures A general procedure is declared when several event procedures perform the same actions. It is a good programming practice to write common statements in a separate procedure (general procedure) and then call them in the event procedure. In order to add General procedure: The Code window is opened for the module to which the procedure is to be added. The Add Procedure option is chosen from the Tools menu, which opens an Add Procedure dialog box. The name of the procedure is typed in the Name textbox Under Type, Sub is selected to create a Sub procedure, Function to create a Function procedure or Property to create a Property procedure. Under Scope, Public is selected to create a procedure that can be invoked outside the module, or Private to create a procedure that can be invoked only from within the module. A new procedure can also be created in the current module by typing Sub ProcedureName, Function ProcedureName, or Property ProcedureName in the Code window. Function Procedures Functions are like sub procedures, except they return a value to the calling procedure. They are especially useful for taking one or more pieces of data, called arguments and performing some tasks with them. Then the function returns a value that indicates the results of the tasks complete within the function. The following function procedure calculates the cube of a number, where n is the number, which it takes as a argument (of data type Double) and finally returns the results. Function CubeofNum (n As Double) As Double CubeofNum = (n*n*n) End Function The above function procedure is written in the general declarations section of the Code window. A function can also be written by selecting the Add Procedure dialog box from the Tools menu and by choosing the required scope and type. Property Procedures A property procedure is used to create and manipulate custom properties. It is used to create read only properties for Forms, Standard modules and Class modules. Visual Basic provides three kind of property proceduresProperty Let procedure that sets the value of a property, Property Get procedure that returns the value of a property, and
Property Set procedure that sets the references to an object. Operators And Expressions In Visual Basic An operator is a code element that performs an operation on one or more code elements that hold values. Value elements include variables, constants, literals, properties, returns from Function and Operator procedures, and expressions. An expression is a series of value elements combined with operators, which yields a new value. The operators act on the value elements by performing calculations, comparisons, or other operations. The value elements that are combined with an operator are called operands of that operator. Operators combined with value elements form expressions, except for the assignment operator, which forms a statement. Visual Basic provides the following types of operators: Arithmetic Operators (+,-,*, /) perform familiar calculations on numeric values, including shifting their bit patterns. Comparison Operators (> , < , >= , <=) compare two expressions and return a Boolean value representing the result of the comparison. Concatenation Operators (&, +) join multiple strings into a single string. Logical and Bitwise Operators (AND, OR, NOT) in Visual Basic combine Boolean or numeric values and return a result of the same data type as the values. Assignment statements carry out assignment operations, which consist of taking the value on the right side of the assignment operator (=) and storing it in the element on the left, as in the following example, v = 42 Naming Conventions Used In Visual Basic These are the rules to follow when naming elements in VB - variables, constants, controls, procedures, and so on: A name must begin with a letter. May be as much as 255 characters long. Must not contain a space or an embedded period or type-declaration characters used to specify a data type; these are ! # % $ & @ Must not be a reserved word (that is part of the code, like Option, End, Stop for example) The dash, although legal, should be avoided because it may be confused with the minus sign. Instead of First-name use First_name or FirstName. DATA TYPES in Visual Basic By default Visual Basic variables are of variant data types. The variant data type can store numeric, date/time or string data. When a variable is declared, a data type is supplied for it that determines the kind of data they can store. The fundamental data types in Visual Basic including variant are integer, long, single, double, string, currency, byte and boolean. Each data type has limits to the kind of information and the minimum and maximum values it can hold. A list of Visual Basic's simple data types are given below. 1. Numeric Byte
Store integer values in the range of 0 - 255
Integer Long Single Double Currency
Store integer values in the range of (-32,768) - (+ 32,767) Store integer values in the range of (- 2,147,483,468) - (+ 2,147,483,468) Store floating point value in the range of (-3.4x10-38) - (+ 3.4x1038) Store large floating value which exceeding the single data type value store monetary values. It supports 4 digits to the right of decimal point and 15 digits to the left
2. String Use to store alphanumeric values. A variable length string can store approximately 4 billion characters 3. Date Use to store date and time values. A variable declared as date type can store both date and time values and it can store date values 01/01/0100 up to 12/31/9999 4. Boolean Boolean data types hold either a true or false value. These are not stored as numeric values and cannot be used as such. Values are internally stored as -1 (True) and 0 (False) and any non-zero value is considered as true. 5. Variant Stores any type of data and is the default Visual Basic data type. In Visual Basic if we declare a variable without any data type by default the data type is assigned as default.
VARIABLES in Visual Basic 6 Variables are the memory locations which are used to store values temporarily. A defined naming strategy has to be followed while naming a variable. A variable name must begin with an alphabet letter and should not exceed 255 characters. It must be unique within the same scope. It should not contain any special character like %, &, !, #, @ or $. There are many ways of declaring variables in Visual Basic. Depending on where the variables are declared and how they are declared. The different ways of declaring variables in Visual Basic are listed below: Explicit Declaration Declaring a variable tells Visual Basic to reserve space in memory. It is not must that a variable should be declared before using it. Automatically whenever Visual Basic encounters a new variable, it assigns the default variable type and value. This is called implicit declaration. Though this type of declaration is easier for the user, to have more control over the variables, it is advisable to declare them explicitly. The variables are declared with a Dim statement to name the variable and its type. The As type clause in the Dim statement allows to define the data type or object type of the variable. This is called explicit declaration. Syntax: Dim variable [As Type] For example, Dim strName As String Dim intCounter As Integer Using Option Explicit statement
It may be convenient to declare variables implicitly, but it can lead to errors that may not be recognized at run time. In Visual Basic, to prevent errors of this nature, the following statement can be declared in the general declaration section of the Form. Syntax: Option Explicit This forces the user to declare all the variables. The Option Explicit statement checks in the module for usage of any undeclared variables and reports an error to the user. The user can thus rectify the error on seeing this error message. The Option Explicit statement can be explicitly placed in the general declaration section of each module using the following steps. 1. Click Options item in the Tools menu 2. Click the Editor tab in the Options dialog box 3. Check Require Variable Declaration option and then click the OK button SCOPE OF VARIABLES The scope of a variable, procedure or object determines which part of the code in our application is aware of the variable's existence. Local Variables A local variable is one that is declared inside a procedure. This variable is only available to the code inside the procedure and can be declared using the Dim statements as given below. Dim sum As Integer The local variables exist as long as the procedure in which they are declared, is executing. Once a procedure is executed, the values of its local variables are lost and the memory used by these variables is freed and can be reclaimed. Variables that are declared with keyword Dim exist only as long as the procedure is being executed. Static Variables Static variables are not reinitialized each time Visual Basic invokes a procedure and therefore retain or preserve value even when a procedure ends. In case, we need to keep track of the number of times a command button in an application is clicked, a static counter variable has to be declared. These static variables are also ideal for making controls alternately visible or invisible. A static variable is declared as given below. Static intPermanent As Integer Variables have a lifetime in addition to scope. The values in a module-level and public variables are preserved for the lifetime of an application whereas local variables declared with Dim exist only while the procedure in which they are declared is still being executed. The value of a local variable can be preserved using the Static keyword. Example: The following is an example of an event procedure for a CommandButton that counts and displays the number of clicks made. Private Sub Command1_Click ( ) Static Counter As Integer Counter = Counter + 1 Print Counter End Sub The first time we click the CommandButton, the Counter starts with its default value of zero. Visual Basic then adds 1 to it and prints the result. Module Level Variables
A module level variable is available to all the procedures in the module. They are declared using the Public or the Private keyword. Private or Dim scope: A variable declared as Private or Dim is visible to all procedures within the module or form where it is declared. This is done in the General Declarations section (The very top of the form/module) using the Dim or Private keywords. If a variable is declared within a procedure, then it becomes a local variable and is only visible to anything that is inside that procedure. Example: Private MyNumber as Integer Public scope: A variable declared as Public at the module or form level that is visible to all procedures within the project. Public variables must be declared in the General Declarations section. Example: Public MyNumbr as Integer The above statement makes MyNumber visible to all forms/modules within the project.
CONTROL STRUCTURES in Visual Basic Control Statements are used to control the flow of program's execution. Visual Basic supports control structures such as if... Then, if...Then ...Else, Select...Case, and Loop structures such as Do While...Loop, While...Wend, For...Next etc method. If...Then selection structure The If...Then selection structure performs an indicated action only when the condition is True; otherwise the action is skipped. Syntax of the If...Then structure: If <condition> Then statement End If e.g.: If average>75 Then txtGrade.Text = "A" End If If...Then...Else selection structure The If...Then...Else selection structure allows the programmer to specify that a different action is to be performed when the condition is True than when the condition is False. Syntax of the If...Then...Else structure: If <condition > Then statements Else statements End If
e.g.: If average>50 Then txtGrade.Text = "Pass" Else txtGrade.Text = "Fail" End If Nested If...Then...Else selection structure Nested If...Then...ElseIf selection structures test for multiple cases by placing If...Then...Else selection structures inside If...Then...Else structures. Syntax of the Nested If...Then...Else selection structure: Nested If can be used in either of the methods as shown: Method 1 Method 2 If < condition 1 > Then statements ElseIf < condition 2 > Then statements ElseIf < condition 3 > Then statements Else Statements End If If < condition 1 > Then statements Else If < condition 2 > Then statements Else If < condition 3 > Then statements Else Statements End If End If EndIf
e.g.: Assume you have to find the grade using nested if and display in a text box If average > 75 Then txtGrade.Text = "A" ElseIf average > 65 Then txtGrade.Text = "B" ElseIf average > 55 Then txtGrade.text = "C" ElseIf average > 45 Then txtGrade.Text = "D" Else txtGrade.Text = "F" End If Select...Case selection structure Select...Case structure is an alternative to If...Then...ElseIf for selectively executing a single block of statements from among multiple blocks of statements. Select...case is more convenient to use than the If...Else...End If. Syntax of the Select...Case selection structure Select Case <test expression> Case <expression1> <statements> Case <expression2>
<statements> Case Else <statements> End Select The following program block illustrate the working of Select...Case. e.g.: Assume we have to find the grade using select...case and display in the text box Dim average as Integer average = val(txtAverage.Text) Select Case average Case 100 To 75 txtGrade.Text ="A" Case 74 To 65 txtGrade.Text ="B" Case 64 To 55 txtGrade.Text ="C" Case 54 To 45 txtGrade.Text ="S" Case 44 To 0 txtGrade.Text ="F" Case Else MsgBox "Invalid average marks" End Select The expression list in a "Case" clause can have any of the following formats: Format Examples <expression> [, expression, . . . ] Case 1, 10, 100 Case "Y", "y" <expression> To <expression> Case 1 To 9 Case "A" To "C" Is <relational operator expression> Case Is >= 21 (combination of any of the above) Case Is <= 5, 20 To 29, 43
LOOPS (Repetition Structures) in Visual Basic A repetition structure allows the programmer to repeat an action until given condition is true. Do While... Loop Statement The Do While...Loop is used to execute statements until a certain condition is met. Syntax: Do While (condition) <statements to be executed> Loop The following Do Loop counts from 1 to 100. Dim num As Integer num= 1 Do While num <= 100
num = num + 1 Loop A variable num is initialized to 1 and then the Do While Loop starts. First, the condition is tested; if condition is True, then the statements are executed. When it gets to the Loop it goes back to the Do and tests condition again. If condition is False on the first pass, the statements are never executed. While... Wend Statement A While...Wend statement behaves like the Do While...Loop statement. The following While...Wend counts from 1 to 100. Syntax: While (condition) <statements to be executed> Wend Dim num As Integer num= 1 While num<=100 num = num + 1 Wend Do...Loop While Statement The Do...Loop While statement first executes the statements and then test the condition after each execution. The following program block illustrates the structure: Syntax: Do <statements to be executed> Loop While (condition) Dim num As Integer num = 0 Do num = num + 1 Loop While num < 201 The program executes the statements between Do and Loop While structure in any case. Then it determines whether the counter is less than 201. If so, the program again executes the statements between Do and Loop While else exits the Loop. Do Until...Loop Statement Unlike the Do While...Loop and While...Wend repetition structures, the Do Until... Loop structure tests a condition for falsity. Statements in the body of a Do Until...Loop are executed repeatedly as long as the loop-continuation test evaluates to False. Syntax: Do Until (condition) <statements to be executed> Loop An example for Do Until...Loop statement. The coding is typed inside the click event of the command button. Dim num As Integer num=0 Do Until num > 1000
num= num + 1 Print num Loop Numbers between 1 to 1000 will be displayed on the form as soon as command button is clicked. Do...Loop Until Statement Statements in the body of a Do Loop Until are executed repeatedly as long as the loopcontinuation test evaluates to True. Syntax: Do (statements to be executed) Loop Until (condition) Example: The coding is typed inside the click event of the command button. Dim LoopCount As Integer Do LoopCount = LoopCount + 1 Loop Until MsgBox("Loop?", vbYesNo) = vbNo LoopCount is simply a counter that is increment every time by 1. The loop keeps on running until No is clicked on the message box, on clicking the command button. The For...Next Loop ForNext statement is used to code a loop that repeats for a specific number of times. Syntax: For counter=startvalue To endvalue [stepvalue] [statements to be executed] Next counter is a numeric variable that keeps track of how many times the loop instructions are repeated startvalue, endvalue, and stepvalue Must be numeric Can be positive or negative, integer or non-integer Default stepvalue is 1 Example, The following loop counts the numbers from 1 to 50: Dim x As Integer For x = 1 To 50 Text1.text=Text1.text & x Next The above loop counts numbers as 1, 2, 3, 4..etc In order to count the numbers from 1 to 50 in steps of 2, the following loop can be used For x = 1 To 50 Step 2 Text1.text=Text1.text & x Next The above loop counts numbers as 1, 3, 5, 7..etc
Exit For and Exit Do Statement A For...Next or Do While loop can be terminated by an Exit For or Exit Do statement under certain condition. Consider the following statement block. Dim x As Integer For x = 1 To 10 Text1.text=Text1.text & x If x = 5 Then Print "The program exited at x=5" Exit For End If Next The preceding code increments the value of x by 1 until it reaches the condition x = 5. The Exit For statement is executed and it terminates the For...Next loop. The Following statements block containing Do...While loop is terminated using Exit Do statement. Dim x As Integer Do While x < 10 Text.text=Text1.text & x x=x+1 If x = 5 Then Print "The program is exited at x=5" Exit Do End If Loop
For EachNext statement The For EachNext statement is used to code a loop whose instructions will processed for each object in a collection. Syntax: For Each element In group [processing statements for element] Next Consider the following code, which is written on a command button click: Dim obj As Object For Each obj In Me If TypeOf obj Is TextBox Then obj.Text = "" End If Next Here, obj is the variable of type object which contain all the objects on Me(ActiveForm). The TypeOf function checks for the object as TextBox, if a TextBox is found its text property will be cleared. So on clicking the command button, all the textboxes will be cleared.