Getting Started With VB 6

download Getting Started With VB 6

of 133

Transcript of Getting Started With VB 6

  • 8/3/2019 Getting Started With VB 6

    1/133

    1

    Getting Started With Visual Basic 6.0

    Visual Basic is initiated by using the Programs option > Microsoft Visual Basic 6.0 > Visual Basic 6.0. Clicking the Visual

    Basic icon, we can view a copyright screen enlisting the details of the license holder of the copy of Visual Basic 6.0. Then

    it opens in to a new screen as shown in figure 1 below, with the interface elements Such as MenuBar, ToolBar, The New

    Project dialog box. These elements permit the user to buid different types of Visual Basic applications.

    The Integrated Development Environment

    One of the most significant changes in Visual Basic 6.0 is the Integrated Development Environment (IDE). IDE is a termcommonly used in the programming world to describe the interface and environment that we use to create ourapplications. It is calledintegratedbecause we can access virtually all of the development tools that we need from onescreen called an interface. The IDE is also commonly referred to as the design environment, or theprogram.Tha 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

    In previous versions of Visual Basic, the IDE was designed as a Single Document Interface (SDI). In a Single DocumentInterface, each window is a free-floating window that is contained within a main window and can move anywhere on thescreen as long as Visual Basic is the current application. But, in Visual Basic 6.0, the IDE is in a Multiple DocumentInterface (MDI) format. In this format, the windows associated with the project will stay within a single container known asthe parent. Code and form-based windows will stay within the main container form.Figure 1 The Visual Basic startup dialog box

    Menu Bar

    This Menu Bar displays the commands that are required to build an application. The main menu items have sub menuitems that can be chosen when needed. The toolbars in the menu bar provide quick access to the commonly usedcommands 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 interfacearea. Additional controls can be included in the toolbox by using the Components menu item on the Project menu. AToolbox is represented in figure 2 shown below.

  • 8/3/2019 Getting Started With VB 6

    2/133

    2

    Figure 2 Toolbox window with its controls available commonly.

    Control Description

    Pointer Provides a way to move and resize the controls form

    PictureBoxDisplays icons/bitmaps and metafiles. It displays text or acts as a visual container for

    other controls.

    TextBox Used to display message and enter text.

    Frame Serves as a visual and functional container for controls

    CommandButton Used to carry out the specified action when the user chooses it.

    CheckBox Displays a True/False or Yes/No option.

    OptionButtonOptionButton control which is a part of an option group allows the user to select only

    one option even it displays mulitiple choices.

    ListBox Displays a list of items from which a user can select one.

    ComboBoxContains 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.

    HScrollBar and

    VScrollBarThese controls allow the user to select a value within the specified range of values

    Timer Executes the timer events at specified intervals of time

    DriveListBox Displays the valid disk drives and allows the user to select one of them.

  • 8/3/2019 Getting Started With VB 6

    3/133

    3

    DirListBox Allows the user to select the directories and paths, which are displayed.

    FileListBox Displays a set of files from which a user can select the desired one.

    Shape Used to add shape (rectangle, square or circle) to a Form

    Line Used to draw straight line to the Form

    Imageused to display images such as icons, bitmaps and metafiles. But less capability than

    the PictureBox

    Data Enables the use to connect to an existing database and display information from it.

    OLEUsed to link or embed an object, display and manipulate data from other windows

    based applications.

    Label Displays a text that the user cannot modify or interact with.

    Project Explorer

    Docked on the right side of the screen, just under the tollbar, is the Project Explorer window. The Project Explorer asshown in in figure servres as a quick reference to the various elements of a project namely form, classesand modules. Allof the object that make up the application are packed in a project. A simple project will typically contain one form, which isa window that is designed as part of a program's interface. It is possible to develop any number of forms for use in aprogram, although a program may consist of a single form. In addition to forms, the Project Explorer window also listscode modules and classes.Figure 3 Project Explorer

    Properties Window

    The Properties Window is docked under the Project Explorer window. The Properties Window exposes the variouscharacteristics of selected objects. Each and every form in an application is considered an object. Now, each object inVisual Basic has characteristics such as color and size. Other characteristics affect not just the appearance of the objectbut the way it behaves too. All these characteristics of an object are called its properties. Thus, a form has properties andany controls placed on it will have propeties 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 tous. It is accessed by selecting Object Browser from the View menu or pressing the key F2. The left column of the ObjectBrowser lists the objects and classes that are available in the projects that are opened and the controls that have beenreferenced in them. It is possible for us to scroll through the list and select the object or class that we wish to inspect. Afteran object is picked up from the Classes list, we can see its members (properties, methods and events) 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 greenblocks, while events are denoted by yellow lightning bolt icon.Object naming conversions of controls (prefix)

    Form -frmLabel-lblTextBox-txt

  • 8/3/2019 Getting Started With VB 6

    4/133

    4

    CommandButton-cmdCheckBox -chkOptionButton -optComboBox -cboListBox-lstFrame-fme

    PictureBox -picImage-imgShape-shpLine -linHScrollBar -hsbVScrollBar -vsb

    Visual Basic 6.0 - Properties, Methods And EventsAll the controls in the ToolBox except the Pointer are objects in Visual Basic. These objects have associated properties,

    methods and events.

    Real world objects are loaded with properties. For example, a flower is loaded certain color, shape and fragrance.Similarly programming objects are loaded with properties. A property is a named attribute of a programming object.Properties define the characteristics of an object such as Size, Color etc. or sometimes the way in which it behaves. Forexample, a TextBox accepts properties such as Enabled, Font, MultiLine, Text, Visible, Width, etc.

    Enables property allows the TextBox to be enabled or disabled at run time depending on the condition setto True or False. Font property sets a particular font in the TextBox. MultiLine property allows the TextBox to accept and display multiple lines at run time. Text property of the TextBox control sets a particular text in the control. Visible property is used to hide the object at run time. Width property sets the TextBox to the desired width at design time.

    The properties that are discussed above are design-time properties that can be set at the design tme by selecting theProperties Window. But certain properties cannot be set at desgn time. For example, the CurrentX and CurrentYproperties of a Form cannot be set at the design time.A method is an action that can be performed on objects. For example, a cat is an object. Its properties might include longwhite hair, blue eyes, 3 pounds weight etc. A complete definition of cat must only encompass on its looks, but should also

    include a complete itemization of its activities. Therefore, a cat's methods might be move, jump, play, breath etc.Siimilarly in object-orinted programming, a method is a connected or built-in procedure, a block of code that can beinvoked to impart some action on a particular object. A method requires an object to provide them with a context. Forexample, the word Move has no meaning in Visual Basic, but the statement,

    Text1.Move 700, 400

    performs a very precise action. The TextBox control has other associated methods such as Refresh, SetFocus, etc.

    The Refresh method enforces a complete repaint of the control or a Form. For example, Text1.Refreshrefreshes the TextBox. The Setfocus method moves the focus on the control. For Example Text1.SetFocus sets the focus toTextBox control Text1.

    Event Driven Programming

    Visual Basic programs are built around events. Events are various things that can happen in a program. this will becomeclearer when studied in contrast to procedural programming. In procedural languages, an application is written is executedby checking for the program logically through the program statements, one after another. For a temporary phase, thecontrol may be transferred to some other point in a program. While in an event driven application, the program statementsare executed only when a particular event calls a specific part of the code that is assigned to the event.Let us consider a TextBox control and a few of its associated events to understand the concept of event drivenprogramming. The TextBox control supports various events such as Change, Click, MouseMove and many more that willbe listed in the Properties dropdown list in the code window for the TextBox control. We will look into a few of them asgiven below.

  • 8/3/2019 Getting Started With VB 6

    5/133

    5

    The code entered in the Change event fires when there is a change in the contents of the TextBox The Click event fires when the TextBox control is clicked. The MouseMove event fires when the mouse is moved over the TextBox

    As explained above, several events are associated with different controls and forms, some of the events being common tomost of them and few being specific to each control.

    Visual Basic 6 (VB6) Data Types, Modules And OperatorsVisual Basic uses building blocks such as Variables, Data Types, Procedures, Functions and Control Structures in itsprogramming environment. This section concentrates on the programming fundamentals of Visual Basic with the blocksspecified.ModulesCode in Visual Basic is stored in the form of modules. The three kind of modules are Form Modules, Standard Modulesand Class Modules. A simple application may contain a single Form, and the code resides in that Form module itself. Asthe application grows, additional Forms are added and there may be a common code to be executed in several Forms. Toavoid the duplication of code, a separate module containing a procedure is created that implements the common code.This is a standard Module.Class module (.CLS filename extension) are the foundation of the object oriented programming in Visual Basic. New

    objects can be created by writing code in class modules. Each module can contain:Declarations : May include constant, type, variable and DLL procedure declarations.Procedures : A sub function, or property procedure that contain pieces of code that can be executed as a unit.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 (but don't forget that somebody has to type the stuff!). Must not contain a space or an embedded period or type-declaration characters used to specify a datatype; these are ! # % $ & @ Must not be a reserved word (that is part of the code, like Option, for example) The dash, although legal, should be avoided because it may be confused with the minus sign. Instead ofFirst-name use First_name or FirstName.

    Data types in Visual Basic 6By 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. Thefundamental data types in Visual Basic including variant are integer, long, single, double, string, currency, byte andboolean. Visual Basic supports a vast array of data types. Each data type has limits to the kind of information and theminimum and maximum values it can hold. In addition, some types can interchange with some other types. A list of VisualBasic's simple data types are given below.1. Numeric

    Byte Store integer values in the range of 0 - 255

    Integer Store integer values in the range of (-32,768) - (+ 32,767)

    Long Store integer values in the range of (- 2,147,483,468) - (+ 2,147,483,468)

    Single Store floating point value in the range of (-3.4x10-38) - (+ 3.4x1038)

    Double Store large floating value which exceeding the single data type value

    Currency store monetary values. It supports 4 digits to the right of decimal point and 15 digits to theleft

    2. StringUse to store alphanumeric values. A variable length string can store approximately 4 billion characters3. DateUse to store date and time values. A variable declared as date type can store both date and time values and it can storedate values 01/01/0100 up to 12/31/99994. BooleanBoolean 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. VariantStores any type of data and is the default Visual Basic data type. In Visual Basic if we declare a variable without any datatype by default the data type is assigned as default.

  • 8/3/2019 Getting Started With VB 6

    6/133

    6

    Operators in Visual BasicArithmetical Operators

    Operators Description Example Result

    + Add 5+5 10

    - Substract 10-5 5

    / Divide 25/5 5

    \ Integer Division 20\3 6

    * Multiply 5*4 20

    ^ Exponent (power of) 3^3 27

    Mod Remainder of division 20 Mod 6 2

    & String concatenation "George"&" "&"Bush" "George Bush"Relational Operators

    Operators Description Example Result

    > Greater than 10>8 True

    < Less than 10= Greater than or equal to 20>=10 True

  • 8/3/2019 Getting Started With VB 6

    7/133

    7

    This is called implicit declaration. Though this type of declaration is easier for the user, to have more control over thevariables, it is advisable to declare them explicitly. The variables are declared with a Dim statement to name the variableand its type. The As type clause in the Dim statement allows to define the data type or object type of the variable. This iscalled explicit declaration.SyntaxDim variable [As Type]

    For example,Dim strName As StringDim intCounter As IntegerUsing Option Explicit statementIt may be convenient to declare variables implicitly, but it can lead to errors that may not be recognized at run time. Say,for example a variable by name intcountis used implicitly and is assigned to a value. In the next step, this field isincremented by 1 by the following statement

    Intcount = Intcount + 1This calculation will result in intcountyielding a value of 1 as intcount would have been initialized to zero. This is becausethe intcount variable has been mityped as incont in the right hand side of the second variable. But Visual Basic does notsee this as a mistake and considers it to be new variable and therefore gives a wrong result.In Visual Basic, to prevent errors of this nature, we can declare a variable by adding the following statement to the generadeclaration section of the Form.

    Option Explicit

    This forces the user to declare all the variables. The Option Explicit statement checks in the module for usage of anyundeclared 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 thefollowing steps.

    Click Options item in the Tools menu Click the Editor tab in the Options dialog box Check Require Variable Declaration option and then click the OK button

    Scope of variablesA variable is scoped to a procedure-level (local) or module-level variable depending on how it is declared. The scope of avariable, procedure or object determines which part of the code in our application are aware of the variable's existence. Avariable is declared in general declaration section of e Form, and hence is available to all the procedures. Local variablesare recognized only in the procedure in which they are declared. They can be declared with Dimand Statickeywords. Ifwe want a variable to be available to all of the procedures within the same module, or to all the procedures in an

    application, a variable is declared with broader scope.Local VariablesA local variable is one that is declared inside a procedure. This variable is only available to the code inside the procedureand 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. Variablesthat are declared with keyword Dim exist only as long as the procedure is being executed.Static VariablesStatic variables are not reinitialized each time Visual Invokes a procedure and therefore retains or preserves value evenwhen 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 alternatelyvisible 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 thelifetime of an application whereas local variables declared with Dim exist only while the procedure in which they aredeclared is still being executed. The value of a local variable can be preserved using the Static keyword. The follwoingprocedure calculates the running total by adding new values to the previous values stored in the static variable value.

    Function RunningTotal ( )Static AccumulateAccumulate = Accumulate + num

  • 8/3/2019 Getting Started With VB 6

    8/133

    8

    RunningTotal = AccumulateEnd Function

    If the variable Accumulate was declared with Dim instead of static, the previously accumulated values would not bepreserved accross calls to the procedure, and the procedure would return the same value with which it was called. Tomake all variables in a procedure static, the Static keyword is placed at the beginning of the procedure heading as given

    in the below statement.

    Static Function RunningTotal ( )

    ExampleThe following is an example of an event procedure for a CommandButton that counts and displays the number of clicksmade.

    Private Sub Command1_Click ( )Static Counter As IntegerCounter = Counter + 1Print CounterEnd Sub

    The first time we click the CommandButton, the Counter starts with its default value of zero. Visual Basic then adds 1 to itand prints the result.Module Levele VariablesA module level variable is available to all the procedures in the module. They are declared using the Publicorthe Privatekeyword. If you declare a variable using a Private or a Dim statement in the declaration section of a moduleastandard BAS module, a form module, a class module, and so onyou're creating a private module-level variable. Suchvariables are visible only from within the module they belong to and can't be accessed from the outside. In general, thesevariables are useful for sharing data among procedures in the same module:

    ' In the declarative section of any modulePrivate LoginTime As Date ' A private module-level variableDim LoginPassword As String ' Another private module-level variable

    You can also use the Public attribute for module-level variables, for all module types except BAS modules. (Publicvariables in BAS modules are global variables.) In this case, you're creating a strange beast: a Public module-levelvariable that can be accessed by all procedures in the module to share data and that also can be accessed from outsidethe module. In this case, however, it's more appropriate to describe such a variable as a property:

    ' In the declarative section of Form1 modulePublic CustomerName As String ' A Public property

    You can access a module property as a regular variable from inside the module and as a custom property from theoutside:

    ' From outside Form1 module...Form1.CustomerName = "John Smith"

    The lifetime of a module-level variable coincides with the lifetime of the module itself. Private variables in standard BASmodules live for the entire life of the application, even if they can be accessed only while Visual Basic is executing code inthat module. Variables in form and class modules exist only when that module is loaded in memory. In other words, whilea form is active (but not necessarily visible to the user) all its variables take some memory, and this memory is releasedonly when the form is completely unloaded from memory. The next time the form is re-created, Visual Basic reallocatesmemory for all variables and resets them to their default values (0 for numeric values, "" for strings, Nothing for objectvariables).Public vs Local VariablesA variable can have the same name and different scope. For example, we can have a public variable named R and withina procedure we can declare a local variable R. References to the name R within the procedure would access the localvariable and references to R outside the procedure would access the public variable.

    Procedures In Visual Basic 6

  • 8/3/2019 Getting Started With VB 6

    9/133

    9

    Visual Basic offers different types of procedures to execute small sections of coding in applications. The variousprocedures are elucidated in details in this section. Visual Basic programs can be broken into smaller logical componentscalled 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 ProceduresA sub procedure can be placed in standard, class and form modules. Each time the procedure is called, the statementsbetween 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 aretwo types of Sub Procedures namely general procedures and event procedures.Event ProceduresAn 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 ProceduresA general procedure is declared when several event procedures perform the same actions. It is a good programmingpractice to write common statements in a separate procedure (general procedure) and then call them in the eventprocedure.In order to add General procedure:

    The Code window is opened for the module to which the procedure is to be added. The Add Procedureoption is chosen from the Tools menu, which opens an Add Procedure dialog box as

    shown in the figure given below. The name of the procedure is typed in the Name textbox Under Type, Subis selected to create a Sub procedure, Functionto create a Function procedureor Propertyto create a Property procedure. Under Scope, Publicis selected to create a procedure that can be invoked outside the module, or Privateto create a procedure that can be invoked only from within the module.

    We can also create a new procedure in the current module by typing Sub ProcedureName, Function ProcedureName, orProperty ProcedureName in the Code window. A Function procedure returns a value and a Sub Procedure does notreturn a value.

  • 8/3/2019 Getting Started With VB 6

    10/133

    10

    Function ProceduresFunctions are like sub procedures, except they return a value to the calling procedure. They are especially useful fortaking one or more pieces of data, called argumentsand performing some tasks with them. Then the functions returns avalue that indicates the results of the tasks complete within the function.The following function procedure calculates the third side or hypotenuse of a right triangle, where A and B are the othertwo sides. It takes two arguments A and B (of data type Double) and finally returns the results.

    Function Hypotenuse (A As Double, B As Double) As DoubleHypotenuse = sqr (A^2 + B^2)End Function

    The above function procedure is written in the general declarations section of the Code window. A function can also bewritten by selecting the Add Proceduredialog box from the Tools menu and by choosing the required scope and type.Property ProceduresA property procedure is used to create and manipulate custom properties. It is used to create read only properties forForms, Standard modules and Class modules.Visual Basic provides three kind of property procedures-Property Letprocedure that sets the value of a property, Property Get procedure that returns the value of a property, and Property Setprocedure that sets the references to an object.

    Control Structures In Visual Basic 6.0Control 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 isskipped.Syntax of the If...Then selectionIf 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 whenthe condition is True than when the condition is False.

    Syntax of the If...Then...Else selection

    If Then

    statements

    Elsestatements

    End If

    e.g.: If average>50 ThentxtGrade.Text = "Pass"ElsetxtGrade.Text = "Fail"End If

  • 8/3/2019 Getting Started With VB 6

    11/133

    11

    Nested If...Then...Else selection structure

    Nested If...Then...Else selection structures test for multiple cases by placing If...Then...Else selection structuresinside If...Then...Else structures.

    Syntax of the Nested If...Then...Else selection structure

    You can use Nested If either of the methods as shown above

    Method 1

    If < condition 1 > Then

    statements

    ElseIf < condition 2 > Then

    statements

    ElseIf < condition 3 > Then

    statements

    Else

    Statements

    End If

    Method 2

    If < condition 1 > Then

    statements

    Else

    If < condition 2 > Then

    statements

    Else

    If < condition 3 > Thenstatements

    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 ThentxtGrade.Text = "A"

    ElseIf average > 65 ThentxtGrade.Text = "B"ElseIf average > 55 ThentxtGrade.text = "C"ElseIf average > 45 ThentxtGrade.Text = "S"ElsetxtGrade.Text = "F"End If

  • 8/3/2019 Getting Started With VB 6

    12/133

    12

    Select...Case selection structure

    Select...Case structure is an alternative to If...Then...ElseIf for selectively executing a single block of statements fromamong multiple block of statements. Select...case is more convenient to use than theIf...Else...End If. The followingprogram block illustrate the working of Select...Case.

    Syntax of the Select...Case selection structure

    Select Case IndexCase 0StatementsCase 1StatementsEnd Select

    e.g.: Assume you have to find the grade using select...case and display in the text box

    Dim average as Integer

    average = txtAverage.TextSelect Case averageCase 100 To 75txtGrade.Text ="A"Case 74 To 65txtGrade.Text ="B"Case 64 To 55txtGrade.Text ="C"Case 54 To 45txtGrade.Text ="S"Case 44 To 0txtGrade.Text ="F"Case Else

    MsgBox "Invalid average marks"End Select

    Note: In this example I have used a message box function. In later lessons you will learn how to use message boxfunctions.

    Loops (Repetition Structures) In Visual Basic 6

    A repetition structure allows the programmer to that an action is to be repeated until given condition is true.

    Do While... Loop Statement

    The Do While...Loop is used to execute statements until a certain condition is met. The following Do Loop counts from 1to 100.

    Dim number As Integernumber = 1Do While number

  • 8/3/2019 Getting Started With VB 6

    13/133

    13

    While... Wend Statement

    A While...Wend statement behaves like the Do While...Loop statement. The following While...Wend counts from 1 to100

    Dim number As Integer

    number = 1While number 1000

    number = number + 1

    Print number

    Loop

    Numbers between 1 to 1000 will be displayed on the form as soon as you click on the command button.

    The For...Next Loop

    The For...Next Loop is another way to make loops in Visual Basic. For...Next repetition structure handles all the details ofcounter-controlled repetition. The following loop counts the numbers from 1 to 100:

    Dim x As Integer

    For x = 1 To 50

    Print x

    Next

  • 8/3/2019 Getting Started With VB 6

    14/133

    14

    In order to count the numbers from 1 yo 50 in steps of 2, the following loop can be used

    For x = 1 To 50 Step 2

    Print x

    Next

    The following loop counts numbers as 1, 3, 5, 7..etc

    The above coding will display numbers vertically on the form. In order to display numbers horizontally the followingmethod can be used.

    For x = 1 To 50Print x & Space$ (2);Next

    To increase the space between the numbers increase the value inside the brackets after the & Space$.Following example is a For...Next repetition structure which is with the If condition used.

    Dim number As IntegerFor number = 1 To 10If number = 4 ThenPrint "This is number 4"ElsePrint numberEnd IfNext

    In the output instead of number 4 you will get the "This is number 4".

    Exit For And Exit Do Statement In VisualBasic 6

    A For...Next loop condition can be terminated by an Exit Forstatement. Consider the following statement block.

    Dim x As IntegerFor x = 1 To 10Print xIf x = 5 ThenPrint "The program exited at x=5"Exit ForEnd IfNext

    The preceding code increments the value of x by 1 until it reaches the condition x = 5. The Exit For statement is executedand it terminates the For...Next loop. The Following statement block containing Do...While loop is terminated using ExitDo statement.

    Dim x As IntegerDo While x < 10Print xx = x + 1If x = 5 ThenPrint "The program is exited at x=5"Exit DoEnd IfLoop

  • 8/3/2019 Getting Started With VB 6

    15/133

    15

    With...End With statement

    When properties are set for objects or methods are called, a lot of coding is included that acts on the same object. It iseasier to read the code by implementing theWith...End Withstatement. Multiple properties can be set and multiplemethods can be called by using the With...End With statement. The code is executed more quickly and efficiently as theobject is evaluated only once. The concept can be clearly understood with following example.

    With Text1.Font.Size = 14.Font.Bold = True.ForeColor = vbRed.Height = 230.Text = "Hello World"End With

    In the above coding, the object Text1, which is a text box is evaluated only once instead of every associated property ormethod. This makes the coding simpler and efficient.

    VB Array - Arrays In Visual Basic 6

    An array is a consecutive group of memory locations that all have the same name and the same type. To refer to aparticular location or element in the array, we specify the array name and the array element position number.

    The Individual elements of an array are identified using an index. Arrays have upper and lower bounds and the elementshave to lie within those bounds. Each index number in an array is allocated individual memory space and therefore usersmust evade declaring arrays of larger size than required. We can declare an array of any of the basic data types includingvariant,user-defined typesand object variables. The individual elements of an array are all of the same data type.

    Declaring arrays

    Arrays occupy space in memory. The programmer specifies the array type and the number of elements required by thearray so that the compiler may reserve the appropriate amount of memory. Arrays may be declared as Public (in a code

    module), module or local. Module arrays are declared in the general declarations using keyword Dim or Private. Localarrays are declared in a procedure using Dim or Static. Array must be declared explicitly with keyword "As".

    There are two types of arrays in Visual Basic namely:

    Fixed-size array : The size of array always remains the same-size doesn't change during the program execution.

    Dynamic array : The size of the array can be changed at the run time- size changes during the program execution.

    Fixed-sized Arrays

    When an upper bound is specified in the declaration, a Fixed-array is created. The upper limit should always be within the

    range of long data type.

    Declaring a fixed-array

    Dim numbers(5) As Integer

    In the above illustration, numbers is the name of the array, and the number 6 included in the parentheses is the upper limitof the array. The above declaration creates an array with 6 elements, with index numbers running from 0 to 5.

    If we want to specify the lower limit, then the parentheses should include both the lower and upper limit along with the Tokeyword. An example for this is given below.

    http://visualbasic.freetutes.com/learn-vb6/lesson6.1.htmlhttp://visualbasic.freetutes.com/learn-vb6/lesson6.1.htmlhttp://visualbasic.freetutes.com/learn-vb6/lesson6.1.htmlhttp://visualbasic.freetutes.com/learn-vb6/lesson6.1.html
  • 8/3/2019 Getting Started With VB 6

    16/133

    16

    Dim numbers (1 To 6 ) As Integer

    In the above statement, an array of 10 elements is declared but with indexes running from 1 to 6.

    A public array can be declared using the keyword Public instead of Dim as shown below.

    Public numbers(5) As Integer

    Multidimensional Arrays

    Arrays can have multiple dimensions. A common use of multidimensional arrays is to represent tables of values consistingof information arranged in rows and columns. To identify a particular table element, we must specify two indexes: The first(by convention) identifies the element's row and the second (by convention) identifies the element's column.

    Tables or arrays that require two indexes to identify a particular element are called two dimensional arrays. Note thatmultidimensional arrays can have more than two dimensions. Visual Basic supports at least 60 array dimensions, butmost people will need to use more than two or three dimensional-arrays.

    The following statement declares a two-dimensional array 50 by 50 array within a procedure.

    Dim AvgMarks ( 50, 50)

    It is also possible to define the lower limits for one or both the dimensions as for fixed size arrays. An example for this isgiven here.

    Dim Marks ( 101 To 200, 1 To 100)

    An example for three dimensional-array with defined lower limits is given below.

    Dim Details( 101 To 200, 1 To 100, 1 To 100)

    Static and dynamic arrays

    Basically, you can create either static or dynamic arrays. Static arrays must include a fixed number of items, and thisnumber must be known at compile time so that the compiler can set aside the necessary amount of memory. You create astatic array using a Dim statement with a constant argument:

    ' This is a static array.Dim Names(100) As String

    Visual Basic starts indexing the array with 0. Therefore, the preceding array actually holds 101 items.

    Most programs don't use static arrays because programmers rarely know at compile time how many items you need andalso because static arrays can't be resized during execution. Both these issues are solved by dynamic arrays. Youdeclare and create dynamic arrays in two distinct steps. In general, you declare the array to account for its visibility (forexample, at the beginning of a module if you want to make it visible by all the procedures of the module) using a Dimcommand with an empty pair of brackets. Then you create the array when you actually need it, using a ReDim statement:

    ' An array defined in a BAS module (with Private scope)Dim Customers() As String...Sub Main()' Here you create the array.ReDim Customer(1000) As StringEnd Sub

  • 8/3/2019 Getting Started With VB 6

    17/133

    17

    If you're creating an array that's local to a procedure, you can do everything with a single ReDim statement:

    Sub PrintReport()' This array is visible only to the procedure.ReDim Customers(1000) As String' ...

    End Sub

    If you don't specify the lower index of an array, Visual Basic assumes it to be 0, unless an Option Base 1 statement isplaced at the beginning of the module. My suggestion is this: Never use an Option Base statement because it makes codereuse more difficult. (You can't cut and paste routines without worrying about the current Option Base.) If you want toexplicitly use a lower index different from 0, use this syntax instead:

    ReDim Customers(1 To 1000) As String

    Dynamic arrays can be re-created at will, each time with a different number of items. When you re-create a dynamic arrayits contents are reset to 0 (or to an empty string) and you lose the data it contains. If you want to resize an array withoutlosing its contents, use the ReDim Preserve command:

    ReDim Preserve Customers(2000) As String

    When you're resizing an array, you can't change the number of its dimensions nor the type of the values it contains.Moreover, when you're using ReDim Preserve on a multidimensional array, you can resize only its last dimension:

    ReDim Cells(1 To 100, 10) As Integer...ReDim Preserve Cells(1 To 100, 20) As Integer ' This works.ReDim Preserve Cells(1 To 200, 20) As Integer ' This doesn't.

    Finally, you can destroy an array using the Erase statement. If the array is dynamic, Visual Basic releases the memoryallocated for its elements (and you can't read or write them any longer); if the array is static, its elements are set to 0 or to

    empty strings.

    You can use the LBound and UBound functions to retrieve the lower and upper indices. If the array has two or moredimensions, you need to pass a second argument to these functions to specify the dimension you need:

    Print LBound(Cells, 1) ' Displays 1, lower index of 1st dimensionPrint LBound(Cells) ' Same as abovePrint UBound(Cells, 2) ' Displays 20, upper index of 2nd dimension' Evaluate total number of elements.NumEls = (UBound(Cells) _ LBound(Cells) + 1) * _(UBound(Cells, 2) _ LBound(Cells, 2) + 1)

    Arrays within UDTs

    UDT structures can include both static and dynamic arrays. Here's a sample structure that contains both types:

    Type MyUDTStaticArr(100) As LongDynamicArr() As LongEnd Type...Dim udt As MyUDT' You must DIMension the dynamic array before using it.ReDim udt.DynamicArr(100) As Long' You don't have to do that with static arrays.udt.StaticArr(1) = 1234

  • 8/3/2019 Getting Started With VB 6

    18/133

    18

    The memory needed by a static array is allocated within the UDT structure; for example, the StaticArr array in thepreceding code snippet takes exactly 400 bytes. Conversely, a dynamic array in a UDT takes only 4 bytes, which form apointer to the memory area where the actual data is stored. Dynamic arrays are advantageous when each individual UDTvariable might host a different number of array items. As with all dynamic arrays, if you don't dimension a dynamic arraywithin a UDT before accessing its items, you get an error 9"Subscript out of range."

    User-Defined Data Types In Visual Basic 6

    Variables of different data types when combined as a single variable to hold several related informations is called a User-Defined data type.

    A Type statement is used to define a user-defined type in the General declaration section of a form or module. User-defined data types can only be private in form while in standard modules can be public or private. An example for a userdefined data type to hold the product details is as given below.

    Private Type ProductDetailsProdID as StringProdName as StringPrice as Currency

    End Type

    The user defined data type can be declared with a variable using the Dim statement as in any other variable declarationstatement. An array of these user-defined data types can also be declared. An example to consolidate these two featuresis given below.

    Dim ElectronicGoods as ProductDetails ' One RecordDim ElectronicGoods(10) as ProductDetails ' An array of 11 records

    A User-Defined data type can be referenced in an application by using the variable name in the procedure along with theitem name in the Type block. Say, for example if the text property of a TextBox namely text1 is to be assigned the nameof the electronic good, the statement can be written as given below.

    Text1.Text = ElectronicGoods.ProdName

    If the same is implemented as an array, then the statement becomes

    Text1.Text = ElectronicGoods(i).ProdName

    User-defined data types can also be passed to procedures to allow many related items as one argument.

    Sub ProdData( ElectronicGoods as ProductDetails)Text1.Text = ElectronicGoods.ProdNameText1.Text = ElectronicGoods.PriceEnd Sub

    Constants, Data Type Conversion, Visual Basic Built-In Functions

    Constants

    Constants are named storage locations in memory, the value of which does not change during program Execution. Theyremain the same throughout the program execution. When the user wants to use a value that never changes, a constantcan be declared and created. The Const statement is used to create a constant. Constants can be declared in local, form,module or global scope and can be public or private as for variables. Constants can be declared as illustrated below.

    Public Const gravityconstant As Single = 9.81

  • 8/3/2019 Getting Started With VB 6

    19/133

    19

    Predefined Visual Basic Constants

    The predefined constants can be used anywhere in the code in place of the actual numeric values. This makes the codeeasier to read and write.

    For example consider a statement that will set the window state of a form to be maximized.

    Form1.Windowstate = 2

    The same task can be performed using a Visual Basic constant

    Form1.WindowState = vbMaximized

    Data Type Conversion

    Visual Basic functions either to convert a string into an integer or vice versa and many more conversion functions. Acomplete listing of all the conversion functions offered by Visual Basic is elucidated below.

    Conversion To Function

    Boolean Cbool

    Byte Cbyte

    Currency Ccur

    Date Cdate

    Decimals Cdec

    Double CDbl

    Integer Cint

    Long CLng

    Single CSng

    String CStr

    Variant Cvar

    Error CVErr

    A conversion function should always be placed at the right hand side of the calculation statement.

  • 8/3/2019 Getting Started With VB 6

    20/133

    20

    Visual Basic Built-in Functions

    Many built-in functions are offered by Visual Basic fall under various categories. These functions are procedures thatreturn a value. The functions fall into the following basic categories that will be discussed in the follwing sections at length.

    Date and Time Functions Format Function String Functions

    Date And Time Functions In Visual Basic 6

    Not only does Visual Basic let you store date and time information in the specific Date data type, it also provides a lot of

    date- and time-related functions. These functions are very important in all business applications and deserve an in-depth

    look. Date and Time are internally stored as numbers in Visual Basic. The decimal points represents the time between

    0:00:00 and 23:59:59 hours inclusive.

    The system's current date and time can be retrieved using the Now, Date and Time functions in Visual Basic. The Nowfunction retrieves the date and time, while Date function retrieves only date and Time function retrieves only the time.

    To display both the date and time together a message box is displayed use the statement given below.

    MsgBox "The current date and time of the system is" & Now

    Here & is used as a concatenation operator to concentrate the string and the Now function. Selective portions of the dateand time value can be extracted using the below listed functions.

    Function Extracted Portion

    Year ( ) Year (Now)

    Month ( ) Month (Now)

    Day ( ) Day (Now)

    WeekDay ( ) WeekDay (Now)

    Hour ( ) Hour (Now)

    Minute ( ) Minute (Now)

    Second ( ) Second (Now)

    The calculation and conversion functions related to date and time functions are listed below.

    Function Description

  • 8/3/2019 Getting Started With VB 6

    21/133

    21

    DateAdd ( ) Returns a date to which a specific interval has been added

    DateDiff ( ) Returns a Long data type value specifying the interval between the two values

    DatePart ( ) Returns an Integer containing the specified part of a given date

    DateValue ( ) Converts a string to a Date

    TimeValue ( ) Converts a string to a time

    DateSerial ( ) Returns a date for specified year, month and day

    DateDiff Function

    The DateDiff function returns the intervals between two dates in terms of years, months or days. The syntax for this isgiven below.

    DateDiff (interval, date1, date2[, firstdayofweek[, firstweekofyear]])

    Format Function

    The format function accepts a numeric value and converts it to a string in the format specified by the format argument.The syntax for this is given below.

    Format (expression[, format[, firstdayofweek[, firstweekofyear]]])

    The Format function syntax has these parts:

    Part Description

    Expression Required any valid expression

    format Optional. A valid named or user-defined format expression.

    firstdayofweek Optional. A contant that specifies the first day of the week.

    firstweekofyear Optional. A contant that specifies the first week of the year

    Working With Controls In Visual Basic 6

    This lesson concentrates on Visual Basic controls and the ways of creating and implementing the. It also helps us tounderstand the concept of Control Arrays. Controls are used to recieve user input and display output and has its own setof properties, methods and events. Let us discuss few of these controls in this lesson.

  • 8/3/2019 Getting Started With VB 6

    22/133

    22

    Creating and Using Controls

    A control is an object that can be drawn on a Form object to enable or enhance user interaction with an application.

    Controls have properties that define aspects their appearance, such as position, size and colour, and aspects of their

    behavior, such as their response to the user input. They can respond to events initiated by the user or set off by the

    system. For instance, a code could be written in a CommandButton control's click event procedure that would load a file o

    display a result.

    In addition to properties and events, methods can also be used to manipulate controls from code. For instance, the movemethod can be used with some controls to change their location and size.Most of the controls provide choices to users that can be in the form of OptionButton or CheckBox controls, ListBoxentries or ScrollBars to select a value. Let us discuss these controls by means of a few simple applications in the followinglessons.Classification of Controls

    Visual Basic cojntrols are broadly classified as standard controls, ActiveX controls and insertable objects. Standardcontrols such as CommandButton, Label and Frame controls are contained inside .EXE file and are always included in theToolBox which cannot be removed. ActiveX controls exist as separate files with either .VBX or .OCX extension. Theyinclude specialized controls such as;

    MSChart control The Communications control The Animation control The ListView control An ImageList control The Multimedia control The Internet Transfer control The WinSock control The TreeView control The SysInfo control The Picture Clip control

    Some of these objects support OLE Automation, which allow programming another application's object from within VisualBasic application.I would like to stress that knowing how and when to set the objects' properties is very important as it can help you to writea 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'

    propertiesHere are some important points about setting up the properties You should set the Caption Property of a control clearly so that a user knows what to do with thatcommand. For example, in the calculator program, all the captions of the command buttons such as +, - , MC, MRare commonly found in an ordinary calculator, a user should have no problem in manipulating the buttons. A lot of programmers like to use a meaningful name for the Name Property may be because it is easierfor them to write and read the event procedure and easier to debug or modify the programs later. However, it isnot a must to do that as long as you label your objects clearly and use comments in the program whenever youfeel necessary One more important property is whether the control is enabled or not Finally, you must also considering making the control visible or invisible at runtime, or when should itbecome visible or invisible

    TabIndex property of Controls

    Visual Basic uses the TabIndex property to determine the control that would receive the focus next when a tab key ispressed. Every time a tab key is pressed, Visual Basic looks at the value of the TabIndex for the control that has focusand then it scans through the controls searching for the next highest TabIndex number. When there are no more controlswith higher TabIndex value, Visual Basic starts all over again with 0 and looks for the first control with TabIndex of 0 orhigher that can accept keyboard input.By default, Visual Basic assigns a tab order to control as we draw the controls on the Form, except for Menu, Timer, Data,Image, Line and Shape controls, which are not included in tab order. At run time, invisible or disabled controls also cannotreceive the focus although a TabIndex value is given. Setting the TabIndex property of controls is compulsory indevelopment environment.

    Using TextBox Control In Visual Basic 6

  • 8/3/2019 Getting Started With VB 6

    23/133

    23

    TextBox controls offer a natural way for users to enter a value in your program. For this reason, they tend to be the mostfrequently used controls in the majority of Windows applications. TextBox controls, which have a great many propertiesand events, are also among the most complex intrinsic controls. In this section, I guide you through the most usefulproperties of TextBox controls and show how to solve some of the problems that you're likely to encounter.

    Setting properties to a TextBox

    Text can be entered into the text box by assigning the necessary string to the text property of the control If the user needs to display multiple lines of text in a TextBox, set the MultiLine property to True To customize the scroll bar combination on a TextBox, set the ScrollBars property. Scroll bars will always appear on the TextBox when it's MultiLine property is set to True and its ScrollBarsproperty is set to anything except None(0) If you set the MultilIne property to True, you can set the alignment using the Alignment property. The testis left-justified by default. If the MultiLine property is et to False, then setting the Alignment property has no effect.

    Run-Time Properties of a TextBox control

    The Text property is the one you'll reference most often in code, and conveniently it's the default property for the TextBox

    control. Three other frequently used properties are these:

    The SelStartproperty sets or returns the position of the blinking caret (the insertion point where the textyou type appears). Note that the blinking cursor inside TextBox and other controls is named caret, to distinguish itfrom the cursor (which is implicitly the mouse cursor). When the caret is at the beginning of the contents of theTextBox control, SelStart returns 0; when it's at the end of the string typed by the user, SelStart returns the valueLen(Text). You can modify the SelStart property to programmatically move the caret. The SelLengthproperty returns the number of characters in the portion of text that has been highlightedby the user, or it returns 0 if there's no highlighted text. You can assign a nonzero value to this property toprogrammatically select text from code. Interestingly, you can assign to this property a value larger than thecurrent text's length without raising a run-time error. The SelTextproperty sets or returns the portion of the text that's currently selected, or it returns anempty string if no text is highlighted. Use it to directly retrieve the highlighted text without having to query Text,

    SelStart, and SelLength properties. What's even more interesting is that you can assign a new value to thisproperty, thus replacing the current selection with your own. If no text is currently selected, your string is simplyinserted at the current caret position.

    When you want to append text to a TextBox control, you should use the following code (instead of using theconcatenation operator) to reduce flickering and improve performance:

    Text1.SelStart = Len(Text1.Text)Text1.SelText = StringToBeAdded

    One of the typical operations you could find yourself performing with these properties is selecting the entire contents of aTextBox control. You often do it when the caret enters the field so that the user can quickly override the existing value witha new one, or start editing it by pressing any arrow key:

    Private Sub Text1_GotFocus()Text1.SelStart = 0' A very high value always does the trick.Text1.SelLength = 9999End Sub

    Always set the SelStart property first and then the SelLength or SelText properties. When you assign a new value to theSelStart property, the other two are automatically reset to 0 and an empty string respectively, thus overriding yourprevious settings.

    The selected text can be copied to the Clipboard by using SelText:

  • 8/3/2019 Getting Started With VB 6

    24/133

    24

    Clipboard.SelText text, [format]

    In the above syntax, text is the text that has to be placed into the Clipboard, and format has three possible values.

    1. VbCFLink - conversation information2. VbCFRTF - Rich Text Format

    3. VbCFText - Text

    We can get text from the clipboard using the GetText() function this way:

    Clipboard.GetText ([format])

    The following Figure summarizes the common TextBox control's properties and methods.

    Property/ Method Description

    Properties

    Enabled specifies whether user can interact with this control or not

    Index Specifies the control array index

    LockedIf this control is set to True user can use it else if this control is set to false the control

    cannot be used

    MaxLengthSpecifies the maximum number of characters to be input. Default value is set to 0 that

    means user can input any number of characters

    MousePointer Using this we can set the shape of the mouse pointer when over a TextBox

    Multiline By setting this property to True user can have more than one line in the TextBox

    PasswordChar This is to specify mask character to be displayed in the TextBox

    ScrollBarsThis to set either the vertical scrollbars or horizontal scrollbars to make appear in the

    TextBox. User can also set it to both vertical and horizontal. This property is used with

    the Multiline property.

    Text Specifies the text to be displayed in the TextBox at runtime

    ToolTipIndex This is used to display what text is displayed or in the control

    Visible By setting this user can make the Textbox control visible or invisible at runtime

    Method

    SetFocus Transfers focus to the TextBox

  • 8/3/2019 Getting Started With VB 6

    25/133

    25

    Event procedures

    Change Action happens when the TextBox changes

    Click Action happens when the TextBox is clicked

    GotFocus Action happens when the TextBox receives the active focus

    LostFocus Action happens when the TextBox loses it focus

    KeyDown Called when a key is pressed while the TextBox has the focus

    KeyUp Called when a key is released while the TextBox has the focus

    Trapping Keyboard Activity - Visual Basic 6 TextBox Control

    TextBox controls support KeyDown, KeyPress, and KeyUp standard events. One thing that you will often do is prevent theuser from entering invalid keys. A typical example of where this safeguard is needed is a numeric field, for which you needto filter out all nondigit keys:

    Private Sub Text1_KeyPress(KeyAscii As Integer)Select Case KeyAsciiCase Is < 32 ' Control keys are OK.Case 48 To 57 ' This is a digit.Case Else ' Reject any other key.KeyAscii = 0End Select

    End Sub

    You should never reject keys whose ANSI code is less than 32, a group that includes important keys such as Backspace,Escape, Tab, and Enter. Also note that a few control keys will make your TextBox beep if it doesn't know what to do withthemfor example, a single-line TextBox control doesn't know what to do with an Enter key.

    Don't assume that the KeyPress event will trap all control keys under all conditions. For example, the KeyPress event canprocess the Enter key only if there's no CommandButton control on the form whose Default property is set to True. If theform has a default push button, the effect of pressing the Enter key is clicking on that button. Similarly, no Escape keygoes through this event if there's a Cancel button on the form. Finally, the Tab control key is trapped by a KeyPress eventonly if there isn't any other control on the form whose TabStop property is True.

    You can use the KeyDown event procedure to allow users to increase and decrease the current value using Up and Down

    arrow keys, as you see here:

    Private Sub Text1_KeyDown(KeyCode As Integer, Shift As Integer)Select Case KeyCodeCase vbKeyUpText1.Text = CDbl(Text1.Text) + 1Case vbKeyDownText1.Text = CDbl(Text1.Text) -1End SelectEnd Sub

  • 8/3/2019 Getting Started With VB 6

    26/133

    26

    There's a bug in the implementation of TextBox ready-only controls. When the Locked property is set to True, the Ctrl+Ckey combination doesn't correctly copy the selected text to the Clipboard, and you must manually implement thiscapability by writing code in the KeyPress event procedure

    Validation Routines For Numbers - Visual Basic 6 TextBox Control

    Although trapping invalid keys in the KeyPress or KeyDown event procedures seems a great idea at first, when you throwyour application to inexperienced users you soon realize that there are many ways for them to enter invalid data.Depending on what you do with this data, your application can come to an abrupt end with a run-time error ormuchworseit can appear to work correctly while it delivers bogus results. What you really need is a bullet-proof method totrap invalid values.

    Before I offer you a decent solution to the problem, let me explain why you can't rely solely on trapping invalid keys foryour validation chores. What if the user pastes an invalid value from the clipboard? Well, you might say, let's trap theCtrl+V and Shift+Ins key combinations to prevent the user from doing that! Unfortunately, Visual Basic's TextBox controlsoffer a default edit menu that lets users perform any clipboard operation by simply right-clicking on them. Fortunately,there's a way around this problem: Instead of trapping a key before it gets to the TextBox control, you trap its effect in theChange event and reject it if it doesn't pass your test. But this makes the structure of the code a little more complex thanyou might anticipate:

    ' Form-level variablesDim saveText As StringDim saveSelStart As Long

    Private Sub Text1_GotFocus()' Save values when the control gets the focus.saveText = Text1.TextsaveSelStart = Text1.SelStartEnd Sub

    Private Sub Text1_Change()' Avoid nested calls.

    Static nestedCall As BooleanIf nestedCall Then Exit Sub

    ' Test the control's value here.If IsNumeric(Text1.Text) Then' If value is OK, save values.saveText = Text1.TextsaveSelStart = Text1.SelStartElse' Prepare to handle a nested call.nestedCall = TrueText1.Text = saveTextnestedCall = False

    Text1.SelStart = saveSelStartEnd IfEnd Sub

    Private Sub Text1_KeyUp(KeyCode As Integer, Shift As Integer)saveSelStart = Text1.SelStartEnd SubPrivate Sub Text1_MouseDown(Button As Integer, _Shift As Integer, X As Single, Y As Single)saveSelStart = Text1.SelStartEnd SubPrivate Sub Text1_MouseMove(Button As Integer, _

  • 8/3/2019 Getting Started With VB 6

    27/133

    27

    Shift As Integer, X As Single, Y As Single)saveSelStart = Text1.SelStartEnd Sub

    If the control's value doesn't pass your tests in the Change event procedure, you must restore its previous valid value; thisaction recursively fires a Change event, and you must prepare yourself to neutralize this nested call. You might wonder

    why you also need to trap the KeyUp, MouseDown, and MouseMove events: The reason is that you always need to keeptrack of the last valid position for the insertion point because the end user could move it using arrow keys or the mouse.

    The preceding code snippet uses the IsNumeric function to trap invalid data. You should be aware that this function isn'trobust enough for most real-world applications. For example, the IsNumeric function incorrectly considers these strings asvalid numbers:

    123,,,123345-$1234 ' What if it isn't a currency field?2.4E10 ' What if I don't want to support scientific notation?

    To cope with this issue, I have prepared an alternative function, which you can modify for your particular purposes. (For

    instance, you can add support for a currency symbol or the comma as the decimal separator.) Note that this functionalways returns True when it's passed a null string, so you might need to perform additional tests if the user isn't allowed toleave the field blank:

    Function CheckNumeric(text As String, DecValue As Boolean) As BooleanDim i As IntegerFor i = 1 To Len(text)Select Case Mid$(text, i, 1)Case "0" To "9"Case "-", "+"' Minus/plus signs are only allowed as leading chars.If i > 1 Then Exit FunctionCase "."

    ' Exit if decimal values not allowed.If Not DecValue Then Exit Function' Only one decimal separator is allowed.If InStr(text, ".") < i Then Exit FunctionCase Else' Reject all other characters.Exit FunctionEnd SelectNextCheckNumeric = TrueEnd Function

    If your TextBox controls are expected to contain other types of data, you might be tempted to reuse the same validation

    framework I showed you previouslyincluding all the code in the GotFocus, Change, KeyUp, MouseDown, andMouseMove event proceduresand replace only the call to IsNumeric with a call to your custom validation routine.Things aren't as simple as they appear at first, however. Say that you have a date field: Can you use the IsDate functionto validate it from within the Change event? The answer is, of course, no. In fact, as you enter the first digit of your datevalue, IsDate returns False and the routine therefore prevents you from entering the remaining characters, and sopreventing you from entering any value.

    This example explains why a key-level validation isn't always the best answer to your validation needs. For this reason,most Visual Basic programmers prefer to rely on field-level validation and test the values only when the user moves theinput focus to another field in the form. I explain field-level validation in the next section.

    The CausesValidation Property And The Validate Event - Visual Basic 6 TextBox Control

  • 8/3/2019 Getting Started With VB 6

    28/133

    28

    Visual Basic 6 has finally come up with a solution for most of the validation issues that have afflicted Visual Basicdevelopers for years. As you'll see in a moment, the Visual Basic 6 approach is simple and clean; it really astonishes methat it took six language versions to deliver such a lifesaver. The keys to the new validation features are the Validate evenand the CausesValidation property. They work together as follows: When the input focus leaves a control, Visual Basicchecks the CausesValidation property of the control that is about to receive the focus. If this property is True, Visual Basicfires the Validate event in the control that's about to lose the focus, thus giving the programmer a chance to validate its

    contents and, if necessary, cancel the focus shift.

    Let's try a practical example. Imagine that you have five controls on a form: a required field (a TextBox control,txtRequired, that can't contain an empty string), a numeric field, txtNumeric, that expects a value in the range 1 through1000, and three push buttons: OK, Cancel, and Help. (See the figure below.) You don't want to perform validation if theuser presses the Cancel or Help buttons, so you set their CausesValidation properties to False. The default value for thisproperty is True, so you don't have to modify it for the other controls. Run the sample program on the companion CD, typesomething in the required TextBox, and then move to the second field. Because the second field's CausesValidationproperty is True, Visual Basic fires a Validate event in the first TextBox control:

    Private Sub txtRequired_Validate(Cancel As Boolean)' Check that field is not empty.If txtRequired.Text = "" Then

    MsgBox "Please enter something here", vbExclamationCancel = TrueEnd IfEnd Sub

    If the Cancel parameter is set to True, Visual Basic cancels the user's action and takes the input focus back on thetxtRequired control: No other GotFocus and LostFocus events are generated. On the other hand, if you typed somethingin the required field, the focus will now be on the second field (the numeric text box). Try clicking on the Help or Cancelbuttons: No Validate event will fire this time because you set the CausesValidation property for each of these controls toFalse. Instead, click on the OK button to execute the Validate event of the numeric field, where you can check it for invalidcharacters and valid range.

    A demonstration program that lets you experiment with the new Visual Basic Validate features

    Private Sub txtNumeric_Validate(Cancel As Boolean)If Not IsNumeric(txtNumeric.Text) ThenCancel = TrueElseIf CDbl(txtNumeric.Text) < 1 Or CDbl(txtNumeric.Text) > 1000 ThenCancel = TrueEnd IfIf Cancel ThenMsgBox "Please enter a number in range [1-1000]", vbExclamationEnd IfEnd Sub

  • 8/3/2019 Getting Started With VB 6

    29/133

    29

    In some circumstances, you might want to programmatically validate the control that has the focus without waiting for theuser to move the input focus. You can do it with the form's ValidateControls method, which forces the Validate event ofthe control that has the input focus. Typically, you do it when the user closes the form:

    Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)' You can't close this form without validating the current field.

    If UnloadMode = vbFormControlMenu ThenOn Error Resume NextValidateControlsIf Err = 380 Then' The current field failed validation.Cancel = TrueEnd IfEnd IfEnd Sub

    Checking the UnloadMode parameter is important; otherwise, your application will mistakenly execute a ValidateControlsmethod when the user clicks on the Cancel button. Note that ValidateControls returns an error 380 if Cancel was set inthe Validate event procedure of the control that had the focus.

    Visual Basic 6's validation scheme has two flaws, though. If your form has a CommandButton whose Default property isset to True, pressing the Enter key while the input focus is on another control results in a click on the CommandButtoncontrol but doesn't fire a Validate event, even if the CausesValidation property of the CommandButton control is set toTrue. The only way to solve this problem is to invoke the ValidateControls method from within the default CommandButtoncontrol's Click event procedure.

    The second flaw is that the Validate event doesn't fire when you're moving the focus from a control whoseCausesValidation property is False, even if the control that receives the focus has its CausesValidation property set toTrue.

    The new Visual Basic 6 validation mechanism is simple and can be implemented with little effort. But it isn't the magicanswer to all your validation needs. In fact, this technique can only enforce field-level validation; it does nothing for record-

    level validation. In other words, it ensures that one particular field is correct, not that all fields in the form contain validdata. To see what I mean, run the demonstration program, enter a string in the first field, and press Alt+F4 to close theform. Your code won't raise an error, even if the second field doesn't contain a valid number! Fortunately, it doesn't takemuch to create a generic routine that forces each control on the form to validate itself:

    Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)' You can't close this form without validating all the fields on it.If UnloadMode = vbFormControlMenu ThenOn Error Resume NextDim ctrl As Control' Give the focus to each control on the form, and then' validate it.For Each ctrl In Controls

    Err.Clearctrl.SetFocusIf Err = 0 Then' Don't validate controls that can't receive input focus.ValidateControlsIf Err = 380 Then' Validation failed, refuse to close.Cancel = True: Exit SubEnd IfEnd IfNextEnd IfEnd Sub

  • 8/3/2019 Getting Started With VB 6

    30/133

    30

    The CausesValidation property and the Validate event are shared by all the intrinsic controls that are able to get the focusas well as by most external ActiveX controls, even those not specifically written for Visual Basic. This is possible becausethey are extender features, provided by the Visual Basic runtime to all the controls placed on a form's surface.

    One Visual Basic operator has great potential when it comes time to validate complex strings but is neglected by mostVisual Basic developers. Let's say you have a product code that consists of two uppercase characters followed by exactly

    three digits. You might think that you need some complex string functions to validate such a string until you try the Likeoperator, as follows:

    If "AX123" Like "[A-Z][A-Z]###" Then Print "OK"

    Auto-Tabbing Fields And Formatting Text - Visual Basic 6 TextBox Control

    Auto-Tabbing Fields

    Users aren't usually delighted to spend all their time at the keyboard. Your job as a programmer is to make their jobseasier, and so you should strive to streamline their everyday work as much as possible. One way to apply this concept isto provide them with auto-tabbing fields, which are fields that automatically advance users to the next field in the Taborder as soon as they enter a valid value. Most often, auto-tabbing fields are those TextBox controls whose MaxLengthproperty has been assigned a non-null value. Implementing such an auto-tabbing field in Visual Basic is straightforward:

    Private Sub Text1_Change()If Len(Text1.Text) = Text1.MaxLength Then SendKeys "{Tab}"End Sub

    The trick, as you see, is to have your program provide the Tab key on behalf of your user. In some cases, this simpleapproach doesn't workfor example, when you paste a long string into the field. You might want to write code that worksaround this and other shortcomings. Auto-tabbing is a nice feature but not vital to the application, so whether you write aworkaround or not isn't a real problem in most cases.

    Formatting Text

    Many business applications let you enter data in one format and then display it in another. For example, numeric valuescan be formatted with thousand separators and a fixed number of decimal digits. Currency values might have a $ symbol(or whatever your national currency symbol is) automatically inserted. Phone numbers can be formatted with dashes tosplit into groups of digits. Credit-card numbers can be made more readable with embedded spaces. Dates can be shownin long-date format ("July 22, 2007"). And so on.

    The LostFocus event is an ideal occasion to format the contents of a TextBox control as soon as the input focus leaves it.In most cases, you can perform all your formatting chores using the Format function. For example, you can add thousandseparators to a numeric value in the txtNumber control using this code:

    Private Sub txtNumber_LostFocus()On Error Resume NexttxtNumber.Text = Format(CDbl(txtNumber.Text), _

    "#,###,###,##0.######")End Sub

    When the field regains the focus, you'll want to get rid of those thousand separators. You can do it easily using the CDblfunction:

    Private Sub txtNumber_GotFocus()' On Error is necessary to account for empty fields.On Error Resume NexttxtNumber.Text = CDbl(txtNumber.Text)End Sub

  • 8/3/2019 Getting Started With VB 6

    31/133

    31

    In some cases, however, formatting and unformatting a value isn't that simple. For example, you can format a Currencyvalue to add parentheses around negative numbers, but there's no built-in Visual Basic function able to return a stringformatted in that way to its original condition. Fear not, because nothing prevents you from creating your own formattingand unformatting routines. I have built two general-purpose routines for you to consider.

    The FilterString routine filters out all unwanted characters in a string:

    Function FilterString(Text As String, validChars As String) As StringDim i As Long, result As StringFor i = 1 To Len(Text)If InStr(validChars, Mid$(Text, i, 1)) Thenresult = result & Mid$(Text, i, 1)End IfNextFilterString = resultEnd Function

    FilterNumber builds on FilterString to strip down all formatting characters in a number and can also trim trailing decimalzeros:

    Function FilterNumber(Text As String, TrimZeros As Boolean) As StringDim decSep As String, i As Long, result As String' Retrieve the decimal separator symbol.decSep = Format$(0.1, ".")' Use FilterString for most of the work.result = FilterString(Text, decSep & "-0123456789")' Do the following only if there is a decimal part and the' user requested that nonsignificant digits be trimmed.If TrimZeros And InStr(Text, decSep) > 0 ThenFor i = Len(result) To 1 Step -1Select Case Mid$(result, i, 1)Case decSep

    result = Left$(result, i - 1)Exit ForCase "0"result = Left$(result, i - 1)Case ElseExit ForEnd SelectNextEnd IfFilterNumber = resultEnd Function

    The feature I like most in FilterNumber is that it's locale-independent. It works equally well on both sides of the Atlantic

    ocean (and on other continents, as well.) Instead of hard-coding the decimal separator character in the code, the routinedetermines it on the fly, using the Visual Basic for Applications (VBA) Format function. Start thinking internationally now,and you won't have a nervous breakdown when you have to localize your applications in German, French, and Japanese.

    The Format function lets you retrieve many locale-dependent characters and separators.Format$(0.1, ".") ' Decimal separatorFormat$(1, ",") ' Thousand separatorMid$(Format(#1/1/99#, "short date"), 2, 1) ' Date separator

    You can also determine whether the system uses dates in "mm/dd/yy" (U.S.) format or "dd/mm/yy" (European) format,using this code:

  • 8/3/2019 Getting Started With VB 6

    32/133

    32

    If Left$(Format$("12/31/1999", "short date"), 2) = 12 Then' mm/dd/yy format

    Else' dd/mm/yyyy format

    End If

    There's no direct way to determine the currency symbol, but you can derive it by analyzing the result of this function:

    Format$(0, "currency") ' Returns "$0.00" in US

    It isn't difficult to write a routine that internally uses the information I've just given you to extract the currency symbol aswell as its default position (before or after the number) and the default number of decimal digits in currency values.Remember, in some countries the currency symbol is actually a string of two or more characters.

    To illustrate these concepts in action, I've built a simple demonstration program that shows how you can format numbers,currency values, dates, phone numbers, and credit-card numbers when exiting a field, and how you can remove that

    formatting from the result when the input focus reenters the TextBox control. Follwoing figure shows the formatted results.

    Private Sub txtNumber_GotFocus()' Filter out nondigit chars and trailing zeros.On Error Resume NexttxtNumber.Text = FilterNumber(txtNumber.Text, True)End SubPrivate Sub txtNumber_LostFocus()' Format as a number, grouping thousand digits.On Error Resume NexttxtNumber.Text = Format(CDbl(txtNumber.Text), _"#,###,###,##0.######")End Sub

    Private Sub txtCurrency_GotFocus()' Filter out nondigit chars and trailing zeros.' Restore standard text color.On Error Resume NexttxtCurrency.Text = FilterNumber(txtCurrency.Text, True)txtCurrency.ForeColor = vbWindowTextEnd SubPrivate Sub txtCurrency_LostFocus()On Error Resume Next' Show negative values as red text.If CDbl(txtCurrency.Text) < 0 Then txtCurrency.ForeColor = vbRed' Format currency, but don't use parentheses for negative numbers.' (FormatCurrency is a new VB6 string function.)txtCurrency.Text = FormatCurrency(txtCurrency.Text, , , vbFalse)End Sub

    Private Sub txtDate_GotFocus()' Prepare to edit in short-date format.On Error Resume NexttxtDate.Text = Format$(CDate(txtDate.Text), "short date")End SubPrivate Sub txtDate_LostFocus()' Convert to long-date format upon exit.On Error Resume Next

  • 8/3/2019 Getting Started With VB 6

    33/133

    33

    txtDate.Text = Format$(CDate(txtDate.Text), "d MMMM yyyy")End Sub

    Private Sub txtPhone_GotFocus()' Trim embedded dashes.txtPhone.Text = FilterString(txtPhone.Text, "0123456789")

    End SubPrivate Sub txtPhone_LostFocus()' Add dashes if necessary.txtPhone.Text = FormatPhoneNumber(txtPhone.Text)End Sub

    Private Sub txtCreditCard_GotFocus()' Trim embedded spaces.txtCreditCard.Text = FilterNumber(txtCreditCard.Text, True)End SubPrivate Sub txtCreditCard_LostFocus()' Add spaces if necessary.txtCreditCard.Text = FormatCreditCard(txtCreditCard.Text)

    End Sub

    Instead of inserting the code that formats phone numbers and credit-card numbers right in the LostFocus eventprocedures, I built two distinct routines, which can be more easily reused in other applications, as shown in the codebelow.

    Function FormatPhoneNumber(Text As String) As StringDim tmp As StringIf Text "" Then' First get rid of all embedded dashes, if any.tmp = FilterString(Text, "0123456789")' Then reinsert them in the correct position.If Len(tmp)

  • 8/3/2019 Getting Started With VB 6

    34/133

    34

    control's width, so this setting is most useful when you're creating memo fields or simple word processor-like programs. Ifyou have both a vertical and a horizontal scroll bar, the TextBox control behaves more like a programmer's editor, andlonger lines simply extend beyond the right border. I've never found a decent use for the other settings of the ScrollBarsproperty (0-None and 1-Horizontal) in a multiline TextBox control. Visual Basic ignores the ScrollBars property if MultiLineis False.

    Both these properties are read-only at run time, which means that you can't alternate between a regular and a multilinetext box, or between a word processor-like multiline field (ScrollBars = 2-Vertical) and an editorlike field (ScrollBars = 3-Both). To tell the whole truth, Visual Basic's support for multiline TextBox controls leaves much to be desired. You can dovery little with such controls at run time, except to retrieve and set their Text properties. When you read the contents of amultiline TextBox control, it's up to you to determine where each line of text starts and ends. You do this with a loop thatsearches for carriage return (CR) and line feed (LF) pairs, or even more easily using the new Split string function:

    ' Print the lines of text in Text1, labeling them with their line numbers.Dim lines() As String, i As Integerlines() = Split(Text1.Text, vbCrLf)For i = 0 To UBound(lines)Print (i + 1) & ": " & lines(i)Next

    The support offered by Visual Basic for multiline TextBox controls ends here. The language doesn't offer any means forlearning such vital information as at which point each line of text wraps, which are the first visible line and the first visiblecolumn, which line and column the caret is on, and so on. Moreover, you have no means of programmatically scrollingthrough a multiline text box. The solutions to these problems require Microsoft Windows API programming. In my opinion,however, Visual Basic should offer these features as built-in properties and methods.

    You should account for two minor issues when including one or more multiline TextBox controls on your forms. When youenter code in a word processor or an editor, you expect that the Enter key will add a newline character (more precisely, aCR-LF character pair) and that the Tab key will insert a tab character and move the caret accordingly. Visual Basicsupports these keys, but because both of them have special meaning to Windows the support is limited: The Enter keyadds a CR-LF pair only if there isn't a default push button on the form, and the Tab key inserts a tab character only if therearen't other controls on the form whose TabStop property is set to True. In many circumstances, these requirements can't

    be met, and some of your users will find your user interface annoying. If you can't avoid this problem, at least add areminder to your users that they can add new lines using the Ctrl+Enter key combination and insert tab characters usingthe Ctrl+Tab key combination. Another possible approach is to set the TabStop property to False for all the controls in theform in the multiline TextBox's GotFocus event and to restore the original values in the LostFocus event procedure.

    Label And Frame Controls In Visual Basic 6

    Label and Frame controls have a few features in common, so it makes sense to explain them together. First they're mostly"decorative" controls that contribute to the user interface but are seldom used as programmable objects. In other words,you often place them on the form and arrange their properties as your user interface needs dictate, but you rarely writecode to serve their events, generally, or manipulate their properties at run time.

    Label Controls

    Most people use Label controls to provide a descriptive caption and possibly an associated hot key for other controls,such as TextBox, ListBox, and ComboBox, that don't expose the Caption property. In most cases, you just place a Labelcontrol where you need it, set its Caption property to a suitable string (embedding an ampersand character in front of thehot key you want to assign), and you're done. Caption is the default property for Label controls. Be careful to set theLabel's TabIndex property so that it's 1 minus the TabIndex property of the companion control.

    Other useful properties are BorderStyle(if you want the Label control to appear inside a 3D border) and Alignment (if youwant to align the caption to the right or center it on the control). In most cases, the alignment depends on how the Labelcontrol relates to its companion control: for example, if the Label control is placed to the left of its companion field, you

  • 8/3/2019 Getting Started With VB 6

    35/133

    35

    might want to set its Alignment property to 1-Right Justify. The value 2-Center is especially useful for stand-alone Labelcontrols.

    Different settings for the Alignment property of Label controls.

    You can insert a literal & character in a Label control's Caption property by doubling it. For example, to see Research &Development you have to type &Research && Development. Note that if you have multiple but isolated &s, the one that

    selects the hot key is the last one and all others are ignored. This tip applies to all the controls that expose a Captionproperty. (The & has no special meaning in forms' Caption properties, however.)

    If the caption string is a long one, you might want to set the Label's WordWrap property to True so that it will extend formultiple lines instead of being truncated by the right border of the control. Alternatively, you might decide to set theAutoSize property to True and let the control automatically resize itself to accommodate longer caption strings.

    You sometimes need to modify the default value of a Label's BackStyle property. Label controls usually cover what'salready on the form's surface (other lightweight controls, output from graphic methods, and so on) because theirbackground is considered to be opaque. If you want to show a character string somewhere on the form but at the sametime you don't want to obscure underlying objects, set the BackStyle property to 0-Transparent.

    If you're using the Label control to display data read from elsewherefor example, a database field or a text fileyou

    should set its UseMnemonics property to False. In this case, & characters have no special meaning to the control, and soyou indirectly turn off the control's hot key capability. I mention this property because in older versions of Visual Basic, youhad to manually double each & character to make the ampersand appear in text. I don't think all developers are awarethat you can now treat ampersands like regular characters.

    As I said before, you don't usually write code in Label control event procedures. This control exposes only a subset of theevents supported by other controls. For example, because Label controls can never get the input focus, they don't supportGotFocus, LostFocus, or any keyboard-related events. In practice, you can take advantage only of their mouse events:Click, DblClick, MouseDown, MouseMove, and MouseUp. If you're using a Label control