+ All Categories
Home > Documents > Visual Basic 5-6 Course Part 3

Visual Basic 5-6 Course Part 3

Date post: 30-May-2018
Category:
Upload: mark-collins
View: 219 times
Download: 0 times
Share this document with a friend

of 24

Transcript
  • 8/9/2019 Visual Basic 5-6 Course Part 3

    1/24

    Visual Basic 5Programming - 3

    A Specialised Training Course

  • 8/9/2019 Visual Basic 5-6 Course Part 3

    2/24

    Visual Basic Book 3 Mark Collins 1999 Page 1

    ContentsARRAYS ........................................................... ........................................................... ........................... 2

    DECLARING ARRAYS WITH DIM ................................................... ........................................................ 2

    REFERENCING ARRAYS WITH SUBSCRIPTS ........................................................ .................................... 3

    SCOPING ARRAYS ..................................................... ........................................................... ................. 4

    USER-DEFINED TYPE (RECORD / STRUCTURE) ....................................................... ................. 4

    CREATING A CONTROL ARRAY ..................................................... ........................................................ 6

    REFERENCING WITH THE INDEX PROPERTY ...................................................... .................................... 6

    USING SHARED EVENT PROCEDURES ...................................................... .............................................. 6

    INTRODUCTION TO PROCEDURES ........................................................... .................................... 7

    PROGRAM FLOW................................ ............................................................ .................................... 8

    UNCONDITIONAL BRANCHING ...................................................... ........................................................ 8

    GoTo ......................................................... ........................................................... ........................... 8

    GoSub...Return ................................................... ........................................................... ................. 8

    CONDITIONAL BRANCHING........................................................... ........................................................ 9

    ENDING EXECUTION ........................................................... ........................................................... ....... 9

    CONDITIONAL TESTING....................................................... ........................................................... ....... 9

    IF...THEN...ELSEIF...THEN...ELSE...END IF ................................................... .................................... 9

    Select Case............................ ............................................................ ............................................ 10

    LOOPING......................................................... ........................................................... ......................... 12For...Next.................................................. ........................................................... ......................... 12

    While...Wend....................................................... ........................................................... ............... 13

    Do...Loop .................................................. ........................................................... ......................... 14

    APPENDIX ....................................................... ........................................................... ......................... 16

    Relational Operators .................................................... ........................................................... ..... 16

    Logical Operators............................................... ........................................................... ............... 16

  • 8/9/2019 Visual Basic 5-6 Course Part 3

    3/24

    Visual Basic Book 3 Mark Collins 1999 Page 2

    Arrays

    Arrays are special data constructs with the ability to hold multiple data

    items under a single name.

    An array can store several occurrences of a single data-type, usually each

    with a similar meaning or use to the program. One way of viewing an

    array is to liken it to a table of data items with rows and columns. An array

    can have multiple rows and columns. If an array is similar to a table with a

    single column and several rows, a list, it is called aone-dimensional

    array. As soon as we add more columns it becomes atwo-dimensional

    array (like a spreadsheet). If you then add depth to this view we can have

    three-dimensionalarrays. And so we can go on with several more

    dimensions although it becomes difficult to conceptualise in our limited

    3-D world.

    For example, lets look at a possible use of arrays to store student scores.

    A simple list of scores for a single question for several students canbe stored in a one-dimensional array.

    If we extend our array to include several question scores for eachstudent making up a single assignment we have a two-dimensional

    array.

    If we have a page for each of several assignments making up a wholesubject we can store this in a three-dimensional array. (this can

    continue to 60 dimensions!)

    For now well concentrate on single dimensional arrays.

    Declaring arrays with DIM

    If we want to create an array we give it a name, establish the data-type and

    specify the number of elements in the array (in each direction /

    dimension). As with simple variables we use the DIM keyword. DIM has

    always been used to define arrays in previous incarnations of BASIC.

    (Later we will see that there are situations where we use the STATIC and

    GLOBAL keywords instead).

    When defining the number of elements it should be understood that there

    is a zero element. To access a specific element we reference an array with

    Subscripts or Indexes, described later. Unlike some other languages when

    an array is defined the contents of its elements are automatically initialised

    to zero for numeric data and null (empty) for strings.

    A Dim statement can appear anywhere in the code before the array is used.

    As with variables you should consider the scope of your array and place it

    accordingly (see scoping arrays below). It is good practice to place your

    DIMs at the start of blocks of code, even if they arent used until the last

    line.

    It is easiest to explain the variations with examples...

  • 8/9/2019 Visual Basic 5-6 Course Part 3

    4/24

    Visual Basic Book 3 Mark Collins 1999 Page 3

    DimPrice(12) as Currency

    creates a single dimensioned array called Price which can store 13

    currency values, 0 to 12.

    DimChessBoard%(7, 7)

    creates a two-dimensional array used to represent a chess board. The data

    type is integer (using type declaration character).

    Option Base 1

    DimChessBoard%(8, 8)

    creates a similar array except the additional line changes the first element

    from 0 to 1.

    DimChessBoard%( 1 To 8, 1 To 8 )

    This has a similar effect to the previous example, but this ability to define

    thebounds of subscripts can be used when a more specific range isneeded.

    DimProfit@(1984 to 1994)

    This array has eleven elements which store a currency value for each of

    the years 1984 to 1994. The subscript range simplifies understanding code

    considerably, removing the need for constant conversions. The range can

    even include negative subscripts.

    It is also possible to define the dimensions using variables or constants.

    Const Students = 25

    DimScores(Students) as Integer

    Finally there may be occasions when we want to resize an array at run

    time, a ReDim statement allows that providing the array is defined as

    being Dynamic. This is done by not initially specifying the 'dimensions'.

    Dim Scores( ) As Integer

    ReDim Scores(NumStudents%,NumScores%)

    Referencing arrays with Subscripts

    When we want to reference an array we specify thesubscript for each

    direction / dimension. This can be done literally or by use of variables

    (most commonly in loops, see later).

    Profit@(1987) = 10345.85

    txtProfit.Text=Str$(Profit@(year))

    ChessBoard(3,5) = 25 25 is White King

  • 8/9/2019 Visual Basic 5-6 Course Part 3

    5/24

    Visual Basic Book 3 Mark Collins 1999 Page 4

    Scoping Arrays

    As with simple variables the scope of an array depends on where it is

    declared.

    Declarations section of aForm - the whole form;

    Declarations section of aModule - the whole module;

    Declarations section of anyModule using Global instead ofDim - thewhole project;

    Inside aProcedure - within that procedure, but....

    If only it were that simple. A simple variable defined in a procedure

    exists only for the period that the procedure is active; this is not possible

    with arrays. Arrays must be permanent, i.e. Static. As with simple

    variables arrays can be made to be Static, irrespective of their scope. But

    if the scope of an array is in a procedure then the array must be static.

    There are two ways of doing this... Declare with Dim, but make the procedure static

    Static Sub DoSomething( )

    DimAnArray(12)...

    Declare a static, fixed sized array in a non-static procedure.

    Sub DoSomething( )

    Static AnArray(12)...

    A static procedure causes all its variables to be static. Which ever way, aprocedure-declared array must be static.

    User-Defined Type (record / structure)

    One of the limitations of the Arrays we have looked at so far is that all the

    elements must be of the same data type. This is not flexible enough formany situations where you need a single line to contain different types.

    A very simple list of employee details for example requiring a string, an

    integer and a currency value for each employee. This can be overcome by

    creating an array for each type...

    Const NUMEMPS 20

    DimName(1 to NUMEMPS)As String * 20

    DimAge(1 to NUMEMPS) As Integer

    DimSalary(1 to NUMEMPS)As Currency

    The disadvantage of this is that they are separate arrays, and if we needed

    to sort the list we would need additional code to sort all three arrays

  • 8/9/2019 Visual Basic 5-6 Course Part 3

    6/24

    Visual Basic Book 3 Mark Collins 1999 Page 5

    correctly. What we want is a single array, generally one-dimensional, of a

    single type. So lets create our own data type called Employee.

    Private Type Employee

    NameAs String * 20

    AgeAs Integer

    SalaryAs CurrencyEnd Type

    This composite data-type is similar to and otherwise known as aRecordor

    a Structure. The block of code defining a data-type must be placed in the

    declarations section of aModule and automatically has Global

    availability. Note the construct of this block and that the components

    (fields) can be any of the standard data types or even another previously

    defined user-defined type of fixed array.

    Type ShiftMember

    PersonAs Employee

    HoursOnDate(1 to 31)As Integer

    End Type

    We can then use the user-defined type to declare variables of that type,

    including arrays, anywhere in our code with the usual individual scope...

    DimManagerAs Employee

    DimWorker(1 to 24)As Employee

    DimBlueShift(1 to 15)As ShiftMember

    The individual components of a variable can be accessed as before by

    using the following syntax...

    Variable[(subscript)].Component

    for example...

    Manager.Name = "David Copperfield"

    Worker(2).Name = "Oliver Twist"

    Worker(7).Salary = 13200.00

    BlueShift(3).Person = Manager

    Blueshift(3).HoursOnDate(4) = 7

  • 8/9/2019 Visual Basic 5-6 Course Part 3

    7/24

    Visual Basic Book 3 Mark Collins 1999 Page 6

    Control Arrays

    Just as we use arrays of variables to group similar data we can place

    similar controls in a Control Array. These could be three check-boxes

    controlling font details (Bold, Italic & Underline) or a group of linkedOption-buttons of which only one can be selected.

    As a Control Array they have several advantages...

    Your program code can manipulate them more efficiently, we willinvestigate loops etc. that permit this later.

    They share the same event procedures.

    Elements can be added and removed at runtime.

    Creating a Control Array

    By giving a set of existing controls of the same type the same name you

    create a control array. Each element of the control array is distinguished

    by the Index property. The only property they do share is the name

    Property, all the others can be different.

    Referencing with the Index Property

    Once a control array is created we refer to each component using its

    unique index. For example if we have three option buttons called

    optPayment we can define their individual captions at run-time as

    follows...

    optPayment(1).Caption = "Access"

    optPayment(2).Caption = "Visa"

    optPayment(3).Caption = "Cash"

    Using shared Event procedures

    If you call up an event for a control array you will see that the first line has

    changed to include (Index As Integer). This is the systems way of

    passing the information as to which element of the control array initiated

    the event. The name is Index by default but you can change it to anything.This is then used as a variable within the code...

    Sub optTest_Click (Index As Integer)

    code to reset all captions then

    optTest(Index).Caption = "Im it!"

    End Sub

    More often than not you will require some conditional processing such as

    If Then or Select Case within your procedure. These are discussed later in

    the book.

  • 8/9/2019 Visual Basic 5-6 Course Part 3

    8/24

    Visual Basic Book 3 Mark Collins 1999 Page 7

    Introduction to Procedures

    A simple view of procedures would be to describe them as a group of code

    lines that perform a sub-task of the overall program. This way of breaking

    down large complex programs is one of the main features of structuredprogramming.

    In BASIC there are three main types of procedure...

    Event procedures - Defined by the system although you create theircontents, they are activated by the system in response to events.

    General procedures - otherwise known as user-definedproceduresthey are written by the user and activated by calls from your code.

    Property procedures - a complex issue best left until later.

    Although our view of these procedures are as separate pieces of text

    within their own code window, they are in fact all stored adjacently in

    files, similar to a more conventional program. This can be seen when you

    print out the code from a form or module.

    Procedures may manipulate variables which are Global or scoped

    throughout the form or module that the procedure is part of. As we have

    discussed earlier they may also have their own set ofLocal variables

    which are not accessible outside the procedure.

    The use of Global variables will upset 'Real' structured programming

    gurus. They will tell you that variables should have as limited a scope as

    possible. This requires passing values to and returning values from

    procedures, forms and modules rather than sharing a single variable

    throughout. Whilst we needn't go to their extremes it necessary to

    understand this technique, especially to pass information between the

    larger objects (forms and modules).

    The example we have already seen of passing values is in control arrays

    where the system passes the element Index as a parameter to the event

    procedure.

    We can also create general procedures that behave as built-in functions,

    i.e. they return a value. For example a function defined as follows...

    Function Add%(First As Integer, Second As Integer)

    Add% = First + SecondEnd Function

    can be used to add two numbers passed to it as parameters using the

    code

    Number% = Add(4, 8)

    We will look at procedures in more depth later in the course.

  • 8/9/2019 Visual Basic 5-6 Course Part 3

    9/24

    Visual Basic Book 3 Mark Collins 1999 Page 8

    Program Flow

    The sequence of processing required through a program, form, module or

    procedure is rarely linear nor is the sequence likely to be identical from

    one occasion to the next. There are frequent decisions that need to be

    made based upon the conditions present or repetition of code, either in aloop or use of procedures for repeated tasks. These possibilities generally

    fall into one of the following categories...

    Unconditional branching (GoTo, GoSub...Return, Call);

    Conditional branching (On...GoTo, On...GoSub);

    Procedure calls (can be used to invoke other forms and modules);

    Terminating Processing (End);

    Conditional testing (If...Then, Select Case);

    Looping (For...Next, While...Wend, Do...Loop).

    Unconditional Branching

    GoTo

    Back in the early days of compulsory line numbers in BASIC programs,

    GoTo was used a lot to skip about your code. You can still use it now, but

    the trouble has always been that you can easily loose track of your GoTos

    and end up in all sorts of logical knots. Use of GoTo statements is

    unnecessary, is considered spaghetti programming and is FORBIDDEN!

    GoSub...Return

    Although strictly not branching, more temporarily diverting, the structured

    alternative to GoTo has always been GoSub. Whereas both jump about

    the code, GoSub returns you to where you called it from.

    In Visual Basic GoSub can be used to unconditionally alter program flow

    within a procedure. To use it you need a Label or Line number to jump to.

    To create a line number at the beginning of a suitable point simply insert a

    number at the beginning of the line. Unlike previous versions it has no

    sequential meaning. A Label is simply an alphanumeric word terminated

    with a colon inserted in the necessary position. The problem with GoSubs

    is that you often end up using a GoTo to bypass them which means that

    the same applies to GoSubs: also FORBIDDEN. The Real alternative is

    to use General Procedures.

    (Procedure) Call

    This is the optional command to call any sub-procedure although the use

    of Call is optional. If you use the Call statement then any parameters must

    be in parentheses. Without the call statement then you should not use

    parentheses except for a specific purpose discussed later. If there are no

    parameters then parentheses (even empty) must not be used whether you

    use Call or not.

  • 8/9/2019 Visual Basic 5-6 Course Part 3

    10/24

    Visual Basic Book 3 Mark Collins 1999 Page 9

    Example

    Sub procCallTest (Number As Integer, MyText As

    String)

    definition of procedure

    lblTest is a control array of two labels

    lblTest(Number).Caption = MyTextEnd Sub

    Sub cmdTest_Click ()

    Calling procedure two ways

    Call procCallTest(0, "First Changed")

    procCallTest 1, "Second Changed"

    End Sub

    The sub-procedure that you call can be any of the following...

    A user defined procedure in a module or Form;

    An event procedure that you want to trigger using code;

    An External DLL procedure, requires declaration.

    NB. When omitting the Call, you do have to use parentheses around a

    single parameter, that forms an expression whose value is passed as the

    argument - this has implications discussed later in the course (by reference

    / by value).

    Conditional Branching

    As we are trying not to use GoTo and GoSub we should avoid the

    On...GoTo and On...GoSub variations. We will however need to return to

    this later in the course for Error Handling.

    Ending Execution

    This allows us to terminate processing at any point in our program by use

    of theEndstatement. This is usually placed in the Click event procedure

    of a Quit button or a general procedure activated by a menu option. Using

    the close option in the Control-box menu also has a similar effect althoughit is often preferable to Unload all the forms.

    Conditional Testing

    If...Then...ElseIf...Then...Else...End if

    Used to execute program statements only if a condition is true. The

    condition is usually an expression (e.g. If chkBold.Value = 1) testing a

  • 8/9/2019 Visual Basic 5-6 Course Part 3

    11/24

    Visual Basic Book 3 Mark Collins 1999 Page 10

    numeric or string value. See tables of Relational and Logical Operators in

    the Appendix.

    Syntax

    Ifcondition1 Then[statementblock-1][ElseIfcondition2Then

    [statementblock-2] ]

    ...

    [Else

    [statementblock-n] ]

    End If

    There can be several ElseIfblocks and the Else block is optional in all

    cases.

    There is a shorter syntax if a single statement is dependent on a single

    condition that does not require an End If. It is however good practice toalways explicitly define your statement block with a Then...End If.

    Select Case

    As I mentioned earlier, the Select Case structure is regarded as a better

    alternative to the On...GoSub option. Whereas the If... structure tests for

    true or false conditions the Select Case structure tests whether the value of

    an expression falls within a predetermined range.

    Syntax

    Select Casetestexpression

    [Caseexpressionlist1[statementblock-1] ]

    [Caseexpressionlist2

    [statementblock-2] ]

    ...

    [CaseElse

    [statementblock-n] ]

    End Select

    The testexpression can be any numeric or string expression including a

    single variable.

    For example...

    Select Case Asc(UserInput) ' If it's a letter.

    Case 65 To 90 ' Must be uppercase.Msg = "Uppercase letter '"

    Msg = Msg & Chr(Asc(UserInput)) & "'."

    Case 97 To 122 ' Must be lowercase.Msg = "Lower-case letter '"

    Msg = Msg & Chr(Asc(UserInput)) & "'."

    CaseElse ' Must be something else.Msg = "You did not enter a letter."

    End Select

    MsgBox(Msg)

  • 8/9/2019 Visual Basic 5-6 Course Part 3

    12/24

    Visual Basic Book 3 Mark Collins 1999 Page 11

    This example uses a Control Array index...

    Sub optProcessor_Click (IndexAs Integer)

    Select Case Index

    Case 0Msg = A 286 is a museum piece

    Case 1Msg = A 386 is too slow

    Case 2Msg = A 486 will probably do

    Case 3Msg = A Pentium is ideal

    CaseElseMsg = Dont say youve got a Mac?

    End Select

    MsgBox(Msg)

    End Sub

  • 8/9/2019 Visual Basic 5-6 Course Part 3

    13/24

    Visual Basic Book 3 Mark Collins 1999 Page 12

    Looping

    For iterated processing of a statement block then there are three

    possibilities...

    For...Next;

    While...Wend;

    Do...Loop.

    These can be used in several situations, including working through all the

    elements of a variable array or for checking/setting each of the values of a

    control array. Which one to use? It depends on the situation...

    If you know the specific number of times a loop must perform (eithera literal, variable or constant number) then use a For...Next loop (e.g.

    To work through an array);

    If the loop depends on a different condition but must be executed at

    least once then use a Do...Loop (e.g. requiring input of at least oneitem before a key is pressed to terminate);

    Otherwise use a While...Wend loop (e.g. taking input of a list until acertain key is pressed).

    For...Next

    Syntax

    Forcounter=startToend[ Stepincrement ]

    [statementblock]

    [Exit For]

    [statementblock]Next [counter[, counter][, ...]]

    The counteris an integer variable used to control the loop. It is

    initialised to the start value and increments by one (unless the Step

    incrementspecifies otherwise) each time theNextcounter

    statement is reached when the counteris tested against the endvalue.

    If they are equal then the loop is terminated, otherwise the statement block

    is executed again.

    The loop can be terminated early by the use of the End For statement in

    the statement block, usually controlled by a conditional structure.

    If you are nesting loops within one another it is recommended to includethe specific counterafter eachNext statement for clarity, otherwise it

    is optional.

    The counter can then be used within the statement block; arrays are a good

    example of this...

    Dim Squares(13) As Integer

    For j = 0 to 13

    Square(j)= j^2

    Next

  • 8/9/2019 Visual Basic 5-6 Course Part 3

    14/24

    Visual Basic Book 3 Mark Collins 1999 Page 13

    While...Wend

    Whereas theFor...Next loop was controlled by a counter variable,

    While...Wendis controlled by a condition. While the condition is True the

    loop will iterate. Note that the test is made on entering the loop for the

    first time, if the condition is False the loop will not be performed. If you

    want the test to occur at the end of the first iteration use Do...Loop.

    Syntax

    Whilecondition

    [statementblock]

    Wend

    The condition can be any predicate expression, the value of the expression

    is used (0 and Null is False, any other value is True). This means that your

    condition could range from a complex test to the value of a single integer

    variable. As the While...Wendloop can not be broken using theExit

    statement (except for closing the application, this is possible withFor...Next andDo...Loop) you should not use the condition of 1 or TRUE.

    The following are examples of the use ofWhile...Wendloops...

    While Colour = Red Or Size Small

    MsgBox Not a small one that could be red!...

    Wend

    Uses a combination of Logical and comparison operators to form a

    specific condition. As a result of the Or operator both parts must be False

    to exit the loop.

    Exchange = True ' Force 1st pass through array.

    While Exchange

    Exchange = False

    For I = 2 To MAX

    If A(I - 1) > A(I) Then

    Exchange = True

    Temp = A(I): A(I) = A(I - 1)A(I - 1) = Temp

    End If

    Next I

    Wend

    This example uses the While...Wendto control a simple bubble sort.

    Nested in the loop is aFor...Next loop within which anIf...EndIf block is

    nested. Note the use of indentation for each level of code and of

    commenting for explanation.

    The While...Wend loop is controlled by the testing of a single variable

    (Exchange) containing the integer equivalent ofTrue orFalse (reserved

    words defined as -1 and 0 respectively). Exchange is set to True before

    the loop, forcing at least a single pass through the loop. At the beginning

    of the loop it is set toFalse, and unless theIf...Next statement block is

    performed at least once in this iteration of the While...Wendthe loop willterminate when it reaches the Wendstatement.

  • 8/9/2019 Visual Basic 5-6 Course Part 3

    15/24

    Visual Basic Book 3 Mark Collins 1999 Page 14

    Do...Loop

    This is a lot more flexible that the While...Wendloop because...

    the condition can be placed at the beginning orthe end of the loop,

    the condition can be used to continue if True or if False

    an End Do statement can exit the loop from within the statementblock.

    Top test Syntax

    Do [{While | Until} condition]

    [statementblock]

    [Exit Do]

    [statementblock]

    Loop

    Bottom test SyntaxDo

    [statementblock]

    [Exit Do]

    [statementblock]

    Loop [{While | Until} condition]

    As you can see we have several possibilities. The While /Untiloption

    basically switches between the two possibilities of...

    Perform the loop WhileTrue (i.e. while the condition is True and

    exit when the condition is False) Perform the loop UntilTrue (i.e. while the condition is False and exit

    when the condition is True.)

    The top test version is similar to the While...Wendloop. The bottom test

    version performs the loop at least once, even if the condition isnt met on

    entering the loop.Exit Do can be used to exit the loop at any stage.

    Examples...

    ex.1) The example creates an infinite Do...Loop that can be exited only if

    the user enters a number in a range.

    Sub Form_Click ()

    DimReply ' Declare variable.

    DoReply = InputBox("Enter a number > 1 and < 9")

    If Reply > 1And Reply < 9 Then

    Exit Do

    End If

    Loop

    End Sub

  • 8/9/2019 Visual Basic 5-6 Course Part 3

    16/24

    Visual Basic Book 3 Mark Collins 1999 Page 15

    ex.2) Alternatively, the same thing can be accomplished by incorporating

    the range test in theDo...Loop as follows...

    Sub Form_Click ()

    DimReply

    Do

    Reply = InputBox("Enter a number > 1 and < 9.")Loop Until Reply > 1And Reply < 9

    End Sub

    ex.3) Or reversing the condition to use While...

    Sub Form_Click ()

    DimReply

    Do

    Reply = InputBox("Enter a number > 1 and < 9.")

    Loop While Reply < 1 Or Reply > 9

    End Sub

    ex.4) Finally we can use a top test combination....

    Sub Form_Click ()

    DimReplyReply = 0

    Do Until Reply > 1And Reply < 9

    Reply = InputBox("Enter a number > 1 and < 9.")

    Loop

    End Sub

    ex.5) Or even...

    Sub Form_Click ()

    DimReplyReply = 0

    Do While Reply < 1 Or Reply > 9

    Reply = InputBox("Enter a number > 1 and < 9.")

    Loop

    End Sub

    In which case we may as well have used...

    Sub Form_Click ()DimReplyReply = 0

    While Reply < 1 Or Reply > 9

    Reply = InputBox("Enter a number > 1 and < 9.")

    Wend

    End Sub

  • 8/9/2019 Visual Basic 5-6 Course Part 3

    17/24

    Visual Basic Book 3 Mark Collins 1999 Page 16

    Appendix

    Relational Operators

    Operator Meaning True if False if Null if

    < Less than expr1 < expr2 expr1 >= expr2 expr1 or expr2 = Null

    Greater than expr1 > expr2 expr1 = Greater than orequal to

    expr1 >= expr2 expr1 < expr2 expr1 or expr2 = Null

    = Equal to expr1 = expr2 expr1 expr2 expr1 or expr2 = Null

    Not equal to expr1 expr2 expr1 = expr2 expr1 or expr2 = Null

    Logical Operators

    And - Both operands are True

    Or - One or both operands are True

    Not -The opposite of the single operand

    Xor - Only one is True

    Eqv - Both operands are identical

    Imp - The entire expression is True, except when the first expressionis True and the second False

    A B Not A A And B A Or B A Xor B A Eqv B A Imp B

    T T F T T F T TT F F F T T F F

    F T T F T T F T

    F F T F F F T T

  • 8/9/2019 Visual Basic 5-6 Course Part 3

    18/24

    Visual Basic Book 3 Mark Collins 1999 Page 17

    Exercises

    Preparation:

    Create Project Directories called... EmpArray

    Truth

    Exercise 1

    Aim: to create an application that creates and manipulates an array of a user-

    defined type.

    1 Load Visual Basic and start a new Project.

    2 Create a new Module - Either select Insert / Module from the menu or use

    the New Module button on the tool bar3 In the [general] / [declarations] section of the new modules code window add

    the following definition...

    Type Employee

    Name As String * 20

    Age As Integer

    Salary As Currency

    End Type

    Close the modules code window

    4 Create a form with the following layout of controls...

  • 8/9/2019 Visual Basic 5-6 Course Part 3

    19/24

    Visual Basic Book 3 Mark Collins 1999 Page 18

    Your controls should have the following properties...

    Type Name Caption / Text Other...

    Form frmEmp Employee

    Label lblName Employee

    NamelblAge Employee Age

    lblSalary Salary

    lblEmploy Employees

    TextBox txtName blank

    txtAge blank

    txtSalary blank

    Command Button cmdAveAge Average Age

    cmdTotSal Total Salary

    cmdQuit Quit Cancel = True

    Horiz Scroll Bar hsbSubscript all default

    5 In the forms [general]/[declarations]section declare a constant for the number

    of employees (NUMEMPS) and set it initially to three. Then define an array of

    type Employee called Worker using the NUMEMPS constant for its

    dimension.

    Const NUMEMPS = 3

    Dim Worker(NUMEMPS) As Employee

    6 As the form loads you will need to enter data so append the code below using

    a for...next loop to do this again using the NUMEMPS constant. We also need

    to set the Max value for our scroll bar to NUMEMPS so that we can use it tomove between elements of our array without exceeding the bounds.

    Sub Form_Load ()

    hsbSubscript.Max = NUMEMPS

    For i = 0 To NUMEMPS

    Worker(i).Name = InputBox("Enter Name", "Name")

    Worker(i).Age = Val(InputBox("Enter Age, "Age"))

    Worker(i).Salary = Val(InputBox("Salary", "Salary"))

    Next i

    End Sub

    7 Define a new general-procedure in your Form to change the currentlydisplayed record to the element with the same subscript as our horizontal scroll

    bars value - call up code window, go to [general]/[declarations] section and

    just type the following in...

    Sub procChangeRecord ()

    txtName.Text = Worker(hsbSubscript.Value).Name

    txtAge.Text = Worker(hsbSubscript.Value).Age

    txtSalary.Text = Worker(hsbSubscript.Value).Salary

    End Sub

  • 8/9/2019 Visual Basic 5-6 Course Part 3

    20/24

    Visual Basic Book 3 Mark Collins 1999 Page 19

    8 Where do we need to put a call to this procedure? We will need to display the

    first record when the data entry part of Form_Load is completed (after Next

    statement in Form_Load) and when the horizontal scroll bar is clicked.

    9 Try our application so far; what happens if you use the scroll bar? When you

    are happy save it all to the Emparray project directory with the names

    EMPARRAY.BAS, EMPARRAY.FRM and EMPARRAY.VBP

    10 As entering data can get tedious you can save time later by commenting out

    your data entry code and placing the following below.

    ' For i = 0 To NUMEMPS

    ' Worker(i).Name = InputBox("Enter Name", "Name")

    ' Worker(i).Age = Val(InputBox("Enter Age" , "Age"))

    ' Worker(i).Salary = Val(InputBox("Salary", "Salary"))

    ' Next i

    Worker(0).Name = "Alfred"

    Worker(0).Age = 45

    Worker(0).Salary = 25000Worker(1).Name = "Belinda"

    Worker(1).Age = 30

    Worker(1).Salary = 20000

    Worker(2).Name = "Carlos"

    Worker(2).Age = 25

    Worker(2).Salary = 15000

    Worker(3).Name = "Davinda"

    Worker(3).Age = 35

    Worker(3).Salary = 25000

    11 Can you devise the necessary code for our Average Age and Total Salary

    buttons?

    12 Can you modify the InputBox syntax such that it provides an indication of the

    number of employees added to the system?

  • 8/9/2019 Visual Basic 5-6 Course Part 3

    21/24

    Visual Basic Book 3 Mark Collins 1999 Page 20

    Exercise 2In this exercise we will create an application to work out the result of

    various logical operator combinations. To do so we will create Control

    Arrays and use the Select Case structure.

    1 Start a new project and create a form similar to the one above with the

    following object properties...

    Type Name Caption / Text Other...

    Form frmTruth TRUTH TABLE

    Frame fraOp1 Operand 1

    fraOp2 Operand 2

    Option Button optOp1 True Value = TrueoptOp1 * False

    optOp2 True Value = True

    optOp2 * False

    Combo Box cboOperator blank

    Label lblResult ? Font Size = 24

    Bold = True

    * - by giving each pair the same name we create a control array. Make sure

    each pair of option buttons is placed inside its own frame when first added to

    the form, otherwise the groupings will be wrong.

    2 The application needs to react to a click in any of the option buttons or aselection of a new operator. The reaction will consist of evaluating the

    expression and displaying the result in the labels caption as True or False.

    First we must create the entries in the Combo box.

    Sub Form_Load ()

    cboOperator.AddItem "And"

    cboOperator.AddItem "Or"

    cboOperator.AddItem "XOr"

    cboOperator.AddItem "Imp"

    cboOperator.AddItem "Eqv"

    End Sub

  • 8/9/2019 Visual Basic 5-6 Course Part 3

    22/24

    Visual Basic Book 3 Mark Collins 1999 Page 21

    3 Next we need a procedure to call to evaluate the result. Create the following

    in the forms [general] / [declarations] section.Note that the lines ending with

    _ are a single line of code extended over two lines. You can extend your code

    over more than one line by using a space + underline at the end of the line.

    Sub procEvaluate ()

    lblResult.Caption = "False"

    Select Case cboOperator.Text

    Case "And"

    If (optOp1(0).Value And

    optOp2(0).Value) Then _

    lblResult.Caption = "True"

    Case "Or"

    If (optOp1(0).Value Or optOp2(0).Value)

    Then _

    lblResult.Caption = "True"

    Case "XOr"

    If (optOp1(0).Value Xor

    optOp2(0).Value) Then _lblResult.Caption = "True"

    Case "Imp"

    If (optOp1(0).Value Imp

    optOp2(0).Value) Then _

    lblResult.Caption = "True"

    Case "Eqv"

    If (optOp1(0).Value Eqv

    optOp2(0).Value) Then _

    lblResult.Caption = "True"

    Case Else

    lblResult.Caption = "?"

    End Select

    End Sub

    Explanation Because each pair of option buttons represent True/False if the True

    member is selected then the value of thattrue option button is true. If

    the False member is selected then the value of the True option button

    is False. We do not need to check that the False members value at all.

    We can use this to our advantage in each of the Case selections by

    using these values directly in our condition.

    4 All we need to do now is place calls to this procEvaluate procedure in the

    single click event procedure for each pair of option buttons as well as the click

    and change events of the combo box.5 Test the application, save the form and project in the truth directory as

    TRUTH.FRM and TRUTH.VBP

  • 8/9/2019 Visual Basic 5-6 Course Part 3

    23/24

    Visual Basic Book 3 Mark Collins 1999 Page 22

    Exercise 3In this exercise we will create an application to work out the result of the scope of the

    variables in local, form, module and global level.

    Make new module, from Project menu, select new module

    In module1, type in general declarations

    Global test as Integer

    Form1

    Control Name Caption

    Command1 Proc1

    Command2 Proc2

    Command3 Form

    Command4 Global

    Form1 Scope of variables

    Now in the form1 general declarations add

    Dim test as Integer

    In form1 load procedure add

    Private Sub Form1_load()

    Module1.test = 2001

    test = 42Form2.show

    End Sub

    Now add the following code to the buttons

    Private Sub Command1_Click()

    Dim test as Integer

    test = 1

    Msgbox Str$(test) local test

    End Sub

    Private Sub Command2_Click()Dim test as Integer

    test = 1

    Msgbox Str$(test) local test

    Msgbox Str$( Form1.test) form1 test

    End Sub

    Private Sub Command3_Click()

    Msgbox Str$(test) form1 test

    End Sub

    Private Sub Command4_Click()

    Msgbox Str$(Module1.test) Global test

    End Sub

  • 8/9/2019 Visual Basic 5-6 Course Part 3

    24/24

    Visual Basic Book 3 Mark Collins 1999 Page 23

    Now create another form

    Form2

    Control Name Caption

    Command1 Form1 change test

    Form2 I can modify form1s test variable

    Now add the following code to the form2s button

    Private Sub Command1_Click()

    Form1.test = 56 form1s test

    End Sub

    Now change in form1s general declarations

    Public test as Integer

    What is the effect of changing the test to Public?


Recommended