VB Script Procedures and Functions

2
289
functions of VbScript or UFT
functions of VbScript or UFT
Spread the love

VB Script Procedures and Functions:

Both procedures and functions are basic block of codes which gives the modularization concept as well as re-usability concept.They allow us to break down the larger complex code into small reusable chunk of codes.

The block of code is a logical grouping of related tasks.They have certain structure. Calling a named block with or without argument is a contract between user and the named block.Once the contract is fulfilled the user can call the block of code to perform the action.

This approach of modularization increases the readability, re-usability and understandability . It is a very important concept while building automation framework.

In VBScript, there are two kinds of modularization techniques available.They are:

  • Sub procedure
  • Function

Naming convention of Sub and Functions:

  • The name should be clear.
  • The name should have a purpose.
  • We need to use verb Noun composition to create a name.

Sub Procedures:

A Sub procedure is a named block of 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 ().There is an alternative implementation also. It says that if the sub does not have any argument,there is no need to provide parentheses(). We can follow any one approach.

Syntax of Sub:


(public|private )Sub ProcedureName ()
Statements
-----------
-----------
End Sub
 

Or


(public|private )Sub ProcedureName(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
 

Function:

A Function is a named block of 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.The return type of a function is a variant.We can define the datatype as well.learn more about datatype to understand return type.

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.However returning a value from function is purely an optional step.

Syntax of Function:


(public|private)Function FunctionName ()
Statements
-----------
-----------
FunctionName =returnValue
End Function
 

Or


(public|private)Function FunctionName (argument1, argument2....argumentN)
Statements
-----------
-----------
FunctionName =returnValue
End Function
 

Example: 1


Function Celsius(fDegrees)
Celsius = (fDegrees - 32) * 5 / 9
End Function
 

Example: 2


Function cal(a,b,c)
cal = (a+b+c)
End Function
 

Why Public or Private is needed?

Public or Private are access control.They are useful while working with class.However in a single .VBS file they does not imply anything. By default all functions or procedures are public. However while working with class they play a significant role.

Getting Data into and out of Procedures or function:

  • Each piece of data is passed into our procedures using an argument.
  • Arguments serve as placeholders for the data we want to pass into our procedure. We can name our arguments any valid variable name.
  • When we create a procedure using either the Sub statement or the Function statement, parentheses must be included after the name of the procedure.
  • Any arguments are placed inside these parentheses, separated by commas.
READ  How to Work With Runtime Objects in VBScript or UFT ?

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)
MyProc firstarg, secondarg
 

Notice that the parentheses are omitted in the call when the Call statement isn’t used.

Note:

  • We can call a sub from function and alternatively we can call a function from Sub.
  • VBscript does not support varargs as java but supports optional arguments.All functions and subs can take optional argument and optional argument must appear at last in the argument list.
  • For arguments we need to mention the mandatory argument first followed by optional arguments.

How to exit from Function or Sub?

The keyword to exit from function is Exit Function and Sub is Exit Sub.The exit Function or Exit Sub keyword will terminate the execution and come out of the function or sub.Once the Exit Function or Exit sub is encountered by WSH the control goes back to the position from where the function or procedure is called with a return value in case of Function.

In general Exit Function and Exit sub does not play a significant role but while using in a loop, they become super relevant.

VB Script Built in Functions

Types of Functions
o Conversions
o Dates/Times
o Formatting Strings
o Input/Output
o Math
o Miscellaneous
o Rounding
o Strings
o Variants

Here are the set of functions that the VBScript or UFT engineers must know.

Asc Function

Returns ANSI character code corresponding to first letter in a string.


Syntax:
Asc(string As String) As Integer
Calling:
n = Asc(string)

Note: if the String is of zero length it will throw an error.

Example:


Dim val
val="hyderabad"
' it treats as H
val=Asc(val)
msgbox val

Chr Function

Returns the character associated with the specified ANSI character code.

Example:

Dim val
val=65
val=Chr(val)
msgbox val 
'Output: A

Date Function

It returns current system Date

Example:

Dim myDate
myDate=Date
msgbox myDate

Abs Function

It returns absolute value of the given number. The absolute value is magnitude free. That is for -1 and 1 if we operate Abs function, both will return 1.

Syntax:
Abs(number As Double) As Double
Calling:
number = Abs(givenNumber)

Example:

Dim num
num=157.56
num=Abs(num)
msgbox num 'Output: 157.56
num=-157.56num=Abs(num)msgbox num 'Output: 157.56
Note: It provide positive value

Array Function

We can enter list of values using this function and gets an array out of it. The resultant array will be of one dimension.


Syntax:
Array(arglist As Variant) As Array
Calling:
a = Array(arglist)

Just in case the arglist is zero length, it will create a zero length array.
Example:

Dim var
'List of strings
var=Array("Kolkata","Howrah", "Hoogly")
msgbox var(0) 'output: Kolkata
msgbox var(1) 'output: Howrah
msgbox var(2) 'output: Hoogly

another one


'List of numeric values 
var=Array(100,200, 300) 
msgbox var(0) 'output: 100 
msgbox var(1) 'output: 200
msgbox var(2) 'output: 300 
'List of mixed values 
var=Array(100,"India", #01-05-2010#) 
msgbox var(0) 'output: 100 
msgbox var(1) 'output: India
msgbox var(2) 'output: 01/05/2010

IsArray Function

It checks weather the given variable is an Array or not and returns true if it is an array or false otherwise.

Example:

Dim var1, var2,x
'List of strings
var1=Array("Kolkata","Howrah", "Hoogly")
x=isArray(var1) 'It returns True/False like Result
msgbox x
x=isArray(var2) 
msgbox x

IsDate Function

It checks weather the given value is Date type data or not . Returns true if it is an array or false otherwise.

READ  Microsoft VBScript runtime error -ActiveX Component Can't Create Object

Examples:

Dim myDate,
myDate=100
x=IsDate(myDate)
msgbox x 
'Output: False
myDate="India"
x=IsDate(myDate)
msgbox x
'Output: False
myDate=#10/05/2010#
x=IsDate(myDate)
msgbox x 
'Output: True
myDate=#10-05-2010#
x=IsDate(myDate)
msgbox x 'Output: True
myDate=#10-05-10#
x=IsDate(myDate)
msgbox x 
'Output: True
myDate=10-05-2010
x=IsDate(myDate)
msgbox x 
'Output: False

DateDiff Function

It provides difference or interval between two dates, based on interval (day/month).

Example:

Dim Date1, Date2,x
Date1=#10-10-2008#
Date2=#10-09-2010#
x=DateDiff("d", date1,date2) 
'd for day
msgbox x
' It subtracts date1 from date2
x=DateDiff("m", date1,date2)
' m for month
msgbox x
' It subtracts date1 from date2
x=DateDiff("y", date1,date2) 
'it considers days only
msgbox x
' It subtracts date1 from date2Note: through this function, we can day or month wise diffrence only.

IsNumeric Function

IsNuremic function returns true or false depending on the variable or expression if that represents a number.

Example:

Dim val,
xval="100"
x=Isnumeric(val)
msgbox x 
'Output: True
val=100
x=Isnumeric(val)
msgbox x 
'Output: True
x=Isnumeric(500)
msgbox x 
'Output: True
x=Isnumeric("India")
msgbox x 
'Output: False

Time Function

Time function returns Date as Variant of subtype Date indicating the current system time.


Dim mytime
mytime=Time
msgbox mytime

VarType Function

Returns a variant subtype of a variable (indicating the subtype of a variable). Read here for more data types.

Example

Dim MyCheck
MyCheck = VarType(300) ' Returns 2.
Msgbox Mycheck
MyCheck = VarType(#10/19/62#) ' Returns 7.
Msgbox Mycheck
MyCheck = VarType("VBScript") ' Returns 8.
Msgbox Mycheck

Len Function

It finds length of the String.

Example:

Dim val,
xval="Delhi"
x=Len(val)
msgbox x 
'Output: 5
val=100
x=Len(val)
msgbox x 
'Output: 3
val="Hoogly100"
x=Len(val)
msgbox x 'Output: 9
val="hy$@*de"
x=Len(val)
msgbox x 'Output: 7
val="100"
x=Len(val)
msgbox x 'Output: 3
val=#10-10-2010#
x=Len(val)
msgbox x 'Output: 10
x=Len("Krishna")
msgbox x 'Output: 7
x=Len(Krishna)
msgbox x 'Output: 0
x=Len() msgbox x 'Output: Error

Left Function

Returns a specified number of characters of a given string from left side Syntax:

Example:

variable=Left(string,Lengh)
Example:
Dim val,x
val="Hydro"
x=Left(val,3)
msgbox x 
' Output: Hyd
val="9247837478"
x=Left(val,1)
msgbox x 
' Output: 9
val="H92yderabad"
x=Left(val,3)
msgbox x 
' Output: H92
x=Left(9247837478,5)
msgbox x 
' Output: 92478
val=#10-10-10#
x=Left(val,3)
msgbox x 
' Output: 10

Dim MyString, LeftString
MyString = "VBSCript"
LeftString = Left(MyString, 3) ' LeftString contains "VBS".

Right Function

Returns a specified number of characters of a given string from Right side.

Example:

Dim val,x
val="Cyberabad"
x=Right(val,3)
msgbox x 
' Output: bad
val="9247837478"
x=Right(val,1)
msgbox x 
' Output: 8
val="H92yderabad"
x=Right(val,3)
msgbox x ' 
Output: bad
x=Right(9247837478,5)
msgbox x 
' Output: 37478
val=#10-10-10#
x=Right(val,5)
msgbox x 
' Output: /2010

Dim AnyString, MyStr
AnyString = "Hello World" ' Define string.
MyStr = Right(AnyString, 1) ' Returns "d".
MyStr = Right(AnyString, 6) ' Returns " World".
MyStr = Right(AnyString, 20) ' Returns "Hello World".

Mid function

Returns a specified number of characters of a given string depending on start index and length.

Example:

Dim val,x
val="Souravalu"
x=Mid(Val,5,3)
msgbox x 
' Output: val
val="Hyderabad"
x=Mid(Val,5)
msgbox x 
' Output: rabad
val="9247837478"
x=Mid(val,6,5)
msgbox x 
' Output: 37478
val="H92yderabad"
x=Mid(val,1)
msgbox x 
' Output: H92yderabad
x=Mid(9247837478,5)
msgbox x 
' Output: 837478
val=#10-10-10#
x=Mid(val,5)
msgbox x ' Output: 0/2010

StrReverse Function

Returns reverse value of a string.

Example:

Dim val,x
val="Hyderabad"
x=StrReverse(val)
msgbox x 
'Output dabaredyH
val="001"
x=StrReverse(val)
msgbox x 
'Output: 100
val=1002
x=StrReverse(val)
msgbox x 
'Output: 2001
val=#10-10-10#
x=StrReverse(val)
msgbox x 
'Output: 0102/01/01
x=StrReverse("Hyderabad")
msgbox x 
'Output: dabaredyH
x=StrReverse(100)
msgbox x 
'Output: 001

StrComp Function

It compares two string (Binary and textual) and returns a value.

If a) Both are equal, returns 0(zero) b) String 1 greater than string 2, returns 1(one) c) String 2 greater than string 1, returns -1

Example:

Dim str1,str2,x
str1="India"
str2="India"
x=StrComp(str1,str2,1)
msgbox x 
'Output 0
str1="india"
str2="INDIA"
x=StrComp(str1,str2,1)
msgbox x 
'Output 0
str1="India"
str2="Indian"
x=StrComp(str1,str2,1)
msgbox x 'Output -1
str1="Indian"
str2="Ndia"
x=StrComp(str1,str2,1)
msgbox x 
'Output -1
str1="Indian"
str2="India"
x=StrComp(str1,str2,1)
msgbox x 
'Output 1
str1=100
str2=100
x=StrComp(str1,str2,1)
msgbox x 
'Output 0
str1=100
str2=101
x=StrComp(str1,str2,1)
msgbox x 'Output -1

Lcase function

Coverts Upper case values into Lower case and returns the string.

Example:

Dim val,x
val="HYDERABAD"
x=Lcase(val)
msgbox x 
'Output hyderabad
val="Hyderabad"
x=Lcase(val)
msgbox x 
'Output hyderabad
val="HederabaD"
x=Lcase(val)
msgbox x
 'Output hyderabad
val="hyderabad"
x=Lcase(val)
msgbox x 
'Output hyderabad
x=Lcase("HYDERABAD")
msgbox x 
'Output hyderabad

Ucase Function

Coverts Lower case values into Upper case and returns the String.

Example:

Dim val,x
val="HYDERABAD"
x=Ucase(val)
msgbox x 
'Output HYDERABAD
val="Hyderabad"
x=Ucase(val)
msgbox x 
'Output HYDERABAD
val="HederabaD"
x=Ucase(val)
msgbox x 
'Output HYDERABAD
val="hyderabad"
x=Ucase(val)
msgbox x 
'Output HYDERABAD
x=Ucase("HYDERABAD")
msgbox x 
'Output HYDERABAD

Round Function

Returns the round value of a given value if value decimal point above .5 it returns, next nearest value, below .5 returns before integer value.

Example:

Dim num,x
num=14.49
x=Round(num)
msgbox x 
'Output: 14
num=14.59
x=Round(num)
msgbox x 
'Output: 15
num="14.49"
x=Round(num)
msgbox x 
'Output: 14
num="Hyd"
x=Round(num)
msgbox x 
'Output: Error

Trim Function

Returns a copy of string without leading or trailing spaces. So it takes any string as a parameter and returns the same string by removing any leading and trailing spaces.

Example:

Dim val
val=" VB Script"
x=Trim(val)
msgbox x
x=Len(x)
msgbox x
val=" 100"
x=Trim(val)
msgbox x
x=Len(x)
msgbox x
val=" 2#$%^"
x=Trim(val)
msgbox x
x=Len(x)
msgbox x
val=" VB Script "
x=Trim(val)
msgbox x
x=Len(x)
msgbox x

Ltrim Function

It removes spaces from left side of a string that is starting from left and returns the String.

Example:

Dim val
val=" VB Script"
x=LTrim(val)
msgbox x
x=Len(x)
msgbox x
val="100 "
x=LTrim(val)
msgbox x
x=Len(x)
msgbox x
val=" 2#$%^ "
x=LTrim(val)
msgbox x
x=Len(x)
msgbox x
val=" VB Script "
x=LTrim(val)
msgbox x
x=Len(x)
msgbox x
val= 100 
x=LTrim(val)
msgbox x
x=Len(x)
msgbox x

Rtrim Function

It removes spaces from right side of a string that is starting from end and returns the String.

Example:

Dim val
val="VB Script "
x=RTrim(val)
msgbox x
x=Len(x)
msgbox x
val=" 100 "
x=RTrim(val)
msgbox x
x=Len(x)
msgbox x
val=" 2#$%^ "
x=RTrim(val)
msgbox x
x=Len(x)
msgbox x
val=" VB Script "
x=RTrim(val)
msgbox x
x=Len(x)
msgbox x
val= 100 
x=RTrim(val)
msgbox x
x=Len(x)
msgbox x

Split Function

Returns a zero-based, one-dimensional array containing a specified number of sub strings.

READ  Using Xp_cmdshell to Query the Windows File System With VBscript and Transact-SQL

Example:

Dim a,b,x
b="VB Script is a Powerful scripting Language"
a=Split(b," ")
x=IsArray(b)
msgbox x 'Output: False
x=IsArray(a)
msgbox x 
'Output: True
msgbox a(6) 
'Output: Language
b="VB,Script,is,a,Powerful,scripting,Language"
a=Split(b,",")
msgbox a(5) 
'Output: Scripting
b="VB Script is a Powerful scripting Language"
a=Split(b)
msgbox a(5) 
'Output: Scripting
b="VB@Script@is@a@Powerful@scripting@Language"
a=Split(b,"@")
msgbox a(5)
 'Output: Scripting
"VBScriptisaPowerfulscriptingLanguage"
a=Split(b)
msgbox a(5)
 'Output: Error

CInt Function

Returns an expression that has been converted to a Variant of subtype Integer.

Example:

Dim num
num=123.45
myInt=CInt(num)
msgbox MyInt

Day Function

Day function returns a number between 1-31 from a Date expression.


Ex1) Dim myday
myday=Day("17,December,2009")
msgbox myday

Ex2) Dim myday
mydate=date
myday=Day(Mydate)
msgbox myday

Hour Function

Returns a whole number between 0 and 23, inclusive, representing the hour of the day.


Dim mytime, Myhour
mytime=Now
myhour=hour (mytime)
msgbox myhour

Join Function

Returns a string created by joining a number of substrings contained in an array.

Example:

Dim mystring, myarray(3)
myarray(0)="Animesh"
myarray(1)=" "
myarray(2)="Chatterjee"
mystring=Join(MyArray)
msgbox mystring

Eval Function

Evaluates an expression and returns the result.


msgbox Eval(CInt(3456.789))
output-3456

Timer Function

Returns the number of seconds that have elapsed since 12:00 AM (midnight).

Example:

msgbox Timer()

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.


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.


Dim MyVar
MyVar = MsgBox ("Hello World!", 65, "MsgBox Example")

Int Function

Int function returns an Integer portion of a given number.

Example:


msgbox Int(56.783227)
output-56

IsEmpty Function

IsEmpty function returns true or false if the variable is not initialized.

Example:


Dim myVar
msgbox IsEmpty(myVar)
output-True
myVar=10
msgbox IsEmpty(myVar)
output-False

Atn Function

Atn function returns an arc tangent(ATAN) value of the argument.

Example:


msgbox ATN(1)

CBool Function

CBool function returns a boolean value of a given expression.On the off chance that expression is zero, at that point returns false, generally returns true . On the other hand if expression can’t be deciphered as a numeric esteem, at that point a runtime error happens.
Syntax:

CBool(expression As Variant) As Boolean

Example:

Dim X, Y, TestCheck
X = 5
Y = 5
TestCheck = CBool(X = Y)  'Check contains true
X = 0
Check = CBool(X)  'Check contains false

CByte Function

CByte function returns a byte value of a given expression.This function is used to convert to a particular datatype instead of default datatype.CByte will force to change the resultant datatype from single-precision, double-precision, or integer arithmetic.Just in case if the expression does not fit into valid byte range, it will throw an error.

Syntax:

CByte(expression As Variant) As Byte
output=CByte(expression)

Example:

Dim nMyDouble, nMyByte
nMyDouble = 123.789
nMyByte = CByte(nMyDouble)  
'nMyByte contains 124

CCur Function

Returns the currency value of a given expression.It can also convert any string or number to sub type currency.

Syntax:
CCur(string As String) As Currency
Calling:
n = CCur(string)
m=CCur(number)

Example:

msgbox CCur("123")
'output 123
msgbox CCur(123)
'output 123

 

VBScript – FormatDateTime a special note

This write-up will operate via some illustrations on how to use VBScript to adjust a day and/or time into diverse formats.

The operate that can make this much easier is termed FormatDateTime.

Remember to Observe:

The structure of the day and time can differ from one computer to the next since it is exhibited as for every configurations in the “Regional and Language Solutions” in the “Regulate Panel”.

Syntax:

FormatDateTime(Date,Structure)

Day:

Any valid date expression

Format:

vbGeneralDate -OR- : Small day and prolonged time

vbLongDate -OR- 1 : Prolonged date

vbShortDate -OR- 2 : Brief date

vbLongTime -OR- 3 : Extended time

vbShortTime -OR- 4 : Short time (24-hour structure)

-OR-

Sample return “2018/09/12 10:10:28 PM”

-OR-

Sample return “12 September 2018”

-OR-

Sample return “2018/09/12”

-OR-

Sample return “10:14:58 PM”

-OR-

Sample return “12 September 2018”

You should Note:

If you switch Now() with a set date without the need of a time, in each individual scenario in which ordinarily a time is revealed, it will be omitted (display only a date) and where by only a time is shown (eg. vbShortTime) it will return “00:00”.

Sample return “00:00”

 


Spread the love
I am the founder and owner of the blog - TechTravelHub.com, always love to share knowledge on test automation,tools,techniques and tips.I am a passionate coder of Java and VBScript.I also publish articles on Travel ideas and great honeymoon destinations.Apart from these, I am a gear-head,love to drive across India. I have shared lots of articles here on How to travel several parts of India.Customization of cars aka car modification is my another hobby.Get in touch with me on ani01104@gamil.com

2 COMMENTS

  1. Warm Greetings,
    Mr. Animesh, would kindly shed some light on the topic of Regression Testing. Some of the QA forums are quite confusing. People have different experiences and they have their own point of view and styles regarding how they approach Regression Testing. Some says that Regression Testing is conducted when there is a new release or build joined the existing application. Some people also include that Regression testing is needed after bug is fixed and sent back to the QA team to recheck. So which is the right definition? and could you also give me a scnerio based example so i will have a better understanding of it. Thanks for listening to me and providing me with your helpful views.

  2. Great website. A lot of useful information here. I’m sending it to several friends ans also sharing in delicious. And certainly, thanks for your effort!

LEAVE A REPLY

Please enter your comment!
Please enter your name here