Procedures And Functions

Tips >> Visual Basic

Procedures and functions provides a means of producing structured programs. Rather than repeating the same operations at several different places in the program, they can be placed in a procedure or function. This not only makes the program easier to read, but saves a lot of time and effort in maintaining the program.

PROCEDURES:

A procedure is a block of code that performs some operation. The events we have been using so far are a special form of procedure known as an event procedure.
For example, associating code with a CommandButton to quit an application is a procedure.
The basic Syntax for a procedure is:

[Private | Public][Static] Sub procName ([arglist])
Parts of the Procedure
Part Description
Public Indicates that the procedure is available to all modules. If Option Private is used in the module, the procedure is not available to modules outside of the project.
Private Indicates that the procedure is only available to other procedures or functions in the current module or form.
Static Indicates that all variables declared within the procedure are retained, even when the procedure is out of scope.
procName The name of the procedure. Must be unique to the module if declared Private, otherwise unique to the project. The name of the procedure follows the naming rule for Variables.
arglist A list of variables passed to the procedure as arguments, and their data types. Multiple arguments are separated by commas. Arguments may be Optional, and may be Read Only.

 

The following example is a Private Procedure to print the sum of two numbers on the Form.

Private Sub printSum(ByVal x As Integer, ByVal y As Integer)
     Debug.Print Str(x + y)
End Sub

OPTIONAL ARGUMENTS:

If an argument has the Optional keyword in front of it, then that argument does not have to be provided to the procedure. MsgBox is an example of a procedure that takes optional arguments. If an argument is omitted, the comma must still be used as a placeholder.

The following calls the MsgBox procedure, but omits the second parameter which describes the dialog box.

MsgBox "Hello", , "Greeting"
The following example is a procedure that uses optional arguments to specify a recipient and a sender.
Private Sub greeting(strMessage As String, Optional strRecipient As String, Optional strSender As String)
     If strRecipient <> "" Then
          Debug.Print "To " & strRecipient & ", ";
     End If
     If strSender <> "" Then
          Debug.Print strSender & " sends the message ";
     End If
     Debug.Print strMessage
End Sub

 

The greeting procedure may be called with any of the following:

greeting "Hello, how are you"
greeting "Hello, how are you?", "Computer"
greeting "Hello, how are you?", "Computer", "Gez"
greeting "Hello, how are you?", , "Gez"

READ ONLY ARGUMENTS

The optional parts ByRef and ByVal are used to determine whether an argument is a copy of the variable, or the actual variable. ByRef indicates the variable is passed by reference, and any changes made within the procedure to the variable will be reflected to where the procedure was called.

ByRef is the default in Visual Basic 6, but this is changed in VB.Net. ByVal indicates the variable was passed by value, and any changes made within the procedure to the variable will not be reflected to where the procedure was called as it's only a copy.

This example is a procedure that alters a variable. The actual variable from where it was called will be changed.

Private Sub changeWhereCalled(ByRef num As Integer)
     num = num + 1
     Debug.Print Str(num)
End Sub

 

This example is a procedure that alters a variable, but does not change the value where it was called.

Private Sub noChangeWhereCalled(ByVal num As Integer)
     num = num + 1
     Debug.Print Str(num)
End Sub

 

 

FUNCTIONS

A function is similar to a procedure, except it returns a value to the calling code. The basic Syntax for a function is:

[Private | Public][Static] Function funcName ([arglist]) As Data Type
     ' Procedure body here
     [funcName = expression]
End Function

 

The following example uses the functions "getFormattedDate", "getWeekName" and "getAdornment" to illustrate the use of functions in Visual Basic.

Private Function getFormattedDate(ByVal dateValue As Date) As String
     Dim strDate As String
     strDate = getWeekName(DatePart("w", dateValue))
     strDate = strDate & DatePart("d", dateValue)
     strDate = strDate & getAdornment(DatePart("d", dateValue))
     strDate = strDate & Format(dateValue, "mmmm yyyy")
     getFormattedDate = strDate
End Function
Private Function getWeekName(ByVal day As Integer) As String
     Select Case day
          Case 1
               getWeekName = "Sunday "
          Case 2
               getWeekName = "Monday "
          Case 3
               getWeekName = "Tuesday "
          Case 4
               getWeekName = "Wednesday "
          Case 5
               getWeekName = "Thursday "
          Case 6
               getWeekName = "Friday "
          Case 7
               getWeekName = "Saturday "
     End Select
End Function
Private Function getAdornment(ByVal day As Integer) As String
     Select Case day
          Case 1
               getAdornment = "st "
          Case 2
               getAdornment = "nd "
          Case 3
               getAdornment = "rd "
          Case Else
          getAdornment = "th "
     End Select
End Function

 

 

MODULES

Modules contain procedures or functions that may be called anywhere within the project if they're declared as Public. To add a new module into the current project, either select "Add Module" from the Project menu, or right-click the Project in the Project Explorer and select "Add", then "Module". The module only has one property, Name. The three-letter mnemonic for a Module name is "mod" (eg. modMathRoutines).

 

RECURSION

Procedures and functions may be recursive (may call itself). Each call to itself requires that the current state of the procedure is pushed onto the stack. This is important to remember as it's easy to create a stack overflow, i.e. the stack has ran out of space to place any more data.

The following example calculates the Factorial of a number using recursion. A factorial is a number multiplied by every other integer below itself, down to 1.

For example, the factorial of the number 6 is:

Factorial 6 = 6 * 5 * 4 * 3 * 2 * 1

Therefore the factorial of 6 is 720. It can be seen from the above example that factorial 6 = 6 * factorial 5. Similarly, factorial 5 = 5 * factorial 4, and so on.

The following is the general rule for calculating factorial numbers.

factorial(n) = n * factorial(n-1)

 

The above rule terminates when n = 1, as the factorial of 1 is 1.

Private Function factorial(ByVal Num As Double) As Double
     ' The factorial of 1 is 1, so terminate recursion,
     ' otherwise, implement recursion
     If Num = 1 Then
          Factorial = 1
     Else
          Factorial = Num * Factorial(Num - 1)
     End If
End Function

 

 

Sub Main

Sub Main is a special procedure that may be used by Visual Basic to launch an application. The procedure should be written in a module. The procedure may not be declared using the keyword Private. The Sub Main procedure should be selected as the "Startup Object" in the "Project Properties" from the "Project" menu.

This example uses Sub Main in a Module to prompt for a name. The name is then added to the caption of the Form.
To try this example, add a Module to your project and change the Startup Object in Project Properties to Sub Main. This example uses a form called frmStart. Change it to the name of the Form you want to start.

Public Sub Main()
     Dim strName As String
     strName = InputBox("Enter your name", "Name")
     frmStart.Caption = "Hello " & strName
     frmStart.Show
End Sub
 

 

If you don't find what you are looking for. Please click here to submit your query, our experts will reply soon.

 

News / Updates : New Money Order MLM Plan! First time in INDIA to implement Money Order MLM. New version of Cheque Printing Software is up.



E-mail : sales at virtualsplat dot com
Phone : +91 022 28067978
<