VBScript User Defined Functions

VBScript has two types of User-defined functions –

1. Sub Procedure
2. Function Procedure

Sub Procedure:

It is a series of statements, enclosed by Sub and End Sub statements.

It performs actions, but does NOT return a value.

It can take arguments. If there are no arguments then it should include an empty set of parentheses.

Syntax:

Sub Mysub(argument1, argument2,...) (No arguments - Mysub())
   'Set of statements
End Sub

Function Procedure:

It is a series of statements, enclosed by Function and End Function statements.

It performs actions and returns a value.

It can take arguments. If there are no arguments then it should include an empty set of parentheses.

In VBScript Functions, the value to be returned would be stored in the function name itself.

Syntax:

Function Myfunction(argument1, argument2,...) (No arguments - Myfunction())
   'Set of statements
   Myfunction = some value
End Function

Call Statement in VBScript:

Call statement is used to call functions or subs in VBScript. We can also call functions or subs without using Call statement.

But there are few important things to be noted when calling functions or subs either with or without Call statement -

1. When calling with Call statement - Arguments required for Function/Sub should be passed within parentheses. Otherwise an error "Expected end of statement" would be displayed.

Ex: Assume that the function/sub "Sample(a,b)" is already defined.

Call Sample(1,2) 'Correct way of calling with Call statement
Call Sample 1,2  'Wrong way of calling with Call statement. Error would be displayed

2. When calling without Call statement - Arguments required for Function/Sub should be passed without parentheses. Otherwise an error "Cannot use parentheses when calling a Sub" would be displayed.

Ex: Assume that the function/sub "Sample(a,b)" is already defined.

Sample 1,2 'Correct way of calling without Call statement
Sample(1,2) 'Wrong way of calling without Call statement. Error would be displayed

3. When returning values – Function calling should not have Call statement while returning values. Arguments required for Function should be passed within parentheses.

Ex: Assume that the function/sub "Sum(a,b)" is already defined.

a = Sum(1,2) 'Correct way of calling
a = Call Sum(1,2) 'Wrong way of calling. Syntax Error would be displayed
a = Sum 1,2 ' Wrong way of calling. Expected End of Statement Error would be displayed

No comments:

Post a Comment