Friday, April 16, 2010

VB Scripting - Passing an argument by Value using byval

Previous21222324252627282930Next

The scope of a variable can be changed in VB Script using parameters associated with the arguments. Passing an argument by value using byval in VB creates a copy of 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 variable is passed as an argument by value then a copy of that variable is created in the memory and is passed into the function. The scope of this new variable is local to the function which implies that this variable will be destroyed at the end of the function. Lets look at one example to understand what it means by byval or passing an argument by value.

x=CINT(Inputbox20("Enter any Value"))
aaamsgbox "The value outside the function is: "&x
myfunc x
aaamsgbox "The value which is again outside the function is: "&x
Function myfunc (byval x)
aaax=30
aaamsgbox "The value inside the function is: "&x
End Function

Let’s debug line by line.
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 20 because the local variable x value is overwritten with the global value and prints 20.

The value which is again outside the function is: 20

Let us look at another example where you can use the name of the function as a variable name inside the function definition and call that function.

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

Function multiply(byval Int1, byval Int2)
aaamultiply = Int1*Int2
End Function
aaamsgbox "The product of Value one and two is: "&multiply(Int1, Int2)

You can write in this way by assigning the function call to a variable and then passing the variable in the msgbox to print the value. The modified code will be like this

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

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

Previous21222324252627282930Next

No comments:

Post a Comment