You are on page 1of 28

CHAPTER 4

MENUS, SUB PROCEDURES


AND SUB FUNCTIONS
Overview

• Create menus and submenus for


program control
• Display and use the windows common
dialog boxes
• Write reusable code in sub procedures
and function procedures and call the
procedures from other locations
Introduction to Menus
Menu consists of a menu bar with menu names, each of which
drops down to display a list of menu commands. Menu commands
are controls – have properties and events. Each menu command
has a Name property and a Click event, similar to a command
button.

• It is easy to create a menu for your


form by using the VB menu editor.
• To use the menu editor, select
Menu Editor from the Tools menu
or click on the Menu Editor toolbar
button.
… Introduction to Menus

• We will use the Menu Editor window to set


up our menus. Menu Caption
• Caption property: holds the words you Menu name
want to appear on the screen (Use prefix ‘mnu’ for menu)

• Name: indicates the name of menu control.


• The drop-down list of commands below a
menu name is called a menu. Arrow button

• When a command on the menu has Menu

another list of commands that pops up, the Sub menu

new list is called a submenu.


• To specify menu names, menu commands, Menu list box

and submenu commands by indentation


(shows as dots …. in the list box).
… Introduction to Menus

• Group the many commands according


to their purpose, by creating a
separator bar in a menu (which draws a
bar across the entire menu).
• To define a separator bar, type a single
hyphen (-) for the Caption and give it a
name (for example: mnuSep1,
mnuSep2, …)
Separator bar
Creating a Menu
Create a project with one form and a menu bar that contains these menu items:
File Help
Exit About
1. Type the Caption (&File) and Name (mnuFile) for the
first menu.
2. Click on the Next button or press Enter – to clear the
text boxes (for writing next menu command).
3. Click on the Right arrow button – sets the
indentation level for a menu command.
4. Click in the Caption text box to set the focus and then
type the Caption and the Name for the Exit menu
command. Click on Next or press Enter.
5. Click on the Left arrow button (outdent) to return to
the previous level.
6. Repeat the steps to create the Help menu and About
command indented below it.
7. Click OK when you are finished. The new menu will
appear on your form.
Coding for Menu Commands

• After create form’s menu bar, it will appear


on the form in design time.
• Just select any menu command, and the
control’s Click event procedure will appear
in the Code window, where you can write
the code.
1. Code the procedure for the Exit by pulling
down the menu and clicking on the word
Exit. Type in the remark and the End
statement.
2. Use a MsgBox statement in the procedure
for the Click event of the About on the Help
menu. The message string should say
“Programmed by “ followed by your name.
Checked and Enables

• A menu command may contain a check


mark beside it (checked), or it may be
grayed (disabled).
• An enabled menu item appears in
black text and is available for selection,
whereas the grayed out or disabled
items are not available.
• A check mark placed next to a menu
command usually indicates that the
option is currently selected.
Toggling Check Marks On and Off
• Check marks are often used on menu commands for options that can be
toggles on and off.
• Choosing the command a second time should remove the check mark and
turn off the option.
• If you create a menu option that can be turned on and off, you should
include a check mark to indicate the current state.
• You can set the initial state of the check mark in the menu editor.
• In code you can change its state by setting the menu item’s checked
property.

Private Sub mnuEditColor_Click()


If mnuEditColor.Checked = True Then
mnuEditColor.Checked = False
Initial state Else
mnuEditColor.Checked = True
End If
End Sub
Common Dialog Boxes
• You can use a set of predefined standard dialog boxes in your projects for
such tasks as specifying colors and fonts, printing, opening and saving.
• To use the common dialog control, you first place a control on your form.
You cannot change the size of the control, and its location doesn’t matter,
since it will be invisible when your program runs.
• The common dialog control may not appear in your toolbox. It is a custom
control and you must add it before you can use it.
1. Open the Project menu and choose
Components.
2. You should see Microsoft Common
Dialog Control 6.0 in the list.
3. Make sure that a check appears next to
the item.
4. Its tool should appear in your toolbox.
Using a Common Dialog Box
• After you place a Common Dialog control on your form, you can display any
of its dialog boxes at run time.
• In code you specify which box you want with the Show method.
• Show Method – General Form:
• Object.ShowMethod

Dialog Box Method Private Sub mnuEditColor_Click()


Open ShowOpen 'Display the color Dialog box
Save As ShowSave dlgCommon.ShowColor

Color ShowColor
'Assign dialog box color to the form
Font ShowFont frmMain.BackColor = dlgCommon.Color
Print ShowPrint End Sub
Color Dialog Box

Private Sub mnuEditColor_Click()


'Select the color and set initial color
With dlgCommon
.Flags = cdlCCRGBInit 'Initialize the dialog box
.Color = frmMain.BackColor 'Set initial color
.ShowColor 'Display the dialog box
End With

'Assign dialog box color to the form


frmMain.BackColor = dlgCommon.Color 'Set color of form
End Sub
Check Point 1
How to change the color of text in a label?

Answer 1

Private Sub mnuEditColor_Click()


'Select the color and set initial color
With dlgCommon
.Flags = cdlCCRGBInit 'Initialize the dialog box
.Color = lblMessage.ForeColor 'Set initial color
.ShowColor 'Display the dialog box
End With

'Assign dialog box color to the form


lblMessage.ForeColor = dlgCommon.Color 'Set color form
End Sub
Check Point 1 (cont)

Answer 2

Private Sub mnuEditColor_Click()


'Select the color and set initial color
With dlgCommon
.Flags = cdlCCRGBInit 'Initialize the dialog box
.Color = lblMessage.ForeColor 'Set initial color
.ShowColor 'Display the dialog box

'Assign dialog box color to the form


lblMessage.ForeColor = .Color 'Set color form

End With
End Sub
Font Dialog Box
• Before you can use the ShowFont method, you must set the Flags property of the
control – to install the fonts to appear in the list box.
• If you forget to set the flags, an error will occur at run time that says “There are no fonts
installed”.
• The value of the Flags property may be cdlCFScreenFonts, cdlCFPrinterFonts, or
cdlCFBoth.
• The Font properties for the common dialog control are different from those used for
other controls.
Font Object of Font Property of Values Private Sub mnuEditFont_Click()
Other Controls Common Dialog
Control 'Display the Font dialog box
With dlgCommon
Font.Bold FontBOld True/False .Flags = cdlCFScreenFonts
To open the Font dialog
.ShowFont box on the screen
Font.Italic FontItalic True/False End With
Font.Name FontName System dependent
'Assign dialog box font to the label
Font.Size FontSize Font dependent With lblMessage.Font
.Name = dlgCommon.FontName
Font.StrikeThrough FontStrikeThru True/False .Bold = dlgCommon.FontBold
End With
Font.Underline FontUnderline True/False End Sub
Setting Current Values
• Before calling the common dialog box for colors or fonts, you should assign the
existing values of the object properties that will be altered.
• This step will provide for the display of the current values in the dialog box.
• It also ensures that if the user selects the Cancel button, the property settings
for the objects will remain unchanged.

'Set the method for Font dialog box


Private Sub mnuEditFont_Click() With dlgCommon
'Display the Font common dialog box .Flags = cdlCFScreenFonts 'Specify screen focus
' and make the changes in the label settings .ShowFont
End With
'Assign the current setting to the dialog box
With dlgCommon 'Assign dialog box font to the label
.FontName = lblMessage.Font.Name With lblMessage.Font
.FontBold = lblMessage.Font.Bold .Bold = dlgCommon.FontBold
.FontItalic = lblMessage.Font.Italic .Italic = dlgCommon.FontItalic
.FontSize = lblMessage.Font.Size .Name = dlgCommon.FontName
End With .Size = dlgCommon.FontSize
End With
End Sub
Check Point 2
Check Point 3
Writing General Procedures

• Often you will encounter programming situations in which


multiple procedures perform the same operation  user
can select either a command button or a menu option to
do the same thing.
• Rather than retyping the code, you can write reusable
code in a general procedure and call it from both event
procedures.
• General procedure useful in breaking down large
sections of code into smaller units that perform a specific
task  simplify any maintenance that needs to be done
in the future.
Creating a New Sub Procedure
• To add a new general procedure to a form:
1. Display the Code window for the form.
2. Select Add Procedure from the Tools menu.
3. Enter a name in the Add Procedure dialog box.
4. Select Private for Scope. Choosing Public makes a procedure available
from other project modules. Note: leave the Type set to Sub for now.
5. Click OK.
Creating a New Sub Procedure (Example)
Passing Variables to Procedures

• At times you may need to use the value of a variable


in one procedure and also in a second procedure that
is called from the first.
• In this situation, you could declare the variable as
module level, but the variable visible to all other
procedures
• To keep the scope of a variable as narrow as possible
 declare the variable as local and passing it to any
called procedures.
Passing Variables to Procedures
(Example)
Expand the capabilities of the previous SelectColor sub procedure to display the
original color when the dialog box appears. Because the SelectColor procedure can
be called from various locations, the original color must be passed to the
procedure.
Note: VB stores colors in Long Integer variables.
Private Sub SelectColor(lngInComingColor As Long) • Notice that the SelectColor procedure now
'Allow user to select a color
has an argument inside the parentheses.
With dlgCommon
• The argument value must be the same
.Flags = cdlCCRGBInit 'Initialize the Color dialog box
.Color = lngInComingColor 'Set the initial color data type in both locations. But, the name
.ShowColor of argument does not have to be the same.
End With • The SelectColor sub procedure will take
End Sub whatever Long Integer value it is passed
and refer to it as lngInComingColor inside
Private Sub cmdChangeMsg_Click() the procedure.
'Change the color of the message • You may specify multiple arguments in both
Dim lngOriginalColor As Long the sub procedure header and the call to the
procedure. But…
lngOriginalColor = lblMessage.ForeColor
SelectColor lngOriginalColor Call sub The number of arguments, their sequence,
lblMessage.ForeColor = dlgCommon.Color procedure and their data types must match in both
End Sub locations!
Passing Arguments ByVal or ByRef

• When you pass a value to a procedure you may pass it ByVal or ByRef (for
by value or by reference).
• The ByVal sends a copy of the argument’s value to the procedure so that
the procedure cannot alter the original value.
• The ByRef sends a reference indicating where the value is stored in
memory, allowing the called procedure to actually change the argument’s
original value.
• You can specify how you want to pass the argument by using the ByVal or
ByRef keyword before the argument.
• If you don’t specify ByVal or ByRef, arguments are passed by reference.

Private Sub SelectColor(ByVal lngInComingColor As Long)


Function Procedures vs. Sub Procedure
• When you insert a new procedure, recall that you can choose
to create a sub procedure or a function procedure.
• A sub procedure is a procedure that performs actions.
• A function procedure may perform an action, but it also
returns a value to the point from which it was called.
• Eg: Predefined functions, such as the FormatNumber
function (returns the formatted characters) and the Val
function (returns the numeric value of the named
argument).
• As a programmer, you may need to calculate a value that will
be needed in several different procedures or programs  you
can write your own function that will calculate a value and
call the function from the locations where it is needed.

Example: Create a function procedure called Commision, which calculates and returns a
salesperson’s commission. <follow the same step as for creating a sub procedure. But, select the
Function option button prior to selecting the OK command button>.
Private Function Commision( ) Private Sub Commision( )

End Function End Sub


Writing Function Procedures
• When you write a function, you declare the argument(s) that the function needs.
• You give each argument an identifier and a data type.
• The argument list you enter establishes the number of arguments, their type, and their
sequence.
• The main difference between coding a function procedure and coding a sub procedure is:
• A function procedure you must set up the return value, named with the same name as the
function name.
• You can also specify the data type of the return value by adding the As clause after the
function name.

Private Sub cmdCalcComm_Click()


Dim curSalesAmount As Currency
curSalesAmount = Val(txtSalesAmount.Text)
lblMessage.Caption = curCommission(curSalesAmount)
End Sub

Public Function curCommission(ByVal curSA As Currency)As


Currency
If curSA < 1000 Then
curCommission = 0
ElseIf curSA <= 2000 Then
curCommission = 0.15 * curSA
Else
Note: Return value is named as the same as
curCommission = 0.2 * curSA the function name
End If
End Function
Writing Function with Multiple Arguments
ANY QUESTION…?

You might also like