Function
A function is a group of reusable code which can be called anywhere in your program or excel sheet by its name. function eliminates the need of re-writing the same code over and over again. This enables us to divide a big program into a number of smaller and manageable functions.Difference between function and sub procedure
The difference between a function and a sub in Excel VBA is that a function can return a value while a sub cannot. Functions and subs become very useful as program size increases.
Note − A function can return multiple values separated by a comma as an array assigned to the function name itself.
Syntax
|
Function Function_name(parameter-list)
statements
End Function
|
lets calculate the area of rectangle with the help of the vba function, to declare a function we need to create a procedure starting function keyword at the beginning of the function
|
Function findArea(Length As Double, Width As Double)
findArea = Length * Width
End Function
Sub rect()
Dim a As Double
Dim b As Double
a = 9
b = 7
Debug.Print findArea(a, b)
End Sub
|
Result
Calling function from the excel sheet
0 Comments