Saturday, August 29, 2020

Functions in Visual Basic:

The function is capable of returning a value to the calling program what is procedure can't do

Steps to create a function:

Tool -> Add Procedure -> Name ->Type(Function) -> Scope (Private/Public)

Syntax for the function definition is:

Public Function  Function_name()  as return data_type

……….

Statements

………..

End function

Public Function Fact (num as integer) As Long

Dim f, i as Long

f=1

For i = 1 to num

f=f*i

Next i

Fact=f

End Function

Private Sub Command1_Click()

Dim x as Long

x=Fact (5)

Msgbox  x

End Sub

A function can return a value in the following format

function_name =return_value

Calling a function:

Usually, you can call a function procedure you have written yourself the same way call intrinsic Visual Basic function like Abs that is by using its name in an expression

MsgboxFact(4)

It is also possible to call a function just like you would call a sub procedure. Following statement both call the same function.

Call Fact(4)

Or 

Fact 6

When you call a function this way, Visual Basic throw away the return value


No comments:

Post a Comment