Dividing the entire software program into smaller chunks of code where each piece handles a specific task is known as modularization. Following are some of the benefits:
- Easy to maintain
- Reusability
- Easier to debug
- More reliable
Hence, all programming languages and scripting languages support modularization. In vbscript modularization can be achieved with two different techniques:
- Functions
- Sub procedures
Sub Procedure:
Syntax:
Sub {name of the Sub procedure} (parameters)
– – – – –
– – – – –
– – – – –
End Sub
To call the Sub procedure in the main script, we need to just type the name of the sub with parameters (if any). Following example demonstrates the declaration and usage of sub procedure.
'************************************************************************ 'Script demonstrates modularization with sub procedure '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 Sub 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 Sub
In the above example, ArithmeticOps is a sub procedure which accepts three parameters (a,b, and op). Depending on the operation provided by the user (op) arithmetic operation will be performed on a & b and the result will be displayed. If the user inputs a wrong number for operation then it throws error saying “need to enter a proper value for op”.
From the above script we can make the following points:
- To call the procedure we need to just mention the name of the sub procedure in main script with parameters (no brackets)
- Sub procedure does not return any value
- Sub procedure may or may not take parameters
In the next post we will try to learn about functions in vbscript.