Wednesday, December 12, 2012

Define procedures in visual basic


Procedures: Visual Basic application is made up of small, self-contained segments. It will be made up of small segments called procedures. Procedures are useful for implementing repeated tasks, such as frequently used calculations.

The two types of procedures are subroutines and functions.

1.      Subroutines: A subroutine is a block of statements that carries out a well-defined task. The block of statements is placed with a pair of Sub/End Sub statements and can be invoked by name. The following subroutine displays the current date in a Message Box and can be called by its name, ShowDate:

Sub ShowDate()
   MsgBox Date()
End Sub

2.      Functions: A function is similar to a subroutine, but a function returns a result. Subroutines perform a task and don’t report anything to the calling program; functions commonly carry out calculations and report the result. The statements that make up a function are placed in a pair of Function/End Function statements. Moreover, because a function reports a result, it must have a type, for example:

Function NextDay() As Date
   NextDay = Date() + 1
End Function

Argument-Passing Mechanisms: One of the most important procedural issues is the mechanism used to pass arguments. The examples so far have used the default mechanism: passing arguments by reference. The other mechanism is passing by value.

1.      Passing Arguments by Reference: Passing arguments by reference gives the procedure access to the actual variable. The calling procedure passes the address of the variable in memory so that the procedure can change its value permanently.
Function Add(num1 As Integer, num2 As Integer) As Integer
   Add = num1 + num2
   num1 = 0
   num2 = 0
End Function
2.      Passing Arguments by Value: When you pass an argument by value, the procedure sees only a copy of the argument. Even if the procedure changes it, the changes aren’t permanent. The benefit of passing arguments by value is that the argument values are isolated from the procedure, and only the program in which they are declared can change their values. Passing arguments by value requires a bit of extra typing, since this isn’t the default argument-passing mechanism.
Function Degrees(ByVal Celsius as Single) As Single
   Degrees = (9 / 5) * Celsius + 32
End Function