Title: Chapter One An Introduction to Programming and Visual Basic
1Chapter OneAn Introduction to Programming and
Visual Basic
2What is Visual BASIC
- Visual
- Using GUI (Graphic User Interface) Technologies
- Window Objects Controls (Forms, Buttons,
- BASIC
- Programming Language (Beginners All-purpose
Symbolic Instruction Code) - Different versions of BASIC
- MBASIC - Microsoft BASIC
- BASICA - BASIC Advanced
- Quick BASIC, QBASIC
3Six Basic Computer Operations
- Input data
- Store data
- Process data
- Compare values and select among alternatives
- Repeat a group of actions
- Output the results
4Types of Computer Languages
- Procedural Programs that run from start to
finish with no intervention from user other than
input - Basic, QBasic, QuickBasic
- COBOL
- FORTRAN
- C
- Object Oriented /Event Driven (OO/ED) Programs
that use objects which respond to events use
small segments of code for each object - Visual Basic
- Visual C
5Levels of Computer Languages
- Low Level at the level of the computer, i.e., in
binary (0-1) format (machine code) - Computer can only execute the binary form of a
program - Intermediate level close to the computer but
uses abbreviated English words e.g., Assembler,
that is converted directly into binary - High Level at the level of the programmer using
English like words and clearly defined syntax
e.g., Visual Basic must be converted or
translated into binary for computer to implement
it, - Need a software program to handle the conversion
of high-level into binary
6Translating from High-level Language to Binary
- Interpreted each statement translated as it is
executed--slow but easy to use (instant results,
easy to debug) - Compiled entire program is converted to
binary--executes faster, but more difficult to
use (.exe files are compiled programs) - VB is interpreted during creation and debug/test
but can then be compiled into an .exe file
7(No Transcript)
8Three Basic Control Structures in a Program
- Sequence control structure
- Decision control structure (Conditions)
- Repetition control structure (Loops)
9Basic Concepts of Windows Programming
- Windows The primary container of programming.
- Events Operation activities (mouse click,
keyboard press,...). - Message Information about the event.
- Objects Identifiable entities (forms, controls,
data objects,) - Properties The attributes associated with an
object (name, caption, size, position, ) - Methods A set of predefined activities that the
object can carry out
10Object Oriented Programming
- Procedural Programming Making the entire
program, from the interface appearance to the
process codes May be divided into the modules. - OOP Only make small pieces of codes into
individual event snippets of objects. Not need to
code for the interface itself.
11OOP Programming Process
- A six step process for writing an OOP computer
program - 1. Define problem.
- 2. Create interface
- 3. Develop logic for action objects
- 4. Write and test code for action objects
- 5. Test overall project
- 6. Document project in writing
12IPO Table for Calculate Button
13Using Pseudocode
- An important part of the developing the logic for
action objects is generating corresponding
pseudocode. - Pseudocode involves actually writing a program
in English rather than in a computer language. - When the actual computer program is written, the
pseudocode is translated into computer language. - A pseudocode program is useful for two reasons
- The programmer may use it to structure the
algorithm's logic in writing. - It provides a relatively direct link between the
algorithm and the computer program
14Pseudocode for Calculate Button
- Begin procedure
- Input Video Price
- Taxes 0.07 x Video Price
- Amount Due Video Price Taxes
- Output Taxes and Amount Due
- End procedure
15Step Six Documentation
- Three levels of documentation
- Comments in the code
- On-line Help
- Users Guide and Programmer Document
16Chapter Two Creating a First Project in Visual
Basic
17Getting Started with Visual Basic
- Double-click VB icon on Desktop or use
StartProgramsVisual Basic to bring up opening
dialog box
18Basic Components of VB
- Project (.vbp)
- Forms (.frm)
- Controls
- Event procedures
- Modules (.bas)
- procedures
- Additional components
- Data Environment Designer - DED (.dsr)
- Data Report Designer - DRD (.dsr)
19VB Development Environment
Form Size
Toolbar
Project Explorer
Initial Form Window
Toolbox
Properties Window
Project Window
Form Layout Window
Sizing Handles
20The Toolbox
Label Control
Textbox control
Used to select a control to place on form.
21Project Explorer Window
View code
View Object
Change Folders
Used to select the code or object or to change
folders.
22The Properties Window
Window Name
Object Box
Properties List Tabs
Scrollable list of properties
Description Pane
Used to change the properties of controls at
design time.
23Important Properties
- Name identifies the object (the text seen by VB)
- Should start with three letter prefix (see
recommendation) - lbl for label
- txt for text box
- frm for form
- Can include letters, numbers, and underscore
- Caption The text (of the object) you see on
screen
24Adding a Control (Special Object)
- Double-click to add control to center of form
- Can be moved around from there
- Use sizing handles to change size
- Single Click and draw on form
- Select an exist one and use Copy/Paste methods.
25Controls to Add to Form
- Label control provides description of other
controls - Image control holds a graphic image
- Stretch property should be set to True
- Picture property is set to graphic file
- Command button control can be clicked to provide
action - Caption property
26Adding Code to Project
- Code is organized in Code Window as EVENT
PROCEDURE - Event procedure begins with Private Sub and
ends with End Sub - Example Use Msgbox command to display dialog box
with message - Msgbox Welcome to Vintage Videos
27Design Time and Run Time
- The project is in Design Time when you are
designing the project and adding code. - The project is in Run Time when you run the
project by clicking the VCR Run icon or Menu Run
Start. - You can stop the project and exit Run time by
clicking the VCR Stop Icon or Menu Run End. The
project returns to Design Time. - You can go to Break Mode by clicking the VCR
Pause Icon or Menu Run Break.
28Difference between End and Break Mode
- When the project is ended, all the internal
results are lost. It can only be started from
beginning. - When project is break, all the internal results
are kept in memory. You can check these results
to see whether your program is in right
direction. It can be re-started just from the
break point.
29The Toolbar and Menu System
- The VB menu system provides access to all
commands. - The Toolbar uses icons for more commonly used
menu commands (benefit? One click through!).
30Files in Visual Basic
- All projects in VB have a .vbp (project) file and
at least one .frm (form file) file. - Always save .frm files first and then save
project files. Use FileSave or FileSave as
commands for this purpose or click Disk icon on
Toolbar. - Projects with graphics also have .frx (binary
form) files. They are saved automatically. - Module files have a .bas extension and are pure
code files.
31Visual Basic Help
- There are three types of Help
- Help menu option
- context-sensitive help
- and Auto Help (IntelliSense)
- In VB 6, Help uses the familiar Internet Explorer
browser interface for the first two types of
help. - You can seek help by selecting Contents, Index,
or Search from the Help menu item - Pay attention to the selected Active Subset
32Context-Sensitive and Auto Help
- With context-sensitive help, pressing the F1 key
provides help on whatever item the cursor is
located. - With Auto Help, VB tries to help you with a code
statement by providing - A list of items to complete the statement
- Info on the statement you have started
- Tips on the type of data you are working with
33Chapter 3Variables, Assignment Statements, and
Arithmetic
34Variables
- Variables are named locations in memory (memory
cells) in which we store data that will change at
run time - Variable names in VB
- Must begin with letter
- cant include period
- cant be over 255 characters
- are not case-sensitive
- Example variable names
- VideoPrice for Video Rental Price
- Taxes for taxes on this price
- AmountDue for sum of price and taxes
- YTDEarnings for year to date earnings
- EmpLastName for employees last name
35Name Convention
- Use capital letters to distinguish parts in a
name. - LastName, StudentID, StreetNum
- Use standard prefix for certain type object
- txt Text box, txtName
- but( or cmd) Command button, butOK
- lst List box, lstPrices
- frm Form, frmInput
- str String variable, strName
- (see the recommendation list)
36Data Types I
- Two primary types of data numeric and string
- Numeric data
- 3.154 2300 -34 .0000354 0.97E-5
- are all numeric constants
- String data must use or as the delimiters
- Dogs 123-45-6789 Dr. Brown
- are all string constants
- Numeric data types can be subdivided into
specific types - currency 55,567.78 integer 255
- single 567.78 long (integer) 35,455
- double 567.78129086 Boolean True or False
37Data Types II
- Numeric data types can be subdivided into
following specific types
38Variant Type
- A special data type in VB that can be used to
store (reference) any previous data type and even
image data.
39Declaring Variables
- Declare ALL variables with the Dim statement
- Syntax
- Dim Variable1 as type1, variable2 as type2
- For example,
- Dim MyName as string, MyValue as single
- Dim Taxes as Currency, Price as Currency
- Dim AmountDue as Currency
- Dim mVar
- Dim mVar, AmountDue as Currency
- Two or more variables can be declared with same
Dim statement but you must include the variable
type - Use variables rather than objects in processing
since all text boxes are strings
40The Option Explicit Statement
- Begin ALL Forms with the Option Explicit
command in the declarations procedure of the
general object. This forces all variables to be
declared - To automatically include Option Explicit, go to
the ToolsOptionsEditor menu selection and check
the box for Require variable declaration - If you fail to declare a variable after the
Option Explicit statement has been entered, an
error occurs at Run time
41Variable vs Constant
- Variable is a memory unit with a named ID
- Constant is a prefixed value in program codes.
- Variable can be changed in run time. Constant
never changes. - Variable is referenced quicker than constant.
Because constant needs to to translated/extracted
from codes. - To improve performance, use variable instead of
constant if that constant is used frequently in a
program.
42Assignment Statements
- Must convert strings in text boxes to numeric
with Val function, eg, - Price val(txtPrice)
- Convert numeric variables to strings before
assigning to text box, e.g., - txtAmountDue str(AmountDue)
- Carry out calculations with assignment
statements, eg, - Taxes 0.07Price
- AmountDue Price Taxes
43Using Functions
- Sometimes we want to convert a string to a number
or vice versa or to compute a single value - To do this, we use a function that is nothing
more than an operation that takes a multiple
arguments and generates a single value - variable functionName(arg1, arg2, )
- Example functions for converting data
- Val to convert a string to a number
- Str to convert a number to a string
- Ccur to convert a string to a currency data type
44Using Assignment Statements for Calculations
- Sometimes, an expression will be on right of
assignment statement - An expression is a combination of one or more
variables and/or constants with operators - Operators are symbols used for carrying out
processing
45Arithmetic Operators
- () for grouping for addition
- for exponentiation - for subtraction
- - for negation
- for multiplication
- / for division
- \ for integer division
- mod for modulus
46Hierarchy of Operations
- Operations within parentheses ( )
- Exponentiation ()
- Negation (-)'
- Multiplication and division (,/)
- Integer division (\)
- Modulo arithmetic (Mod)
- Addition and subtraction (,-)
- String concatenation ()
47Arithmetic Example
- 3 (Salary - Taxes)2 Bonus/Months
- 3 1 2 5
4 (order) - Order
- 1 Subtract Taxes from Salary
- 2 Square the result
- 3 Multiply this result by 3
- 4 Divide Bonus by Months
- 5 Subtract result from first expression
48Symbolic Constants
- We can assign a name to a constant with the Const
statement - const constant name as variable type value
- Example
- Const IntRate as single 0.07
49Comments
- To explain the purpose of a statement, a comment
statement is added - Any statement beginning with an apostrophe or REM
is a comment - Comments can be added to end of statements using
apostrophe
50Formatting Data
- To display information in a well designed form,
we can use the Format function - variable Format(variable, format expression)
- Where the format expressions are in quotes and
include - Currency
- Fixed
- Standard
- Percent
- Scientific
- Example
- txtTaxes.text Format(Taxes, currency)
51Print Form, Clearing Entries and Setting Focus
- To print the form, use the PrintForm command
- To clear a text box, set it equal to the null
string - To set the focus to a text box, use the Setfocus
method - For example,
- txtCustName.SetFocus sets focus to this textbox
52Using Other Arithmetic Functions
- Other useful functions include
- Abs for absolute value Sqr for square root
- FV for future value PV for present value
- IRR for internal rate of return Pmt for payment
- Ucase/Lcase to convert to upper/lower case
- Len for length of a string
- Date for the system date
- DateValue for the date corresponding to string
argument - We will use Pmt to compute the monthly payment
- MonPay Pmt(rate, Nper,-LoanAmt)
- ?Pmt(.08/12,60,-10000) (The result is 256.03 )
53Creating a Monthly Payment Calculator
- Assume you wanted to determine the monthly
payment necessary to pay off a loan at a given
interest rate in some number of months - Use PMT function
- PMT(rate, nper, pv) where
- rate monthly interest rate
- nper number of months
- pv negative value of loan amount
54The Monthly Payment Form
55Compute Button Click event
Dim Amount as currency, Months as integer, Rate
as single Dim Payment as currency Amount
Ccur(txtAmount) Months Cint(txtMonths) Rate
Csng(txtRate) Payment Pmt(Rate, Months,
-Amount) txtPayment Format(Payment,
Currency) txtAmount Format(Amount,
Currency) txtRate Format(Rate, Percent)
56Visual Basic Errors
- Syntax errors (Design Time) caused by incorrect
grammar, vocabulary, or spelling . Also caused by
using a keyword. Usually caught as you enter the
statement. These are pointed out by VB and are
usually easy to find and correct. - Run time errors errors not caught at entry but
which involve an incorrect statement or bad data,
e.g, dividing by zero. The presence of an error
is detected by VB when you run the program, but
you still have to find the source of the error.
More difficult to correct than syntax errors. - Logic errors those that are VB does not catch as
being wrong, but which involve erroneous
logic, say, only having a program include 11
months of data instead of 12. These are the
hardest to find! - Debugging is the art and science of finding
errors. VB has debugging tools to be discussed
later.
57Chapter 4 The Selection Process in Visual Basic
58The Selection Process
- One of the key operations of a computer is to
select between two or more alternatives to make a
decision - Every decision involves a comparison between a
variable and a constant, variable, or expression
using comparison operators and logical operators - Decisions can involve two-alternatives or
multiple alternatives
59The If-Then-Else-End If Decision Structure
- For two alternative decisions, the
If-Then-Else-End If decision structure should be
used - In pseudocode, this is
- If condition is true then
- implement true alternative
- Else
- implement false alternative
- End Decision
60Multiple Alternatives
- For multiple alternatives, the general form in
pseudocode is - Select one
- Condition 1 is true implement alternative 1
- Condition 2 is true implement alternative 2
- Condition 3 is true implement alternative 3
- End Selection.
61The Two Alternative Decision Structure
- The If-Then-Else statement is
- If condition is true Then
- statements for true alternative
- Else
- statements for false alternative
- End if
- The If-Then condition
- expression1 ComparisonOperator expression2
- where comparison operator is one of these six
operators - Equal to Less then lt
- Greater than gt Less than or equal to lt
- Greater than or equal to gt Not equal to ltgt
62The If-Then-Else Decision Structure (cont.)
63Example of If-Then-Else Decision to Compute
Payroll
sngPayrate Csng(txtPayRate.text) intHours
Cint(txtHours.text) If intHours gt 40 then
sngPay sngPayRate 40 1.5 sngPayRate
(intHours - 40) Else sngPay intHours
sngPayRate Endif txtPay.text Format(sngPay,curr
ency)
64One-Alternative Decision
- If there is only a true alternative, then this is
a special case of the two-alternative decision
structure - If condition is true Then
- true alternative is implemented
- End If
- One-alternative decision can be combined with
InputBox used to validate user input, e.g., to
test that Customer Name textbox has something in
it - If TxtCustName.Text then
- txtCustName.Text InputBox(Enter Name and try
again) - Exit Sub
- End if
- Where the Exit Sub statement exits the event
procedure
65If-Then-ElseIf Decision Structure
- One way to implement a multiple alter-native
decision structure is through the If-Then-ElseIf
decision structure - If condition1 true then
- first set of statements
- ElseIf condition2 true then
- second set of statements
- ElseIf condition3 true then
- third set of statements
- Else
- last set of statements
- End if
66If-Then-ElseIf Decision StructureAssume
condition3 is True
67Example of If-Then-ElseIf for Letter Grade
Determination
- Dim intAverage as Integer, strLetterGrade as
string - intAverage Cint(txtAverage.text)
- If intAverage gt 90 then
- strLetterGrade A
- ElseIf intAverage gt 80 then
- strLetterGrade B
- ElseIf intAverage gt 70 then
- strLetterGrade C
- ElseIf intAverage gt 60 then
- strLetterGrade D
- Else
- strLetterGrade F
- End if.
- txtLetter.Text strLetterGrade
68Using the Select Case Decision Structure for
Multiple Alternatives
- General form
- Select Case expression
- Case Condition1 is true
- First set of statements
- Case Condition2 is true
- Second set of statements
- Case Condition3 is true
- Third set of statements
- Case Else
- Last set of statements
- End Select
69Case Conditions
- Conditions for Case statement can be in 3 forms
- Test Condition Example
- Exact Value Case 91, 92, 93
- Range of values Case 90 to 100
- Comparison condition Case Is gt 89
70Example of Select Case to Determine LetterGrade
Dim intAverage as Integer, strLetterGrade as
String intAverage CInt(txtAverage.text) Select
Case intAverage Case Is gt 90 strLetterGrade
A Case Is gt 80 strLetterGrade B
Case Is gt 70 strLetterGrade C Case Is gt
60 strLetterGrade D Case
Else strLetterGrade F End Select
71Using the List Box and Combo Box
- The List box enables the user to select from a
list of items. - lst is prefix for name and the List property of
the list box can be set at design time or run
time. - The Text property of the list box is equal to the
selected item. - We can test the Text property to determine which
item was selected.
72Important Properties and Methods of ListBox
ComboBox
- Property
- List()
- ListCount
- ListIndex
- Method
- AddItem
- RemoveItem
- Clear
- Examples of using ListBox Add/Remove Items, Show
List(),ListCount,ListIndex
73More Complex Decisions
- Decisions within decisions are know as nested
decisions - Interior decision must be an alternative of outer
decision - Decisions that combine two or more test
conditions using logical operators are known as
compound decisions - And, Or, Not, and Xor are logical operators
(Hierarchy Not - And - Or, Xor) - Both conditions must be able to stand alone
74Example of Nested Decisions
- Need to check if employee is hourly paid before
checking for overtime - if PayType Hourly then Hourly, Can make
overtime - If hours gt 40 then
- Pay 40 PayRate 1.5 (Hours-40) PayRate
- Else
- Pay Hours PayRate
- End if
- Else Salaried employee cannot be paid overtime
- Pay 40 PayRate
- End if
75Example of Compound Decisions
- Using compound condition to test for average AND
number of absences - If Average gt 90 AND Absences lt 3 then
- LetterGrade A
- ElseIf Averager gt 80 AND Absences lt 5 then
- LetterGrade B
- etc.
- In this case, if a student has an average of 93
and 4 absences, he/she will receive a grade of
B because he/she has more than 3 absences. -
76Example of Using List Box
- Dim VideoType as String, Price as Currency
- VideoType lstTypes.Text lstTypes is list box
- Select Case VideoType
- Case Kids
- Price 0.99
- Case Regular
- Price 1.99
- Case Classic
- Price 2.99
- End Select
- txtVideoType.text Format(Price,currency)
- End Sub
77Using the Form_Load Event
- The Form_Load event occurs when the project is
started and the form is loaded. - Code from a command button can be cut (or copied)
and then pasted into the form_load event
78Using the Debug ToolBar
- To view the Debug Toolbar, Select ViewToolbars
and click the Debug checkbox - The Debug Toolbar
Run Stop Step Into Step Out
Immediate Window Quick Watch
Break Toggle Step Over
Locals Watch Window Call Stack
Breakpoint
Window
79Debugging With the Immediate Window
- By clicking the Immediate Window icon on the
debug toolbar, you can then print the current
value of a textbox or variable - Use the Print variable or textbox command to
display its current value - This can enable you to find errors in the code
80Chapter 5 The Repetition Process in Visual Basic
81The Repetition Process
- The capability to repeat one or more statements
as many times as necessary is what really sets a
computer apart from other devices - All loops have two parts
- the body of the loops (the statements being
repeated) - a termination condition that terminates the loop
- Failure to have a valid termination condition can
lead to an endless loop
82Types of Loops
- There are three types of loops
- event-driven
- determinate
- indeterminate
- Event-driven loops are repeated by the user
causing an event to occur - Determinate loops repeat a known number of times
- Indeterminate loops repeat an unknown number of
times - Variables should be initialized before being used
in a loop
83Event-Driven Loops
- Event-driven loops are repeated by user causing
an event to occur--clicking a button - Variable scope is important for loops Variables
in event procedures are local and are reset to
zero when procedure terminates - Variables defined at form level are known to all
procedures and retain their value between events - Form-level variables are declared in the
Declarations procedure of the General object - Static variables retain their value between
events but are local to event procedure - Declared with Static keyword
84Form-level Variables
85Use of AddItem and Clear Methods
- The AddItem method is used to add items to a list
box at run time - Form of AddItem method
- list1.Additem string
- Always add a string to list box since it contains
text - The Clear method clears a list box
- list1.Clear
86Code to Sum a Series of Numbers
- Private Sub cmdCalc_Click()
- Dim TheValue As Integer
- TheValue CInt(txtTheValue.text)
- Sum Sum TheValue Sum declared at form
level - NumValues NumValues 1 NumValues declared
as form level - txtSum.Text Str(Sum)
- txtNumValues.text Str(NumValues)
- lstEntries.AddItem str(TheValue)Add value to
list box - txtTheValue.text "
- txtTheValue.SetFocus Set focus back to
txtTheValue - End Sub
87Determinate Loops Using For-next Loop
- Best way to create a determinate loop is to use a
For-Next Loop - Form of For-Next Loop
- For variable start value to end value Step
change value - statements that compose body of loop
- Next variable
- where variable the counter variable in the
loop - start value the beginning value of the
counter variable - end value the ending value of the counter
variable - change value the amount the counter
variable changes each time through the loop - Next variable the end of the For loop
88Example of For-Next Loop
89Code To Sum using For-Next Loop
- Private Sub cmdCalc_Click()
- Dim TheValue as Integer, Sum as Integer
- Dim NumValues as Integer, Counter as Integer
- Sum 0 Initialize Sum to Zero
- If txtNumValues.Text "" then Number not
entered - Msgbox "Please enter number of values to be
summed" - Exit Sub Do not go into loop
- End if
- NumValues CInt(txtNumValues.Text)
- For Counter 1 to NumValues
- TheValue CInt(InputBox("Enter next value"))
- Sum Sum TheValue
- lstEntries.AddItem Str(TheValue) Add value to
list - Next
- txtSum.Text Str(Sum)
- lstEntries.AddItem "Sum is " str(Sum)
- End sub
90Printing a List
- To print the contents of listbox, use the
Listcount and List() properties of the list box - Listcount is the number of items in list box but
list() property runs from 0 to Listcount -1 - List(Counter) is equal to the contents of the
corresponding list box - Code to print contents of list box to Immediate
Window - For Counter 0 to lstEntries.ListCount - 1
Debug.Print lstEntries.List(Counter) - Next
91Indeterminate Loops
- Indeterminate loops run for an unknown number of
repetitions until a condition is true or while a
condition is true - Four types of indeterminate loops
- Until loop with termination condition before body
of loop - While loop with termination condition before body
of loop - Until loop with termination condition after body
of loop - While loop with termination condition after body
of loop - Pre-Test loops have termination condition before
loop body - Post-test loops have termination condition after
loop body
92Form of Pre- and Post-Test Loops
- The form of the pre-test loops is
- Do Until (or While) condition
- body of loop
- Loop
- The form of the post-test loops is
- Do
- body of loop
- Loop Until (or While) condition
93Pre and Post-Test Loops
94Processing an Unknown Number of Values from a
File
- A data file is a collection of data stored on
magnetic or optical secondary storage in the form
of records. - A record is a collection of one or more data
items that are treated as a unit. - Files are identified by the computers operating
system with filenames assigned by the user. - Files are important to processing data into
information because they provide a permanent
method of storing large amounts of data that can
be input whenever needed for processing into
information - Three types of files sequential access, database,
and direct access files - We will use sequential access files as input.
95Using Sequential Access Files
- Sequential access files must be read in same
order as they are created so they replicate the
action of entering data from a keyboard. - The number of records on a sequential access file
is often unknown, but there is an invisible
binary marker at the end of the file called the
EOF (end of file) marker. - Use a Do While loop or a Do Until loop to input
data from sequential access file. - Loops can input data until the EOF marker is
encountered (or while it has not been
encountered). - Create sequential access files by using the
Notepad text editor
96Opening and Inputting Data from a File
- Files must be opened with the Open statement
- Open filename" for Input as n
- To input data from a file, use the Input n,
statement - Input n, list of variables
- Files must be closed at end of procedure
- Close n
- Using an Until loop to input data from file
- Do Until EOF(n)
- Input n, list of variables
- Loop
97Code to Input and Sum values from File
- Private Sub cmdCalc_Click()
- Dim TheValue As Integer, Sum As Integer
- Dim NumValues As Integer
- Open "a\SumData.txt" For Input As 10
- Sum 0
- NumValues 0
- Do Until EOF(10) Input to end of file
- Input 10, TheValue
- Sum Sum TheValue
- NumValues NumValues 1
- lstEntries.AddItem str(TheValue)
- Loop
- txtNumValues.text Str(NumValues)
- txtSum.Text Str(Sum)
- lstEntries.AddItem "Sum is " str(Sum)
- Close 10
- End Sub
98The Combo Box
- A combo box is a combination of a text box and a
list box. It typically a drop-down list box - It has a text box portion that is displayed at
all times and a drop-down list of items that can
be displayed by clicking on the down arrow. - One property of note for the combo box is the
Style property, which can be set at design time
to Drop Down combo (the default), Simple Combo,
or Drop Down list. Its prefix is cbo . - The combo box has all the properties and methods
of the list box including the AddItem, Listcount,
and list properties.
99More on Combo Boxes
- The default event for the Combo box is the Change
event--to use the Click event, you must change to
it. - The Sorted property is a useful property for the
combo and list boxes that arranges the items in
the box. - Items can be removed from a combo or list box
with the RemoveItem method which requires that
number of the item to be remove be given.
However, to remove a selected item, use the
ListIndex property, e.g, - cboMembers.RemoveItem cboMembers.ListIndex
100Nested Loops
- A Nested loop is a loop within a loop. Must
complete the inner loop within the outer loop. - Nested For-Next loops have a For-Next loop within
a For-Next loop in which the inner loop will go
through all its values for each value of the
outer loop. - Three key programming rules to remember about
using nested For-Next loops - Always use different counter variables for the
outer and inner For-Next loops. - Always have the Next statement for the inner
For-Next loop before the Next statement for the
outer For-Next loop. - Always include the counter variable in the Next
statements to distinguish between the loops.
101Creating an Executable File
- An executable file is one that can be executed on
any computer on which it is installed. - Creating an executable file in VB is accomplished
with the FileMake filename.exe menu selection. - Once an executable file is created, a shortcut to
it can be created by right-clicking the file name
in Windows Explorer and selecting Create
Shortcut. - Drag the shortcut to the desktop.
102Debugging Loops
- Debug a loop by inserting a debug.print command
in the loop to print to the Immediate Window. - Add a Quick Watch by locating the pointer on a
variable and clicking the eyeglass icon on the
Debug Toolbar. The values for this variable will
be shown in the Watch Window. - Use the Locals window to display the values of
variables local to a procedure. - Use the Toggle Breakpoint icon to pause execution
at a designated line in the code and then use the
various windows to view the values for variables.
103Chapter 6 Using Arrays
104Using Control Arrays
1. A control array is group of the same type
control which is assigned a single name. 2. The
individual controls are identified by the control
array name and an index value. 3. The Case
decision structure can be useful in working with
a control array. 4. To create a control array,
just enter the same name for more than one
control and replay yes to the query. 5. The
order in which the controls are entered
determines the index values for the controls in
the control array.
105Using List Arrays
- Arrays are lists or tables of data which have
single name. Individual array elements are
identified by the array name and one or more
subscripts or index values. - To be use in Visual Basic, an array must be
declared arrays can be fixed size or dynamic
size (we use only fixed arrays.) - The default lower limit on an array index is zero
but this can be changed to one or any other
value.. - It is not possible to exceed the upper limit or
go below the lower limit on the array index
values - To declare an array
- Dim arrPrice(25) As Currency
- or Dim arrPrice() As Currency
-
- Redim arrPrice(25)
106Comparing Listboxes and Arrays
107Entering Array Data
1. Arrays can be input with any of the three
types of loops discussed earlier--Event-driven,
For-Next, or While/Until loops. 2. Event-driven
loops and For-Next loops are good for keyboard
input While or Until loops are good for input
from a file. 3. In any case, each array element
must be input using its subscript value. 4. With
an event driven loop, each click of a button
increments a counter and inputs the corresponding
array element. 5. With a For-Next loop, you must
input the number of arrays elements. The array
values must be input with an InputBox with the
For-Next counter variable matching the array
index. 6. With an Until loop, you can input from
a file. You must increment a counter that matches
the index for the array element.
108Code to Input from For-Next and Until Loops
For-Next Loop Dim counter As Integer NumPrices
ccint(InputBox("How many prices?")) For counter
0 To NumPrices - 1 Prices(counter)
CCur(InputBox("Next price")) Next Until
Loop Open "a\prices.txt" For Input As 1 Do
Until EOF(1) Input 1, Prices(NumPrices)
NumPrices NumPrices 1 Loop
109Processing Arrays
1. Typical array operations include summing and
averaging the array values and finding the
largest or smallest value in the array. 2.
Working with arrays usually involves a For-Next
loop. 3. Summing Prices array elements involves
using a statement of the form Sum Sum
Prices(Counter) 4. Averaging Prices array
elements involves dividing the Sum by the number
of elements 5. Finding the largest or smallest
value involves multiple comparisons of array
elements. 6. To find the maximum Price, you must
compare each array value to the current highest
price if it is higher, it becomes the highest
price. Do this using For-Next loop and If-then
If Max lt Price(Counter) then Max
Price(counter) end if
110Code to Find Maximum Value in List
Private Sub cmdFindMax_Click() Dim Counter As
Integer, Largest As Currency Largest
Prices(0) For Counter 1 To NumPrices - 1
If Prices(Counter) gt Largest Then Largest
Prices(Counter) End If Next txtMaxPrice
Format(Largest, "currency") End Sub
111Finding items and working with multiple lists
1. It is possible to work with multiple list
arrays by matching the index values for the
arrays. 2. Finding a specific array value
involves comparing each array element to the
desired value. A flag is often used to indicate
whether a match was found. 3. The Msgbox can be
used as a function by including multiple
parameters within parentheses. These parameters
can be internal constants and the Msgbox function
returns a value which can be checked to determine
which button was clicked. varMsgBox(message,butt
ons,title)
112Pseudocode to Find Price for Part Identifier
Begin procedure to find part identifier Input
part identifier Set Flag to false Repeat for
each part in parts list If part identifier
identifier on parts list then Flag True Save
index of part identifier on parts list End
decision End repeat If Flag true Use saved
index to display part identifier and price
Else Display message that part not on parts
list End decision End procedure
113Code to Find Price for a Part Identifier
Private Sub cmdFind_Click() Dim Counter As
Integer, Results As Integer, FindID as string Dim
Found As Boolean, PriceIndex as
Integer FindPartID InputBox("Input part
identifier to find") Found False For Counter
0 To NumPrices - 1 If FindPartID
PartId(Counter) Then Found True PriceIndex
Counter Exit For End If Next If Found
Then txtFound PartId(PriceIndex) " "
_ Format(Prices(PriceIndex), "Currency") Else Resu
lts MsgBox("Part not found", VbExclamation,
"Price Search") End If End Sub
114Code to Save Index of Part with Highest Price
Private Sub cmdFindMax_Click() Dim Counter As
Integer, Largest As Currency, MaxIndex as
Integer Largest Prices(0) For Counter 1
To NumPrices - 1 If Prices(Counter) gt Largest
Then Largest Prices(Counter)
MaxIndex Counter End If Next
txtMaxPrice PartId(MaxIndex) " " _
Format(Prices(MaxIndex), "Currency") End Sub
115Working with Multiple Forms
1. It is possible to have multiple forms in a
project. To display a form, use Object.Show To
hide the form, use Object.Hide 2. A new form can
be added using the ProjectNew Form menu option
or the New Form icon on the toolbar. 3. If a
control on one form is referred to on another
form, the form name must be included as a part of
the control reference.
116Searching in Strings
Searching for strings using a loop requires
that you use Ucase or Lcase to convert all
strings to the same case. To search for a
substring within a string, you use the
(Instr(string to search, search string)
function. For example, Instr(Go Dogs, D )
returns 4 because D is in the 4th position. If
the character does not exist, Instr returns a
zero. NOTE Instr is case sensitive!!!
117Code to Search for a Partial Video Name
Private Sub cmdSearch_Click() Dim VideoName As
String, Counter As Integer, NumMatches As
Integer VideoName txtSearch lstVideos.Clear
lstVideos.AddItem "Video Name" For Counter 0
To NumVideos If InStr(UCase(Videos(Counter)),
UCase(VideoName)) gt 0 Then NumMatches
NumMatches 1 lstVideos.AddItem
Videos(Counter) End If Next If NumMatches
0 Then MsgBox ("No matching videos found!
Try again.") ElseIf NumMatches lt 5 Then
lstVideos.AddItem Str(NumMatches) " videos
found" Else lstVideos.Clear MsgBox
("Too many matching videos!") End If End Sub
118Code to Display Video Information
Private Sub lstVideos_Click() Dim VideoName As
String, Counter As Integer VideoName
lstVideos lstVideos.Clear For Counter 0 To
NumVideos If VideoName Videos(Counter)
Then lstVideos.AddItem VideoName " "
_ Format(VideoPrice(Counter), "currency")
_ " " VideoLoc(Counter) Exit For
End If Next End Sub
119Two-dimensional Arrays
- When you are working with a table instead of a
list, you have a 2-dimensional array - 2-D arrays two subscripts with the first
subscript referring to the row value and the
second subscript referring to the column value - Nest For-next loops are often used to work with
2-D arrays with the inner loop matching the
columns and the outer loop matching the rows.
120Using the Step Commands for Debugging
Stepout of
Step into
The Step Commands
Step Over
If you select Step Into, you can step through
the code, line by line and note the result of the
code in the various windows--Watch, Locals, or
Immediate.
121Chapter 7Using Functions, Subs, and Modules
122Design for Expanded Vintage Videos project
123Membership Management Form
124Modified Videos Form
125Using General Procedures
- Event procedures are associated with a particular
event and are not usually available to other
forms - General procedures are used for specific tasks
that are not associated with an event. - General procedures are defined in the General
object of form and then invoked (called)
elsewhere in the project. - Two types of general procedures
- subs (subroutines)
- functions
126Advantages of General Procedures
- Share the abilities.
- Reduce the complexity and redundancy.
- Enhance the adaptability easy to change. Similar
to the concept of symbolic constants.
127Relationship between general and event procedures
128Subs and Functions
- A sub is a unit of code that performs a specific
tasks but returns no value - A function is similar to the built in functions
in that arguments are passed to it and processed
to compute a single value returned by its name. - In both case, the arguments (variables passed to
the sub) will be changed.
129Primary purposes of subs and functions
130Working with General Procedures
- General procedures must be created and then
invoked - Invoking a function
- variable functionname(arg1, arg2, , argn)
- Invoking a sub
- subname arg1, arg2, , argn
131Creating Subs and Functions
- To create a sub or function you can
- Use the ToolsAdd Procedure menu command and
select the type of procedure to add - or
- simply type the word Sub or Function and press
Enter after any existing event or general
procedure - In either case, then add the parameters
132Creating a Function
- The definition statement is
- Function FuncName(parameter1 as type, parameter2
as type, ) as type - FuncNameltexpressiongt
- End Function
- For example
- Function FindMax(Num1 as Integer, Num2 as
Integer) as Integer - An important rule is that the name of the
function must be assigned a value in the function
133Creating a Sub
- The general form of the sub definition statement
is - Sub SubName (parameter1 as type, parameter2 as
type, ) - Note that the sub name is not assigned a type
- Example
- Sub Reverse(First as Currency, Second as Currency)
134Relationship between Sub definition statement and
statement invoking the sub
135Relationship between Function definition
statement and the statement invoking the function
136Matching Arguments and Parameters
- For both sub and functions, the number and type
of arguments in invoking statement must match the
number and type of parameters in the procedure
definition statement - In both the argument and parameter list,
fixed-size arrays are referenced by the name of
the array followed by parentheses
137Function to Compute Income Taxes
- Public Function ComputeTaxes(NumExm As Integer, _
- GrossIncome As Currency) as Currency
- Dim TaxIncome As Currency
- TaxIncome GrossIncome - 4150 - NumDep 2650
- Select Case TaxIncome
- Case Is lt 24650
- ComputeTaxes 0.15 TaxIncome
- Case Is lt 59750
- ComputeTaxes 3697.50 0.28 (TaxIncome -
24650) - Case Is lt 124650
- ComputeTaxes 13525.50 0.31 (TaxIncome -
59750) - Case Is lt 271050
- ComputeTaxes 33644.50 0.36 (TaxIncome -
124650) - Case Else
- ComputeTaxes 86348.5 0.396 (TaxIncome -
271050) - End Select
- End Function
138Sub to Reverse two values
Sub Reverse(First as Currency, Second as
Currency) Dim Temp as Currency Temp First First
Second Second Temp End sub
139Sort the Items in a List Bubble Sort
- Bubble sort is the simplest, although not the
fastest, sorting method. - Pseudocode of Bubble Sort
- Repeat until not reversals made
- Repeat for each pair of the items
- If the two items are not in the order
- Reverse the items
- End if
- End inner repeat
- End outer repeat
140Sub to Sort arrays
- Public Sub Sort(FirstList() As Currency,
SecondList() _ - As String, NumList As Integer)
- Dim NoReversal As Boolean, Counter As Integer
- NoReversal False
- Do Until NoReversal
- NoReversal True
- For Counter 0 To NumList - 2
- If FirstList(Counter) gt FirstList(Counter
1) Then - Reverse FirstList(Counter),FirstList(Counter
1) - Reverse SecondList(Counter),SecondList(Counter1)
- NoReversal False
- End If
- Next
- Loop
- End Sub
- To call the sub, enter Sort Prices(),PartID(),Num
Prices
141Global Declarations and the Code Module
- In a global declaration, the scope of global
variables covers all parts of the project. They
must be defined in a code module. - Use Public statement to declare variables
- Public varName1 as type, varName2 as type,
- Global variables cant be defined again in
procedures. - The Code Module is the section of pure code that
is known to all parts of the project.
142Scope of Global Variables
143Use of String Functions
- Len(string)--returns number of characters in
string - Left(string, N) or Right(string, N)--returns the
leftmost or rightmost N characters in a string - Mid(String,P,N)--returns N characters in a string
starting at Pth character - Trim(String), Ltrim(string) or Rtrim(String) --
trims blank characters from left (right) end of
string
144Passing by Value in Subs
- If there is a two-way communication between
arguments and parameters, then you have passing
by reference - If there is a one-way communication between (you
dont want the variables in mail procedure being
affected), then you have passing by value - To pass by value, add the keyword ByVal prior to
a variable in the procedure definition statement - E.g. Sub Reverse(ByVal First As Currency, Second
As Currency)
145Global Variable vs Pass Variable
- To exchange the data among variables in different
procedures, both methods can be used. - Global variables will be changed anywhere they
are used. Difficult to debug. - Using the variable pass method can keep the
privacy of variables.
146Chapter 8Security, Menus, and Files
147Security
- Passwords are often used to control access to a
computer or software program - Passwords should be at least 6 characters in
length and something that cannot be easily
guessed - It should not be possible to move, resize, or
bypass the password form in VB and it should be
the Startup object. - The Tag property for a textbox can be used for
the password and the PasswordChar property can be
used to hide the password as it is entered. - A user should be given a set number of chances
to enter the correct password.
148Menu Systems in VB
- A menu system for a form can be created using the
Menu Editor. - Menu bar options as well as submenus can be
created with this editor - Menu and submenu items have caption and name
properties (the prefix is mnu) - Code is written for menu items just like for
other event procedures (Click the menu item to
enter) - Menu options are always click events
- Most menus contain File and Help menu bar options
in addition others specific to the application
149Access Key and Shortcut Key
- Assign before one of the letters of a controls
CAPTION to make the control accessible by key
combination ALTletter (available to Buttons or
Menu items) - Assign Ctrl or Shift or Function Key plus a
letter or a Function Key to create a shortcut key
and make to control be accessible by keyboard.
(available to Menu items)
150Custom Controls
- Beyond the standard controls, there are some
custom controls to be added. - To add custom controls, select menu
ProjectComponents and then make ticks. - Useful controls
- Masked Edit Control
- Common Dialog Control
151Important Properties of Masked Edit Box
- Format Decide the display format of the box.
- Mask Decide the input format of the box.
- In Microsoft Library, choose help index MaskEDBox
to see how to use this control.
152Important Properties Methods of Common Dialog
Control
- Filter sets the filters that are displayed in
the Type list. - FilterIndexSets a default filter for dialog box.
- ShowOpen Displays the CommonDialog control's
Open dialog box. - ShowSave Displays the CommonDialog control's
Save As dialog box.
153Use Common Dialog Control
- The Filter property of the common dialog control
is used to display a list of files - It has the form
- dlgName.Filter description1filter1descr
iption2filter2etc - The FilterIndex property determines the default
file type - When a file is selected or a filename entered,
this becomes the Filename property for the dialog
box - The FreeFile function returns an unused file
number and the On Error Goto statement causes
control to jump to a label when an error is
encountered. Both ar useful in working with
files.
154Other File Operations
- A file can be opened from a common dialog box
with the ShowOpen method - The contents of the file can be input using the
Input function - Input(number, filenumber) where number
number of characters in file that is identified
by filenumber - The LOF(FileNumber) function can be used to
determine the number of characters in a file - A memo can be saved by printing its contents to a
file--its common to query the user to save the
file if it has been changed.
155Error Handling
- As a mature software, it shouldnt be terminated
by any errors. - To direct the error handling, use On Error
statement - On Error Goto ltlinegt Go to the handling block
started by the line - On Error Resume Next Go to next statement after
the error position - On Error Goto 0 Disable the error handling
156Error Handling Block
- Begins with the line code with a colon ().
- Should use Exit Sub at the places needed.
- Use Err object to detect the error. Useful
properties are - .Number The error code number.
- .Source Name of the current Visual Basic
project. - Description Error description.
157Some Useful Functions
- Input(NumChar, FileNum) Returns a string from
a file opened with the FileNum. The length is
decided by NumChar. - LOF(FileNum) Returns the length of the file
opened with FileNum
158Creating a Memo Editor
- Creating a memo editor in VB involves using a
textbox as the location of the text and a menu
system for the various editor commands - The textbox should have its Multiline property
set to true and its Scrollbars property set to
vertical. - The Form_Resize event occurs when the user
changes forms size--it can be used to cause the
memo text box to fill its form by setting the
Height and Width properties to ScaleHeight and
ScaleWidth
159The Memo Editor File Menu
- The File Menu should have options to begin a new
memo, open an existing memo, save a memo under
the current name or a new one, close the memo,
print it, or exit the memo editor. - Key to the File Menu is the use of the common
dialog control which must be added to the Toolbar
with the ProjectComponents VB menu option before
being added to the form - The common dialog control (with dlg prefix) can
be used to open or save files with the ShowOpen
and ShowSave methods