Saturday 29 March 2014

Sub Procedures in VBScript

Sub procedures are used to perform the specific task. Sub procedures are used to increase the reusability of the code.

Simple example of the procedure


Suppose you want to find the sum of 2 numbers. Without procedures, you will write below code.

a = 10
b = 20
c = a+ b
Msgbox c

To add another 2 different numbers, you will use below code

a = 33
b = 65
c = a+ b
Msgbox c

In above examples, we have to add 2 numbers. So the operation is same (Repeating) So we can write the procedure which will take 2 parameters as shown below.

sub sum(byref a, byref b)

    msgbox cint(a) + cint(b)

end sub

Calling procedures in VBScript

To call the procedures we can use below statements.

Call sum(10,20)
Call sum(33,65)

Thus we can call procedures many times in the code. This reduces the lines of code as well as maintainability of the code.

Passing arguments to the procedure

We can pass the arguments to the procedure by 2 ways.
  1. Pass by reference 
  2. Pass by value

Pass by reference

By default, values are passed to the procedure by reference. When we pass the values by reference the changes made to the variables in the called procedure are reflected in the calling procedure.

a = 10
call findsqr(a)
msgbox a  'prints 100

sub findsqr(byref a)

  a = a*a

  msgbox a   'prints 100

end sub


Pass by value

When we pass the values by value, the changes made to the variables in the called procedure are not reflected in the calling procedure.

a = 10
call findsqr(a)
msgbox a  'prints 10

sub findsqr(byval a)

  a = a*a

  msgbox a   'prints 100

end sub




No comments:

Post a Comment

Total Pageviews