Function and Sub procedures

Function and Sub are part of procedure that help in reusability of the code.
Procedure:
1. Function
2. Sub

In other words, Function and sub contain a set of statement which are common for multiple scenarios.

E.g. Consider 2 scenarios.
1. Checking emails count
2. Delete email

Now, for both the scenarios we have to login first ,then only we can perform these tasks like checking emails count and delete any email.
So, we can put login functionality into the Function or Sub and call them in any script.
Let’s understand these in details.

Sub:
1. Sub are used to perform a particular functionality and support reusability, but does not return any value.
2. Sub can be used with arguments and without arguments.
3. Code is enclosed by Sub and End Sub statements.
4. ‘Call’ statement is used to call the sub, but optional.
5. Without arguments, it must include an empty set of parentheses ().
6. If Sub contains arguments and Call statement is used to call them. Then arguments must be enclosed in        parentheses,otherwise it will throw an syntax error.

E.g.

'Calling the Sub
Call mySub

'Sub without arguements
Public Sub mySub()
Print "It is a sub"
	
End Sub
'Calling the Sub which is doing a addition of 2 numbers
Call mySub(2,4)

'Sub with arguments a,b
Public Sub mySub(a,b)
	a = a+b
    Print "It is a sub"
End Sub
Note: Note:
If Sub has arguments and we call the Sub without using ‘Call’ Statement then it will give the error message.
Error: Can not use parentheses when calling a sub. mySub(2,4)

 

Function:
1. Function are used to perform a particular functionality and support reusability, it can return a value which can be used for some other manipulation or reporting etc.
2. Function can be used with arguments and without arguments.
3. Code is enclosed by Function and End Function statements.
4. ‘Call’ statement is used to call the Function, but optional.
5. Without arguments, it must include an empty set of parentheses ().
6. If Function contains arguments and Call statement is used to call them. Then arguments must be enclosed in        parentheses,otherwise it will throw an syntax error.

 

'Calling the function which is without arguments
Call myFunction()

Function myFunction()
	Print "It is a Function"
End Function
'Calling the function with arguments
rv =  addNumber(2,4)
Print rv

Function addNumber(a,b)
    a=a+b
    'returning value of 'a'. Assign value to the function name
	addNumber = a
End Function
Note: Note:
If Function has arguments and we call the Function without using ‘Call’ Statement then it will give the error message.
Error: Can not use parentheses when calling a sub. mySub(2,4)
Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...