Friday, April 16, 2010

VB Scripting - Passing an argument by reference- byref

Previous21222324252627282930Next

The scope of a variable can be changed in VB Script using parameters associated with the arguments. Passing an argument by reference using byref in VB will destroy the previous assigned value to the variable.


An argument is always defined by parameters either by reference or by value depending upon how it is declared in the function or procedure.

If a value is passed into a function as an argument by reference then the value of that variable is passed to the function. If the value of that variable is changed inside the function it would impact the original value. In other words the original value is replaced by this value.

Let’s take an example and try to understand what happens when a value to an argument is passed by reference.

x= CINT(Inputbox("Enter a number"))
aaamsgbox "The value outside the function is: "&x
myfunc x
aaamsgbox "The value which is again outside the function is: "&x
Function myfunc (byref x)
aaax=30
aaamsgbox "The value inside the function is: "&x
End Function

First the x is assigned as 20 and the msgbox in the second line prints 20.

The value outside the function is: 20

Then the ‘myfunc’ function is called in line 3 and this function call executes the function from line 5. Since in the Function definition locally we have assigned x value as 30 so the msgbox will print 30 and the function is terminated.

The value inside the function is: 30


Then the line 4 which is after the function call ‘myfunc’ is executed and the msgbox prints x value as 30 because the global variable x value is overwritten with the local value and prints 30. Since we are using the argument by reference after the function is called the value of x is 30 and since it is by reference the value of x permanently becomes 30

The value which is again outside the function is: 30


Another way of calling an argument value by reference

Int1=CINT(Inputbox("Enter value one"))
Int2=CINT(Inputbox("Enter value two"))

Function multiply (byval Int1, byval Int2, byref prod)
aaaProd = Int1*Int2
End Function
Multiply Int1, Int2, x
aaamsgbox"The product of Value one and two is: "&x

Assignment: Convert all the previous written scripts like Fibonacci series, Prime number Generation, Odd number generation, conversion from centigrade to Fahrenheit, Addition, Multiplication etc using functions in VB Script.

Note: Use Inputbox to as the user choice to perform what operation is required. Create Function calls and then Use Select Case to select the particular function based on the user choice.

For Answer Please Click Here

Previous21222324252627282930Next

No comments:

Post a Comment