Saturday, December 26, 2009

USER DEFINED FUNCTIONS / SUBROUTINES

Making code changes easily

Subs enable you to change code easily. If you have a body of code that you need to use repeatedly, put the code in a sub. Then, if you need to make a change in the code, simply go to the sub to make changes. If you don't put the code in a sub, you will have to go to every instance of the code in your program to make the required change. The more dispersed your code is, the harder it is to
make changes effectively and efficiently.


A sub is a procedure that executes the lines of code within its block but doesn't return a value. The syntax for a simple sub is as follows:

[Private|Public] Sub SubName()
.....lines of code
End Sub

In this syntax

[Private|Public] are the optional Visual Basic keywords that define the scope of the sub.

Sub is the Visual Basic keyword that denotes the type of procedure.

SubName is the name that you assign to your sub.

End Sub are the Visual Basic keywords that denote the end of a code block.

The following code snippet is an example of a simple sub:

Public Sub DataNotFound()
MsgBox "Data Not Found", vbInformation
End Sub

When you call this sub from other areas of your code, the sub displays a Windows message box with the string Data Not Found. The message box will display whatever text is used for the string constant.

Listing 3.1 shows the sub being called with the Visual Basic Call statement (line 2). Using the Call statement is optional. Although you can call a Sub by using only its name, using the Call keyword makes
your code more readable.


LISTING 3.1 18LIST01.TXT--Calling a Sub from an Event Procedure

01 Private Sub itmOpen_Click()
02 Call DataNotFound
03 End Sub


Making Subs by Using Add Procedure


You can add a sub to your project in two ways:

By writing the code directly into the General Declarations section of a form or module.

By using the Tools menu's Add Procedure option.


Enabling the Add Procedure menu item

For the Add Procedure menu item to be enabled, you must be in Code window view of the form or module into which you want to add the procedure.



Add a sub to your project with Add Procedure
1. From the Tools menu, choose Add Procedure to display the Add Procedure dialog.

2. Enter the sub Name
3. Click OK to add the sub's code block to the form or module (see Figure 18.2).


.

After you create the sub code block with the Add Procedure dialog, you add the procedure's code within the code block. Don't enter any code for the Sub after the End Sub keywords; this is illegal and
generates syntax errors when you compile the code.

No comments:

Post a Comment