Wednesday, July 7, 2010

Function & Procedure

Functions:-
A VBA function is a lot like a workbook function in an Excel spreadsheet. It performs a calculation and then returns the appropriate result. Functions provide information that is useful in building VBA procedures. In the previous example, the Msgbox function was used to display the path information on the screen.

VBA Functions should not be confused with Function Procedures. A Function Procedure is a series of Visual Basic statements enclosed by the Function and End Function statements. A Function procedure is similar to a Sub procedure, but a function can also return a value. A Function procedure can take arguments, such as constants, variables, or expressions that are passed to it by a calling procedure. If a Function procedure has no arguments, its Function statement must include an empty set of parentheses. A function returns a value by assigning a value to its name in one or more statements of the procedure.

Procedures:-
When you create VBA code inside an Excel workbook it will be stored as a “Module” within the workbook. Unlike, Lotus 1-2-3 macros, these modules are not entered in cells but are still a part of the workbook files. They can only be viewed by using the VBA Editor.


Code within a module is organized into procedures. A procedure tells the application how to perform a specific task. Use procedures to divide complex code tasks into more manageable units. There are three types of VBA procedures: Sub, Function, and Property.

The most common type of procedure is the Sub. A Sub procedure is a series of Visual Basic statements enclosed by the Sub and End Sub statements that performs actions but doesn't return a value. A Sub procedure can take arguments, such as constants, variables, or expressions that are passed by a calling procedure. If a Sub procedure has no arguments, the Sub statement must include an empty set of parentheses. The following is an example of a simple Sub:

Sub Center_Across_Selection()

' Center_Across_Selection Macro
' Macro recorded 4/19/2003 by Carlton Collins
With Selection
.HorizontalAlignment = xlCenterAcrossSelection
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.ShrinkToFit = False
.MergeCells = False
End With
Selection.Style = "Comma"
Selection.Font.Underline = xlUnderlineStyleSingleAccounting
End Sub

No comments: