You are on page 1of 48

• List & Combo Box

• Masked edit control


• Common Dialog boxes
• Arrays
• Error Handling
• Passing arguments
• Functions
• Menus
• General, Function & sub procedures
• Multiple Forms, SCM
• Splash & About forms
1
2
• List/Combo boxes allow a list of items

• Combo box • List box


– has style property – does not
» simple combo boxes
» dropdown combo
boxes
» dropdown lists

– has design-time text – has only run-time text


property property

– does not have a – has MaxLength


MaxLength property property

3
Filling the List
• One can fill the list at design- or run-time

• Fill at design time if list rarely changes


– Click List property, type entry, press
Ctrl+Enter
– Make Sorted property true to keep list in order

• Fill at run time if list is volatile


– Use AddItem method to add items
– Form: object.AddItem value [,Index]
– Example: lstFruits.AddItem "Apple"

4
List/Combo Box Methods & Properties
• Sorted maintains list in
• AddItem - Add item to list order (if true)
cboFruits.AddItem "Kiwi"
cboFruits.AddItem cboFruits.Text
• ListIndex holds user-
selected item index
• Clear - Delete all items number (begins at zero,
from the list -1 if none selected)
cboFruits.Clear – setting the ListIndex
property highlights a
selection in the list
• ListCount: the number
of items in list
• List object.List(index)
extracts string value of
list item
5
List/Combo box Events

• Change Occurs when user types text into


combo box (list box does not have this)

• GotFocus Occurs when control receives


control

• LostFocus Occurs when control loses control

6
Masked edit control
• provides restricted data input as well as formatted
data output

• generally behaves as a standard text box control with


enhancements for optional masked input and
formatted output

• if you define an input mask using the Mask


property, each character position in the Masked Edit
control maps to either a placeholder of a specified
type or a literal character
– literal characters, or literals, can give visual cues about
the type of data being entered or displayed
» e.g., the parentheses surrounding the area code of a
telephone number are literals: (206).
7
A masked edit box and its Format property

8
Common properties
Property Description
Format Lets you select a format that
determines how the data will be
formatted after it is entered into
the box.
Mask Lets you define an input mask that
restricts the data that the user can
enter.
Typical input masks
Mask Mask when run Typical entry
(###) ###-#### (___) ___-____ (555) 384-2384
(###) &&&-&&&& (___) ___-____ (800) TAG-2000
##/##/## __/__/__ 12/25/98
##-???-## __-___-__ 12-Dec-98

9
Common Dialog Boxes
• Only need one Common dialog box/form
– Use prefix “dlg” for name of control

• Code determines which of the possible


dialog boxes is displayed
– Open, Font, Color, Save As, and Print
» dlgCommon.ShowColor
» dlgCommon.ShowFont

10
Single/Multi Dimensional Arrays
• An array contains a list of values

• Individual values are called elements


» Each array element is of same type
» Elements are just like any other variable
» an element is referred using its subscript

• Using 2 subscripts with an array


– First subscript is row; second is column
» Dim X(1 to 10, 5 to 15) As Integer
» Dim X(2,7) As String

11
Control arrays
• a group of controls that all have the same
name
– Advantage: controls in array share a single
click event
» Using a case statement, we may determine
which button is selected

12
When a run-time error occurs…

• VB generates an error 11 Division by 0


number 13 Type mismatch
482 Printer error
• VB checks the number 53 File not found
against a table of known 61 Disk full
error codes 68 Device unavailable
71 Disk not ready
• Programmer can intercept 75 Path/file access error
the error code and take 76 Path not found
action before VB terminates
the project

13
Error Trapping Steps
• Turn on the error-handling feature using On
Error statement in subprocedure

• Create error handling code routines


– Set them off from other code with line labels

• Write code to continue after the error is


"handled"

14
On Error Statement
• Use this statement at the beginning of a
procedure to activate error trapping

• Designate a line label in the same procedure


to go to if an error occurs
– Line labels - begin in column 1, end with
colon:

Refers to
On Error GoTo ErrorHandler
line label

15
Error Handling Code
• Precede with Exit Sub statement (or Exit Function)

• Check the error number(s)


– Single error number -- If structure
– Multiple error numbers -- Select Case

• Inform user if necessary

• Designate next line of code to execute


– Resume
– Resume Next
– Resume line label

16
Error Handling Standards
• Use Resume if the problem • Use Resume line label
is identified and the user
could correct it to exit the procedure

• Use Resume Next if the • Call the exit procedure


problem is identified and
execution can proceed to end without
without running the error displaying any error
generating line of code message
• Raise the error again
(Err.Raise Err) if the • Turn off error
problem cannot be
identified so VB will
handling/trapping
handle it and generate a with:
system error message On Error GoTo 0
17
Handling One Error Number
Private Sub Whatever( )
On Error GoTo ErrorHandler
code to do whatever this subprocedure does
Exit Sub
ErrorHandler:
If Err.Number=71
msgbox to inform user of error for
correction
Resume
Else
Err.Raise Err
End If
End Sub
18
Handling Multiple Error Numbers
Private Sub Whatever( )
On Error GoTo ErrorHandler
code to do whatever this subprocedure
does
Exit Sub
ErrorHandler:
Select Case Err.Number
Case 71
Msgbox
Case 53, 76
Msgbox
Case Else
Err.Raise Err
End Select
Resume
End Sub

19
Trapping Program Errors
• Visual Basic generates an
error number whenever an The statements
error occurs for error handling
Syntax
• To handle errors, one must On Error GoTo label
– Turn on error handling On Error Resume Next
feature: On Error... On Error GoTo 0
– Create error handling Resume
code Resume Next
– Determine what is to be
Resume label
done after processing
the error (continue, end Exit Sub
program,…)

20
The Err Object
• When a trappable error occurs in VB, the Err
object holds information about error that just
occurred
– Properties:
» Err.Source holds the source of the error
» Err.Number holds the error number
» Err.Description contains error description

21
A procedure that contains an error-handling
routine
Private Sub cmdCalculate_Click()
On Error GoTo ErrorHandler
txtFutureValue.Text = _
FormatNumber(FV(txtInterestRate / 12, _
txtYears * 12, _
txtMonthlyInvestment, 0, 1) * -1)
Exit Sub
ErrorHandler:
MsgBox "Error Number: " _
& Err.Number & vbCrLf _
& "Error Description: " _
& Err.Description
End Sub

22
Exit and Exit Sub Statements
• Exit Sub immediately exits current sub
procedure

• Exit Function immediately exits current


function

• Exit is used to prematurely halt execution of


sub procedure or function when
extraordinary conditions occur

• Place Exit Sub above error handling label


23
• By default, the arguments that are passed to a Sub procedure
are passed by reference. In this case, the called procedure
can modify the value in the calling procedure.

• When an argument is passed by value, a copy of the variable


is passed to the called procedure. Then, if the called
procedure modifies the value, the value in the calling
procedure isn't changed. To pass an argument by value, you
use the ByVal keyword.

24
The syntax of the Function and End
Function statements
[Private|Public] Function name([argumentlist])
[As type]
statements
name = expression
End Function

The syntax of the Call statement


[Call] name[(argumentlist)]

• If you use the keyword Call to call a function, the return


value is discarded.
• You can use the ByVal keyword when you define an
argument for a function just as you can for a Sub procedure.

25
A function named FutureValue that
requires three arguments
Private Function FutureValue( _
Months As Integer, _
InterestRate As Single, _
MonthlyInvestment As Currency) _
As Currency
Dim iIndex As Integer
For iIndex = 1 To Months
FutureValue = _
(FutureValue + _
MonthlyInvestment) _
* (1 + InterestRate)
Next iIndex
End Function

26
Some date and time functions
Date Returns the current date.
Now Returns the current date and time.
Time Returns the current time.
DateValue Receives a date string and returns a
date numeric value.
Two dialog box functions
MsgBox Displays a message in a dialog box, waits
for the user to click a button, and returns
an integer indicating which button the
user clicked.
InputBox Displays a message in a dialog box, waits
for the user to enter text or click a button,
and returns a string that contains what the
user entered.
27
The syntax of the MsgBox function
MsgBox(prompt[, buttons][, title])

A MsgBox function that doesn’t


return a value
MsgBox "Invalid data. Check all entries."

A MsgBox function that returns a


value
Private Sub Form_Unload(Cancel As Integer)
If MsgBox("Do you want to exit?", _
vbYesNo + vbDefaultButton1, _
"Confirm Exit") = vbNo Then
Cancel = True
End If
End Sub

28
InputBox Syntax

VariableName = InputBox("Prompt" [, "Title"]


[, Default] [, XPos] [, YPos])

Where:
Prompt - displays in the dialog to inform the user of what to
input
Title - displays in the title bar of the dialog
Default - default value than displays in the text box of the
dialog
XPos - Horizontal position of the top left corner of the dialog
YPos - Vertical position of the top left corner of the dialog

29
InputBox Examples

strName = InputBox ("Enter Your Name")


intQuan = InputBox ("How many do you want?", _
"Order Quantity", 1)

30
Some of the string functions
InStr Returns the position of the first
occurrence of one string within another.
Left Returns a specific number of characters
from the start of a string.
Len Returns the length of a string.
LTrim Removes spaces from the start of a
string.
Mid Returns a specific number of characters
from a string starting from a specific
location in the string.
Right Returns a specific number of characters
from a string starting from the right
31
Some of the math and finance
functions
Int Returns the integer portion of a number.
Val Returns the number contained in a string
as a numeric value.
Rnd Returns the next random number as a
decimal fraction between 0 and 1.
FV Calculates the future value of a periodic
payment amount.
SLN Calculates a straight-line depreciation
amount.
SYD Calculates a sum-of-years’ digits
depreciation amount.

32
The immediate If function
IIf Evaluates a conditional expression and
returns one value if the expression is true and
another value if the expression is false.
IIf(expr, truepart, falsepart)

The IIf function syntax has these named arguments:

Part Description

expr Required. Expression you want to evaluate.

truepart Required. Value or expression returned if expr is True.

falsepart Required. Value or expression returned if expr is False.

IIf always evaluates both truepart and falsepart, even


though it returns only one of them. Because of this, we
should watch for undesirable side effects
33
Menus
• Define menus: Tools -> Menu Editor
– Caption
» holds menu "words“
» use & before keyboard access key
– Name (mnuMenuxxCommand)

• Follow naming conventions:


– mnu + <menu name>
– mnu + <menu name> + <command name>
» e.g., mnuFileExit, mnuEditClear or mnuFile

• Sub menus
– menu within a menu
– defined by indenting command

34
Creating a Menu
• Create a menu structure • Follow existing
like this one: Windows standards
File Help – File menu is leftmost
Exit About menu in menu bar
1. Type caption – Help menu is
rightmost menu in
2. Type name menu bar
3. Indent if necessary • Use keyboard access
4. Repeat as needed keys; match them to
existing ones
• Use keyboard shortcuts
– e.g., Ctrl + P for print

35
The Menu Editor dialog box

36
How to create drop-down menus
• The Caption and Name properties are required
for all menu objects, and the prefix mnu is
commonly used in the name of a menu object.
• Use the ellipsis (…) at the end of the Caption
property to identify menu commands that lead to
dialog boxes.
• Use a single hyphen (-) in the Caption property to
display a separator bar between menu commands.
• To create a Window menu that lists all of the
open child forms in a parent form, select the
WindowList property. Then, you can use this
menu to switch between the open forms.
37
How to create popup menus
• To create a popup (or shortcut) menu that's
different from the other menus, remove the check
mark from the Visible property. Then, you can
use code to test whether the right mouse button
has been clicked and, if so, to display the popup
menu.
• Some controls provide built-in popup menus. If,
for example, you right-click on any masked text
box control, a popup menu is displayed with
these standard Windows commands: Undo, Cut,
Copy, Paste, Delete, and Select All.

38
Coding for Menu Commands
• Build commands first
– double click each command to bring up its click event
procedure

• menu order or command order are modified by


invoking Menu Editor again

• Property
– Checked
» contains check
» toggles on and off
– Enabled
» command available or not (based on this property)

39
General Procedures
• General procedures respond when specifically called
by other procedures

• They are not event driven

• They are used to “package” a commonly used series


of instructions

• Invoke general procedures by calling them

• Select Tools, Add Procedure to insert one

40
Functions vs. Sub Procedures
• Functions vary from sub procedures in one
way: they return a value

• One calls a general procedure by simply


writing its name along with any arguments

• Somewhere in the procedure, one must set


the function’s name equal to the value to be
returned

41
The dialog box for the Add Module
command in the Project menu

Operation
• Use this command to add a standard module to
your project.
• To save and name the new module, press Ctrl+S
and complete the dialog box that appears.

42
The Project Properties dialog box

Skills
• Change the Startup Object to the form that you
want displayed when the project starts.
• Change the Startup Object to Sub Main when you
want the project to start by running code in a
standard module.
43
Multiple Forms
• Create form:
– Project, Add Form, Select form type
– 1st form created is, by default, the startup form
• Add/Remove forms
– Project, Add Form and then click the existing tab
– Project, Remove File
• Hide & Show methods
– frmAbout.Show
– frmAbout.Hide
– general form is formname.Show <style>
» style 1 (modal) or default style 0 (nonmodal)
• modal form requires the user to respond to the form in
some way, whereas a modeless form does not
44
Multiple Forms
• Load & Activate events
– The first time a form is displayed, it triggers a form
load event followed by a form activate event
» Load calls the module into memory
» Activate occurs when the form receives control
• If something should occur each time a form is displayed,
then put that code in the form activate event, not the form
load event.
– The form load event occurs only (typically) once, but
activate occurs each time the form gets control.
• Referring to objects in other forms
– reference: FormName!ObjectName.property
» frmSummary!txtName = …
» frmSummary!txtName.Font.Name = ...
• This implies that control names are unique within a form
but need not be unique across forms.

45
Standard Code Modules
• Create SCM: Project, Add Module
– SCM has the extension .BAS
– Public procedures/variables are visible to all
forms

• DIM variables in the Gen. Dec. section of


SCM are visible to all procedures in the SCM,
but not to procedures in the form modules.

46
About Box & Splash Screen
About Box Splash Screen
• a modal form with an • Create:
OK button and label – Project, Add Form, then
boxes displaying select Splash Screen
information
– Displays information • Splash screen displays
about the while program loads
programmers, version,
– loads before main form
and so on
– Create :
» use VB’s About • Place splash screen load
Dialog template statement in Sub Main
procedure in Standard
Code Module
47
Summary (forms)
• Projects can have unlimited # forms
• Load statement loads forms but does not display
them
• Me refers to currently active form
• Refer to object in another form with form name as
prefix
• SCM contains public variables and public sub
procedures that are global to project
– Public can appear only in the General Declarations
section of a module—place it in SCM only by
convention
• Program execution can begin in a sub procedure
called Main located in Standard Code Module
48

You might also like