Download - Advanced VB Script Guide
[email protected] | Contact: 91+8142402254
www.pavanoltraining.blogspot.in | www.pavantestingtools.blogspot.in
VBScript
Fundamentals
[email protected] | Contact: 91+8142402254
www.pavanoltraining.blogspot.in | www.pavantestingtools.blogspot.in
VBScript Variables
A variable is a convenient placeholder that refers to a computer memory location where we can
store program information that may change during the time our script is running.
Declaring Variables
We declare variables explicitly in our script using the Dim statement,
For example:
Dim city
Dim x
We declare multiple variables by separating each variable name with a comma. For example:
Dim x, Top, Bottom, Left, Right
We can also declare a variable implicitly by simply using its name in our script. That is not
generally a good practice because we could misspell the variable name in one or more places,
causing unexpected results when our script is run. For that reason, the Option Explicit statement is available to require explicit declaration of all variables.
The Option Explicit statement should be the first statement in our script.
Option Explicit
Forces explicit declaration of all variables in a script.
Option Explicit ' Force explicit variable declaration.
Dim MyVar ' Declare variable.
MyInt = 10 ' Undeclared variable generates error.
MyVar = 10 ' Declared variable does not generate error.
Naming Restrictions for Variables
Variable names follow the standard rules for naming anything in VBScript. A variable name:
Must begin with an alphabetic character.
Cannot contain an embedded period.
Must not exceed 255 characters. Must be unique in the scope in which it is declared.
[email protected] | Contact: 91+8142402254
www.pavanoltraining.blogspot.in | www.pavantestingtools.blogspot.in
Scope of Variables
o A variable's scope is determined by where you declare it.
o When we declare a variable within a procedure, only code within that procedure can
access or change the value of that variable.
o If we declare a variable outside a procedure, we make it recognizable to all the
procedures in our script. This is a script-level variable, and it has script-level scope.
Assigning Values to Variables
Values are assigned to variables creating an expression as follows:
The variable is on the left side of the expression and the value you want to assign to the variable is on the right.
For example:
B = 200
City = “Hyderabad”
Scalar Variables and Array Variables
A variable containing a single value is a scalar variable.
A variable containing a series of values, is called an array variable.
Array variables and scalar variables are declared in the same way, except that the declaration
of an array variable uses parentheses () following the variable name.
Example:
Dim A(3)
Although the number shown in the parentheses is 3, all arrays in VBScript are zero-based, so
this array actually contains 4 elements.
We assign data to each of the elements of the array using an index into the array. Beginning at
zero and ending at 10, data can be assigned to the elements of an array as follows:
A(0) = 256
A(1) = 324
A(2) = 100
A(3) = 55
Similarly, the data can be retrieved from any element using an index into the particular array
element you want.
[email protected] | Contact: 91+8142402254
www.pavanoltraining.blogspot.in | www.pavantestingtools.blogspot.in
For example:
SomeVariable = A(4)
Arrays aren't limited to a single dimension. You can have as many as 60 dimensions, although
most people can't comprehend more than three or four dimensions.
In the following example, the MyTable variable is a two-dimensional array consisting of 6 rows
and 11 columns:
Dim MyTable(5, 10)
In a two-dimensional array, the first number is always the number of rows; the second number
is the number of columns.
Dynamic Arrays
We can also declare an array whose size changes during the time our script is running. This
is called a dynamic array.
The array is initially declared within a procedure using either the Dim statement or using the
ReDim statement.
However, for a dynamic array, no size or number of dimensions is placed inside the parentheses.
For example:
Dim MyArray()
ReDimAnotherArray()
To use a dynamic array, you must subsequently use ReDim to determine the number of
dimensions and the size of each dimension.
In the following example, ReDimsets the initial size of the dynamic array to 25. A subsequent
ReDim statement resizes the array to 30, but uses the Preserve keyword to preserve the contents of the array as the resizing takes place.
ReDimMyArray(25)
ReDim Preserve MyArray(30)
[email protected] | Contact: 91+8142402254
www.pavanoltraining.blogspot.in | www.pavantestingtools.blogspot.in
There is no limit to the number of times we can resize a dynamic array, although if we make an
array smaller, we lose the data in the eliminated elements.
VBScript Data Types
VBScript has only one data type called a Variant. A Variant is a special kind of data type that
can contain different kinds of information, depending on how it is used. Because Variant is the only data type in VBScript, it is also the data type returned by all functions in VBScript.
Variant
Beyond the simple numeric or string classifications, a Variant can make further distinctions
about the specific nature of numeric information. For example, we can have numeric
information that represents a date or a time. When used with other date or time data, the
result is always expressed as a date or a time. We can also have a rich variety of numeric
information ranging in size from Boolean values to huge floating-point numbers. These different
categories of information that can be contained in a Variant are called subtypes. Most of the
time, we can just put the kind of data we want in a Variant, and the Variant behaves in a way that is most appropriate for the data it contains.
The following table shows subtypes of data that a Variant can contain.
Subtype Description
Empty Variant is uninitialized. Value is 0 for numeric variables or a zero-length
string ("") for string variables.
Null Variant intentionally contains no valid data.
Boolean Contains either True or False.
Byte Contains integer in the range 0 to 255.
Integer Contains integer in the range -32,768 to 32,767.
Currency -922,337,203,685,477.5808 to 922,337,203,685,477.5807.
Long Contains integer in the range -2,147,483,648 to 2,147,483,647.
Single Contains a single-precision, floating-point number in the range -
3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to
3.402823E38 for positive values.
Double Contains a double-precision, floating-point number in the range -
1.79769313486232E308 to -4.94065645841247E-324 for negative
values; 4.94065645841247E-324 to 1.79769313486232E308 for positive
values.
Date (Time) Contains a number that represents a date between January 1, 100 to
December 31, 9999.
String Contains a variable-length string that can be up to approximately 2 billion
characters in length.
Object Contains an object.
Error Contains an error number.
We can use conversion functions to convert data from one subtype to another.
[email protected] | Contact: 91+8142402254
www.pavanoltraining.blogspot.in | www.pavantestingtools.blogspot.in
VBScript Operators
Operators are used for performing mathematical, comparison and logical operations.
VBScript has a full range of operators, including arithmetic operators, comparison operators, concatenation operators, and logical operators.
Arithmetic Operators:
Operator Description
1) Exponentiation Operator (^) Raises a number to the power of an exponent.
2) Multiplication Operator (*) Multiplies two numbers.
3) Division Operator (/) Divides two numbers and returns a floating-point result.
4) Integer Division Operator (\) Divides two numbers and returns an integer result.
5) Mod Operator Divides two numbers and returns only the remainder.
6) Addition Operator (+) Sums two numbers.
7) Subtraction Operator (-) Finds the difference between two numbers or indicates the
negative value of a numeric expression.
8) Concatenation Operator (&) Forces string concatenation of two expressions.
Comparison Operators
Used to compare expressions.
Operator Description Operator Description
1) = Equal to 5) <= Less than or equal to
2) <> Not equal to 6) >= Greater than or equal to
3) < Less than 7) Is Object equivalence
4) > Greater than
Concatenation Operators
Operator Description
1) Addition Operator
(+)
Sums two numbers.
If Then
1) Both expressions are numeric Add.
2) Both expressions are strings Concatenate.
3) One expression is numeric and the
other is a string
Add.
2) Concatenation
Operator (&)
Forces string concatenation of two expressions.
[email protected] | Contact: 91+8142402254
www.pavanoltraining.blogspot.in | www.pavantestingtools.blogspot.in
Logical Operators
Operator Description Syntax
Not Performs logical negation on an
expression.
result= Not expression
And Performs a logical conjunction on two
expressions.
result= expression1 And
expression2
Or Performs a logical disjunction on two
expressions.
result= expression1 Or
expression2
Eqv Performs a logical equivalence on two expressions.
result= expression1
Eqvexpression2
Input/ Output Operations
InputBox() Function
Displays a prompt in a dialog box, waits for the user to input text or click a button, and returns
the contents of the text box.
Example:
Dim Input
Input = InputBox("Enter your name")
MsgBox ("You entered: " & Input)
MsgBox Function
Displays a message in a dialog box, waits for the user to click a button, and returns a value
indicating which button the user clicked.
Syntax:
MsgBox(prompt, buttons, title)
Prompt :String expression displayed as the message in the dialog box.
Buttons: the icon style to use.
Title: String expression displayed in the title bar of the dialog box.
[email protected] | Contact: 91+8142402254
www.pavanoltraining.blogspot.in | www.pavantestingtools.blogspot.in
Button Settings:
Msgbox Return value
Example:
Dim MyVar
MyVar = MsgBox ("Hello World!", 64, "MsgBox Example")
' MyVar contains either 1 or 2, depending on which button is clicked.
[email protected] | Contact: 91+8142402254
www.pavanoltraining.blogspot.in | www.pavantestingtools.blogspot.in
VBScript Constants
A constant is a meaningful name that takes the place of a number or string and never changes.
Creating Constants
We create user-defined constants in VBScript using the Const statement. Using the Const
statement, we can create string or numeric constants with meaningful names and assign them literal values.
Const statement
Declares constants for use in place of literal values.
Example:
ConstMyString = "This is my string."
ConstMyAge = 49
ConstCutoffDate = #6-1-97#
Note thatString literal is enclosed in quotation marks (" ").
Represent Date literals and time literals by enclosing them in number signs (#).
We declare multiple constants by separating each constant name and value with a comma. For example:
Const price= 100, city= “Hyderabad”, x= 27
[email protected] | Contact: 91+8142402254
www.pavanoltraining.blogspot.in | www.pavantestingtools.blogspot.in
Conditional Statements
We can control the flow of our script with conditional statements and looping statements.
Using conditional statements, we can write VBScript code that makes decisions and repeats actions. The following conditional statements are available in VBScript:
1) If…Then…Else Statement
2) Select Case Statement
Making Decisions Using If...Then...Else
The If...Then...Else statement is used to evaluate whether a condition is True or False and,
depending on the result, to specify one or more statements to run. Usually the condition is an
expression that uses a comparison operator to compare one value or variable with another.
If...Then...Else statements can be nested to as many levels as you need.
Running a Statements if a Condition is True (single statement)
To run only one statement when a condition is True, use the single-line syntax for the
If...Then...Else statement.
Dim myDate
myDate = #2/13/98#
If myDate< Now Then
myDate = Now
Running Statements if a Condition is True(multiple statements)
To run more than one line of code, we must use the multiple-line (or block) syntax. This syntax
includes the End If statement.
Dim x
x= 20
If x>10 Then
msgbox "Hello Pavan"
msgbox "x value is: "&x
msgbox "Bye Bye"
End If
[email protected] | Contact: 91+8142402254
www.pavanoltraining.blogspot.in | www.pavantestingtools.blogspot.in
Running Certain Statements if a Condition is True and Running Others if a Condition is
False
We can use an If...Then...Else statement to define two blocks of executable statements: one
block to run if the condition is True, the other block to run if the condition is False.
Example:
Dim x
x= Inputbox (" Enter a value")
If x>100 Then
Msgbox "Hello Pavan"
Msgbox "X is a Big Number"
Msgbox "X value is: "&X
Else
Msgbox "PAVAN"
Msgbox "X is a Small Number"
Msgbox "X value is: "&X
End If
Deciding Between Several Alternatives
A variation on the If...Then...Else statement allows us to choose from several alternatives.
Adding ElseIf clauses expands the functionality of the If...Then...Else statement so we can
control program flow based on different possibilities.
Example:
Dim x
x= Inputbox (" Enter a value")
If x>0 and x<=100 Then
Msgbox "Hello Pavan"
Msgbox "X is a Small Number"
Msgbox "X value is "&x
Else IF x>100 and x<=500 Then
Msgbox "Hello PAVAN"
Msgbox "X is a Medium Number"
Else IF x>500 and x<=1000 Then
Msgbox "Hello Pavan"
Msgbox "X is a Large Number"
Else
Msgbox "Hello Sir"
Msgbox "X is a Grand Number"
End If
End If
End If
[email protected] | Contact: 91+8142402254
www.pavanoltraining.blogspot.in | www.pavantestingtools.blogspot.in
Executing a certain block of statements when two / more conditions are True
(Nested If...)
Example:
Dim State, Region
State=Inputbox ("Enter a State")
Region=Inputbox ("Enter a Region")
If state= "AP" Then
If Region= "Telangana" Then
msgbox "Hello Pavan"
msgbox "Dist count is 10"
Else if Region= "Rayalasema" Then
msgbox "Hello PAVAN"
msgbox "Dist count is 4"
Else If Region= "Costal" Then
msgbox "Hello Pavan"
msgbox "Dist count is 9"
End If
End If
End If
End If
Making Decisions with Select Case
The Select Case structure provides an alternative to If...Then...ElseIf for selectively
executing one block of statements from among multiple blocks of statements. A Select Case
statement provides capability similar to the If...Then...Else statement, but it makes code more efficient and readable.
Example:
Option explicit
Dim x,y, Operation, Result
x= Inputbox (" Enter x value")
y= Inputbox ("Enter y value")
Operation= Inputbox ("Enter an Operation")
Select Case Operation
Case "add"
Result= cdbl (x)+cdbl (y)
Msgbox "Hello Pavan"
Msgbox "Addition of x,y values is "&Result
Case "sub"
Result= x-y
[email protected] | Contact: 91+8142402254
www.pavanoltraining.blogspot.in | www.pavantestingtools.blogspot.in
Msgbox "Hello Pavan"
Msgbox "Substraction of x,y values is "&Result
Case "mul"
Result= x*y
Msgbox "Hello Pavan"
Msgbox "Multiplication of x,y values is "&Result
Case "div"
Result= x/y
Msgbox "Hello Pavan"
Msgbox "Division of x,y values is "&Result
Case "mod"
Result= x mod y
Msgbox "Hello Pavan"
Msgbox "Mod of x,y values is "&Result
Case "expo"
Result= x^y
Msgbox "Hello Pavan"
Msgbox"Exponentation of x,y values is "&Result
Case Else
Msgbox "Hello Pavan"
msgbox "Wrong Operation"
End Select
[email protected] | Contact: 91+8142402254
www.pavanoltraining.blogspot.in | www.pavantestingtools.blogspot.in
Other Examples
Write a program for finding out whether the given year is a leap year or not?
Dim xyear
xyear=inputbox ("Enter Year")
If xyear mod 4=0 Then
msgbox "This is a Leap year"
Else
msgbox "This is NOT"
End If
Write a program for finding out whether the given number is, Even number or Odd
number?
Dim num
num=inputbox ("Enter a number")
If num mod 2=0 Then
msgbox "This is a Even Number"
Else
msgbox "This is a Odd Number"
End If
Read two numbers and display the sum?
Dim num1,num2, sum
num1=inputbox ("Enter num1")
num2=inputbox ("Enter num2")
sum= Cdbl (num1) + Cdbl (num2) 'if we want add two strings conversion require
msgbox ("Sum is " &sum)
Read P,T,R values and Calculate the Simple Interest?
Dim p,t, r, si
p=inputbox ("Enter Principle")
t=inputbox ("Enter Time")
r=inputbox ("Enter Rate of Interest")
si= (p*t*r)/100 ' p= principle amount, t=time in years, r= rate of interest
msgbox ("Simple Interest is " &si)
Read Four digit number, calculate & display the sum of the number or display Error
message if the number is not a four digit number?
Dim num, sum
num=inputbox ("Enter a Four digit number")
If Len(num) = 4 Then
sum=0
[email protected] | Contact: 91+8142402254
www.pavanoltraining.blogspot.in | www.pavantestingtools.blogspot.in
sum=sum+num mod 10
num=num/10
num= left (num, 3)
sum=sum+num mod 10
num=num/10
num= left (num, 2)
sum=sum+num mod 10
num=num/10
num= left (num, 1)
sum=sum+num mod 10
msgbox ("Sum is " &sum)
else
msgbox "Number, you entered is not a 4 digit number"
End If
Read any Four digit number and display the number in reverse order?
Dim num,rev
num= inputbox("Enter a number")
If len(num)=4 Then
rev=rev*10 + num mod 10
num=num/10
num= left(num,3)
rev=rev*10 + num mod 10
num=num/10
num= left(num,2)
rev=rev*10 + num mod 10
num=num/10
num= left(num,1)
rev=rev*10 + num mod 10
msgbox "Reverse Order of the number is "&rev
Else
msgbox "Number, you entered is not a 4 digit number"
End If
Read 4 subjects marks; calculate the Total marks and grade?
(a) If average marks Greater than or equal to 75, grade is Distinction
b) If average marks Greater than or equal to 60 and less than 75 , then grade is First
c) If average marks Greater than or equal to 50 and less than 60 , then grade is
Second
d) If average marks Greater than or equal to 40 and less than 50 , then grade is Third
e) Minimum marks 35 for any subject, otherwise 'no grade fail')
Dim e,m,p,c, tot
e=inputbox ("Enter english Marks")
m=inputbox ("Enter maths Marks")
[email protected] | Contact: 91+8142402254
www.pavanoltraining.blogspot.in | www.pavantestingtools.blogspot.in
p=inputbox ("Enter physics Marks")
c=inputbox ("Enter chemistry Marks")
tot= cdbl(e) + cdbl(m) + cdbl(p) + cdbl(c)
msgbox tot
If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot >=300 Then
msgbox "Grade is Distinction"
else If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot >=240
and tot<300 Then
msgbox "Grade is First"
else If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot >=200
and tot<240 Then
msgbox "Grade is Second"
else If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot >=160
and tot<200 Then
msgbox "Grade is Third"
else
msgbox "No Grade, Fail"
End If
End If
End If
End If
Display Odd numbers up to n?
Dim num,n
n=Inputbox ("Enter a Vaule")
For num= 1 to n step 2
msgboxnum
Next
Display Even numbers up to n
Dim num,n
n=Inputbox ("Enter a Vaule")
For num= 2 to n step 2
msgboxnum
Next
Display Natural numbers in reverse order up to n?
Dim num,n
n=Inputbox ("Enter a Vaule")
For num=n to 1 step -1
msgboxnum
Next
[email protected] | Contact: 91+8142402254
www.pavanoltraining.blogspot.in | www.pavantestingtools.blogspot.in
Display Natural numbers sum up to n? (Using For...Next Loop)
Dim num, n, sum
n= inputbox ("Enter a Value")
sum=0
For num= 1 to n step 1
sum= sum+num
Next
msgbox sum
Display Natural numbers sum up to n? (Using While...Wend Loop)
Dim num, n, sum
n= inputbox ("Enter a Value")
While num<=cdbl (n)
sum= sum+num
num=num+1
Wend
msgbox sum
Display Natural numbers sum up to n? (Using Do...Until...Loop)
Dim num, n, sum
n= inputbox ("Enter a Value")
sum=0
num=1
Do
sum= sum+num
num=num+1
Loop Until num =cdbl (n+1)
msgbox sum
Write a Function for Natural Numbers sum up to n
Function NNumCou (n)
Dim num, sum
sum=0
For num= 1 to n step 1
sum= sum+num
Next
msgbox sum
End Function
[email protected] | Contact: 91+8142402254
www.pavanoltraining.blogspot.in | www.pavantestingtools.blogspot.in
Verify weather the entered value is a 10 digit value or not and Numeric value or not?
(using multiple if conditions)
Dim a,x,y,z,num
num=Inputbox ("Enter a Phone Number")
d1= left (num,1)
d10=Right (num,1)
d2=mid (num, 2, len (1))
d3=mid (num, 3, len (1))
d4=mid (num, 4, len (1))
d5=mid (num, 5, len (1))
d6=mid (num, 6, len (1))
d7=mid (num, 7, len (1))
d8=mid (num, 8, len (1))
d9=mid (num, 9, len (1))
If len (num) =10 Then
If isnumeric (d1) = "True" and isnumeric (d2) = "True" and isnumeric (d3) = "True" and
isnumeric (d4) = "True"andisnumeric (d5) = "True"andisnumeric (d6) = "True"andisnumeric
(d7) = "True"andisnumeric (d8) = "True"andisnumeric (d9) = "True"andisnumeric (d10) =
"True" Then
msgbox "It is a Numeric Value"
End If
End If
If len (num) <> 10 Then
Msgbox "It is NOT valid Number "
End If
[email protected] | Contact: 91+8142402254
www.pavanoltraining.blogspot.in | www.pavantestingtools.blogspot.in
Looping Through Code
Looping allows us to run a group of statements repeatedly.
Some loops repeat statements until a condition is False;
Others repeat statements until a condition isTrue.
There are also loops that repeat statements a specific number of times.
The following looping statements are available in VBScript:
1. Do...Loop: Loops while or until a condition is True.
2. While...Wend: Loops while a condition is True.
3. For...Next: Uses a counter to run statements a specified number of times.
4. For Each...Next: Repeats a group of statements for each item in a collection or each
element of an array.
Using Do Loops
We can use Do...Loop statements to run a block of statements an indefinite number of times. The statements are repeated either while a condition is True or until a condition becomes True.
Repeating Statements While a Condition is True
Repeats a block of statements while a condition is True or until a condition becomes True
a) Do While condition
Statements
-----------
-----------
Loop
Or, we can use this below syntax:
Example:
Dim x
Do While x<5 x=x+1
Msgbox "Hello Pavan"
Msgbox "Hello UFT"
Loop
b) Do
Statements
-----------
-----------
LoopWhile condition
[email protected] | Contact: 91+8142402254
www.pavanoltraining.blogspot.in | www.pavantestingtools.blogspot.in
Example:
Dim x
x=1
Do
Msgbox "Hello Pavan"
Msgbox "Hello UFT"
x=x+1
Loop While x<5
Repeating a Statement until a Condition Becomes True
c) Do Until condition
Statements
-----------
-----------
Loop
Or, we can use this below syntax:
Example:
Dim x
Do Until x=5 x=x+1
Msgbox "Pavan"
Msgbox "Hello UFT"
Loop
Or, we can use this below syntax:
d) Do
Statements
-----------
-----------
LoopUntil condition
Or, we can use this below syntax:
Example:
Dim x
x=1
Do
Msgbox “Hello Pavan”
Msgbox "Hello UFT"
x=x+1
Loop Until x=5
[email protected] | Contact: 91+8142402254
www.pavanoltraining.blogspot.in | www.pavantestingtools.blogspot.in
While...Wend Statement
Executes a series of statements as long as a given condition is True.
Syntax:
While condition
Statements
-----------
-----------
Wend
Example:
Dim x
x=0
While x<5 x=x+1
msgbox "Hello Pavan"
msgbox "Hello UFT"
Wend
For...Next Statement
Repeats a group of statements a specified number of times.
Syntax:
Forcounter= starttoend [Stepstep]
statements
Next
Example:
Dim x
For x= 1 to 5 step 1
Msgbox "Hello Pavan"
Next
For Each...Next Statement
Repeats a group of statements for each element in an array or collection.
[email protected] | Contact: 91+8142402254
www.pavanoltraining.blogspot.in | www.pavantestingtools.blogspot.in
Syntax:
For Each itemInarray
Statements
Next
Example:
Dim a,b,x (3)
a=20
b=30
x(0)= "Addition is "&a+b
x(1)="Substraction is " & a-b
x(2)= "Multiplication is " & a*b
x(3)= "Division is " & a/b
For Each element In x
msgbox element
Next
Example:
MyArray = Array("one","two","three","four","five")
For Each element In MyArray
msgbox element
Next
[email protected] | Contact: 91+8142402254
www.pavanoltraining.blogspot.in | www.pavantestingtools.blogspot.in
VBScript Procedures
In VBScript, there are two kinds of procedures; the Sub procedure and the Functionprocedure.
Sub Procedures
A Sub procedure is a series of VBScript statements (enclosed by Sub and End Sub statements) that perform actions but don't return a value.
A Sub procedure can take arguments (constants, variables, or expressions that are passed by a
calling procedure).
If a Sub procedure has no arguments, its Sub statement must include an empty set of parentheses ().
Syntax:
SubProcedure name ()
Statements
-----------
-----------
End Sub
(Or)
SubProcedure name (argument1, argument2)
Statements
-----------
-----------
End Sub
Example: 1
Sub ConvertTemp()
temp = InputBox("Please enter the temperature in degrees F.", 1)
MsgBox "The temperature is "& Celsius(temp) & " degrees C."
End Sub
[email protected] | Contact: 91+8142402254
www.pavanoltraining.blogspot.in | www.pavantestingtools.blogspot.in
Function Procedures
A Function procedure is a series of VBScript statements enclosed by the Function and End
Function statements.
A Function procedure is similar to a Sub procedure, but can also return a value.
A Function procedure can take arguments (constants, variables, or expressions that are passed to it by a calling procedure).
If a Function procedure has no arguments, its Function statement must include an empty set of parentheses.
A Function returns a value by assigning a value to its name in one or more statements of the procedure. The return type of a Function is always a Variant.
Syntax:
FunctionProcedure name ()
Statements
-----------
-----------
End Function
Or
FunctionProcedure name (argument1, argument2)
Statements
-----------
-----------
End Function
[email protected] | Contact: 91+8142402254
www.pavanoltraining.blogspot.in | www.pavantestingtools.blogspot.in
Example: 1
FunctionCelsius(fDegrees)
Celsius = (fDegrees - 32) * 5 / 9
End Function
Example: 2
Functioncal(a,b,c)
cal = (a+b+c)
End Function
Using Sub and Function Procedures in Code
A Function in our code must always be used on the right side of a variable assignment or in an expression.
For example:
Temp = Celsius(fDegrees)
-Or-
MsgBox "The Celsius temperature is "& Celsius(fDegrees) & " degrees."
To call a Sub procedure from another procedure, type the name of the procedure along with values for any required arguments, each separated by a comma.
The Call statement is not required, but if you do use it, you must enclose any arguments in
parentheses.
The following example shows two calls to the MyProc procedure. One uses the Call statement in the code; the other doesn't. Both do exactly the same thing.
Call MyProc(firstarg, secondarg)
MyProcfirstarg, secondarg
**Notice that the parentheses are omitted in the call when the Call statement isn't used.
[email protected] | Contact: 91+8142402254
www.pavanoltraining.blogspot.in | www.pavantestingtools.blogspot.in
ByRef and ByVal Parameters
When you call a subroutine or function, each argument can be passed by
reference or by value.
When an argument is passed by reference, the called procedure can change the value of
the variable. The change persists after the procedure is called.
When an argument is passed by value, any changes that the called procedure makes to
the value of the variable do not persist after the procedure is called.
In a Sub or Function declaration, each parameter can be specified as ByRef or ByVal. If
neither is specified, the default is ByRef.
If ByVal is specified, the corresponding argument is always passed by value when the
subroutine is called.
Below are few simple but quite important differences between passing values byByRef or
ByVal.
ByRef ByVal
Function fun_1( ByRef var_1)
var_1= var_1+ 1
End Function
Dim x: x = 3
'Pass parameter to the function ByRef
fun_1 x
MsgBox x
Result is 4
Function fun_1( ByVal var_1)
var_1= var_1+ 1
End Function
Dim x: x = 3
'Pass parameter to the function ByVal
fun_1 x
MsgBox x
Result is 3
Another way to pass parameter ByRef
Function fun_1( var_1)
var_1= var_1+ 1
End Function
Dim x: x = 3
'Pass parameter to the function ByRef
call fun_1 (x)
MsgBox x
Result is 4
Another way to pass parameter ByVal
Function fun_1( var_1)
var_1= var_1+ 1
End Function
Dim x: x = 3
'Pass parameter to the function ByVal
call fun_1 ((x))
MsgBox x
Result is 3
Function abc(a)
if Not IsArray(a) Then Exit Function
a(0) = "Text"
Function abc(a)
if Not IsArray(a) Then Exit Function
a(0) = "Text"
[email protected] | Contact: 91+8142402254
www.pavanoltraining.blogspot.in | www.pavantestingtools.blogspot.in
End Function
Dim w(2), x
For x = 0 To 2
W(x)= x
Next
call abc(w)
for i=0 to UBOUND (w)
Wscript.Echo w(i)
Next
Shows Text,1 and 2
End Function
Dim w(2), x
For x = 0 To 2
W(x)= x
Next
call abc((w))
for i=0 to UBOUND (w)
Wscript.Echo w(i)
Next
Shows 0,1 and 2
Example 1 - passing arguments by ByRef and ByVal
Sub PassArgs(ByRef x, ByVal y, z)
x = 10
y = 11
z = 12
End Sub
Dim a, b, c
PassArgs a, b, c
Msgbox a „shows 10
Msgbox b „shows empty messagebox
Msgbox c „shows 12
Here 3 global variables are used as arguments. The first parameter is declared ByRef, and so
the variable becomes 10 when the assignment statement x= 10 executes. The second
parameter is declared ByVal, and so the varibale b is unaltered by the PassArgs procedure. The
third parameter uses default parameter passing. Because the argument is a varibale, the
argument is passed by reference, and the assignment statement z= 12 does alter the value of
the variable c.
Example 2 - passing arguments by ByRef and ByVal
Sub PassArgs(ByRef x, ByVal y, z)
x = 10
y = 11
z = 12
End Sub
PassArgs 1, 2, 3
Here three expressions (actually just numbers) are used as arguments. Using expressions as
arguments forces VBScript to pass the arguments by value regardless of the procedure
declaration.
[email protected] | Contact: 91+8142402254
www.pavanoltraining.blogspot.in | www.pavantestingtools.blogspot.in
Example 3 - passing arguments by ByRef and ByVal
Sub PassArgs(ByRef x, ByVal y, z)
x = 10
y = 11
z = 12
End Sub
Dim a, b, c
PassArgs (a), (b), (c)
Msgbox a „shows empty messagebox
Msgbox b „shows empty messagebox
Msgbox c „shows empty messagebox
For more details about VBScript:
http://msdn.microsoft.com/en-us/library/0ad0dkea(v=vs.84).aspx