Function procedure is a discrete block of code that is written to accomplish a particular task. The difference between a Sub procedure and Function procedure is that function can return a value.

Syntax:

Function {name} (parameters)

– – – – – –

– – – – – –

– – – – – –

End Function

Example:

'************************************************************************ 'Script demonstrates modularization with function 'Author - Seetaram Hegde '************************************************************************ ' a=inputbox("enter value for 'a'") b=inputbox("enter value for 'b'") op=Inputbox("which arithmetic operation?"&_ "enter numbers for each operation"&vbnewline&_ "1 - Addition"&vbnewline&_ "2 - Subtraction"&vbnewline&_ "3 - Multiplication"&vbnewline&_ "4 - Division") ArithmeticOps a,b,op Function ArithmeticOps(a,b,op) Select Case op Case 1: msgbox "Addition of A & B is : "&cint(a)+cint(b) Case 2: msgbox "Subtraction of B from A is : "&a-b Case 3: msgbox "Multiplication of A & B is : "&a*b Case 4: msgbox "Division of A by B is : "&a/b Case Else: msgbox "Enter proper number for operation (i.e. 1 or 2 or 3 or 4)" End Select End Function

In the previous post I have explained about Sub procedure and used the same example. The difference is I have just replaced the “Sub” with “Function”. It works the same way. But we can write functions which returns value. If a function returns value, then it has to be called as below:

rval=ArithmeticOps(a,b,op)

Here, while calling the function we have used brackets “()” and also we have assigned the return value to a variable. We will re-write the function and make it return a value.

'************************************************************************ 'Script demonstrates the function returning value 'Author - Seetaram Hegde '************************************************************************ ' a=inputbox("enter value for 'a'") b=inputbox("enter value for 'b'") op=Inputbox("which arithmetic operation?"&_ "enter numbers for each operation"&vbnewline&_ "1 - Addition"&vbnewline&_ "2 - Subtraction"&vbnewline&_ "3 - Multiplication"&vbnewline&_ "4 - Division") ans=ArithmeticOps(a,b,op) msgbox "Answer :"&ans Function ArithmeticOps(a,b,op) Select Case op Case 1: ArithmeticOps= cint(a)+cint(b) msgbox "Addition of A & B is : "&cint(a)+cint(b) Case 2: ArithmeticOps=a-b Case 3: ArithmeticOps=a*b Case 4: ArithmeticOps=a/b Case Else: msgbox "Enter proper number for operation (i.e. 1 or 2 or 3 or 4)" End Select End Function

This example shows how to return values in Function procedure in vbscript. As shown in the above code snippet, we need to assign the value to the *name of the function*. So, the returned value is assigned to the variable “ans” and then it is displayed using msgbox.