VB

Programming Basic

What is Visual Basic?

3 kinds of Errors

Programming Process

Constants and Variables

Invalid, Valid Variable Name Exercise

Data Types

Internal Data Representation

Declaring Variables in Visual Basic

Variable Declaration Exercise

Identifying Variables, Constants

Assignment Statements

Internal Documentation

Visual Basic Terms

Event, Control, Property

Designing the User Interface

Design Time, Run Time, and Break Mode

Concatenation - &

Concatenation exercise

Functions

Creating an Executable File

Math Operators

More on Assignment Statements

Sequence Control Structure

FlowChart

Walking Though Code

Val() and Conversion Functions

Visual BASIC Functions

Focus

Format Function

Pseudocode

Flowchart

Simple Visual Basic If Statement

Order of ASCII exercise

Simple If Exercise

If Else

Selecting Text in Text boxes

Elseif

Visual Basic Message Box

White Space

Guidelines for adding white space

Nested If Selection Structure

Nested If

How deep is too deep?

Input Data Validation

Using BreakPoints

Logical operators and compound If statements

The Or operator

Not operator

Hierarchy of Logical Operators

Case Structure Pseudocode

Select Case Statement in Visual Basic

Counter & Accumulators

Scope

Division by Zero

Pseudocode Iteration Control Structure

Charting Multiple Statements Inside a Loop

Iteration (Do Loop)

Random Numbers

InputBox

Iteration Control Structure in Visual Basic

Converting Flowchart/Pseudocode to VB Code

General Procedures

Pseudocodeing and Flowcharting General Procedures

Flowchart using general procedures

Passing Arguments to Procedures

Data Files & Data Hierarchy

Sequential Data Files

Write to a Sequential Data Files

Close a Sequential Data Files

Read from a Sequential Data Files

Date Function

Reports

Method of Layout Design

Printer Object

Printing Variable Length Data

Variable Arrays

Searching an Array

VB Message Box Function

Programmer Defined Functions

Control Break Logic


Untitled Document
Programming Basic
Hardware is the equipment or machinery associated with a computer.
Software refers to the data and instructions used to generate information.

⊕ Information Processing Cycle

Input Data
Storage
  • Primary Storage (Memory/ RAM)
  • Secondary Storage - Mass Storage Device (Disk)
Process a running software
Processor CPU (Central Processing Unit)
Computer Program Software
Output Information is output in a useable form

    Software or Programs can be divide into two categories.

System software Windows is an example of system software.
Application software Word is an example of application software.

    All software is written by programmers.

♦ Off-the-Shelf software

♦ In-house or customized development

⊕ Systems Development

♦ System Analysis & Design

♦ Implementation includes (among other things)

Programming- Programmers write programs
Testing and debugging

⊕ What a Computer Can Do

Accept data via input device
Store Data in Memory Variables
Perform Arithmetic operations (add, subtract, multiply, divide) on data
Compare data to other data determine if one value is less than, greater than, or equal to another value
Output Results via output device

⊕ Programs and Programming

♦ Logic / Algorithm - Step-by-step instructions

♦ Structured Programming

⊕ Programming Languages -

    Programmers write programs using a programming language best suited for the application they are creating.

Machine Language the only language the computer really understands. No one really write in machine language. Instead an assembler, compiler, or interpreter converts the instructions written by the programmer, (the source code) into machine language.
Low-Level Language closest to machine language Assembly Language
High-Level Languages closer to English Cobol, C, C++, Java, Fortran, Perl, RPG, Visual Basic,
Fourth-Generation Language Intended for programmer as well as non-programmer use SQL, FOCUS

⊕ Translating Source Code to Machine Code

Source Code instructions written in a computer language
Assembler Assembly languages are assembled.
Compiler Checks all instructions in a high-level program for syntax errors, if any error is found a list of detected errors is produced. If no errors are found the entire program is translated into machine code and stored in machine language ready for execution.
Interpreter Checks instructions in a high-level program for syntax errors one line at a time. If no error is found the instruction is translated into machine code then executed and the interpreter moves on to the next line in sequence.

⊕ Procedural Language

⊕ Event-Driven Programming Language

⊕ Object-Oriented Language

Sat Feb 5 07:28:04 CST 2011

Untitled Document
What is Visual Basic?

    Visual Basic evolved from the text-based language - BASIC (Beginne's All-purpose Symbolic Instruction Code). With the development of the Microsoft Windows GUI in the early 1990's writing programs to run in the graphical environment was difficult. Visual Basic was created by Microsoft and released in 1991 to simplify the process.

    Creating an application using VB is sometimes referred to as Rapid Application Development. Visual Basic is the most widely used RAD language.

⊕ Visual Basic

high-level Programming Language
Event oriented As opposed to procedure oriented. In a procedural language there is always a beginning, middle, and an end.
High-visual Uses a GUI (Graphical User Interface) Interpreted in development stage
Can be compiled The runtime file - msvbvm60.dll usually found in the System directory is needed to run a Visual Basic application without the Visual Basic program.

♦ Using Visual Basic we will create forms (windows) and the code that will be executed when an "event" happens.

♦ The environment we use to develop VB applications is called an Integrated Development Environment or IDE. It provides tools to draw the visual interface, write the code behind the interface, compile, and test and debug the application.

⊕ Versions of Visual Basic

1991 1.0
1992 2.0 Faster
1993 3.0 Simple way to control databases
1995 4.0 Supports 32-bit processing. It generates 32-bit applications for Windows 95 or NT. Began providing developers with some object-oriented capabilities.
1997 5.0 New interface. Programmers can create their own controls.
1998 6.0 Includes new data access and Web development features.
2002 .NET Major changes (among other things) enhances Internet Application

⊕ Editions of Visual Basic

Learning Edition Allow beginning Visual Basic Programmers to easily create powerful applications for the Windows platform. It includes all intrinsic controls, plus grid, tab, and data-bound controls. Documentation includes Learn VB Now (a multimedia CD-ROM title), plus Microsoft Developer Network CDs containing full on-line documentation.
Professional Edition Designed for professional programmers. Includes all the features of the leaning edition plus additional ActiveX controls, the Internet Information Server Application Designer, Integrated Data Tools and Data Environment to support high-speed database access, and the Dynamic HTML Page Designer. Documentation includes the Visual Studio Professional Features book.
Enterprise Edition Intended for development and support of robust distributed applications in a team setting. Includes all the features of the Professional edition plus Back Office tools such as SQL Server, Microsoft Transaction Server, Internet Information Server, Visual SourceSafe, SNA Server and more.

⊕ Other flavors

Working Edition Like the Learning Edition but may not compile to an .EXE file and no online Documentation. Comes with textbooks.
VBA/Visual Basic for Application What is Visual Basic Included with Microsoft Office applications to provide programming-development capability from within them.
Sat Feb 5 07:28:04 CST 2011 Untitled Document
3 kinds of Errors

⊕ Syntax Errors

♦ Syntax errors, called Compile errors by the IDE, occur when the compiler or interpreter is unable to convert a line of code written by a programmer into executable code.

♦ They occur when the programmer has violated a rule of the language.

♦ Some syntax errors are detected as soon as you move to the next line.

♦ Other syntax errors are not detected until you attempt to run the program

⊕ Run Time Error

♦ Run Time errors occur when the program is executing and has encountered an instruction which attempts to do something which is not allowed.

♦ For example

    if you attempt to assign a string value to a numeric property or variable the following error will occur

♦ For both Compile errors and Run-Time errors the editor will flag the line of code which caused the error.

⊕ Logic Errors

♦ Logic errors occur when the program statements are syntactically correct but do not produce the desired results.

    Remember - Programs always do exactly what you tell them to do but not always what you intend them to do.

⊕ Debugging

♦ Locating and correcting errors in a program is called Debugging.

Sat Feb 5 07:28:05 CST 2011 Untitled Document
Programming Process

⊕ 1. Define/Understand Problem

State the output requirements What are you trying to do?
Identify the available input What are you given to work with?
Determine necessary processing What do you have to do with or to the available input to produce the desired output?

⊕ 2. Develop the logic

♦ Decompose into smaller segments

♦ Design Tools

Structure Charts  
Flowchart Pictorial representation of a program solution
Pseudocode Solution to programming task that is language independent
Walkthrough  

⊕ 3. Code / Write the program

Compile Program Syntax Errors – A violation of the rules of the language.

Example: Pint "Hello World " (Print is misspelled)

Test Program Logic Errors – when a program does exactly what it is told to do but not what the programmer intended it to do.

Example: GrossPay = PayRate / HoursWorked

⊕ 4. Document the Program

⊕ 5. Maintenance - Make changes or enhancements to programs as needed or requested.

Sat Feb 5 07:28:05 CST 2011 Untitled Document
Constants and Variables

    Data is categorized as either constants or variables and either numeric or non-numeric.

⊕ Constants

Numeric constants
  • May have sign in front of number
  • May have decimal point
  • No commas, dollar signs, percent signs
  • May be used in calculations
  • For example - 5     4.5    -7
Nonnumeric constants Anything enclosed in quotation marks is considered a Nonnumeric constant, also called string constants or alphanumeric constants or literals

Nonnumeric constants SHOULD NOT be used in calculations

For example - "Hello World", "5", "Five", "", (Quotes with nothing, not even a space between them are called a zero-length string or empty string.)

⊕ Variables

♦ A variable is a named storage location (area of memory) that can contain data that can be modified during program execution. A variable can store only 1 item of data at any one time.

♦ Programmers often need to store values for later use. For example, you may have values entered by a user for the number of hours worked and a rate of pay. You plan to multiply the two values and store the result in memory so you can use it later. For this you will need a variable.

♦ Memory is made up of contiguous bytes. One byte can store one character. To store the word CLINTON requires 7 bytes of storage. When you declare a variable, memory space is allocated to that variable.

♦ Each variable has a name that is supplied by the programmer. When you reference that variable name in your program you are accessing the value stored in the memory location associated with that variable.

♦ The contents of the memory location can change; the name of the memory location will stay the same.

⊕ Rules for naming variables in Visual Basic

Unique within scope
<= 255 characters (other languages may have different length restrictions)
Begin with a letter
No embedded spaces or many special characters (. , “ - $ # * and others). The underscore _ is a valid character.
Cannot be a reserved word
Use upper and lower case with purpose.

Once a variable is declared you do not have to be concerned with upper/lower case. The editor recognizes words that are the same except for case and makes them all the same for you. (use of upper and lower case differ between languages)

It is always good programming practice to use names that are descriptive or mnemonic.
Sat Feb 5 07:28:05 CST 2011 Untitled Document
Invalid, Valid Variable Name Exercise

    Based on the rules for naming variables in Visual Basic indicate whether the following variable names are VALID or INVALID. Check the appropriate column for each variable name. Are the GOOD variables names?

Variable Name Valid? Invalid? Good Variables Name? If not why?
GPA YES      
Count#1        
$grosspay        
GradePointAverage        
Attempted.Hours        
Attempted-Hours        
Interest Rate        
A2        
2A        
Print        
Printitout        
MONEYAFTERALLTAXES        

⊕ Rules for naming variables in Visual Basic

Unique within scope
<= 255 characters (other languages may have different length restrictions)
Begin with a letter
No embedded spaces or many special characters (. , “ - $ # * and others). The underscore _ is a valid character.
Cannot be a reserved word
Use upper and lower case with purpose. Once a variable is declared you do not have to be concerned with upper/lower case. The editor recognizes words that are the same except for case and makes them all the same for you. (use of upper and lower case differ between languages)
It is always good programming practice to use names that are descriptive or mnemonic.
Sat Feb 5 07:28:05 CST 2011 Untitled Document
Data Types

♦ Every variable has a data type. The data type specifies the kind of data the variable can store.

♦ As with constants all programming languages have at least two kinds of data types.

Nonnumeric data type (called String, text, alphanumeric, or character data in different languages ) can be used to store any kind of data.
Numeric data types are used to store numbers.

♦ Different programming languages may have other data types.

⊕ Data Types in Visual Basic

♦ Visual Basic has 14 different data types. We are interested in only a few for now.

String String variables are a nonnumeric data type that can be used to store text values up to 2 billion characters long. The maximum length will differ on individual machines because of available memory, overhead, and other programs.

Any characters may be stored in a string variable.

Integer Integer data type can be used to store a whole number between -32,768 to 32,767
Long Integer data type can be used to store a whole number between -2,147,483,648 to 2,147,483,647

Note: If you know that a variable will always store whole numbers (such as 12) rather than numbers with a fractional amount (such as 3.57), declare it as an Integer or Long type. Operations are faster with integers, and these types consume less memory than other data types.

Single Is used to store single-precision floating-point numbers. In other words they are used to store numbers with fractions.
Double Is used to store double-precision floating-point numbers. That is numbers that are very large, very small, or have many decimal positions.
  • Boolean Variables are used as a flag or switch. The value of a Boolean variable is either True or False. Boolean variables are used to indicate the absence or presence of a certain condition. The properties Default, Cancel, Visible, and Enabled are all Boolean properties.
    Date The date data type can store a date anywhere from Jan 1, 100 to Dec 31, 9999. The date is stored as a number of days from 12/30/1899. Negative numbers reflect dates prior to 12/30/1899.

    Time is stored in the decimal portion of a Date type variable.

    Sat Feb 5 07:28:06 CST 2011 Untitled Document
    Internal Data Representation

      Data is stored internally in bits or electric circuits that are either on or off.

      On external storage devices bits are recorded as magnetic or reflective spots.

    ♦ 8 bits make up 1 byte.

    ♦ When string data is stored in memory each character/symbol requires 1 byte of storage.

    ♦ The following representation of a byte is how the character “a” is stored in ASCII.

      0   1   1   0   0   0    0   1
    

    ⊕ ASCII

      ASCII stands for American Standards Committee for Information Interchange and is a standard coding scheme used by most personal computers to represent letters, numerals, symbols, as well as keys on the keyboard like Enter, Backspace, etc.

      When we refer to the ASCII code we usually will use the decimal equivalent to the binary (base 2) number represented by the ons and offs (1’s and 0’s). So we would say that the character “a” is represented by the ASCII code 97. To convert a binary number to decimal we need to understand how numbers in different bases work.

    ♦ The number 789 in base ten is equal to

                  9 * 100  = 9    (any number raised to the power of zero equal 1)
              +  8 * 101 = 80   (any number raised to the power of one equals itself)
              +  7 * 102 = 700
     
       9 + 80 + 700 = 789
    

    ♦ The same can be done with a binary (base 2) number

      0   1   1   0   0   0    0   1
      _   _   _   _   _   _    _   _
      27  26  25  24  23  22  21 20 
    
                  1 * 20 = 1
                +0 * 21 = 0
                +0 * 22 = 0
                +0 * 23 = 0
                +0 * 24 = 0
                +1 * 25 = 32
                +1 * 26 = 64
                +0 * 27 = 0
                1 + 32 + 64 = 97
    

      The ASCII coding scheme uses only 7 bits of a byte (0 – 128). Computers also use numbers 129 through 255 to represent additional characters but this list is not really standardized so you may find difference between charts.

    ♦ Unicode

      Because 256 characters are not sufficient to represent all characters used in Asian languages a new standard has emerged. The "Unicode" character set uses two bytes of storage and contains more than 32000 characters. Since the standard has to be supported by the entire industry, unicode is still not widely used. Windows 2000 and MacOS X offer full support for it

    ♦ Numbers are stored in binary as well

       0   1   1   0   0   0   0   1
       _   _   _   _   _   _   _   _
       27  26  25  24  23 22 21 20
    

      is also equivalent to the unsigned integer 97

      How the contents of an area of memory are interpreted is based on how it is defined. If this area is defined as character data, it will be treated as ASCII character "a".

      If it is defined as an unsigned integer, it will be treated as the number 97.

      Actually an unsigned integer uses at least 2 bytes or 16 bits and can store a number as large as 65,535. (1 + 2 + 4 + 8 + 16 + 32 + 64 + 128 + 256 + 512 + 1024 + 2048 + 4096 + 8192 + 16384 + 32768)

    
      1   1   1   1   1   1   1   1   1   1   1   1   1   1   1  1
      215 214 213 212 211 210 29 28 27 26 25 24 23 22 21 20
     
    

      Signed integers store the sign in the left most bit.

      A signed integer that uses 2 bytes can store any whole number between -32,768 and 32,767

      A signed long integer that uses 4 bytes can store any whole number between -2,147,483,648 and 2,147,483,647

      The number of bytes used to store a particular numeric data type (and therefore the range of values) may vary on different platforms.

      The data types Single and Double can store numbers with decimals. Numbers stored in floating-point variables are stored in scientific notation. A portion of the variable is used to store the sign and exponent. Sometimes a large or small number is displayed in scientific notation – 1.234568E+08 1.234568E-08

      The more memory available to store a number the larger or more precise it can be.

    ♦ When declaring numeric variables, what should they be?

      When fairly large or fairly small numbers are needed use double precision.

      Working with integers is faster than single or double precision so if floating point numbers are not needed integers will improve speed. They also don't take up as much memory.

      On some large mainframe systems data is stored using a different coding scheme – EBCDIC.

    Sat Feb 5 07:28:06 CST 2011 Untitled Document
    Declaring Variables in Visual Basic

      Before you use a variable you should declare it. To declare a variable you can use the Dim statement.

    Dim  intNumber as integer
    Dim sngInterestRate as single
    

      It is good programming practice in any language to use naming conventions (rules, standards) to name your variables. In Visual Basic the naming conventions include using a prefix that identifies the variable’s data type.

    intNumber The prefix int would signify an integer variable, use lng for Long
    sngHours The prefix sng would signify an single variable, use dbl for Double
    strName The prefix str would signify a string variable
    blnYearEnd The prefix bln would signify a Boolean variable
    dtmBDay The prefix dtm would signify a date/time variable

    ♦ It is not REQUIRED to declare variables before you use them.

      If you do not declare variables the default data type is Variant. While the variant data type is flexible since it can hold any data type it is generally advised to avoid variant data types because they require more memory and are slower to process.

    ♦ Option Explicit

      To avoid variant variables we specify Option Explicit in the General Declarations Section. The General Declarations Section is at the top of the code window.

      If Option Explicit is declared and you attempt to use a variable that has not been declared an error will occur.

      You could set Option Explicit up as the default by turning on the Require Variable Declaration check box on the Editor tab of the Tools/Options dialog box. This automatically inserts the Option Explicit statement in any new modules, but not in modules already created; therefore, you must manually add Option Explicit to any existing modules within a project. The Option Explicit statement it must be placed in the Declarations section of every form.

    ♦ It is not a violation of the rules of the language to declare more than one variable on the same line

    Dim intnumber as integer, sngamount as single, lngBigNumber as long
    

      But it is not advised. You should declare only one variable per line

    Dim intnumber as integer
    Dim sngamount as single
    Dim lngBigNumber as long
    

    ⊕ Variable Scope

    ♦ Variables may be declared at form level in the declarations section or within the procedure in which they will be used.

    ♦ A variable declared at form level is "known" to every procedure in the form. That means all procedures may use variables declared at "form level".

    ♦ A variable declared at the "procedure level" is "known" only to that procedure and can only be referenced by statements within that procedure.

    ⊕ Initialization

    ♦ In Visual Basic all variables are assigned an initial value automatically. All numeric variables have an initial value of 0 (zero) All string variables are empty

    ♦ This is NOT the case in all computer languages. C, C++, and Java do NOT automatically initialize variables.

    ♦ Since the need for variables arise throughout the programming process you will typically work back and forth between the variables declarations and the instructions during the creation of a program, declaring new variables as the need arises.

    Sat Feb 5 07:28:06 CST 2011 Untitled Document
    Variable Declaration Exercise

    ♦ Write an appropriate Visual Basic declaration statement to define variables to store the following information. Be sure to use appropriate prefixes. I have completed the firs one for you.

      Information Declaration
    1. Age Dim intAge as Integer
    2. Address  
    3. FICA tax withheld  
    4. GPA  
    5. Marital status  
    6. End of month flag  
    7. Social Security number  
    8. Date account opened  
    9. Telephone number  
    10. Beginning of shift  
    11. Account closed indicator  
    12. Interest rate  
    13. Number in stock  
    Sat Feb 5 07:28:06 CST 2011 Untitled Document
    Identifying Variables, Constants

    ♦ For each of the following identify each data item as

    Numeric variable or constant
    String variable or constant
    Undetermined
    Data Numeric? Nonnumeric? Constant? Variable? ????
    5.5 yes No yes no
    strName        
    "5.5"        
    -250        
    intScore        
    Five        
    "Parkland College"        
    sngRate        
    .0875        
    0        
    "Invalid Date Vreenter"        
    ""        
    Sat Feb 5 07:28:06 CST 2011 Untitled Document
    Assignment Statements

      To store a value in a variable or to change the setting of a property we will use an assignment statement.

    ♦ Format

    Let variable/property = Variable
    Let variable/property = Property
    Let variable/property = Constant
    Let variable/property = Expression

    ♦ Example

    Let frmMain.Caption = strFileName
    Let lblOutput.Caption = txtInput.Text
    Let txtInput.FontSize = 24
    Let dblGrossPay = sngPayRate * sngHours

    ♦ The equal signs in these examples are assignment operators, not equality operators.

    ♦ Whatever is on the right of the assignment operator is evaluated and the result is placed in whatever is on the left.

    ♦ What is on the left is made equal to what is on the right.

    ♦ Only a variable, object or property can be to left of equal sign in an assignment statement.

      The word LET is optional

                                    frmMain.Caption = strFileName
                                    lblOutput.Caption = txtInput.Text
    

    ♦ You should only assign numeric data to numeric variables/properties and string data to string variables/properties. If you attempt to assign a nonnumeric value to a numeric variable or numeric property a run-time error may occur

    ♦ All numeric data types can be assigned to each other.

      When you assign a floating-point number to an integer Visual Basic rounds rather than truncates the fractional part.

    ♦ Examples of assigning constants to variables and properties of controls:

      To clear the caption property of a label

      lblOutput.caption = ""
      txtInput.text = ""
    

      Quotes with nothing, not even a space between them are called a zero-length string or empty string.

    ⊕ Initialization

      To initialize a variable means to give a beginning value to a variable

    ♦ To initialize a numeric variable to zero.

        intCount = 0
    

    ♦ To assign a value to a string variable

        strName = "Clinton Lien"
    

    ♦ To assign a value to a Boolean variable

    	blnSalaried = True
    

    ♦ To assign a Constant to a date type variable you must include the date in pound (#) signs.

    	dtmDateHired = #01/31/98#
    

    ♦ To assign a time to a date type field it must “look like” a time and be enclosed in quotes.

    	dtmEndTime = "9:50"
    

    ♦ To indicate morning or afternoon time you can include am or pm in the constant as in

      "9:30 am" or "3:30 pm" or

      you could state the time based on a 24 hour clock - "15:30" would be 3:30 pm.

    ♦ NOTE: Variables can be declared in the Declarations Section of your form. They may NOT be assigned a value outside of a procedure.

    Sat Feb 5 07:28:07 CST 2011 Untitled Document
    Internal Documentation

      Since program maintenance (fixing, changing and enhancing) occupies the largest amount of programmer's time, programs should include identifying information within the program and be written in such a way that they can be understood long after they have been written and by people other than their original author.

      Good naming practices are paramount in writing understandable code.

      Comments can also be used to explain the purpose and function of entire programs as well as procedures and individual lines of code.

      Comments, indicated in a Visual Basic program by an ‘ (apostrophe) are not executable and therefore are not considered by the interpreter or compiler.

      You MUST include comments at the top of your program (in the declaration section) your name and a brief description of the programs purpose.

    ♦ For example

    ‘Author:  Kari Couch
    ‘Lab 1: The purpose of this lab is to declare variables of different types, assign them values, and display them in a picture box with appropriate labels.
    

    ♦ Comments appear green in the IDE. (Integrated Development Environment)

      Comment can be placed throughout your program. The interpreter/compile will ignore anything to the right of an apostrophe. You should include comments at the top of each procedure to explain what is going on in the procedure.

      Comments should also be used to explain code that appears obscure.

      Please be aware that sometimes there can be TOO MUCH of a good thing.

    Sat Feb 5 07:28:07 CST 2011 Untitled Document
    Visual Basic Terms
    Object An object consists of code and data that work together as a unit. Most of the objects we will be working with are controls.
    Control Object attached to a form
    Form Container or windows for other forms and controls
    Property Attribute or characteristic that control an object’s appearance or behavior
    Setting Current value of a property. Initial value established in property window but can be altered using code.
    Event Driven A program is written to respond to actions taken by the user. The user is somewhat in control of the order of operations.
    Event Action that is recognized by an object

    ♦ Examples

    • Click
    • Keypress
    • Gotfocus
    • Lostfocus
    • Dblclick
    • Change
    • Keydown
    • Dragdrop
    Event Procedure Code written to tell the program how to respond when an event occurs. Events are associated with objects.

    ♦ objectname_event()

    ♦ Example:

    • cmdPrint_click()
    • txtUserinput_change()
    Code or Instructions Tell the program what to do and are entered in the Code Window

    ♦ Print "This is an output message"

    Assignment Statement

    ♦ objectname.property = setting

      Example

    • txtInput.Text = ""
    • txtInput.FontBold = True
    Method A procedure that is connected to an object. Action an object is capable of performing

    ♦ Format: object.method

      Example:

    • Text1.SetFocus
    • Text1.move 1000
    • Listbox.additem

    ♦ List of Visual Basic Events

    ♦ List of Visual Basic Statements

    ♦ List of Visual Basic Methods A-M

    ♦ List of Visual Basic Methods N - Z

    Sat Feb 5 07:28:07 CST 2011 Untitled Document
    Event, Control, Property

    ⊕ VB Event

    Click
    Keypress
    Gotfocus
    Lostfocus
    Dblclick
    Change
    Keydown
    Dragdrop

    ⊕ VB Controls

    Command Button V used by the user to initiate an action
    Label Used to display text the user cannot change
    Text Box Used to accept text input from the user.
    Option Button Used for user input
    Check Box Used for user input
    Combo Box  
    Directory List Box  
    Drive List Box  
    File list Box  
    Frame  
    List Box  
    Scroll Bar  

    ⊕ VB Commom Properties

    Caption Controls what appears in the title bar of Form and what is displayed on Command Buttons and Labels (An Access Key can be created for a control by inserting an & before a letter in the Caption. An Access key allows the user to select an object using the Alt key in combination with a letter.) The Caption is not related to the Name property.
    Name The name used to refer to the object while writing code. Similar to a variable name, the Name must begin with a letter and be no more than 40 characters long.

    Objects are given default names when created. You should rename objects using the standard prefixes (in lowercase) for the control type followed a word that describes its function (beginning with an uppercase letter).

    • txtFilename ( txt prefix signifies a text box)
    • frmLab1 ( frm prefix signifies a form)
    • cmdPrint ( cmd prefix signifies a command button)
    Cancel If the setting for the cancel property is True pressing the esc key generates the click event for this button.
    Default If the setting for the default property is True pressing the enter key will generate the click event for this button unless another command button has focus.
    Focus Object that is active or ready for input is said to “have focus”.
    Text The value displayed or typed in a textbox is stored in the Text property of the textbox.
    TabIndex Determines the order controls receive focus when the user uses the Tab key.

    If the value of TabIndex = 0 this object will have focus when Form is loaded.

    Object with TabIndex = 1 will have Focus after pressing the Tab key once.

    TabIndex is automatically set to 0 for first control placed on form, next = 1 and so forth. You can change the TabIndex in the Properties window.

    Sat Feb 5 07:28:07 CST 2011 Untitled Document
    Designing the User Interface

      When developing programs that will be used “on line” there is another step to the programming process.

      After defining and understanding the problem and before developing the logic you usually design the user interface. That is, you draw out what the user will see on the screen while they are using the program. Typically this is done in collaboration with the user.

    Sat Feb 5 07:28:08 CST 2011 Untitled Document
    Design Time, Run Time, and Break Mode
          The following material is mostly taken from MSDN Help

      To test and debug an application, you need to understand which of three modes you are in at any given time. You use Visual Basic at design time to create an application, and at run time to run it.

      Break mode, which suspends the execution of the program so you can examine and alter data.

    ♦ Identifying the Current Mode

      The Visual Basic title bar always shows you the current mode. The following images show the title bar for design time, run time, and break mode.

    ♦ The characteristics of the three modes are listed in the following table.

    Mode Description
    Design time Most of the work of creating an application is done at design time. You can design forms, draw controls, write code, and use the Properties window to set or view property settings.

    From the Run menu, choose Start, or click the Run button to switch to run time.

    Run time When an application takes control, you interact with the application the same way a user would. You can view code, but you cannot change it. Sometimes it may appear that you machine is "hung" because it does respond to any keyboard input in the code window. This is usually because you are in Run Mode.

    From the Run menu, choose End, or click the End button to switch back to design time.

    Break mode From the Run menu, choose Break, click the Break button, or press CTRL+BREAK to switch to break mode.

    Execution is suspended while running the application. You can view and edit code (choose Code from the View menu, or press F7), examine or modify data, restart the application, end execution, or continue execution from the same point.

    ⊕ Using the Toolbar to Change Modes

    The toolbar provides three buttons that let you change quickly from one mode to another.

    ♦ Whether any of these buttons is available depends on whether Visual Basic is in run-time mode, design-time mode, or break mode. The following table lists the buttons available for different modes.

    Mode Toolbar buttons available
    Design time Start
    Run time Break, End
    Break Continue, End (in break mode, the Start button becomes the Continue button)
    Sat Feb 5 07:28:08 CST 2011 Untitled Document
    Concatenation - &

    ♦ When we need to tack one expression on to the end of another we concatenate them.

    ♦ We can also use concatenation to embed formatting instructions within a string.

      For example - we can embed a carriage return to cause a string to be printed on two lines.

    ⊕ vbNewLine vbCrLf

    ♦ The VB intrinsic constant vbCrLf (Carriage Return Line Feed) is equivalent to the ASCII character 13 and 10, which are the ASCII values for Carriage return and line feed respectively. Another VB intrinsic constant vbNewLine does the same thing.

    lblOutput.Caption  = "This is a very long message which  " _
    	& Chr(13) & Chr(10) & "will need more than one line to  "  _
    	& vbCrLf & "display" _
    	& vbNewLine _
    	& vbNewLine &  "Please respond”
    

      Will produce the following

      We can include variables also

        Dim strName As String
        strName = "Joe Smith"
        lblOutput.Caption = "This is a very long message which  " _
            & vbNewLine & "will need more than one line to  " _
            & vbNewLine & "display" _
            & vbNewLine _
            & vbNewLine & "Please respond [K1] " & strName
    

    ♦ Continuation Symbol _

      Generally you are to place only one statement per line and use only one line of code per statement. Sometimes the entire statement will not fit on one line. To continue a statement to the next line we must use the continuation operator _ (underscore).

      When using the continuation symbol use it with purpose. Break your statement into logical pieces and indent subsequent lines.

    Sat Feb 5 07:28:08 CST 2011 Untitled Document
    Concatenation exercise

    ♦ Assuming that

    the variable strFName contains the string Joe
    the variable strMiddleIntial contains the string L
    the variable strLName contains the string Smith

      What does each of the following expressions resolve to? Would any result it an error message?

    Expression Answer
    1. strFName & strMiddleInitial & strLName JoeLSmith
    2. "strFName" & "strMiddleInitial" & "strLName"  
    3. strFName & ""strMiddleInitial & "." & strLName  
    4. strFName & " " & strMiddleInitial & ". strLName"  
    5. strFName & " " & strMiddleInitial & ". " & strLName  
    Sat Feb 5 07:28:08 CST 2011 Untitled Document
    Functions

      A function is a predefined procedure which accepts one or more arguments and returns a single value. We (programmers) can write our own functions but many computer applications and languages supply predefined functions.

    ♦ The Sum() function in spreadsheets is one that most people are familiar with.

    ⊕ Predefined Functions

      Predefined functions are used to carry out common operations and make it unnecessary for programmers to "reinvent the wheel".

    ♦ Functions take the arguments passed (input) to them, do "something" with them (process) and return (output) a value.

      The arguments passed must be of the correct data type, separated by commas, enclosed in parenthesis, and in the order the function expects to receive them.

      For example, If we need the uppercase equivalent to a string

                            strUpper = UCase("abc")
     

    Makes strUpper equal to "ABC"

      We can pass a function a constant, variable, property, or expression as long as the argument(s) passed to the function is the correct data type, that is, it is the data type the function is expecting.

                            strName = UCase(txtName.text)
    
    Sat Feb 5 07:28:08 CST 2011 Untitled Document
    Creating an Executable File

      Be sure to name your project before you create an executable file from your source code. The name you give your project will be the default name for the executable file with an .exe extension. All files with .exe extensions are executable files.

    Choose Make xxxxx.exe from the file menu.

    And then using the drop down Save In list box travel to the location you wish to save the executable file at
    You can change the name of the file at this point.
    Choose OK.

      Note: You may save the executable on your personal storage device and then copy it anywhere you want.

      When you Run the program from the IDE the Visual Basic Interpreter translates each line of code just prior to executing it. When you Make an executable the Visual Basic compiler translates your source code into machine language and saves it permanently in the .exe file.

    Sat Feb 5 07:28:09 CST 2011 Untitled Document
    Math Operators

    ⊕ Format of assignment statement

    Let variable/property = Variable
    Let variable/property = Property value
    Let variable/property = Constant
    Let variable/property = Expression

    ⊕ Expression, Operator, Operand

      An expression is a combination of variables/property values/constants called operands with operators.

    ♦ Operators are symbols used to tell the computer what to do.

    ⊕ Types of operators

    Arithmetic Used to do calculations
    Concatenation Used to put strings together
    Relational Used in comparisons
    Logical Also used in comparisons

    ⊕ Arithmetic operators

    Exponentiation ^
    Negation -
    Multiplication *
    Division /
    Integer Division \
    Modulus Division Mod
    Addition +
    Subtraction -

    ♦ There are three different division operators.

    Regular division 11 / 2 = 5.5 returns a floating point (with decimals) answer
    Integer division 11 \ 2 = 5 returns a whole number, discarding the remainder
    Modulus division 11 Mod 2 = 1 returns only the remainder

      Note: Integer and Modulus division only work with integer type data (integer and long). If you use floating point values they will be rounded to integers before the division takes place.

    ⊕ Examples of expressions -

    sngRadius^2
    -intyardage
    sngAmount * sngSalesTaxRate
    intTotal / intCount
    sngAmount + sngSalesTax
    sngAmount - sngDiscount
    intCandyBars \ intNumPeople
    intCandyBars Mod intNumPeople

    ♦ We can combine multiple operators and operands in one expression

    ♦ What is the result of the following expression?

    sngAnswer = 6 - 3 * 6 / 9
    

    ⊕ Order of Precedence

      The computer evaluates expression based on a set of rule called the hierarchy of operations or order of precedence which is the same order of precedence you learned in math class. We can alter the order of precedence by using parenthesis

    sngAnswer = (6 - 3) * (6 / 9)
    

    ♦ Order of Precedence

    exponentiation
    multiplication and division (as they occur from left to right)
    integer division
    modulus division
    addition and subtraction (as they occur from left to right)
    Sat Feb 5 07:28:09 CST 2011 Untitled Document
    More on Assignment Statements

      It is not uncommon to place the same variable on both sides of an assignment statement. The statement
      intTotal = intTotal + intAmount
      
      repeated several times can be used to add up a series of values. In this example intotal is called an accumulator.

      The statement
      intCount = intCount + 1
      
      can be used to count how many times a set of instructions has been executed. intCount is called a counter.

    ♦ Given the following values how would each expression be evaluated?

    intA=2         intB=4        intC=3
    intA = intA + intB
    intC = intC + 1
    intA = intA + intC
    

    ♦ In some languages there are special operators to do this

    VB C
    intC = intC + 1 intC++
    intC = intC - 1 intC--
    intA = intA + intB intA += intB
    intA = intA - intB intA -= intB
    intA = intA * intB intA *= intB
    intA = intA / intB intA /= intB

    ♦ COBOL allows you to do math using words rather than operators for example

    Multiply Hours by Rate giving Gross
    1 to Counter giving Counter
    Sat Feb 5 07:28:09 CST 2011 Untitled Document
    Sequence Control Structure

      In the mid-1960's, mathematicians proved that any program, no matter how complicated, can be written using only 3 basic control structures.

    Sequence
    Selection
    Iteration also called repetition

      Control structures are used to control which instruction will be executed next.

    ♦ The sequence control structure is the default or overriding structure.

      The sequence structure indicates instructions are to be executed one statement at a time in the order they occur from top to bottom unless a different control structure dictates otherwise.

    Sat Feb 5 07:28:09 CST 2011 Untitled Document
    FlowChart
    Sat Feb 5 07:28:10 CST 2011 Untitled Document
    Walking Though Code

      To debug a computer program it is often necessary to "walkthrough code" to determine what will occur when a series of program statements are executed

      Walkthrough the following instructions to determine the final values for each variable. Analyze each statement in sequence and record each change in value and any output produced.

    ♦ Example

    Dim intA as integer          
    Dim intB as integer          
    Dim sngC as single          
    Dim sngD as single          
      intA intB sngC sngD Output
    intA = 5          
    intB = 10          
    sngD = 2.4          
    Print "sngC = ", sngC          
               
    intA = sngD          
    intB = intA * intB          
    Print "intB = ", intB          
    sngC = intA * intB - intA          
    sngD = sngC / 2          
    Print "sngC = ", sngC          
    sngD = sngD + intA + intB          
    Print "sngD = ", sngD          
    Sat Feb 5 07:28:10 CST 2011 Untitled Document
    Val() and Conversion Functions

    ⊕ Why use Val()?

      In our programs input will often be entered through textboxes on a form.

      All caption and text properties are variant data type. They can hold number and/or strings equally. You can do calculations with caption and text properties if they contain numeric data. But it is not advised.

      If you attempt to use a text and/or caption property in a calculation and it does not contain numeric data you will get a run-time error

      Your program will die.

      One way to ensure that data from text boxes is numeric is to use the Val() function.

    ⊕ Function

      A function is a predefined operation that accepts one or more arguments and returns a single value. Functions are often used in assignment statements.

    variable/property = functionName(argument1, argument2,etc)
    

    ♦ Functions take the arguments passed (input) to them, do "something" with them (process) and return (output) a value.

    ♦ The arguments passed must be of the correct data type, separated by commas, enclosed in parenthesis, and in the order the function expects to receive them.

    ⊕ Val() function

    ♦ The val() function can be used to ensure data obtained from a text box is numeric.

    Dim sngHoldnum as single
    sngHoldnum = Val(txtInput.Text)
    

      The Val() function always returns a numeric value.

      If you attempt to use the Val() function on nonnumeric data Val() returns a 0.

    intNumber = Val("nonnumeric")
    Print intNumber          'output -  0
    

      If you pass data the begins with numeric characters but than has nonnumeric characters Val() will return the number portion of the data.

    intNumber = Val("98junk")
    Print intNumber             'output -  98
    
    intNumber = Val("junk98")
    Print intNumber             'output -  98
    

    ♦ We will always use the Val() function when accepting NUMERIC input from textboxes.

    Dim intYear as Integer
    intYear = Val(txtYear.Text)
    

    ⊕ Other Conversion Functions

    Str(expression)
    CBool(expression)
    CDate(expression)
    CDbl(expression)
    CInt(expression)
    CLng(expression)
    CSng(expression)
    CStr(expression)

      where expression is an appropriate string or numeric value.

    ♦ It is advised to use the appropriate conversion function to produce the desired data type.

      For example

    Dim lngAnswer as long
    lngAnswer = 24 * 24 * 60
    

      will cause "overflow" run time error

      Because Visual Basic will attempt to store intermediate results in an integer since all operands in the expression are integers. (24 * 24 * 60 = 34,560 which is larger than an integer can hold)

    ♦ What to do?

    lngAnswer = CLng(24) * 24 * 60
    

      Will promote the integer 24 to a long so intermediate results will be placed in a long, which can hold 34,560.

    Sat Feb 5 07:28:10 CST 2011 Untitled Document
    Visual BASIC Functions
    A E IsNull PPmt TypeName
        IsNumeric PV  
    Abs Environ IsObject   U
    Array EOF   O
    Asc Error L   UBound
    AscB Exp   OBColor UCase
    Atn   LBound    
      F LCase R V
    C   Left    
      FileAttr Len Rate Val
    CBool FileDateTime LoadPicture ReadProperty VarType
    CByte FileLen LoadResData RGB
    CCur Fix LoadResPicture Right W
    CDate Format LoadResString Rnd
    CDbl FreeFile Loc RTrim
    Choose FV LOF   Weekday
    Chr   Log S
    ChrB G LTrim   Y
    CInt     Second  
    CLng GetAllSettings M Seek Year
    Command GetAttr   Sgn  
    Cos GetObject Mid Shell  
    CreateDatabase GetSetting Minute Sin  
    CreateObject   MIRR SLN  
    CSng H Month Space  
    CStr   MsgBox Spc  
    CurDir     Sqr  
    CVar Hex N Str  
    CVErr Hour   StrComp  
        Now StrConv  
    D I   String  
        NPer Switch  
    Daate Ilf NPV SYD  
    DateAdd IMEStatus      
    DateDiff Input      
    DatePart InStr O T  
    DateSerial Int      
    DateValue IPmt Oct Tab  
    Day IRR OpenDatabase Tan  
    DDB IsArray   Time  
    Dir IsDate P Timer  
    DoEvents IsEmpty   TimeSerial  
      IsError Partition TimeValue  
      IsMissing Pmt Trim  
    Sat Feb 5 07:28:10 CST 2011 Untitled Document
    Focus

    ⊕ Clearing Text Boxes and Setting Focus

    ♦ To clear a text box we assign the Text property to ""

    ♦ To cause the cursor to move to a particular text box in preparation to accept data input we use the SetFocus method.

    Private Sub cmdClear_Click()
    TxtName.Text = ""
    TxtAddress.Text = ""
    TxtName.SetFocus
    End Sub
    
    Sat Feb 5 07:28:10 CST 2011 Untitled Document
    Format Function

    ♦ The Format function can be used to format numeric output with commas and dollar signs as well as in several different date and time formats.

    Format(variable/object, "format name")
    

    ♦ The following table identifies the predefined numeric format names:

    Format name Description
    General Number Display number with no thousand separators and no fixed number of decimal postions.
    Currency Display number with thousand separators, if appropriate; display two digits to the right of the decimal separator. Output is based on system locale settings.
    Fixed Display at least one digit to the left and two digits to the right of the decimal separator. Does not display thousand separators.
    Standard Display number with thousand separators, at least one digit to the left and two digits to the right of the decimal separator.
    Percent Display number multiplied by 100 with a percent sign (%) appended to the right; always display two digits to the right of the decimal separator.
    Scientific Use Standard Scientific Notation
    Yes/No Display No if number is 0; otherwise, display Yes.
    True/False Display False if number is 0; otherwise, display True.
    On/Off Display Off if number is 0; otherwise, display On.

    ♦ Example

    sngAmount = 100
    lblAmtOut.caption = Format(sngAmount,"currency")
    
    
    

    ⊕ VB predefined date and time format names:

    Format Name Description
    General Date Display a date and/or time. For real numbers, display a date and time, for example, 4/3/93 05:34 PM. If there is no fractional part, display only a date, for example, 4/3/93. If there is no integer part, display time only, for example, 05:34 PM. Date display is determined by your system settings.
    Long Date Display a date according to your system's long date format.
    Medium Date Display a date using the medium date format appropriate for the language version of the host application.
    Short Date Display a date using your system's short date format.
    Long Time Display a time using your system's long time format; includes hours, minutes, seconds.
    Medium Time Display time in 12-hour format using hours and minutes and the AM/PM designator.
    Short Time Display a time using the 24-hour format, for example, 17:45.

    ♦ Example

    dtmDate = #02/28/2004#
    lblDateOut.caption = Format(dtmDate, "long date")
    
    
    

    ⊕ More Format Examples

    Function Output
    Format (12345.628, "Standard") 12,345.63
    Format (12345.628, "Currency") $12,345.63
    Format (12345.628, "#,0") 12,346
    Format (.628, "Percent") 62.80%
    Format (12345.628, "Scientific") 1.23E+04
    Format (1 / 4, "Standard") 0.25
    Format (2 + 3.759, "Currency") $5.76
    Format (-1234, "Standard") -1,234.00
    Format (-1234, "Currency") ($1,234.00)
    Format (".2", "Currency") $0.20
    Format ("7/4/04", "Long Date") Thursday, July 4, 2004
    Format ("7/4/04, "Medium Date") 04-Jul-04

    ⊕ New VB6 format functions

    ♦ For currency

    FormatCurrency(curamount,[# of decimal postions])      Note: Arguments enclosed in square brackets are optional
    

    ♦ Example

    sngAmount = 100
    lblAmtOut.caption = FormatCurrency(sngAmount)
    
    
    lblAmtOut.caption = FormatCurrency(sngAmount,0)
    
    
    

      More FormatCurrency() Examples

    Function Returns
    FormatCurrency (12345.628) $12,345.63
    FormatCurrency (12345.628, 0) $12,346
    FormatCurrency (345.645) $345.65
    FormatCurrency (345) $345.00
    FormatCurrency (12345.6) $12,345.60

    ♦ For dates and times

    FormatDateTime(Date[,NamedFormat])
    

      The NamedFormat argument has the following settings:

    Constant Value Description
    vbGeneralDate 0 Display a date and/or time. If there is a date part, display it as a short date. If there is a time part, display it as a long time. If present, both parts are displayed.
    vbLongDate 1 Display a date using the long date format specified in your computer's regional settings.
    vbShortDate 2 Display a date using the short date format specified in your computer's regional settings.
    vbLongTime 3 Display a time using the time format specified in your computer's regional settings.
    vbShortTime 4 Display a time using the 24-hour format (hh:mm).
    dtmDate = #02/28/2004#
    lblDateOut.caption = FormatDateTime(dtmDate, vblongdate)
    
    
    
    Sat Feb 5 07:28:11 CST 2011 Untitled Document
    Pseudocode

    ♦ Pseudocode is a technique that uses English-like statements to portray the sequence of steps involved in a program. Pseudocode is used when planning the solution to a problem.

    ♦ We use words like Get, Input, Accept or Read to represent receiving information from some external source (the user, a file)

    Get FirstName from textbox
    Input Year from textbox
    

    ♦ We use words like Print, Output, Write or Display to represent reporting information on a screen, printer or file.

    Print "Name is", FirstName  on screen
    Display Name is", FirstName in label
    Output EmployeeInformation to Printer
    

    ♦ We can use words like Calculate or Compute along with arithmetic symbols (* / + - etc.) to do arithmetic.

    Compute  OvertimeHours = Hours – 40
    Calculate GrossPay = Hours * PayRate
    

    ♦ We can also use words like Add, Subtract, Multiply, Divide, etc. to do arithmetic.

    Add Hours To TotalHours
    Subtract FICAAmount from GrossPay
    

    ♦ When assigning values to variables we are doing one of 4 things

    Inputting value from external source (covered above).
    Store the result of a calculation (also covered above).
    Initializing, Reinitializing can be indicate by Let or initialize or reinitialize
    Save a value for later use. To indicate storing a value for later use we can use words like Store, Save, Hold.

    ⊕ Initialization

    ♦ Initializing means placing a beginning value in a variable

    Let the FICARate = .0768
    Initialize StateTax Rate to .03
    

    ♦ Reinitializing means replacing the initial value in a variable after it might have been alter by code.

    Let EmployeeDeductions = 0
    Reinitialize OvertimeHours to 0
    

    ⊕ Save a value for later use.

      Save Sales Amount in CurrentHighSaleAmt

      When swaping the contents of two variable, save first value in a temporary variable, and copy it to the second variable after copying the first to the second.

    Sat Feb 5 07:28:11 CST 2011 Untitled Document
    Flowchart

    ♦ Pictorial representation of a program solution

      A Flowchart is a visual tool used to represent the logic of a program.

      Flowcharts are used when planning the solution to a problem.

      Symbols are used to represent the common kinds of operations found in a program's Input, Process and Output and are connected with flow lines that indicate the order the operations are carried out.

      If the flowchart is too big to fit on one page or must be continued from the bottom of a page to the top of the page in a new column reference symbols are used to connect the logic.

    Sat Feb 5 07:28:11 CST 2011 Untitled Document
    Simple Visual Basic If Statement

      Like all other programming languages Visual Basic makes use of the common control structures: Sequence, Selection, and Iteration.

      A common implementation of the selection structure is the If statement. With an If statement you may compare the value of a variable, property, constant or expression to another variable, property, constant, or expression.

    ♦ Simple Selection

    If condition Then statement
    

    ♦ If Block

    If condition Then
    statement
    statement
    statement
    End if        'End If is two words
    

      Example

    If txtinput.Text = "" Then
               Print "you must enter a value in the text box"
           End If
    

    ♦ The If statement uses a relational operator to compare two operands. The two operands should be of the same data type. You should only compare numbers to numbers and strings to strings.

    ⊕ Relational operators

    = Equal to
    > Greater than
    < Less than
    <> Not equal to
    >= Greater than or Equal to
    <= Less than or Equal to

    ♦ Compare Two String Operands

      When comparing two string type operands the comparison is based on the ASCII coding scheme where uppercase is less than lowercase, (H (ASCII 72) is less than h (ASCII 104)); numerals are less than uppercase characters (2 (ASCII 50) is less than H (ASCII 72)). Symbols (* (ASCII43), [ (ASCII 91), } (ASCII 125)) are scattered around the numerals and letters.

    ♦ A condition is an expression.

      Like all expressions conditions are evaluated and return a single value. In Visual Basic if a condition is True it returns a -1, If it is False it returns a 0 (zero).

      In an If statement if the expression (which is often but not always a condition) evaluates to anything other than 0 it is considered True.

      The floowing code fragment is syntactically correct and will print "this is true"
      If 6 then
      Print "this is true"
      End if
      

    ⊕ Use of Boolean Varialbes for Condition

      A Boolean variable is declared as type Boolean and is intended to reflect the absence or presence of a condition. They are used as flags.

        Any value other than 0 will reflect a True condition.

        When a Boolean variable is displayed it displays "True" or "False"

    ♦ Example:
    Dim blnFlag as Boolean
    :
    :
    :
    If blnFlag then   'blnFlag is either True or False
       Print "the flag is on"
    Else
       Print "the flag is off"
    End if
    

    ♦ More If Examples

    If intAge >= 18   then
              Print “Able to Vote”
    End If
    
    If intScore = 100 then
              Print “Perfect Score”
    End If
    
    If intAge < 21 then
              Print “underage”
    End If
    
    Sat Feb 5 07:28:11 CST 2011 Untitled Document
    Order of ASCII exercise

    ♦ Reorder the following character strings so they are in ascending order based on the ASCII coding system?

      To do this exercise you will need to know the ASCII codes for different characters. You may look in the Visual Basic Help. Use the Index and type in ASCII, Display the ASCII character set 0 - 127 or look at the Decimal column of ASCII table at the following site'ASCII code

    Dave
    5
    five
    America
    David
    carport
    DAVID
    $100
    Amy Sue
    AmySue
    (A Comment)
    zoo
    car
    100
    <insert name>
    Sat Feb 5 07:28:12 CST 2011 Untitled Document
    Simple If Exercise

    ♦ Walkthrough the following if statements and indicate the output produced

    Code Output
        If 5 < 15 Then
            Print "1 - True"
        End If
    
     
        If "Andy" > "Bob" Then
            Print "2 - true"
        End If
    
     
        If "bob" < "BOB" Then
            Print "3 - true"
        End If
     
    
     
        If 15 <= 15 Then
            Print "4 - true"
        End If
    
     
        If 5 = 15 Then
            Print "5 - True"
        End If
    
     
        If "Bob" < "Bobby" Then
            Print "6 - true"
        End If
    
     
        If "bob" <> "BOB" Then
            Print "7 - true"
        End If
    
     
    If "15" <= "fifteen" Then
            Print "8 - true"
        End If
    
     
        If "A" < 6 Then
            Print "9 - true"
        End If
    
     
     If "6" > 5 Then
            Print "10 - true"
        End If
    
     
        If "Bob" < "" Then
            Print "11 - true"
        End If
    
     
        If "" < " " Then
            Print "12 - true"
        End If
    
     
    If "6" > “!” Then
            Print "13 - true"
        End If
    
    Sat Feb 5 07:28:12 CST 2011 Untitled Document
    If Else

      With the simple selection we did something when the stated condition was True and did nothing when it was False.

      When we want to do something when a condition is True and something different when the condition is False we use the word Else

    ⊕ If ... Else Statement in Visual Basic

    If condition Then
       statement
       statement
       statement
    Else
       statement
       statement
    End If
    

        In a block If statement the If condition is on a line by itself as is End If

        The Else is generally on a line by itself but it is not required to be.

    ♦ Example:

    If txtInput.Text = "" Then
       Print "you must enter a value in the text box"
       Else
         'Will be executed when txtInput.Text is NOT = ""
         Print "you entered "; txtInput.Text
       End If
    

      The following sections of code will result in the same outcome.

    If intTestScore > 69 Then
    	strGrade = "Pass"
    	Else
    	strGrade = "Fail"
    End If
    If intTestScore > 69 Then
    	strGrade = "Pass"
    End If
    If intTestScore <= 69 Then
    	strGrade = "Fail"
    End If
    

      Neither way is more "correct" than the other but you may believe that one is clearer than the other.

    ♦ Another example

    If sngHours <= 40 Then
    	sngRegular = sngHours * sngRate
    	sngOvertime = 0
    Else
    	sngRegular = 40 * sngRate
    	sngOvertime = (sngHours – 40) * (sngRate * 1.5)
    End if
    
    
    If sngHours <= 40 Then
    	sngRegular = sngHours * sngRate
    	sngOvertime = 0
    End If
    If snghours > 40 Then
    	sngRegular = 40 * sngRate
    	sngOvertime = (sngHours – 40) * (sngRate * 1.5)
    End if
    
    If intTicketsSold = intTicketsAvailable Then
    	Print  “Sold Out”
    Else
    	Print “Tickets Available”
    End If
    
    
    If intTicketsSold = intTicketsAvailable Then
    	Print  “Sold Out”
    End If
    If intTicketsSold <> intTicketsAvailable Then
    	Print “Tickets Available”
    End If
    

      Consider: Do you see a flaw in the preceding logic?

    Sat Feb 5 07:28:12 CST 2011 Untitled Document
    Selecting Text in Text boxes

      As you tab around a form or dialog box and the focus rests on a text box the contents of the text box is often highlighted.

      When a user wishes to change the contents of a text box and the current contents is highlighted they do not have to delete what is already there. By typing any character (including the delete key) the highlighted text is replaced.

    ⊕ SelStart and SelLength

      To select text in a text box we use the properties SelStart, and SelLength.

    ♦ SelStart and SelLength are run time properties;

      they are not available at design time.

      The SelStart property specifies the position of the insertion point. In this case we use it to indicate which character to start the selection with.

      The SelLength property specifies how long selection is.

      We can use the Len function to determine the length of the current contents of a textbox and in the GotFocus() event

    Private Sub txtInput_GotFocus()
        txtInput.SelStart = 0
        txtInput.SelLength = Len(txtInput.Text)
    End Sub
    

    ♦ You will need to code a GotFocus() event for each text box.

    Sat Feb 5 07:28:12 CST 2011 Untitled Document
    Elseif

      When there are more than two possible actions to take we sometimes use a serial if statement.

    Input Age
    If Age < 6 then
            School = "Preschool"
    ElseIf Age < 14
            School = "Elementary"
    ElseIf Age < 18 then
            School = "Secondary"
    Else
            School = "Post secondary"
    End If
    Report School
    

    ⊕ ElseIF Statement

      When there are more than two possible actions to take we sometimes use a serial if statement.

    ♦ Format

    If condition then
          statement
       statement              
    ElseIf condition then
       statement
       statement
       statement
    ElseIf condition then
       statement
       statement
       statement
    Else
       statement
       statement
       statement
    End if
    

      With a serial If statement each condition is tested until one is found to be true. If a condition is found to be true the conditional statements will be executed and then control will be passed to the statement following the End If.

      If none of the conditions stated is true the Else branch is executed and then control will be passed to the statement following the End If.

      The Else is optional. If there is no Else branch no action is taken and execution continues with the statement following the End If.

    ♦ Example

    If txtinput.Text = "" Then
            Print "you must enter a value in the text box"
    ElseIf IsNumeric(txtinput.Text) Then
            Print "you entered the number "; txtinput.Text
    Else
            Print "you entered the string "; txtinput.Text
    End If
    

    ♦ Another example

    If sngSales < 1000 then
            sngCommissionRate = .10
    ElseIf sngSales < 5000  then
            sngCommissionRate = .11
    ElseIf sngSales < 10000  then
            sngCommissionRate = .12
    Else
            sngCommissionRate = .13
    EndIf
    

      Consider: Can you write the preceding selection structure using only simple block if statements? If Yes how? If not why not?

      Can you write the following statement using simple block if statements? If Yes how? If not why not?

    If strEmployeeCode = "S" then
            strStatus = "Salaried"
    ElseIf strEmployeeCode = "H" then
            strStatus = "Hourly"
    Else
            strStatus = "Contractual"
    End If
    

    ♦ Unlike the simple If..Then..Else..EndIf statement which can also be written as a series of simple block If statements the If..Then..ElseIf..Else..EndIf often cannot be.

    ♦ ElseIf is one word. What do you think the compiler would do with the following segment of code?

    If strEmployeeCode = "S" then
            strStatus = "Salaried"
    Else 
    If strEmployeeCode = "H" then
                    strStatus = "Hourly"
    Else
                    strStatus = "Contractual"
    End If
    

    ♦ Above code will get Run Time Error!!

      Every If requires an End If statement. ElseIf do not.

    If strEmployeeCode = "S" then
            strStatus = "Salaried"
    Else 
    	If strEmployeeCode = "H" then
                    strStatus = "Hourly"
    	Else
                    strStatus = "Contractual"
    	End If
    End If
    

        Notice the alignment of the instructions. If should always be aligned with its corresponding Else and End If statements.

      The preceding code would be better written as follows

    If strEmployeeCode = "S" then
            strStatus = "Salaried"
    ElseIf strEmployeeCode = "H" then
            strStatus = "Hourly"
    Else
            strStatus = "Contractual"
    End If
    
    Sat Feb 5 07:28:13 CST 2011 Untitled Document
    Visual Basic Message Box

    ♦ A MsgBox can by used to communicate with the user. It can be used to

    Indicate invalid data entry You must enter numeric data for Hour Worked
    Confirm an action Do you really want to exit program?
    Warn of possible consequence of the user action If you exit without saving your file you will lose your changes
    Keep the user informed File sent to printer

    ♦ The MsgBox is used to inform the user and can be used to request direction from the user.

    ♦ The MsgBox statement displays a message in a box with an OK button and requires the user to respond before returning to the form.

    ♦ Format

    Msgbox strMessage [,,strTitle]
    
    
    

    ♦ Example

    MsgBox "this is a message"  
    

      strTitle (a string variable or nonnumeric constant) is optional (all parameter listed between square brackets are optional) but if provide will display in the title bar of the message box. The box will automatically adjust its size to fit the message.

    ♦ Example 2

            Dim strMessage as string
            strMessage = "this is a message”
    	MsgBox strMessage, , "Demo Message Box"
    

    ♦ The extra comma must be used because we are skipping another optional parameter.

      If your message will need more than one line you will need to include a line feed in the message.

        Dim strMessage As String
        strMessage = "This message will" _
                   & vbNewLine _
                   & "appear on two lines"
        MsgBox strMessage, , "Demo Message Box"
    

    ♦ The user must respond to the message box to continue in the program.

    Sat Feb 5 07:28:13 CST 2011 Untitled Document
    White Space

    ♦ White Space refers to the blank lines inserted in your code to clearly identify blocks of code and to visual convey relationships between lines of code.

    ♦ White Space also refers to indentation of statements to indicate the subordination of lines of code to other lines of code.

    ♦ While White Space does not affect the logic of your program it is VERY important. For anyone reading your code, including yourself, white space conveys information about the logic you intend your program to carry out.

    ♦ From your indentation I infer your understanding of the relationships between lines of code. Proper use, of or even improper but deliberate use, of white space can draw attention to errors in logic and syntax.

    Sat Feb 5 07:28:13 CST 2011 Untitled Document
    Guidelines for adding white space
    Indent all statements within procedures at least one tab stop.
    Separate each group of like or related statements with a blank line. (for example add blank lines between Procedures, after Dim statements, after input statements)
    Use the continuation operator _ to continue long statement from one line to the next. Use continuation so that you can see all the code on the screen without scrolling to the right and to prevent lines from wrapping on their own when printed. Break lines at logical points.
    Indent lines that are continued from the previous line.
    Line each If up with its matching, Else, ElseIf and End IF.
    Indent all subordinate statements within an If statement. Precede and follow each If statement block with a blank line.
    Indent nested IF.
    Sat Feb 5 07:28:14 CST 2011 Untitled Document
    Nested If Selection Structure
    Get Student Name
    Get Grade Point Average from User
    Get Hours Completed from User
     If  Grade Point Average is greater than 3.5 then
               If  Hours Completed is greater than or equal to 15 then
                       Display Student Name " is Honor Student"
              End If
    End If
    
    Get Age from voter
     If  Age is greater than 17 then
              Get Registration Status from voter
               If  voter is registered then
                       Display "You may Vote"
              Else
                       Display "You must register to vote"
              End If
    Else
              Display "You are too young to vote."
    End If        
    
    Sat Feb 5 07:28:14 CST 2011 Untitled Document
    Nested If

      There are times when we want to do something only when two separate conditions are true. For this we can use a Nested If statement.
      If condition Then
      	If condition Then
      		statement
      		statement
      	End if
      End if
      
      is true that is the second If statement begins the block of statements that will be executed only when the first If statement is True

      Indentation of subordinate statements is not syntactically required but is required for good programming technique.

    ♦ Each If MUST be paired with an End If

      Example

    blnHonorStudent will be assigned the value of True only
    blnHonorStudent = False
    If intGPA > 3.5 then
            If intHoursCompleted >= 15 then
    		blnHonorStudent = true
    	End if
    End if
    Print blnHonorStudent
    

      The second test (intYearsEmployed > 2)
      will only take place if sngSales IS greater than 300000

      sngBonus will be assigned the value of 1000 only if both conditions are true

      If sngSales is greater than 300000 BUT intYearsEmployed is NOT greater than 2 sngBonus will be made equal to 500.

      Notice if sngSales is NOT greater than 300000 no value is placed in sngBonus.

      sngBonus = 0
      If sngSales > 300000 Then
      	If intYearsEmployed > 2 Then
      		sngBonus = 1000
      	Else
      		sngBonus = 500
      	End If
      End If
      Print sngBonus
      

      If intAge is greater than 17 AND blnRegistered = True
      the message will be "You may vote".

      If intAge is greater than 17 BUT blnRegistered is not True the message "You must register to vote " will be displayed.

      If intAge is NOT greater than 17 the variable blnRegistered will not be tested. The message "You are too young to vote" will be displayed.

      If intAge > 17 Then
              If blnRegistered Then
                      lblMessage.caption = "You may vote"
              Else
                      lblmessage.caption = "You must register to vote"
              End If
      Else
              lblmessage.caption = "You are too young to vote"
      End If
      

      If sngAmtWithdrawal <= sngBalance the program will then test to see if the sum of sngAmtRecentWithdrawal and sngAmtWithdrawal is less than or equal to 500 (imagine a daily withdrawal limit of $500).

      If BOTH conditions are true a new sngBbalance and sngAmtWithdrawa l will be calculated.

      If sngAmtWithdrawal <= sngBalance BUT the withdrawal combined with recent withdrawals will exceed the limit the withdrawal is denied.

      If there is not enough money to cover the withdrawal the withdrawal is denied, the test for exceeding the limit is not checked.

      If sngAmtWithdrawal <= sngBalance Then
          If sngAmtRecentWithdrawal + sngAmtWithdrawal <= 500 then
              sngBalance = sngBalance -  sngAmtWithdrawal
              sngAmtRecentWithdrawal = sngAmtRecentWithdrawal + sngAmtWithdrawal
          Else
              sngAmtWithdrawal = 0
          End If
      Else
          sngAmtWithdrawal = 0
      End If
      Print "Amount current withdrawal = " & sngAmtWithdrawal
      Print "Total recent withdrawals = " & sngAmtRecentWithdrawal
      Print "New Balance = " & sngBalance
      

    Sat Feb 5 07:28:14 CST 2011 Untitled Document
    How deep is too deep?

    ♦ You may create a nested if statement which is nested quite deeply.
    If blnSalaried = False Then
         If intYearsEmployed > 5 Then
               If sngMonthSales > 200000 Then
                     If sngLastMonthSales > 200000 Then
    		      sngCommission = sngMonthSales * .10
    	         Else
    		      sngCommission = sngMonthSales * .8
    	         End If
               Else
    		sngCommission = sngMonthSales * .6
    	   End If
        Else
    	  sngCommission = sngMonthSales * .04
        End If
    Else
        sngCommission = sngMonthSales * .05
    End If
    

    ♦ Different languages may have different limits to how deep you may nest an If statement without generating an error

    ♦ but it is generally accepted that an If statement nested more than three deep may be too difficult to follow and should be avoided.

    ♦ In other words, the example above is an example of poor programming practices.

    ♦ The following is an alternative way to code the same logic.
    If blnSalaried = True  Then
        sngCommission = sngMonthSales * .05
    ElseIf intYearsEmployed <= 5 Then
        sngCommission = sngMonthSales * .04
    ElseIf sngMonthSales > 200000 Then
        If sngLastMonthSales > 200000 Then
           sngCommission = sngMonthSales * .10
        Else
           sngCommission = sngMonthSales * .8
        End If
    Else
       sngCommission = sngMonthSales * .6
    End If
    

    Sat Feb 5 07:28:14 CST 2011 Untitled Document
    Input Data Validation

    ⊕ IsNumeric() Function

      One thing you are responsible for as a programmer is, to the best of your ability, to validate data that is entered by the user. Data validation can take several forms.

    Testing for blank entry fields
    Testing for nonnumeric data
    Testing for values within acceptable ranges
    Testing for values that are within a predetermined set of values.

      Testing for numeric values when numeric input is required is particularly necessary because programs may die if nonnumeric data is entered when the program expects numeric data.

      The IsNumeric() Function can be used to determine it a variable, constant or expression is numeric or not.

    ♦ Format
    	IsNumeric(variable, constant, or expression)
    evaluates to a number.
    
    
    or expression does not evaluate to a number.
    
    
    

    ♦ Example
    IF IsNumeric(txtIncome.Text) = False then
        MsgBox "You must enter a valid number for income"
        lblTax.Caption = ""    'do not displace any thing displayed in the output 
    label for invalide data
    Else
        sngIncome = val(txtIncome.text)
        If sngIncome > 30000 then
    	sngTax = 4500 + ((sngIncome – 30000) * .28)
        Else
    	sngTax = sngIncome * .15
        EndIf
    lblTax.Caption = FormatCurrency(sngTax)    
    the test for numeric input, It is NOT controlled
    by the test of sngIncome.
    
    
    End If
    

      We will use the IsNumeric() function to validate numeric user input in all future labs. If the input which should be numeric is not numeric we will notify the user with an appropriate message.

    Sat Feb 5 07:28:15 CST 2011 Untitled Document
    Using BreakPoints

    ♦ Logic errors can be tricky to find.

      A good way to see what your code is doing is to walkthrough your code line by line "playing computer".

      Often close scrutiny of the code can reveal the error but sometimes we just don't see it.

      Frequently erroneous assumptions on our part send us down the wrong path of the program logic.

    ⊕ IDE (Interactive Debugging Environment)

      There is a wonderful debugging tool built into the Visual Basic IDE that you can use to show you exactly what is happening when the program is executed.

      You can step through your code by setting a BreakPoint and then watch as each statement is executed.

    ⊕ To set and use breakpoints

    1) Click the gray margin beside a statement prior to where you believe the problem occurs. For our programs it is usually best to set the breakpoint at the top of the procedure, on the first line after the Dim statements. A reddish dot will appear in the margin. This breakpoint indicates that execution of the code will pause when it reaches this statement.
    2) Run the program, enter input values that produce the incorrect output, and click the appropriate command button
    3) Execution will be suspended at the breakpoint. The program will be in Break mode and the statement will be highlighted in yellow. A statement highlighted in yellow has not yet been executed.
    4) At this point you should use your mouse (point at each variable or property in the statement) to ascertain the current value of each operand. A data tip will pop up to display the current value.

    ♦ a. Are the values what you expected them to be?

    5) Based on the values of the operands evaluate the expression a nd decide what you think will happen

        a. if is in an assignment statement determine the value that will be stored

        b. if it is an If statement determine the next statement that will be executed

    ♦ NOTE: it is VERY IMPORTANT that you THINK about what will happen before you move on

    6) Press the F8 key. This will move execute the highlighted statement and move the highlight to the next statement to be executed.

        a. If the previously highlighted statement was an assignment statement point at the variable that received a new value

        i. Is the value what you expected it to be?

        b. If the previously highlighted statement was an If statement did the highlighted move to the statement you expected it to?
        If the result was not what you expected this MAY be the source of your error

    7) Repeat steps 4 - 6 until the end of the procedure or you have found the error.

      At anytime you can continue without stepping through the code by clicking the continue button (right pointing triangle) on the tool bar.

      You can remove the breakpoint by clicking the red dot.

    Sat Feb 5 07:28:15 CST 2011 Untitled Document
    Logical operators and compound If statements

    ♦ Often actions are controlled based on multiple conditions.

      ♦ Example

      Commission rate is .03 if the salesperson sells more than $300,000 wort of product AND they have been employed more than 4 years. Otherwise it is .02.
      If sngSales > 300000 Then
          If intYearsEmployed > 4 then
              sngCommission  =sngSales * .03
          Else
              sngCommission = sngSales * .02
          End If
      Else
          sngCommission = sngSales * .02
      End If
      

      Commission rate is .03 if the salesperson sells more than $300,000 worth of product OR they have been employed more than 4 years. Otherwise it is .02.
      If sngSales > 300000 Then
         sngCommission  =sngSales * .03
      elseIf intYearsEmployed > 4 then
         sngCommission  =sngSales * .03
      Else
         sngCommission = sngSales * .02
      End If
      

      Commission rate is .03 for salespersons who sell more than $300,000 worth of product AND are not considered management.
      sngCommission   = 0
      If sngSales > 300000 Then
          If blnManagement Then
          Else
              sngCommission = sngSales * .03
          End If
      End If
      

    ♦ Another way to make statements conditional based on more than one condition is to use compound If statements. Compound If statements use logical operators - And, Or, Not.

    ⊕ And operator

    If (condition) And (condition) then
        statement
        statement
        statement
    end if
    

      When using the logical operator And All conditions stated must be true for the condition to be true.

      ♦ Example

      If sngSales > 300000 And intYearsEmployed > 4 then
                sngCommission = sngSales * .03
      Else
                sngCommission = sngSales * .02
      End If
      

      One way to illustrate logical operator is with a Venn Diagram
      Sales > $300.000 And Years employed > 4
      
      AND - All conditions are present.

      Another way to resolve a condition with logical operators is with a truth table

    ♦ Truth Table for Conjunctions
    1st Condition 2nd Condition Statement
    A B A and B
    true true true
    true false false
    false true false
    false false false

    ♦ Example

    If sngYearsEmployed > 4 _
       And sngSales > 300000 _
       And sngPreviousSales > 300000 then
                sngCommission = sngSales * .03
    Else
              sngCommission = sngSales * .02
    End If
    
    Years employed > 4
    And Sales > $300.000
    And Previous Sales > $300,000
    
    AND - All conditions are present.

    ♦ Truth Table for Conjunctions
    1st Condition 2nd Condition 3rd Condition Statement
    A B C A and B and C
    true true true true
    true true false false
    true false true false
    true false false false
    false true true false
    false false true false
    false true false false
    False False false false

      Note: When constructing compound conditions you may not have implied operands.

    If sngSales > 100000  And < 300000 then
                sngCommission = sngSales * .03
    End If
    
    If sngSales > 100000 And sngSales < 300000 then sngCommission = sngSales * .03 End If
    Sat Feb 5 07:28:16 CST 2011 Untitled Document
    The Or operator
    If (condition)  Or (condition) then
    	statement
    	statement
    	statement
    End if
    

    ♦ Example
    If sngSales > 300000 Or intYearsEmployed > 4 then
         sngCommission = sngSales * .03
    Else
         sngCommission = sngSales * .02
    End If
    

    ♦ When using the logical operator Or only one of the conditions stated must be true for the condition to be true.
    Sales > $300.000 Or Years employed > 4
    
    (more than one conditions may be present).

    ♦ Truth Table for Disjunctions
    1st Condition 2nd Condition Statement
    A B A or B
    true true true
    true false true
    false true true
    false false false

      Example

    If sngSales > 300000 _
    Or intYearsEmployed > 4 _
    Or blnManagement then
         sngCommission = sngSales * .03
    Else
         sngCommission = sngSales * .02
    End If
    

    Years employed > 4
    Or Sales > $300.000
    Or is Management
    

    ♦ Truth Table for Disjunctions
    1st Condition 2nd Condition 3rd Condition Statement
    A B C A or B or C
    true true true true
    true true false true
    true false true true
    true false false true
    false true true true
    false false true true
    false true false true
    False False false false

    Sat Feb 5 07:28:17 CST 2011 Untitled Document
    Not operator

    If  Not (Condition) then
            Statement
            Statement
    End if
    

      Example

    sngCommission   = 0
    If sngSales > 300000
        If Not blnManagement   then
    	sngCommission  = sngSales * .03
        End If
    End If
    

      When using the logical operator Not the conditional statements will only be executed if the condition is False.

      Using the Not operator is generally avoided. It is often more understandable to state the condition in the positive even if it means having an empty branch.
      sngCommission   = 0
      If sngSales > 300000
          If blnManagement
          Else
              sngCommission = sngSales * .03
      End If
      

    Sat Feb 5 07:28:17 CST 2011 Untitled Document
    Hierarchy of Logical Operators

      Like arithmetic expressions we must understand how expressions that contain more than one kind of operator are evaluated.

      How shall we evaluate the following?

    Given 
    intYearsEmployed  = 6
    sngSales = 300500
    sngPreviousSales = 250000
     
    If intYearsEmployed > 4 _
    	Or sngSales > 300000 _
    	And sngPreviousSales > 300000
    	     sngCommission = sngSales * .03
    Else
         sngCommission = sngSales * .02
    End If
    

    ♦ Order of precedence of logical operators is: NOT, AND, OR.

      That is, an AND operation will be performed before an OR operation if both operations are included in a condition, unless parentheses are used to override priority of logical operators.

      Expressions in parentheses are processed first.

      Thus the previous expression is equivalent to
      If intYearsEmployed > 4 _
          Or (sngSales > 300000 And sngPreviousSales > 300000) Then
      	sngCommission = sngSales * .03
      Else
          sngCommission = sngSales * .02
      End If
      

      We can change the meaning with parenthesis
      If (intYearsEmployed > 4 Or sngSales > 300000) _
      	And (sngPreviousSales > 300000) Then
      

    Sat Feb 5 07:28:17 CST 2011 Untitled Document
    Case Structure Pseudocode

      The Case structure can be used in place of a series of If ..ElseIf.. statements.

    ♦ By Elseif
    Input a Grade
    If the Grade = 100 then
    	Report "Perfect Score"
    ElseIf  the Grade > 89 then
    	Report "Grade = A"
    ElseIf  the Grade > 79 then
    	Report "Grade = B"
    ElseIf  the Grade > 69 then
    	Report "Grade = C"
    ElseIf  the Grade > 59 then
    	Report "Grade = D"
    Ese
    	Report "Grade = F"
    End if
    

    ♦ By Case Statements
    Input a Grade
    Case based on Grade
    Case 100
    	Report "Perfect Score"
    Case > 89
    	Report "Grade = A"
    Case > 79
    	Report "Grade = B"
    Case > 69
    	Report "Grade = C"
    Case > 59
    	Report "Grade = D"
    Default
    	Report "Grade = F"
    End Case
    

      Each condition is evaluated using the expression or value identified at the top of the structure in the order they appear. As soon as a condition evaluates to True the statements that follow it are executed and then control passes to the statements following the End Case.

      Note: You can replace an If...Then...ElseIF…. structure with a Select Case structure only if the If statement and each ElseIf statement evaluates the same expression.

    Sat Feb 5 07:28:17 CST 2011 Untitled Document
    Select Case Statement in Visual Basic

    ♦ Format of the Select Case
    Select Case testexpression
    [Case expressionlist1
    	statementblock]
    [Case expressionlist2
    	statementblock]
    [Case Else
    	statementblock]
    End Select
    

    ♦ The expression list can be
    a value Case 1
    a list of values Case "red", "yellow"
    a range of values Case 1 to 10
    a comparison Case Is > 5
    a combination Case 1, 4 to 5, is > 10

      The testexpression and expression list should be the same data type.

      Each testexpression is tested in the order they appear.

      As soon as an expression list satisfies the test expression the statements that follow are executed and control passes to the statements following the End select.

    ♦ If testexpression matches an expressionlist expression in more than one Case clause, only the statements following the first match are executed.

      The Case Else statement is optional. the testexpression the statement following the Case Else is executed.

    intGrade = Val(txtGrade.Text)
    Select Case intGrade
    Case 100            'equality Implied
    lblGrade.caption =  "Perfect Score"
    Case Is > 89        'The word Is is required with relational operators
    	lblGrade.caption = "Grade = A"
    Case 80 To 89       'specific range identified
    	lblGrade.caption = "Grade = B"
    Case Is > 69
    	lblGrade.caption = "Grade = C"
    Case Is > 59
    	lblGrade.caption = "Grade = D"
    Case Else
    	lblGrade.caption = "Grade = F"
    End Select
    
    Sat Feb 5 07:28:18 CST 2011 Untitled Document
    Counter & Accumulators

    ⊕ Counter

    ♦ In programming we often need to Count. To count we must

      1. Declare an integer variable to hold the "how many" value.

      2. Add 1 to the variable whenever what ever we want to count happens.

    ♦ To count how many times we click a button
    Dim intCount as integer
    Private sub cmdCount_click()
       intCount = intCount + 1
    End Sub
    Private sub cmdReportCount_click()
       Print intCount
    End Sub
    
    The pattern for the statement used to count is
    	A = A + 1    (where A is an integer variable)
    

    ⊕ Accumulation

      We also often have to Accumulate. That is - we have to add up a series of values. To accumulate we must
      1. Declare a variable to hold the Accumulated Value
      2. Repeatedly execute a statement that adds each desired value to the accumulator variable
      3 To add up values enter in a text box
      Dim sngTotal as Single
      Private sub cmdAddIt_click()
              Dim sngNumber as Single
              sngNumber = Val(txtNumber.Text)
      	sngTotal = sngTotal +  sngNumber
      End Sub
      --------------------------------------
      Private sub cmdReportCount_click()
      	Print sngTotal
      End Sub
      
      The pattern for the statement used to add up a series of values is
      A = A + B    
      
      and B contains the value you want to add up.)

      Sometimes we will need to build a string from several pieces. We can apply the accumulator pattern to building strings.
      Private sub cmdCount_click()
          intCount = intCount + 1
          lblCounting.Caption = lblCounting.Caption _
                                    & " " & intCount
      End Sub
      
      The pattern for the statement used to build a string over a series of steps is
      A = A & " " & B   
      

    Sat Feb 5 07:28:18 CST 2011 Untitled Document
    Scope

    ♦ Scope - Where variables are declared and how that affects their use.

      Whether variables are accessible or not - Their Scope depends on how and where they are declared.

      Within a Form Module, variables may be declared in
      Procedures
      Declarations section

    ⊕ Form Module

      A Form Module is a file that contains a form and all the code associated with that form.

    ⊕ Local Variable

      If declared within a procedure with a Dim statement the variable is local to that procedure. The variable is know only to that procedure and cannot be used by any other procedure.
      Private sub cmdPrintMess_Click()
         Dim intNumber as Integer
         intNumber = intNumber + 5
         Print intNumber
      End Sub
      

    ♦ What do you think will happen if you attempt to access a variable declared in a different procedure
    Private sub cmdPrintTheNumber_Click()
       Print intNumber
    End Sub             
    

    ⊕ Dynamic Variable

      All procedural variables (those defined within a procedure) are Dynamic unless otherwise specified. Dynamic means they removed from memory when the procedure ends and are reinitialized to the default or assigned value every time the event procedure is invoked.

    ⊕ Static Variable

    ♦ To make a variable retain its value from the previous time the procedure was called we could declare it as Static
    Private sub cmdprintmess_click()
       Static intNumber as integer
       intNumber = intNumber + 5
       Print intNumber
    End Sub
    

      A static variable is still local to the procedure in which it was declared that is it is know only to that procedure and cannot be used by any other procedure.

    ⊕ Form Level Variable

      If declared in the Declarations Section of the Form Module with a Dim statement the variable is called a Form Level variable and known to all procedures in the form module. It is local to the form.

    ♦ Form level variables are by default Static. They remain in memory throughout execution of the program.

      A variable can be declared in the declarations section of a form module but may not be assigned a value at that time.

      Only declarations are allowed in the Declarations Section.

      If you attempt to assign a value to a variable in the Declaration Section you will get a compile error when you run the program
      Option Explicit
      Dim intNumber As Integer
      intNumber = 5
      

      Although VB will assign values to variables automatically YOU, as the programmer, are responsible for the values stored in them.

      To initialize Form Level variables we can use the Form_Load() Event. The Form_Load() event is invoked every time the form is loaded.
      Private sub Form_Load()
        dblMaxLoanAmt = 1000000
        dblMaxInterestRate = .25
      End Sub 
      

      The concepts of local variables allows for the same name to be used for different variables (different areas of memory) within a project.

      If a form level variable has the same name as a procedure level variable the procedure level variable is used.

      It is generally advised to limit the scope of a variable to the smallest possible range.

      If a variable is needed only within one procedure it should be declared at procedural level.

      If a variable is needed only within one procedure but must retain pervious value declare it at procedural level with the Static statement

      If the value stored in the variable will be accessed by more than one procedure within the form module the variable should be declared at form level.

    Sat Feb 5 07:28:18 CST 2011 Untitled Document
    Division by Zero

      If your program attempts to evaluate an expression which contains a divisor = 0 your program will die with a fatal run time error

      If you want to know why your program cannot handle division by zero visit the following site.

    ♦ Because it is unacceptable for a program to die programmers must write their code so that division by zero never happens.
    If intDivisor <> 0 then
            sngAnswer = intDividend / intDivisor
    End If
    

      Note: Because division often results in numbers that are NOT whole number you should always store the result of a division in a floating point data type.

    Sat Feb 5 07:28:18 CST 2011 Untitled Document
    Pseudocode Iteration Control Structure

    ♦ Pseudocode to print all the numbers between 1 and 10
    Counter = 1
    Do as long as Counter is <= 10
        Print counter
        Counter = Counter + 1
    End loop
    

    ♦ Pseudocode to print the sum of numbers between 1 and 1,
    and then the sum of numbers between 1 and 2,
    and then 1 and 3, and so on.
    Counter = 1
    Total = 0
    Do until Counter > 10
           Total = Total + Counter
           Output "Sum of numbers between 1 and " & Counter & " = " & Total
           Counter = Counter + 1
    End Loop
    Output Total
    

      Note: Something must happen inside the loop so that the result of the condition changes. If the condition DOES NOT change you will be in an infinite loop.

    Sat Feb 5 07:28:19 CST 2011 Untitled Document
    Charting Multiple Statements Inside a Loop

    ♦ There are often many statements inside of a loop.

      When charting many statements in a loop it is difficult to place them all within the flow lines of the loop control test.

    ♦ To chart multiple lines of code within a loop we can use a Predefined procedure symbol
    Then detail the instruction inside the loop separately.

    Sat Feb 5 07:28:19 CST 2011 Untitled Document
    Iteration (Do Loop)

        Sequence and selection are control structures we have already used. Looping also called Iteration is another powerful control structure.

    ♦ Looping allows us to execute the same instruction(s) over and over using the same code.

    ⊕ Do and For

      Do and For loops provide use with several possible tools to use for looping.

    ♦ Do Loops

      The Do loop is used when you do not know how many times you will need to execute a block of code.

      It is used when you will execute the same block of code repeatedly until something changes to indicate you are done.

      The Do loop is controlled by a condition.

    ♦ There are several forms to the Do loop control structure.

      The difference between the forms of the Do loops is when the condition is tested and whether you will execute the conditional block of code as long as the condition is true OR as long as it is false.

    Do While condition        
    :                                             
            Statements to execute while condition is true                    
    :                                     
    Loop
    Next instruction
    
    Do
    :
    Statements to execute while condition is true                    
            :
    Loop While condition
    Next instruction
    
    Do until condition                           
    :                                                     
    Statements to execute until condition is true                     
    :                                                     
    Loop
    Next instruction
    
    Do
    :
    Statements to execute until condition is true
                    :      
    Loop until condition
    Next instruction
    

    ⊕ The position of the condition

      The position of the condition (at the top or at the bottom of the loop) determines the minimum number of times the statements inside the loop will be executed.

    While The instructions inside loop will be executed as long as the condition is True.
    Until The instructions inside loop will be executed as long as the condition is False.
    intCount = 0 intCount = 0
    Do While intCount <> 3 Do Until intCount = 3
    intCount = intCount + 1 intCount = intCount + 1
    Print intCount Print intCount
    Loop Loop

      In all cases after the loop has been satisfied execution continues with the next instruction after the Loop command.

    ⊕ Terminating a loop

      Something must happen inside the loop so that the result of the condition changes.

      You must be careful not to code impossible or unreasonable loops.

      The following code don't stop

      Dim intCount as integer
      intCount = 1
      Do until intCount = 100
         Print intCount
         intCount = intCount + 2
      Loop
      
      Do
         Print
      Loop
      

    ⊕ Use Ctrl/Break To stop an Endless Loop

      Do loops are suitable when you do not know the number of times to repeat an action (indeterminate loop).

    Sat Feb 5 07:28:19 CST 2011 Untitled Document
    Random Numbers

    ⊕ Rnd()

    ♦ There are times when we would need to generate random number, numbers that are in no particular order. We can use the Rnd() function.

      Rnd() will return a value less than 1 and >= to zero.

      To generate an integer value we can multiply the value returned by an appropriate number.

    ♦ To generate a random integer less than 100
        Dim intRandomNumber as integer
        intRandomNumber = rnd() * 100
    

    ⊕ Seed

      The Rnd() function uses a seed, or an initial value, to generate the random numbers.

      For any given initial seed, Rnd() will generate the same number sequence because each successive call to the Rnd() function uses the previous number as a seed for the next number in the sequence.

    ♦ Before calling Rnd, use the Randomize statement to initialize the random-number generator with a seed based on the system timer
    Dim intRandomNumber as integer
    Randomize
    intRandomNumber = rnd() * 100
    Visual Basic Input Box
    

    Sat Feb 5 07:28:19 CST 2011 Untitled Document
    InputBox

    ♦ The InputBox function can be used to accept keyboard input into a variable.
    variable = InputBox("a prompt", ["title"])
    
    to enter the desired information.

    return to the named variable. The variable must be of like type.

      The statement
      intNum = InputBox("Enter a number", "input box")
      
      Will display the following
      If the user chooses the Cancel button the function returns a null value.

    Sat Feb 5 07:28:20 CST 2011 Untitled Document
    Iteration Control Structure in Visual Basic

    ♦ Sequence and Selection are control structures we have already used.

    Looping also called Iteration is another powerful control structure. without the user reinitiating the action.

    with several possible tools to use for looping.

    ⊕ FOR.... NEXT loop

    ♦ The FOR.... NEXT loop is used when we need a counter controlled loop,

      Format

     For  loopVariable  = StartValue  To StopValue   Step  StepValue
         one or more VB instructions
     Next  loopVariable 
    

      Example (a simple For..next loop:)

    For  intx = 1   To 10  Step 1
        Print intx     
    Next    intx   
    Print "the end"
    

    ⊕ What is happening?

    1) The loop variable is initialized to the Start Value .
    2) The loop variable is compared to the stop value.

    When the loop variable becomes greater than the stop value the loop has been satisfied

    and control passes to the statement following the Next intX statement.

    3) If the loop variable is not greater than the stop value the instructions inside the loop are executed.
    4) At the end of the loop the loop variable is incremented by the step value.
    5) Control passes back to the top of the loop to compare the loop variable to the stop value again.

    There are several ways you can think about whether the statements inside the loop are going to be executed. The statements will be execute

      Until the loop variable becomes greater than the stop value

      Or as long as the condition intX > 10 is False

      Or While the loop control variable is less than or equal to the stop value

      Or as long as the condition intX <= 10 is True.

      The preceding code will produce the following

    ♦ The step value is optional.

    Explicitly stating the loop control variable in the Next statement is optional as well.
    For intNum = 1 To 10
    Print intNum
    Next
    Print "The End"
    

    ⊕ Negative Step Value

    ♦ It is possible to have a negative step value
    For intNum = 10 To 0 Step -1
             Print intNum
    Next intNum
    Print "The End"
    Print intNum
    
    When the Step Value is negative the loop is executed until the loop variable becomes less than the Stop Value. intNum after the loop is completed is -1.

    ♦ The Start Value and step value can be other values as well
    For intNum = 10 To 100 Step 10
          Print intNum
    Next intNum
    Print "The End"
    Print intNum
    

    ⊕ Watch out for Impossible Loop!!

      You must be careful when constructing For loops as with any kind of loop not to create impossible loops.

      What do you think will happen with the following loop?

          For intNum = 12 To 1 Step 2
              Print intNum
          Next intNum
      
      What do you think the result of the following loop will be?
              For intNum = 1 To 10 Step 0
                      Print intNum
              Next intNum
      

    ♦ IMPORTANT: Before you test this you should know that to stop a Visual Basic program that is in an endless loop you can use the Ctrl/Break key combination. The Break key is often found at the top right side of your keyboard and shares the key with Pause.

    ⊕ Don't set a Step Value to 0

      You would never consciously set a Step Value up as zero

    ♦ But ! Value as well as the Initial and Stop values can and often are variables.

    Value as in the following code. What is the result?
    intBegin = 1
    For intNum = intBegin To intStop Step 1
    	Print intNum
    Next intNum
    

    ⊕ Nested For Loop

      Because you can place any statements inside of a For..Next loop you can nest a For..Next loop inside of another For..Next loop. When a For..Next Loop is nested within another For..Next loop t he inner loop must be satisfied before the outer loop continues. What would be the result of the following?
      For intRow = 1 to 3 step 1
          For intCol = 1 to 3 step 1  
              print "*";
          Next intCol
          Print
      Next intRow
      Print "The End"
      
      advancing to the next line. Print by itself simply advances to the next line.

    ⊕ For loop can be done using Do loop

      For...Next loops are used when you know how many times you need to execute a block of instruction. Do loops can be also be used when you know the number of times to repeat an action. However if you use a Do loop instead of a For...Next loop when you know how many times you need to execute a block of code you are responsible for keeping track of how many times you have executed the conditional block of code.

    Sat Feb 5 07:28:20 CST 2011 Untitled Document
    Converting Flowchart/Pseudocode to VB Code
    If your Pseudocode is as follows Given the For...Next loop format
    Counter = 1
    Do as long as Counter is <= 10
       Print counter
       Counter = Counter + 1
    End loop
    
    For loopVar = IntValue to StopValue Step IncrValue
        one or more VB instructions
    Next  loopVar
    

    ♦ When writing a For..Next loop based on Pseudocode or flowchart logic you must keep in mind the three things the For..Next statement has built in
    1. The loop control variable is initialized
    2. The loop control variable is compared to the stop value
    3. The loop control variable is incremented by the step value

     

    Counter = 1
    Do as long as Counter is <= 10
    Print counter
    Counter = Counter + 1
    End loop
     
    For Counter = 1 to 10 step 1
    Print counter
    Next counter

    ⊕ Watch out!

      Therefore you must not have any code in the For...Next block of code to be executed that alters the value of the loop control variable.

    ♦ Also the loop control variable red must not be the same variable as the stop value variable

     

    Problematic Code Healthy Code
    For Counter = 1 To Counter
            Print Counter
    Next Counter
    
    For Counter = 1 To StopVariable
            Print Counter
    Next Counter
    
    Sat Feb 5 07:28:20 CST 2011 Untitled Document
    General Procedures

      There are several different kinds of procedures we can use in Visual Basic. Some of them are:
      Event procedures tell objects how to respond to events.
      General procedures General procedures are programmer defined.

    ♦ Event procedures

    Click event procedures. Event procedures can be initiated (made to execute) by actions of the user or by something that happens in the code.

    ♦ General procedures That is they are created by the programmer and initiated by the programmer. There are two kinds of general procedures

    Sub procedures
    Function procedures

    ⊕ Sub procedure Vs. Function procedure

      The difference between Sub procedures and Function procedures is that Function procedures return a value and Sub procedures do not.

        We have made use of several language supplied functions in the code we wrote so far - Val(), IsNumeric(), UCase(), LCase(). All of these functions returned something that we used in our code.

      All computer languages use procedures but they may call them something different. All of the following can be considered synonyms for procedure in some computer language.
      Function
      GoSub
      Method
      Module
      Paragraph
      Predefined Process
      Procedure
      Subroutine

      We will use the general term subroutine for the sake of the following discussion

    ⊕ Definition of Subrouting

    ♦ A subroutine is a group of related instructions that can be initiated by Calling the subroutine from anywhere in the program.

    ♦ Benefits for using subroutines.
    They make it easier to see "the big picture" by placing detail level instructions away from the skeleton (the main logic) of the program.
    Different programmers can be assigned the task of creating subroutines.
    Subroutines may be called from multiple places in a program or reused in other programs.

    ⊕ Guideline for Creating Subroutine

    When creating subroutines each subroutine should be charged with one basic task.
    You should be able to describe the purpose of the subroutine in the name of the subroutine.
    You, the programmer, supply the names for subroutines. give your procedures names that are descriptive.

        A good rule to follow is the verb-noun or verb-adjective-noun guideline.

    • CalculateGrossPay
    • DisplayAverage
    • DetermineMonthlyRent
    • PrintAmortizationSchedule
    • ClearLabels
    you should consider breaking the subroutine into smaller subroutines.

    ♦ In Visual Basic a general procedure can be declared
            Private Sub InitializeVariables()
                    :
                    :
            End sub
    
    and then called from anywhere in the module
            Call InitializeVariables
    
    The word "Call" is optional
            InitializeVariables
    

    ♦ When you Call a general procedure, control is passed to the top of the general procedure and when the procedure is completed control passes back to the statement following the Call statement.
    Private Sub Form_Load()
       Call InitializeVariables
       txtName.SetFocus      'this line will be executed after the 
    InitializeVariables procedure is completed
              :
              :
    

    ⊕ When to use subroutines or general procedures

    Subroutines are used to break complex sections of code into smaller more manageable pieces and to prevent very long procedures.
    Any time you find the need for 3 or more statements to be repeated in your program you should consider using a subroutine.

      You can add a general procedure to your module by simply typing in the procedure or you can use the menu by selecting
      		     Tools / Add Procedure
      

    The following dialog box will appear
    Enter the name for the new procedure and press OK. Type of procedure you wish to create.

    ♦ Property and Event procedures

      In addition to Sub and Function procedures there are also Property and Event procedures which we will not cover in this course.

    ⊕ Private

      For the Scope option I suggest you select the Private option button. This option determines whether or not the procedure may be called from outside of the module in which it is defined.

      A shell of a procedure will be created

      Private Sub InitializeVariables()
      End Sub
      
      You can now add code to the procedure.

    Sat Feb 5 07:28:21 CST 2011 Untitled Document
    Pseudocodeing and Flowcharting General Procedures

    ⊕ Pseudocode

    Main Procedure
       Get Purchase amount from user
       Get Membership status from user
       If purchase amount invalid
              Display error message
       Else
              If member
                       Call calculate member discount procedure
              Else
                       Call calculate nonmember discount procedure
              End if
       End if
    End Main Procedure
    
    Calculate Member Discount Procedure
              If Purchase <= 100
                       Discount = purchase * .1
              Else
                       Discount = (purchase * .1) + (purchase – 100 * .05)
              End if
              Display discount
    End Calculate Member Discount Procedure
    
    Calculate NonMember Discount Procedure
              If Purchase >= 100
                       Discount = (purchase * .1)
              Else
                       Discount = 0
              End if
              Display discount
    End Calculate NonMember Discount Procedure
    

    ⊕ Flowchart

      When flowcharting general procedure we use the predefined process symbol with the name of the procedure stated inside the symbol
      To chart the procedure we begin with a terminator symbol
      Sat Feb 5 07:28:21 CST 2011

      Untitled Document
      Flowchart using general procedures
      Sat Feb 5 07:28:21 CST 2011 Untitled Document
      Passing Arguments to Procedures

        Sometimes to avoid form level or global variables when using a user-defined procedure you will want to pass arguments to the procedure.

        To pass arguments to a procedure in Visual Basic you place them after the procedure name in the call statement. The argument may be enclosed in parenthesis.
                  :
        Call TotalSales (sngSaleAmount)   'will pass sngSalesAmount to 
        TotalSales           :
        
        The word "Call" is sometimes optional.
                  :
        TotalSales sngSaleAmount 
                  :
        
        And sometimes not. It is conditioned on whether and how you pass arguments to the called procedure. If you pass arguments enclosed in parenthesis you must use the Call statement.

        You may pass more than one arguments at a time.
        	   Call TotalSales (sngSaleAmount, dblTotalSales)
        

      ♦ When we pass something to a procedure we must provide an argument when the procedure is called and also provide a memory location in the called procedure to store the argument being passed.

        Calling statement

      	Call CalculateFICA   (sngGrossPay)
      

        Called procedure

              Private sub CalculateFICA (sngPay as single)
                       :
                       :
              End sub
      

      ♦ The data type must be the same in the calling statement as in the called procedure but the name does not have to be the same. If more than one argument is passed they must be listed in the called procedure in the same order as they were passed

        Calling statement

               Call TotalSales (sngSaleAmount, dblTotalSales)
      

        Called procedure

                Private sub TotalSales (sngSaleAmount as Single, dblTotalSales as 
      Double)
                         :
                End sub
      

      ⊕ Passing By Value or By Reference

        When passing arguments to a procedure you may pass ByVal (by value) or ByRef (by reference). To indicate which way to pass a value you include the keyword ByVal or ByRef before the argument.

      ♦ ByRef is the default.

                Private sub CalculateFICA (ByVal sngPay as single)
                         sngFICA = pay * .06875
                         :
                         :
                End Sub
      

      ♦ Pass By Value to the called procedure and placed in a new memory location. There will be two copies of the passed argument in memory.

    original argument can NOT be permanently changed by the called procedure.

    ♦ Pass By Referene called procedure. The variable declared in the called procedure contains a reference to (the memory address of) the argument in the calling procedure.

    of the original argument CAN be permanently changed by the called procedure. Sat Feb 5 07:28:21 CST 2011 Untitled Document
    Data Files & Data Hierarchy

      While information is being used by a computer it is stored in memory. Memory is temporary. Information often must be stored is such a way that it can be retrieved at a later time by the same or a different program.

    ♦ Information or Data is permanently stored by computers in files.

    ♦ There are several different kinds of files.
    Executables (.exe)
    System files (.dll, .sys, .ini, etc.)
    Documents (word files, PowerPoint, etc.)
    Source code files (.frm, .bas)
    Data Files (files that contain facts about people or things)
     

    At this time we are interested in Data files

      Information about people (students, employees, customers, clients, patients) and things (inventory items, vehicles, books, accounts, recipes, contracts, invoices, sales, video or music collections etc.) is stored in data files in the form of records.

    ⊕ File

    A file is a collection of related records. (Employees, videos, accounts, etc.)
    Each record is composed of fields and contains all the information about one object. (Employee, video, account)
    Each field contains one piece of information about the object (name, address, title, artist, etc.) and is composed of characters, each of which usually requires 1 byte of storage.

      For example, a personnel file might contain records that have three fields: a name field, an address field, and a phone number field.

    ⊕ CSV (Comma separated text file)

      One very simple kind of data file is called a comma delimited text file. In comma delimited files fields within records are separated by commas and quotation marks are placed around text fields. Comma delimited files are files that contain only ASCII characters and can be created and/or opened using utility programs such as NotePad.

      Comma delimited files useful for exporting to data between different applications and/or different platforms.

    ♦ Example of comma delimited text file.

    #2006-11-20#,"couch",112.25
    #2006-11-20#,"couch",12.25
    #2006-11-20#,"hoyne",125.5
    #2006-11-20#,"thompson",58.25
    #2006-11-21#,"Couch",15.25
    

    ⊕ Database

    ♦ A database is a collection of related files also called tables. For instance a bank may have a database that contains all the information about the various different kinds of accounts  

    Savings, Checking, Installment Loan, Safety Deposit Boxes, etc.

      We often need to write programs that will access information stored on storage devices as well save information to the storage device.

    Sat Feb 5 07:28:21 CST 2011

    Untitled Document
    Sequential Data Files
    Data is stored in files.
    Files are stored on disk (usually).
    Files are made up of records.
    Records are made up of fields.

    ⊕ Sequential Data File

    ♦ Sequential data files are files that are read or written in order from the first record until the last.

      Some files are random files.

          The records in random files may be accessed in any order or randomly.

    ♦ For a program to access data stored in a sequential disk file or save data to a sequential disk file it must
    Open the file
    Read or Write to the file
    Close the file when it is finished.

    ⊕ To open a sequential file using Visual Basic

    Open "path\filename" for mode as #filenum
    

      The filename can be a string constant or a string variable that contains the path and filename

      The mode identifies whether the file is to be
      • read (mode = input)
      • created (mode = output)
      • added to (mode = append).

    ♦ Example 1

    Open "a:\input.dat" for input as #1
    

    ♦ Example 2 the file specifier of the file to be opened.

    strFileName = "f:\myfile.txt"
    Open strFileName for input as #1
    

      If a file that is opened as input does not exist an error will occur.

      If a file that is opened as append does not exist it will be created.

      If a file that is opened as output already exists the original file will be overwritten.

    ♦ The #filenumber assigned to a file must be an integer.

      Anytime you need to use the file in the rest of the program you will use the filenumber.

    Sat Feb 5 07:28:22 CST 2011 Untitled Document
    Write to a Sequential Data Files

    ♦ To write to sequential disk file we use the Write statement
    Write #1, data1, data2, data3
    

      Example

    :
    Dim strName as string
    Dim strPhone as string
    strName = "George"
    strPhone = "356-8932"
    open "a:\input.dat" for output as #1
    write #1, strName, strPhone
    
    The data that is written could come from a control on a form.
    Write #1, txtName.text, txtPhone.text
    

    Sat Feb 5 07:28:22 CST 2011 Untitled Document
    Close a Sequential Data Files

    ♦ To close a file opened as #1
    Close #1
    
    Close
    

    ♦ When the Close statement is executed, the association of a file with its file number ends.

    Sat Feb 5 07:28:22 CST 2011 Untitled Document
    Read from a Sequential Data Files

    ♦ To read from a sequential disk file

    We use the input statement to read from a data file.

    We must provide a variable for every data element read.

    Those variables must of course be defined.

      Format:

    Input #1, var1, var2, var3
    

      Example

    :
    Dim strName as string
    Dim strPhone as string
    open "a:\input.dat" for input as #1
    Input #1, strName, strPhone
    

      To read subsequent records we must execute the Input statement again. We can put the Input in a loop.

      We will Input the data over and over until we run out.

      We can use the EOF (End Of File) function to determine when there is no more data to Input.

      The EOF function takes an integer argument that specifies which open file to test for end of file.

      This is the only time we refer to the file number (assigned to it when the file was opened) without using the pound (#) sign.

    Do While Not EOF(1)
    Input #1, strName, strPhone
    :
    loop
    
    Sat Feb 5 07:28:22 CST 2011 Untitled Document
    Date Function

      Date is not only a keyword that is used to declare a variable as a Date data type it is also a Function that returns a date type value which contains the current date.

      We have other functions that can tell us date and time information

    ⊕ Now

      Now is a function that returns a Date type value which contains the current date and current time. Remember the integer portion of a Date type variable represents a date and the decimal portion represents a time.

    ⊕ Time

      Time is a function a reserved word that that returns a Date type value which contains just the current time. (The date portion would be 0)

      To use any of these functions we just use the keyword.

      The statement

      Print Date
      
      e Will print the current date.

      Remember to store a Date in a variable we must declare the variable as a Date data type

            Dim dtmDateSale as Date
    

      To store a literal date in a date type variable we enclose the date in # signs
              dtmDate = #06/30/1950#
      

        Visual Basic is "smart" enough to handle different formats of date literals.

        You will notice when you look at the file you create the dates that you write to the file will be enclosed in # s  

        #2004-04-21#,"tim",50

    Sat Feb 5 07:28:23 CST 2011 Untitled Document
    Reports

      Printed reports are used when the output from a process is Viewed by people outside of the organization
      Used by management
      Used in presentations
      For control or audit purposes

      Reports can contain different kinds of information depending on the use of the report.
      Transaction information
      Time card information
      Information about a particular sale
      A grade to be posted
      A credit card payment
      Bank deposit
      Master Information
      Employee information including Year To Date information
      Savings account information. (Balance, YTD interest paid, Date last deposit)
      Summary Information
      Total payroll this pay period
      Average daily sales total
      Report organization

    ⊕ Tabular Report

      In the most common type of report, a tabular report - data from many records are displayed in rows and columns on a page.

      The records are typically in order by a key field or by date or time entered.

      This kind of report may include a grand total of some amount.

      Some tabular reports sort and/or group records according to some field, like Department or Employee Category.

      These reports may also include subtotals for each group of records printed.

      Some tabular reports only generate lines of information which summarize a larger group of records...example, printing the total sales amounts of each employee, rather than printing each individual sales record for each employee.

    ⊕ A typical tabular report may have the following parts

    Report Header The report header contains items which print only once, at the top (or beginning) of a report.
    Current Date The current date is often included in the report header.
    Page Footer The page header contains items which print only once, at the top of EACH page. Usually the items are column headings, which label what data is in each column on the report. The date and a page number can be included in the page header.
    Report Footer The report footer contains items which print only once, at the bottom of a report, like a grand total amount at the bottom of the last page.
    Page Footer The page footer contains items which print only once, at the bottom of each page. Usually the page footer contains a page number.
    Detail Lines Detail lines contain data from the records in a file...one line per record. The detail lines can be grouped under control break headers. A page break will occur when there are more records in the file than will fit on a page.

    ⊕ Control Break

      What is a "Control break"? Detail lines are often reported in order of a key field (salesperson number, department number, date) and when ever there is a change in the key field, summary information is generated. For instance, a file containing records that represent individual sales might be sorted by salesperson number. A report lists all the sales made by a salesperson and then displays a total for all sales. Such a report is said to break on salesperson number. This means that there is a break in the listing when the salesperson number changes.

    ♦ Control break headers each new group, such as Department Number, Employee Category, or Salesperson Number. A control header may appear several times on a page depending on how many records are in each group.

    ♦ Control break footers group, such as the total number of records in the group, or the total sales amount for a salesperson.

    Sat Feb 5 07:28:23 CST 2011 Untitled Document
    Method of Layout Design

    ♦ To crate the following report

      1) On a sheet of paper, write down what the report and column headings will be and determine the amount of space each heading will require and the maximum width of data to be displayed in each column

                          11
                       ABC Company
         4             4                    12
       Date           Name              Hours Worked
        10             20                    5
    Xx/xx/xxxx       x---x                  xx.xx
    

      2) decide the number of positions available. This will depend on the medium (screen, paper) and font size you are using. Note: this method works only for fixed or mono-spaced fonts. For this example I will use 80 positions. It is easy to make adjustments later.

      3) To center the heading, subtract the width of the heading from the positions available a divide by 2. (80 – 11)/ 2 = 34 (Number of spaces to print before heading) I will add the extra space on the right.

      4) add up the maximum width of each column
               10
            +  20
            +  12   (use 12 because the column heading is wider than the 
      data.) -----------------
               42
      

      5) subtract the number of used spaces (42) from the number available (80) to determine the amount of white space I have to spread before and between the columns
      
                      80 - 42 = 38 (white spaces)
      

      6) determine the number of blocks of white space I will use. White space on the left, between each column, and on the right = 4

      7) Divide the number of white spaces by the number of white space blocks to determine how wide each white space block will be.
              38 / 4 = 9 (Width of white space block) with 2 positions 
      left over which I will add to the right and left margin.
      

      8) Because I used the column heading for the third column to determine the width of the column and the data is smaller I will center the data under the heading. To center the data under the heading I subtract the width of the data from the width of the heading and divide by 2. (12 - 5) / 2 = 3 (Number of spaces before data to center under heading). I will place the remaining space on the right.
      (34 spaces)         11   (35 spaces)
                     ABC Company
                    4                            4                          12
                   Date                         Name                    Hours Worked
                   10                           20                          5
      (10 spc) Xx/xx/xxxx    (9 spc)          x---x  (9 + 3 spc)          xx.xx (4 
      + 10 spc)
      

      9) To center the column headings over the data I do the same thing I did to center the third columns data under the heading. I subtract the width of the heading from the width of the data and divide by 2.  

      For Date
                10  (the width of the data)
            -    4 (the width of the heading
            --------
                 6  / 2 = 3 (the number of spaces to print before the heading)
      
       

      For Name
                20  (the width of the data)
            -    4 (the width of the heading
            --------
                16  / 2 = 8  (the number of spaces to print before the heading)
      

       (34 spaces)         11   (35 spaces)
    		     ABC Company
                      4                       4                        12
    (10 + 3 spaces) Date(3 + 9 + 8 spaces)   Name   (8 + 9  spaces) Hours 
    Worked(10  spaces)
                    10                        20                        5
       (10 spc) Xx/xx/xxxx    (9 spc)       x---x  (9 + 3 spc)        xx.xx (3 + 1 + 10 spc)
    

      10) when you are done the numbers for each line should add up to 80

     

    Report Heading
              34
          +   11
          +   35 
    -----------------
              80
    
     

    Column Headings
              10
          +    3
          +    4
          +    3
          +    9
          +    8
          +    4
          +    8
          +    9
          +   12
          +   10
    ----------------
              80
    
     

    Detail line
              10
          +   10
          +    9
          +   20
          +    9
          +    3
          +    5
          +    3
          +    1
          +   10
    ------------------
             80
    

      When I code the print statement I take complete control of the spacing (I will not use any commas or semicolons)

                       (34 spaces)         11   (35 spaces)
                                       ABC Company
                      4                       4                        12
    (10 + 3 spaces) Date(3 + 9 + 8 spaces)   Name   (8 + 9  spaces) Hours 
    Worked(10  spaces)
                    10                        20                        5
       (10 spc) Xx/xx/xxxx    (9 spc)       x---x  (9 + 3 spc)        xx.xx (3 + 1 + 10 spc)
    

    ♦ For report heading

      Print space(34) & "ABC Company"

    ♦ For Column headings

      Print Space(13) & "Date" & Space(20) & "Name" & Space (17) & "Hours Worked"

    ♦ For Detail line

      Print space(10) & strFixedDate & space(9) & strName & Space(12) &

    strFixedHours

      Note: For this problem I don't really have to worry about how many spaces will be used in the right margin since the line will simply end with that last character printed.

    ♦ The whole premise of this procedure is that you know exactly how much space will be used for each column which means
    1) you must use a mono-spaced font 2) you must use fixed length string when printing the column data
    Discussed later or here -> Printing variable length fields in fixed length columns
    Once you have the general spacing it is just a matter of adding a space here and removing a space there to make it "pretty" Sat Feb 5 07:28:23 CST 2011 Untitled Document
    Printer Object

    ⊕ Printer Object

    ♦ To control the default printer we use the Printer object.

    ♦ The print method is used to send output to the printer.

    Printer.Print "My Phone List"
    

    ⊕ Positioning Output on the Printer

      There are several options to choose from when controlling the spacing of printed output. For our purposes the first two methods are the best choices.

    ♦ 1) You can control the position of the output by using the Space() function. The Space() function returns a string of spaces the length of the integer passed to it

    Both

    Printer.Print Space(25) &  "My Phone List" & vbCrLf _
                         Space(15) &  "Name" & Space(10) & "Phone"
    
    And
    Printer.Print Space(25) &  "My Phone List"
    Printer.Print  Space(15) &  "Name" & Space(10) & "Phone"
    
    Would produce the same output -
                        My Phone List
                   Name          Phone
    

    ♦ 2) You can control the position of the output using the CurrentX and CurrentY properties of the printer object. The CurrentX property setting is 0 at an object's left edge, and the CurrentY property setting is 0 at its top edge. Coordinates are expressed in twips or the current unit of measurement. A twip is a unit of measurement equal to 1/20 of a printer's point. There are approximately 1440 twips to a inch.

    For example
    Printer.CurrentY = 14400
    Printer.CurrentX = 6120
    Printer.Print Printer.Page   'to print current page # at the bottom of an 8 ? 
    by 11 page
    

    ♦ 3) Another way you can control the position of the output is by using semicolons and commas. position.

    Code Output produced
    strName = "Joe Smith"
    Printer.Print  "Name ";  strName   'Note – there is a space after the 'e’
     in the string constant
    
    Name Joe Smith
    

      When you use commas the next item to print will print in the next print zone. Print zones begin every 14 columns. The width of each column is an average of the width of all characters in the point size for the selected font.

    Code Output produced
    Printer.Print "Name",,"Phone Number"
    
    Name                        Phone Number
    

        I suggest using commas and/or semicolons to begin with just to get the information out to view. After successfully displaying the information you could then determine the correct spacing and change the statements to use the Space() function and concatenation.

    ⊕ Controlling Font and FontSize

      When attempting to design the layout of a report the font size and font t ype you choose will have a significant affect. Notice how the different fonts require different amounts of horizontal space even when the font size is the same in the following samples.

    This is a sample of Courier New
    This is a sample of Times New Roman
    This is a sample of Arial Narrow
    This is a sample of Arial

      You can control the font type and size by setting the Font and FontSize property of the printer object at run time.
              Printer.Font = "courier new"
              Printer.FontSize = 12
      
      Font and FontSize will remain in effect until changed in code or the program ends.

    ♦ When controlling the way a report is formatted based on columns and print positions you must use a monospaced font. A monospaced font uses the same amount of horizontal space for every letter and character. Courier New is a monospaced font.

      This is a sample of Courier New

    Wwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
    iiiiiiiiiiiiiiiiiiiiiiiiiiiiiii

        In a font that is not monospaced the letter i requires less space than the letter w.

      This is a sample of Times New Roman

    Wwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
    iiiiiiiiiiiiiiiiiiiiiiiiiiiiiii

    ⊕ Advancing to a New Page

    ♦ The NewPage method will advance to the top of the next page.
    If Printer.CurrentY > 12960 Then   'to check for current position on 
    page.     Printer.NewPage
       Call NewPage
    End If
    
    12960 will be about 9 inches from the top of the page.

      To release the print file to the printer you use the EndDoc method
                    Printer.EndDoc
      
      it will not print until the program ends.

    Sat Feb 5 07:28:24 CST 2011 Untitled Document
    Printing Variable Length Data

      When sending data to a fixed length output fields you must ensure that the length of the data is appropriate. For instance, if you design your report around a 20 character name field when you print the name it must use all 20 characters or the information that follows it will not be aligned properly. Also if you allow for a number to be up to 99,999.99 and reserve 9 print positions you must use all 9 positions. The following sample code illustrates what happens when you print variable length data.
      Do While Not EOF(1)
              Input #1, strName, sngAmount
              Print Space(10); strName; Space(5); FormatCurrency(sngAmount)
      Loop
      

      When you declare a variable length string with the following statement
       Dim strName as string.
      
      You may store any length of string in strName. If you assign "Max" to strName, strName will require 3 bytes of memory, if you assign "Maxwell" to strName, strName will require 7 bytes of memory.

      To ensure that the length of string data is always the same you can use a fixed length string.

      You declare a fixed length string by specifying the amount of memory required in the Dim statement.

       Dim strName as string * 20
      
      This strName variable reserve 20 bytes of memory regardless what is stored in it.
      Dim strName As String * 20
          :
          Do While Not EOF(1)
              Input #1, strName, sngAmount
              Print Space(10); strName; Space(5); FormatCurrency(sngAmount)
          Loop
      
       

      This is an improvement but there is more to do.

    ♦ If there were more fields to print following the dollar amounts we would have the same problem as before

      We can control the length of numeric output in a similar way as we did the string data. The data type of the formatted number printed is actually string because the Format functions return string data types. We can store the result of the Format in a fixed length string and then print the string.
      Dim strName As String * 15
      Dim strFormatedNumber As String * 9
                :
      Do While Not EOF(1)
         Input #1, strName, sngAmount, strDepartment
         strFormatedNumber = FormatCurrency(sngAmount)
         Print Space(10); strName; Space(5); strFormatedNumber; _
         Space(5); strDepartment
      Loop
      
       

      Notice the dollar amounts are left justified.

    ⊕ Right Justify a number

    ♦ Numbers should be right justified use RSet statement.

      The RSet statement Right aligns a string within a string.

    Rset strFormatedNumber = FormatCurrency(sngAmount)
    
    Sat Feb 5 07:28:24 CST 2011 Untitled Document
    Variable Arrays

      Each time we read or input data into a variable the previous value read or inputted is destroyed.

    ♦ A variable can only hold one value at a time.

      If we need to retain access to several previously inputted values we could read/input them into separate variables
      	Dim strName1 as string
      	Dim strName2 as string
      	Dim strName3 as string
      
    • To use each of these variables we would need unique code for each
      	strName1 = txtName.text
      	print  strName1
      	strName2 = txtName.text
      	print  strName2
      	strName3 = txtName.text                 
      	print  strName3
      
      This might work if we only had 3 names but what about 25 or 50?

      When we need to store several occurrences of the same type of data we use

    Variable Arrays
    

      A variable array is a group of variables of the same data type with the same name. You can use the same instructions to manipulate all the variables in the array by varying a subscript or index to the array.

      Whenever we refer to a variable array we must qualify it with a subscript or Index
      	Print strName(1)
      	Print strName(3)
      

      If we use constants for the subscript we are no better off than when we used different variable names.

      We usually use an integer variable for a subscript
                      Print strName(intSub)      
      
      The subscript can be any whole number. It can be in the form of a numeric constant, a variable (integer or long), or an expression that resolves to a whole number.

      The value of the subscript indicates which strName we want to access.

    ⊕ Declare an Array

      We must declare arrays before any reference can be made to it in code.

    ♦ To define a fixed length array
    	Dim variablename(n to n) as datatype
    
    Or
    	Dim variablename(n) as datatype
    

      For Example
      	Dim strPhoneNum(1 to 50) as string      
      	Dim strPhoneNum(0 to 49) as string
      	Dim strPhoneNum(49) as string      
      
      Each of the previous Dim statements reserves memory for 50 string variables called strPhoneNum.

      When you use the strPhoneNum(n to n) form of the declaration you are identifying the lowest and highest subscript value that will be used to access the array.

      The standard way to declare arrays is.
      	Dim strPhoneNum(49) as string      
      
      When working with computers we often start counting with zero.

    The first element in the preceding array is referred to as strPhoneNum(0)
    The second element is strPhoneNum(1)
    The fiftieth is strPhoneNum(49)
    The subscript indicates a displacement from the beginning of the arrays.

    ♦ IMPORTANT

      You are responsible for staying within the bounds of your array. If your subscript becomes too large, greater than the number of array entries or too small, less than 0 you will get an error message
      	Subscript out of range
      
      And your program dies.

    ♦ You must always keep track of your subscript.

    ⊕ There are four basic things we do with arrays

    1. Initialize or load values into an array from using constants, user input or from a file.
    2. Dump or printout the contents of the array.
    3. Lookup or search an array for a particular element.
    4. Change an array element

    ♦ To load values into an array from an InputBox

            Dim strNames(24) As String
            Dim intIndex As Integer
            intIndex = 0
            strNames(intIndex) = InputBox("enter a name, 'quit' to quit")
            Do While LCase(strNames(intIndex)) <> "quit"
                    intIndex = intIndex + 1
                    strNames(intIndex) = InputBox("enter a name, 'quit' to quit")
            Loop
            Print "names in array "; intIndex
    

    ♦ To dump the values stored in the previous code -

    intIndex = 0
    Do While LCase(strNames(intIndex)) <> "quit"
            Print strNames(intIndex)
            intIndex = intIndex + 1
    Loop
    
    Sat Feb 5 07:28:24 CST 2011 Untitled Document
    Searching an Array

    ♦ There are four basic things we do with arrays

    1. Initialize or load values into an array from using constants, user input or from a file. (Discussed on previous web page.)
    2. Dump or printout the contents of the array. (Discussed on previous web page.)
    3. Lookup or search an array for a particular element.
    4. Change an array element

      When writing code to lookup or search an array for a particular element you can use a loop to work your way through the array, beginning with the first element and then moving on to the second element, and then the third, etc.

    ♦ The loop will be satisfied
    when you find what you are looking for
    OR when you know that you will not find what you are looking for.

      If the array IS in order by the field you are looking for you know the value you are searching for does not exist in the array once you reach an array value > than the value you are looking for.

      If the array IS NOT in order by the field you are looking for you know the value you are searching for does not exist in the array once you reach either
      The end of the array
      The last value stored in the array (the array may be declared to hold up to 25 elements but only 15 elements have actually been loaded into the array.

      The following code scrap will search an unordered array for the value stored in strSearchString. It compares the search string to each element in the array until
      §       it finds a match OR
      §       it finds an empty string (which we will assume means there are no other entries in the array) OR
      §       it has looked at all 25 elements.
      Dim strNames(24) As String
      :
      :
          Do While strSearchString <> strNames(intindex) And strNames(intindex) <> “” And intindex < 24
              intindex = intindex + 1
          Loop
          If strSearchString = strNames(intindex) Then
              MsgBox strSearchString & " was found at location " & intindex
          Else
              MsgBox strSearchString & " not found."
          End If
      

    Sat Feb 5 07:28:24 CST 2011 Untitled Document
    VB Message Box Function

    ♦ A MsgBox can by used to communicate with the user. It can be used to
    Indicate invalid data entry
    Confirm an action
    Warn of possible consequence of the user action
    Keep the user informed

    ♦ The MsgBox can be used as a statement or a function

      The MsgBox function allows the user to indicate a preferred action by clicking a button.

      The format of the MsgBox function

      	intAnswer = MsgBox (message, [buttons], [title])
      

      The buttons argument is optional and when used indicates which of the seven different buttons than can be displayed in the message box will be used. (ok, cancel, abort, retry, ignore, yes, or no). OK alone is the default.

      It also tells what icon should be displayed. (None, red X, balloon ?, !, or balloon I )

      The buttons argument is the sum of the desired properties.

        For example if you want the yes and no buttons to show (4) and the ? in a balloon (32), the buttons argument = 36.

      The title argument is optional and if used will be displayed in the title bar of the message box.

    ♦ All message boxes are modal. That is, the user must respond to the box to continue.

    ♦ You may use built in Visual Basic constants for the buttons argument

      The buttons argument settings are:

    Constant Value Description
    vbOKOnly 0 Display OK button only.
    vbOKCancel 1 Display OK and Cancel buttons.
    vbAbortRetryIgnore 2 Display Abort, Retry, and Ignore buttons.
    vbYesNoCancel 3 Display Yes, No, and Cancel buttons.
    vbYesNo 4 Display Yes and No buttons.
    vbRetryCancel 5 Display Retry and Cancel buttons.
    vbCritical 16 Display Critical Message icon.
    vbQuestion 32 Display Warning Query icon.
    vbExclamation 48 Display Warning Message icon.
    vbInformation 64 Display Information Message icon.
    vbDefaultButton1 0 First button is default.
    vbDefaultButton2 256 Second button is default.
    vbDefaultButton3 512 Third button is default.
    vbDefaultButton4 768 Fourth button is default.
    vbApplicationModal 0 Application modal; the user must respond to the message box before continuing work in the current application.
    vbSystemModal 4096 System modal; all applications are suspended until the user responds to the message box.
    vbMsgBoxHelpButton 16384 Adds Help button to the message box
    VbMsgBoxSetForeground 65536 Specifies the message box window as the foreground window
    vbMsgBoxRight 524288 Text is right aligned
    vbMsgBoxRtlReading 1048576 Specifies text should appear as right-to-left reading on Hebrew and Arabic systems

    The first group of values (0–5) describes the number and type of buttons displayed in the dialog box;
    the second group (16, 32, 48, 64) describes the icon style;
    the third group (0, 256, 512) determines which button is the default;
    and the fourth group (0, 4096) determines the modality of the message box.
    When adding numbers to create a final value for the buttons argument, use only one number from each group.

      The MsgBox function returns a value to indicate which button the user clicked. If you use any button other than the OK button you must provide an integer variable to place the return value in.

      An Example:

      	Dim intAnswer as integer
      	intAnswer = msgbox(“Are you sure”, vbYesNo + vbQuestion)
      	If intAnswer = 7 then
      
      Return Values
      Constant Value
      vbOK 1
      vbCancel 2
      vbAbort 3
      vbRetry 4
      vbIgnore 5
      vbYes 6
      vbNo 7
      If intAnswer = vbNo then

    Sat Feb 5 07:28:25 CST 2011 Untitled Document
    Programmer Defined Functions

      A function is a procedure which returns a single value. We have used many built-in functions
      lblAmount.Caption = FormatCurrency(sngAmount,0)
      sngAmount = Val(txtAmount.text)
      if IsNumeric(txtAmount.text)
      
      We (programmers) can write our own Programmer Defined functions.

      In Visual Basic the header for a function looks like
      Public Function FunctionName([arguments]) [As type]
      :
      :
                FunctionName = (some value)
      End Function
      
      For example
      Public Function Square(ByVal intNum as Integer) as long ‘ return data type
           ‘To return a value you make the name of the function = the return value    Square = intNum ^ 2         
      End Function
      
      The statement that calls the preceding function might look like
         lngAnswer = Square(intNum)
      

    Sat Feb 5 07:28:25 CST 2011 Untitled Document
    Control Break Logic

      Detail lines contain data from the records in a file...one line per record. The detail lines can be grouped by a key field and summary information about the group may be printed when ever a Control Break occurs.

      What is a “Control break” ? When detail lines are reported grouped in order by a key field (salesperson number, department number, date) and there is a change in the key field a control break occurs. For instance, a file containing records that represent individual sales might be sorted by date. A report lists all the sales made on a particular date and then displays a total for all sales on that date. Such a report is said to break on transaction date. This means that there is a “break” in the listing when the date changes.

    ⊕ To handle control break logic you must do the following

    ♦ Establish a working variable to store the value of the key field for the current group.

    ♦ After inputting each record compare the record’s key field value to the stored key field value to see if a “break” has occurred.

      If a “break” has occurred
      Report summary information for the group just completed. If the key field value is to be used in the summary information you must use the value stored in the working variable.
      	Total for   7/23/2003       320.99
      
      You might add any intermediate accumulators or counters to grand totals.
      Reinitialize any accumulators or counters associated with the group
      Save new key field value in the working variable

    ⊕ More things to consider.

    ♦ You must store the value stored in the key field of the first record in the working variable to prevent a break from happening at the beginning of the report. You could use a Boolean variable to indicate it is the first record
    	If blnFirstRecord = True then
    		Save key field value in working variable
    		Turn Boolean variable off
    	End if
    
    Note: remember that the default value for a Boolean variable in Visual Basic is False

    ♦ A“control break” happens at EOF because there are no more records for the last group. Since you will be reporting summary information in two places (when the key value changes and at EOF) you might consider putting the instructions that handle the control break in a general procedure and calling if from those two places.

    Sat Feb 5 07:28:25 CST 2011