You are on page 1of 60

VB Scripting - Important Terminology

Before actually looking into VB scripting it is


good to understand some terminology and
also what they mean. We should know
some thing about programming, scripting,
compiler, scripting to have a better
understanding.

Let’s look at what Programming and Scripting means

Programming: Programming is used for application development and involves


writing of code and should have in depth knowledge of a programming language.

Scripting: Scripting on the other hand does not involve in writing the entire code
for the application but involves in writing some lines of code or instructions so as to
validate the application developed. To put in simple language Scripting is used for
validation.

What is Compiler and Interpreter

Compiler: Programming uses compiler to compiles the entire code in one go and
creates an executable file. This executable file will be used for execution. The
advantage of compiler is that it has a faster execution rate compared to the
interpreter. The big disadvantage of compiler is that there is no way you can
change your code in the executable file and you have to go back to the code and
make changes and again create an executable file.

Interpreter: Scripting uses Interpreter to read the code one line at a time and
executes one line at a time. The advantage is that if the interpreter encounters an
error it stops executing the remaining lines and you have the chance to correct it
and re run it. At any point of time you can interrupt wile running and change the
code and continue running it. The biggest disadvantage is that each time the code
is executed it has to read each line and is time consuming and is also slow.
What is VB Script?

1. VB Script is a scripting language.


2. A scripting language is a lightweight
programming language.
3. VB Script is a subset of Microsoft's
programming language Visual Basic.
4. VB Script is not case sensitive but as a
part of best coding standards we use
appropriate casing.

How to create and run a VB script?

It is very simple to create a VB script. Just write the code in a Microsoft Note pad
and save the file by giving the file name with an .vbs extension. For example in the
File name text box while saving you can enter this file name “example1.vbs”. In the
Save as File choose the option “All Files” other wise it will save as a text file. As
soon as you save your file as a VB script file you can run the script by double
clicking on it.

Msgbox Function in VB Scripting is a very


basic function and Let’s start with a simple
VB Script to display a message for the user
using the Msgbox Function and try to
understand how it works.
Msgbox
Step 1: Open your note pad and type in this statement.

Msgbox “This is First VB Script”

Step 2: Click File > Save As and in the Save window

1. Enter the fine name as sample.vbs


2. Choose “All Files” option for the Save as Type
3. Click Save button

Step 3: On the desktop or the location you have given you will see a file with this
icon

Step 4: Double clicking on this file your message box will be displayed with the
predefined message you gave “This is First VB Script”
Let’s understand what Msgbox function does

Msgbox is used for displaying the output. It is an inbuilt VB function used to output
(display) a value to the user. This value can be a constant or a variable. Msgbox
contains a OK button. Until the user clicks the OK button the execution will not
move on to the next line.

Input box function in VB Scripting is used to


get information from the user and then
that value is stored in a variable.
Type in the statement below in your note pad and save as sample2.

UserInput = Inputbox(“Please Enter your Name”)

When you execute the file by double clicking it is displayed like this.

“UserInput” in the above statement is a variable and whatever the user enters in
the text box is stored in the variable called “UserInput”. If we want to view the data
entered on the screen then we need to call this variable in the Msgbox function and
the variable value is displayed for the user. In order to do this modify your code like
this

UserInput = Inputbox(“Please Enter your Name”)


Msgbox "UserInput"
When you execute the file again with this changes what happens. First you are
prompted to enter a value and clicking OK button will display the message box with
the value entered.

To put in as a definition Input box is an inbuilt VB Scrip function used for getting an
input from the user during runtime. Input box provides a text box and allows the
user to type in some data. When the user clicks the OK button this data is assigned
to a variable. The default input type for an input box is a string.

VB Scripting has some building blocks and


are important to know them and use them
in an appropriate manner. Below are given
the building blocks used in VB Scripting.

1. Variable has something called as data types.

2. Operators like =,+,-,* etc..

3. Branching statements to make decisions (If then else conditions)

4. Looping Constructs (For loop, While loop)

5. Functions and Procedures

6. String, Conversion, Date and Time

7. File System Object

What is a Variable?

Variable in VB Script is a place holder in the


memory used to store some data or
information.
The information assigned in the variable is a reserved section in the computer’s
memory for storing data. The Memory used is temporary. The information stored in
the memory is not permanent.

Rules for VBScript Variable usage

A variable in the VB script cannot start with a numeric value (Ex – 1stvalue). It can
be a combination of Alphabets and Numbers together (Value1) or separated by a
underscore (Value_1). There is no way you can use arithmetic operators and also
space is not allowed because if space is given then VB script will recognize them as
two different variables. Below are the basic rules followed while creating a Variable.

• It must always begin with a letter


• Should not contain a period (.) or arithmetic operators (+, -, *, /, ^)
• The max length of the variable is 256 characters

Types of Variable Declaration

In VB Script Variable Declaration happens in two ways:

1.ImplicitDeclaration.
2. Explicit Declaration.

Assigning values to a Variable

A value to a variable can be assigned either using Implicit Declaration or Explicit


Declaration.

Example

Value1=20
Jobtype=“Permanent”

From the above we can see that = is an assignment operator. The left hand side of
the expression is the variable name and the right hand side of the expression is the
value assigned to the variable.

Implicit Declaration:

Implicit Declaration is a default declaration


type in VB and there is no need for us to
declare a variable before assigning a value
to the variable. The declaration and
definition happens in one step.
Implicit declaration is easy to use. We don’t need to keep track of the variables
used in the VB script.

Example

Int1 = 28
Int2 = 30
Prod = Int1 * Int2
Msgbox Prod

Let’s see how this is stored in the memory.

From the above example Int1 and Int2 are operands and the * is the operator and =
is the assignment operator. Int1, Int2, Prod are Implicit Variables and as the script is
executed in the memory the variables get created in the memory and the
respective values are stored in those locations. With this type of declaration it is
easy to create variables as and when required.

The one disadvantage of Implicit variables is that if there is a typo error in any line
like for example "Prod" is mistyped as "Prd" then when the scrip is executed it
creates another variable called "Prd" and the resultant out put is null (Nothing will
be displayed). We should be careful in using the Implicit Declarations.

Explicit Declaration
Explicit Declaration is used to avoid the
unnecessary confusion created while typing
and also to avoid loading the memory with
variables because of errors we can use
Explicit Declaration. In order to use
explicit declaration type we need to declare
the variables before the script begins or it
should be in the starting of the script.
We will use the same example used for Implicit Declaration but will change the
script. In order to create Explicit Declaration in the beginning of the code we need
to add one more line of code as ‘Option Explicit”. Take a look at the code for Explicit
Declaration

Option Explicit
Dim Int1, Int2, Prod
Int1 = 28
Int2 = 30
Prod = Int1 * Int2
Msgbox Prod

Now lets debug the code. If by mistake instead of “Prod” you type “Prd” in Line 6 as
Msgbox Prd then what will happen. Since “Prd” is not declared when you run the
script it executes the first five line and when it executes the sixth line it throws error
and till it is not rectified the resultant output is not displayed. It will throw error as
“Variable is undefined: ‘Prd’.

This is the advantage of using Explicit Declaration.


What are the Data Types in VB Script?

Data types in VB Script is used in context of


Variable. There is only one data type in VB
Script called as Variant. The specialty of a
Variant is that it can hold different forms
of data or information within the variable
and there is no need to explicitly define the
type of data.
A Variant can hold data which contains either a numeric or a string value. The
Variant behaves in the way you want i.e. behaves as a numeric value when used in
a numeric context and behaves like a string when used in a string context. The only
difference is that any data which is enclosed in quotation marks (" ") behaves like a
string even though it contains only numbers.

Variant Subtypes

Variant can hold any type of data like Integer, String, Long, Single or double etc.
The different categories of information/data which a Variant can hold are called as
subtypes.

Below table gives a clear picture of subtypes of data which a Variant can hold or
contain.
Subtype Description

Integer The size is of 2 bytes, Value can be from 0 to 255, The Integer range is from
-32,768 to 32,767.

Long Long is for numbering system, The Integer range is from -2,147,483,648 to
2,147,483,647.

Single Holds small precision, floating point range is from -3.402823E38 to -1.401298E-
45 for negative values and for positive values is from 1.401298E-45 to
3.402823E38.

Double Holds big precision, floating point range is from -1.79769313486232E308 to


-4.94065645841247E-324 for negative values and for positive values is from
4.94065645841247E-324 to 1.79769313486232E308.
Currency Ranges from -922,337,203,685,477.5808 to 922,337,203,685,477.5807.

Date The range is between January 1, 100 to December 31, 9999.


(Time)

Object Contains an object.

Boolean Contains a boolean value either True or False.

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.

Byte Contains integer in the range 0 to 255.

You can use the conversion functions to convert the data from one subtype to
another subtype which will be discussed in Type Cast lesson.

What is the need for Operators?

Operators in VB Script are to used to


perform some operations or do some
manipulation on variables or values.
Operator is a notation to perform
operation and this operation will happen
on one or more operands.
Operators in VB script can be classified in to mainly four. They are

• Arithmetic Operators.
• Logical Operators.
• Relational or Comparison Operators.
• Concatenation Operator.
VB Script – Arithmetic Operators

Arithmetic operators are used for arithmetic operations or mathematical


operations such as Addition, Subtraction, Multiplication and other kinds of
operations.
Please find the list of Operators with some examples for easy understanding.
Operator English Meaning Example Result
+ Add 5+2 7

- Subtract 5-2 3

* Multiply 5*2 10

/ Floating Point Division 5/2 2.5

\ Integer Division 5\2 2

^ Exponent 5^2 25

Mod Modulus 5 Mod 2 1

Logical Operators

Logical operators are used to perform logical operations. They are used to
manipulate statements or create logical expressions. The Logical operators
are AND, OR and NOT.
Please find the list of Operators with some examples for easy understanding.
Operator English Meaning Example Result
Not Inverts Value Not False True

Or Either Can Be True True or False True

And Both Must Be True True And False False

Relational or Comparison Operators

Relational operators are also called as comparative operators like if we want


to compare numbers etc. Generally they are used in conditional statements
like IF Else or While loops.
Please find the list of Operators with some examples for easy understanding.
Operator English Meaning Example Result
= Equal To 20 = 45 False

> Greater Than 20 > 45 False

< Less Than 20 <> True

>= Greater Than or Equal To 20 >= 45 False

<= Less Than or Equal To 20 <= 45 True

<> Not Equal To 20 <> 45 True


Concatenation Operator

In order to combine two strings and display as a single string we use


Concatenation Operator (&). We use “&” to join two expressions.
Please find below the description with examples for easy understanding.
Operator English Meaning Example Result
& Join or Connect "Hello" & "World" Hello World

What is Branching and types of Branching Statements?

Branching Statements in VB Scripting


provides a user with a choice to execute
certain piece of code based on the
condition. This would help us to validate
different conditions for one expression.
In general to say that the program or code has to make a decision based on a
condition when a user gives a input or based on some parameters or values the
decision has to be made then branching statements plays a vital role.

For example take this scenario of giving different grades to a student based on the
percentage. For one student you can assign the marks to different variables and
based on the average you can branch out your code and give the grade but imagine
if you have to run it for more that one student then manually you have to go into
the code and change for every student and save and run.

Branching Statements helps you in making the code decide the grade based on the
conditions you give in the code once and ask the user to enter the marks for each
student. Using these branching statements you can branch out your code to
different conditions.

Basically there are three types of Branching Statements

1. If Else
2. If Elseif
3. Switch Case
Out of these the popular branching or conditional statement used is the If Else,
Endif

Else and Elseif are used to branch out different conditions.

If Else statement in VB script is used when


you want to execute a block of code based
on certain condition.

Syntax for If Else Statement

If [Condition] Then
AAAACode
AAAACode
Else
AAAACode
AAAACode
End If

Example to show how If Else Statement is Used

We will write a script asking the user to enter the average scored and based
conditions given appropriate message is displayed.

'Code to demonstrate If Else condition


Varint1 = Inputbox("Enter the average score you gained:")
If Varint1 > 80 Then
AAAAmsgbox "You scored " &Varint1& " percentage and are the
winner"
Else
AAAAmsgbox "You scored " &Varint1& " percentage and do not
qualify."
End If

If the user enters 85 then the output displayed will be


You Scored 85 percentage and are the winner

If user enters any thing less than 80 say 75 the output displayed will be

You Scored 85 percentage and do not qualify.


The If Else statement we discussed previously executes one block of code if the
value is greater than 80 or executes the other piece of code if the condition is not
satisfied. Now think what you will do if you have different ranges.

To do this you need Else If statement.

What Else if does is that it creates and if statement within an if statement and goes
on and in this manner you can check different conditions in a single if Statement.

Syntax for Else If Statement

If [condition] Then
Code
Elseif [condition] Then
Code
Elseif [condition] Then
Code
Elseif [condition] Then
Code
Else
Code
End If

Example to show how Else If Statement is used

Now let write a script to see how this works. We will calculate the average for three
subjects and based on the percentage we will display the average and the
appropriate messages.

'Calculating the average for three subjects


mt = Inputbox("Enter the marks scored for Manual Testing:")
qtp = Inputbox("Enter the marks scored for QTP:")
sql = Inputbox("Enter the marks scored for SQL:")
'Calculating average
avg=(mt+qtp+sql)/3
'Displaying the average to the user
msgbox "The average marks scored is: "&avg
'Branching statements to display appropriate message
If avg >= 90 Then
msgbox "You scored "&avg&" percentage and you will get a
Job"
ElseIf avg >= 80 and avg < 90 Then
msgbox "You scored "&avg&" percentage and you have to put
in more effort"
ElseIf avg >= 70 and avg < 80 Then
msgbox "You scored "&avg&" percentage and you are not up
to the mark"
Else
msgbox "You scored "&avg&" percentage and you have to
repeat the course"
End If

What happened why did this result came as 100.333333333333 and the first
message will be displayed which is wrong.

Let’s debug the script line by line.

mt=3, qtp=0, sql=1


avg=(mt+qtp+sql)/3
avg=(3+0+1)/3
avg 301/3
avg=100.333333333333

Let me explain you what happened so that we will be clear as to what happened
and how to rectify the code.

Even though we say that in the condition avg=(mt+qtp+sql)/3 we have used


addition (+) operator but just to remind that the default type of Inputbox is string
because we have not explicitly declared the variables and that’s why by default
what ever values you have entered in the input box is taken as string and in context
of this + is treated as a concatenation operator which means that it will join the
three values as 3+0+1 to make 301 and not add them up to 4. That is the reason
we are getting a different result.
In order to rectify this issue we need to use a conversion type (Type Cast) which in
our case actually converts the default data type to integer type. For this we need to
use CINT. CINT can be used with input box or while on the expression calculating
the average (In our case). You cannot use CINT for some variables while accepting
values and for some on the expression. You can either use CINT on the expression
or while taking input on variables.

Let’s rewrite the code and see what happens

'Calculating the average for three subjects


mt = CINT(Inputbox("Enter the marks scored for Manual
Testing:"))
qtp = CINT(Inputbox("Enter the marks scored for QTP:"))
sql = CINT(Inputbox("Enter the marks scored for SQL:"))
'Calculating average
avg=(mt+qtp+sql)/3
'Displaying the average to the user
msgbox "The average marks scored is: "&avg
'Branching statements to display appropriate message
If avg >= 90 Then
msgbox "You scored "&avg&" percentage and you will get a
Job"
ElseIf avg >= 80 and avg < 90 Then
msgbox "You scored "&avg&" percentage and you have to put
in more effort"
ElseIf avg >= 70 and avg < 80 Then
msgbox "You scored "&avg&" percentage and you are not up
to the mark"
Else
msgbox "You scored "&avg&" percentage and you have to
repeat the course"
End If

Now run the script and you will get the right percentage and the required message.

Note: You can also use CINT on the expression instead on inputbox. It will look like
this.
(CINT(mt)+CINT(qtp)+CINT(sql))\3

Assignments on Else If Statement


1. Write a script to print the greatest of three integers.
2. Write a script to print the least of the three integers.

Click Here for answers for Assignments

Select Case statement in VB Scripting is also


a branching statement. We branch out the
code by evaluating one expression. Select
Case is an alternative for If Else. Select
Case can be used invariably (any where)

Syntax for Select Case Statement

Select Case [condition]


Case 1
aaaCode
Case 2
aaaCode
Case 3
aaaCode
Case Else
aaaCode
End Select

Example to understand it easily

Let us write a script which can display the resultant value of two integers based on
the selection made. We are computing Addition, Subtraction, Multiplication and
division of the two integers and based on the user selection the operation is
performed.

UserInput = Inputbox("Enter any of the following options"&vbnewline&" "


&vbnewline&"1 for Addition"&vbnewline&"2 for
Subtraction"&vbnewline&"3 for Multiplication"&vbnewline&"4 for
Division")

Var1 = CINT(Inputbox("Enter the First Value"))


Var2 = CINT(Inputbox("Enter the Second Value"))

Select Case UserInput

Case 1
aaamsgbox"The Sumation of "&Var1& " and " &var2& " is: "&Var1 +
Var2
Case 2
aaamsgbox"The difference between "&Var1& " and " &var2& " is:
"&Var1 - Var2
Case 3
aaamsgbox"The product of "&Var1& " and " &var2& " is: "&Var1 *
Var2
Case 4
aaamsgbox"The quotient between "&Var1& " and " &var2& " is: "&Var1
\ Var2
Case Else
aaamsgbox "Invalid entry"
End Select

Constant in VB Scripting is a meaningful and


specific name that takes the place of a data
type like integer or string and never
changes. There are two types of constants.

1. Named Constant
2. Built in Constant

Constant is like a variable but unlike variable the value does not change for the
constant. It is a permanent value stored in the memory.

Named Constant

You will actually assign a integer or a string to a variable but the value assigned to
this variable cannot be changed. It is like a variable but not behave like a variable.
The value does not change and it cannot be used as a variable.
As part of the coding convention it is better to write all the constants in upper case
even though VB Scripting is case insensitive but for easy understanding it is written
and this makes no difference.

Note: The variables are written in lower case. A constant cannot be used
as a variable.

You can create user defined constants using the const statement and can be
created on numeric and string values giving meaningful names.

Syntax

Const [Name] = [Expression]

Const GREETING = “Welcome to the world of constants”


Const Age = 50

Example

Const GREETING = “Welcome to VB Scripting”


Msgbox GREETING

What is a Built in Constant in VB script?

Built in Constants are those which are


already created and stored in VB Library
and they cannot be changed and they can
be used as it is for various purposes. They
in turn help you to print information with
meaning and also messages with some
action.
Different types of Built in Constants

Please find the list of built in constant and their meaning.


Built in Constants What it does
vbOKOnly OK button only

vbOKCancel OK and Cancel buttons

vbAbortRetryIgnore Abort, Retry, and Ignore buttons

vbYesNoCancel Yes, No, and Cancel buttons

vbYesNo Yes and No buttons

vbRetryCancel Retry and Cancel buttons

vbCritical Critical Message icon

vbQuestion Warning Query icon

vbExclamation Warning Message icon

vbInformation Information Message icon

vbDefaultButton1 First button is default

vbDefaultButton2 Second button is default

vbDefaultButton3 Third button is default

vbDefaultButton4 Fourth button is default

vbApplicationModal Application modal i.e. the current application will not work until the user responds to the message box

vbSystemModal System modal i.e. all applications wont work until the user responds to the message box

Example

Const TEST = "Are you sure you want to exit"


msgbox TEST, vbYesNo

The message box displayed will be like this with Yes and No buttons.
Different types of Looping Constructs in VB
Script and its usage in VB Scripting.
Looping constructs allows a user to run a group of statements or piece of code
repeatedly that many times as desired by the user. There are some loops which
repeat statements until the condition become false and others loops which repeat
statements until the condition becomes true. Also there are those loops which
repeat statements for a specific number of times.

There are different kinds of looping construct and based on the requirements we
can use any of this Looping constructs. The are basically two types of looping
constructs FOR and DO. Let’s look at them

FOR Looping Construct

1. For Next Loop


2. For Step Next Loop
3. For Each Next

DO looping Constructs

1. Do Loop While
2. Do Loop Until
3. Do While Loop
4. Do Until Loop
5. While WEnd Loop

FOR Looping Constructs in VB Scripting


For Loop is used to run a piece of code iteratively for a finite number of times. The
start and end conditions are known in advance and the counter automatically
increments by one and this increment is by default.

FOR Looping Construct Example


Syntax
For [condition]
Code
Next

A simple for loop example

For i = 1 to 10
Msgbox "This loop is repeated "&i& " times"
Next

When you run this script the message box will display “This loop is repeated 1
times” and as you click the number increments till it reaches 10 times and also in
the message the number is incremented and displayed.

For Step Next Looping Construct

In this kind of looping construct we actually change the increment to the desired
number and the increment happens as we desire. To change the default increment
value we use “STEP” along with the For Loop or you can have user defined
increment like i=i+1 etc.

Syntax

For [condition] Step [increment/expression]


Code
Next

Example: We will use the above example and change the increment value as
desired.

For i = 1 to 10 Step 2
Msgbox "This loop is repeated "&i& " times"
Next

Now when you run the script the value is incremented by 2 and the value in the
message box will change and will display as “This loop is repeated 1 times” initially
and then the value changes to 3,5,7,9 and the script terminates because next value
is 11 and is greater than 10.

Assignment to do for FOR Looping Construct

1. Hope you remember the SELECT CASE statement in which we have looked at a
code where in the user can perform a particular type of operation like addition,
subtraction, multiplication and division. Now using the For loop try to ask the user
how many times the operation should perform. For ex if the user enters 3 then the
code should run for three times.

Look the script for this Select Case Statement

Click Here to view the Answer

2. Write a script to print prime numbers based on the user input for the prime
number limit.

Click Here to view the Answer

3. Write a script to generate the Fibonacci series. Again ask the user for the limit.

Click Here to view the Answer

4. Write a script to print all the odd numbers till 100. Do not use the STEP
statement.

5. Write a script to convert degrees to Fahrenheit.

Functions and Procedures in VB Script are


used to make the task very easy for the
user.
Procedure is a named block of code used for performing a specific task. Procedures
help us to break a complex architecture into reusable blocks and yields modularity.

Syntax

Function [name](arguments)
Code
Code
End Function

Functions in VB Script
Functions helps us to avoid using the same piece of code at different places making
the code bulky instead putting this piece of code in a function and calling it would
solve all the issues and also it maintainable.

Functions are of two types.

1. In built Functions
2. User Defined Functions
In built Functions are those which are already loaded in the VB Script Library while
User Defined Functions are those which the user defines for specific task.

User Defined Function Example

Function Multiply(byVal Int1, byVal Int2)


Prod = Int1*Int2
End Function

Multiply 3,4

When this script is run the function returns a value of 12. The Variable Multiply is
known as Function Name, byVal is known as Passby, Int1 and Int2 are called as
arguments. The code within the Function name and End Function is called the
Function Body. End Function marks the end of the Function and the whole piece of
code is known as Function Definition.

Generally a function is written to perform a single function i.e. one specific task at a
time. There is a difference between a Function or Procedure and a sub procedure. a
function or procedure returns a value to the calling function while a sub procedure
does not return a value. To put in general

A procedure returning a value is called function procedure.

A procedure which does not return a value is called Sub Procedure.

What is a Function Call in VB Script?

In continuation with the previous discussion


of Functions and Procedures in VB Script,
Let us understand what a Function call is
and why a Function Call is used.
In order to execute a Function we need to call that function at a point in our script
and this is called Function call. The whole Function what we write is called a
Function Definition and if a piece of code which is converted into a function will not
get executed unless we create a call to the function. So to put in a simple way we
need to call the functions which we write in the script other wise it is just occupying
some lines of code and makes no sense.

This is a general rule that the Function Definition should happen first and then the
Function Call. Why is it so? The answer is that since we know the requirements and
know how many variables or in this context arguments we use in the function we
should define a function and then write the Function Call because we will use these
arguments in the Function Call. A function can have zero or more arguments.

Function call can happen any where in the script. Function definition can happen
any where in the script but as per coding standards the Function Calls should be at
one place before the Function Definitions and these should also be at one place for
maintainability, ease of understanding.

VB Script searches first the function and then goes and Function Definition and
executes the function.

Defining the Scope of a Variable in VB Script

Variables in VB Script is used for assigning


values and using them for different
operations. The scope of Variable in VB
Script can be classified as Local Variable
and Global Variable.
In any programming language there is a scope for everything used in the code and
likewise in VB scripting also there is a scope for a variable. The scope of a variable
determines where it should be used in the script. The scope of a variable depends
on its declaration in the script. The scope of a variable is of two types.

1. Procedure Level Variable.


2. Script Level Variable.

Procedure Level Variables are also called as Local Variables because they can only
be used in the Procedure or Function. If a variable exists within a function then it
works for that function meaning it is used within the function and the value gets
destroyed once it comes out of the function.

Script Level variables are also called as Global Variables and they can be called
anywhere in the script. These variables can be used even in the Functions but
based on the passby values. These Script Level variables are always declared out
side the procedures.

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

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.

What is a File System Object

File System Object or FileSystemObject


helps us to deal with Files, Folders and
Drives using VB Script. We generate
Scripts using VB to interact with them.
We can interact with FileSystemObject using VB Script and can perform different
kinds of operations as we desire. Using FileSystemObject in VB Script we can create
a File, Folder. You can also write data or information in a File. Yo
u can also Delete a File, Folders or data in VB using FileSystemObject.

It is possible to get different kind of information on Files, Folders and Drives with the
help of FileSystemObject using VB Script.

FileSystemObject is a separate library and not included in VB Script Library. VB


Script needs to call the FileSystemObject Library. Like wise VB Script can interact
with different libraries and call them using different objects.

VB Script can talk to any of the libraries like FileSystemObject, Word, Excel etc. This
is referred to as Component Object Model or COM

Look at the Component Object Model or COM figure.


What is an Object?

Let’s spend some time in understanding what


is a class, object. Class is a collection of
objects which has properties and methods.
Classes are of two types.

1. Standard Class: which are loaded in the Library or which are predefined and we
just need to call them and use them. We cannot make any changes to them.

2. User Defined Class: These are define d by the user for specific tasks.

Let us see what an Object contains.

1. Objects have properties and Methods.

2. An object is an instance of a Class.

3. Properties define characteristics of an Object.

4. Methods are the actions performed by the Objects.

Let’s take an example of a Class Room. Let’s say that we have two classes named
Male and Female. All the individuals are Objects and they fall into either of the
class. Now each of this Object (individual) has some properties and Methods.

Properties for the above object can be Name, Date of Birth, Height, Weight, Color
and some properties are Read Only which cannot be changed while some others
can be changed. For Example: Date of Birth cannot be changed while height and
weight can be changed or even the name.
Methods for the above Object can be Sleeping, Eating, working, playing etc which
are actions performed by the Object.

How to call from FileSystemObject Library

For us to write VB scripts for QTP we


generally interact with FileSystemObject
and Excel Objects. There is a process in
calling a FileSystemObject Object and use
it in the VB script to get the desired output.

In order to call from FileSystemObject (FSO) Library we first need to create and
Object Variable.

An Object Variable is a Variant with sub type which holds an Object and should be
prefixed with a Key word called "SET". To interact with different libraries we need to
create Objects and these Objects are used along with different Methods to perform
different operations.

Let us look at some examples to create Object to use from different


Libraries.

Set Fso = CreateObject("Scripting.FileSystemObject")

Here we are creating an object to call a method from the File System Object Library
Set xlapp = CreateObject("Excel.Application")

Here we are creating an object to call a method from the Excel Library

Set IE = CreateObject("InternetExplorer.Application")

Here we are creating an object to call a method from the Internet Explorer Library

Set QtpApp = CreateObject("QuickTest.Application")

Here we are creating an object to call a method from the Quick Test Library

Set doc = CreateObject("Word.Application")

Here we are creating an object to call a method from the Microsoft Word Library

Set OutlookObj = CreateObject("OutLook.Application")

Here we are creating an object to call a method from the Outlook Library

All the above variables are used as a standard convention to understand as to what
the object is doing.

Please look at the following scripts where File System Object is used in VB
Script for various purposes.

1. How to Create a Text File using VB Script? Click Here for the Code

2. How to create multiple Text Files? Click Here for the Code

3. How to create a Folder using VB script? Click Here for the Code

4. How to display File Properties in VB script? Click Here for the Code

VB Script Examples

VB Script using Excel Library Methods and


Properties
Write a Script to create a workbook and
create a worksheet and add information in
the cells in VB script using Excel Library.
The Script to create a workbook and worksheets with cells is given below.

'Create an Object variable to interact with Excel Library


Set xlapp = CreateObject("Excel.Application")

'Create New Excel Workbook using the xlapp object


Set wbook = xlapp.workbooks.Add

'Create a pointer to the first sheet in the workbook


Set wsheet = xlapp.worksheets(1)

'Here we are adding the data in first column and color in


second column
For i = 1 to 56

wsheet.cells(i,1).value = "The code of this color is: "&i


wsheet.cells(i,1).font.Name = "Verdana"
wsheet.cells(i,1).font.Size = 14
wsheet.cells(i,1).font.bold=TRUE
wsheet.cells(i,1).font.colorindex=i
wsheet.cells(i,2).interior.colorindex=i

Next

wbook.SaveAs "F:\Textexcel.xls"
wbook.Close
xlapp.Quit

'Releasing the objects


Set wsheet=Nothing
Set wbook=Nothing
Set xlapp = Nothing

Once you run this script go to the folder where the excel workbook is created and
open and see how it looks like. The work sheet now contains information in two
columns and in the Cell (1,1) you will find the value as The code of this color is 1 in
black color and in bold and in the cell (1,2) you will find the cell filled with black
color and like wise till row number 56.

You can manipulate the cells or using the wsheet.cells(rows,columns) syntax.

Write a VB Script to check whether a given


number is prime or not?
We can use a For Next Loop or Do While Loop to check
whether a number given is a prime number or not in
VB Script. The challenge lies in writing a VB script
without using any built in functions of VB Script.

Method 1

a = cint(Inputbox("Enter a number to check whether it is a prime


number or not"))
count = 0
b=1
Do while b<=a
aaaif a mod b = 0 Then
aaaaaacount = count +1
aaaEnd If
b=b+1
Loop
If count = 2 Then
aaamsgbox "The number "&a& " is a prime number"
Else
aaamsgbox "The number "&a& " is not a prime number"
End if

Method 2

val=Inputbox("Please enter any number")


valprime = 0
For i=2 to Int(val/2)
aaaIf val mod I = 0 Then
aaamsgbox "The number"&val&" is not a prime number"
aaavalprime=1
aaaExit for
End If
Next
If valprime=0 Then
aaamsgbox "The number"&val&" is a prime number"
End If

Write a Script in VB to reverse a string given


by the user
This VB Script demonstrates how we can reverse a string
or a number given by the user and print it in a reverse
order. Here we use Len and Mid methods of VB Script
library. In the method one we will find the length of
the string and store in y variable and then use a for
loop in a descending order and give step as -1.

Method 1

MyStr = InputBox(“Enter a string to be reversed”)


y = Len(MyStr)
For x = y To 1 Step -1
aaachar = Mid(MyStr,x,1)
aaaNewStr = NewStr & char
Next
aaamsgbox newstr

Method 2 using the StrReverse Method.

val=Inputbox("Please enter any number or a string")


a = strReverse(val)
msgbox "The reverse of "&val& " is: "&a
Write a VB script to print a Text File in
reverse way i.e from the Last line to first
line
This VB scripts demonstrates on using the
FileSystemObject to read a text file and display the
lines in the text file in a reverse order i.e the lines
begins with the last line in the text file and ends with
the first line as the last line.

Dim arrLines()
i=0

Set FSO = CreateObject("Scripting.FileSystemObject")


Set Fil = FSO.OpenTextFile("F:\TestFolder\Text1.txt", 1)

Do Until Fil.AtEndOfStream
aaaRedim Preserve arrLines(i)
aaaarrLines(i) = Fil.ReadLine
aaai = i + 1
Loop

Fil.Close

For l = Ubound(arrLines) to LBound(arrLines) Step -1


aaastr = str&arrLines(l)&vbnewline
Next

msgbox str

Write a Script to print the phone list in VB


Script using Arrays dynamically
Write a Script to print the phone list in VB Script using
Arrays dynamically.

Here we are using a Dynamic array because we do not know the


lower and upper bound of the array and the user enters the
column and row count for the array. Also we are asking the
user to give input the field values for the array. The script in
VB looks like this. You can copy the script and paste it in a
notepad and save as a .vbs file and execute it.

Method 1 for writing the script

col = InputBox("Enter the number of Columns")


row = InputBox("Enter the number of Rows")
Dim arrphonelist()

ReDim arrphonelist(col,row)

For i = 0 to row
aaaFor j = 0 to col

aaaaaaArrphonelist(j,i) = InputBox("Enter the First name")


aaaaaaaaaj=j+1
aaaaaaArrphonelist(j,i) = InputBox("Enter the Last name")
aaaaaaaaaj=j+1
aaaaaaArrphonelist(j,i) = InputBox("Enter the Phone Number")
aaaNext
Next

arrubound = ubound(arrphonelist,2)

For k = 0 to arrubound
aaastr = str&arrphonelist(0,k)&" "
aaastr = str&arrphonelist(1,k)&" "
aaastr = str&arrphonelist(2,k)&vbnewline
Next

aaaMsgbox "The Phone List is "&vbnewline&str


Method 2 where we only ask the number of rows and keep the
columns fixed to 3

row = InputBox("Enter the number of Rows")

Dim arrphonelist()
ReDim arrphonelist(2,row)

For i = 0 to row -1
aaaFor j = 0 to 2

aaaaaaArrphonelist(0,i) = InputBox("Enter the First name")


aaaaaaaaaj=j+1
aaaaaaArrphonelist(1,i) = InputBox("Enter the Last name")
aaaaaaaaaj=j+1
aaaaaaArrphonelist(2,i) = InputBox("Enter the Phone Number")
aaaNext
Next

arrubound = ubound(arrphonelist,2)

For k = 0 to arrubound
aaastr = str&arrphonelist(0,k)&" "
aaastr = str&arrphonelist(1,k)&" "
aaastr = str&arrphonelist(2,k)&vbnewline
Next

aaaMsgbox "The Phone List is "&vbnewline&str

Write a Script to print a Phone List in VB


using Arrays
Write a Script to print the phone list in VB Script using
Arrays.

Here we are using a static array because we are giving the


lowerbound and upperbound of the array. Also we are
giving the array values. The script in VB looks like this.
You can copy the script and paste it in a notepad and
save as a .vbs file and execute it. You have to
remember that the column and Row count in VB using
Arrays start by default with zero and hence for 3
columns we are giving 2 because 0 to 2 makes it 3
columns and like wise for rows.

'Initializing an array with 3 columns and 4 rows

Dim arrphonelist(2,3)

'Giving all the values of different columns for the 4 rows.


Arrphonelist(0,0) = "John"
Arrphonelist(1,0) = "Abharam"
Arrphonelist(2,0) = "9854685623"

Arrphonelist(0,1) = "Mark"
Arrphonelist(1,1) = "Robin"
Arrphonelist(2,1) = "9955662233"

Arrphonelist(0,2) = "Peter"
Arrphonelist(1,2) = "Marshal"
Arrphonelist(2,2) = "8080454525"

Arrphonelist(0,3) = "Alex"
Arrphonelist(1,3) = "Blackston"
Arrphonelist(2,3) = "9865653526"

'Initializing the upperbound of the array for checking the no of


rows
'for this we have entered 2 which represents the 2nd
dimension
arrubound = ubound(arrphonelist,2)
For i = 0 to arrubound
aaastr = str&arrphonelist(0,i)&" "
aaastr = str&arrphonelist(1,i)&" "
aaastr = str&arrphonelist(2,i)&vbnewline
Next

aaaMsgbox "The Phone List is "&vbnewline&str

How to print all the Lines of a Text File in


Excel sheet using VB Script
Write a script in VB to write all the lines of a Text File into
an excel spreadsheet using FileSystemObject

VB Script to write all the lines of a text file in to a Excel


spread sheet. There are two ways to write all the lines
by opening an existing Text File and the second one to
create a Text File and write some lines and then
writing them in the Excel Sheet.

Method 1

Set objExcel = CreateObject("Excel.Application")


objExcel.Visible=True

objExcel.workbooks.Add()

Const ForReading =1

Set FSO = CreateObject("Scripting.FileSystemObject")


Set file = FSO.OpenTextFile("F:\TestFolder\Text1.txt", 1)

x=1

Do Until File.AtEndOfStream
Line = File.ReadLine
objExcel.Cells(x,1) = Line

x=x+1
Loop

objFile.Close

Method 2

'Script to create and write few lines in a Text file


'and write them in the excel sheet

'Create an object variable to interact with the File System


Object
Set Fso = CreateObject("Scripting.FileSystemObject")
Set xlapp = CreateObject("Excel.Application")

'Create a text files using CreateTextFile method


Set fil = Fso.CreateTextFile("F:\TestFolder\Text1.txt")
Set wbook = xlapp.Workbooks.Add
set wsheet = xlapp.worksheets(1)

'Write few lines into the first text file


For i = 1 to 100
fil.WriteLine("This is Line "&i)
Next

Set fil = nothing

'Open first text file in read mode and write in excel sheet
Set fil1 = fso.OpenTextFile("F:\TestFolder\Text1.txt",1, False)

X=1
Do Until fil1.AtEndOfStream
strLine = fil1.ReadLine
xlapp.Cells(x,1) = strLine
X=x+1
Loop

wbook.SaveAs "F:\TestFolder\Test.xls"

set wbook=nothing
xlapp.quit
set wsheet = nothing
Set fil = nothing
Set fil1=Nothing
Set fil2 = nothing

Write a script in VB to display only the Text


Files in a Folder using FileSystemObject
VB Script used to display only the Text files of a Folder by
using the GetFolder and Files method and also arrays
to print all the Text Files.

'Step 1: Create and object variable to interact with the File system
object
Set fso = CreateObject("Scripting.FileSystemObject")

'Step 2: Point to the folder from which we want to print


'the file names
Set fol = fso.GetFolder("F:\TestFolder")

'Step 3: Return all the files collection from the specified folder
Set fil = Fol.Files

'Print only the text file names from the specified folder
For each f in fil
str = f.name
arr = split(str, ".")
If arr(1) = "txt" then
var = var&Vbnewline&f.name
End If
Next

msgbox "The Text Files in the Folder "TestFolder" are:


"&vbnewline&var
How to display all the files in a Folder in VB
Script
Write a script in VB to display all the files in
a Folder using FileSystemObject

The VB Script to display all the files of a


Folder uses the GetFolder and Files
method to print all the files.

'Step 1: Create and object variable to interact with the File system
object
Set fso=createobject("Scripting.FileSystemObject")
'Step 2: Point to the folder from which we want to print the file
names
Set fol = fso.GetFolder("F:\YouTube Downloader")

'Step 3: Return all the files collection from the specified folder
Set fil = fol.files

'Print all the file names from the specified folder


For each f in fil
str = str&" "&f.name&", "
Next

Msgbox The files in the Folder YouTube Downloader are "


&Vbnewline&str

Write a Sample VB script using Arrays


Write a VB script using Array to print different color
Names.

Here we declared an Array and indexed it to 6 columns


even though we gave the index as 5. we need to
remember that in VB the index starts from zero. When
we declared the array and assigned the values we are
now assigning the array upperbound to a variable so
that using that variable we can use a for loop to print
all the values.

Dim arrcolors(5)
aaaarrcolors(0) = "Blue"
aaaarrcolors(1) = "Green"
aaaarrcolors(2) = "Red"
aaaarrcolors(3) = "White"
aaaarrcolors(4) = "Black"
aaaarrcolors(5) = "Yellow"

arrubound = ubound(arrcolors)
aaamsgbox arrubound
aaaaaaFor i = 0 to arrubound
aaaaaaaaamsgbox arrcolors(i)
aaaaaaNext

aaaaaaFor each element in arrcolors


aaaaaaaaamsgbox element
aaaaaaNext

Excel Parameters in VB Scripting


To interact with Excel Library from VB
Script we need to create an object which
points to the excel library from VB Script.
Let us look at some of the common methods used to deal with Excel
Library.

Workbooks Method is used to point to a work book.


Worksheet method is used to point to a worksheet.

Before creating a Workbook or worksheet we need to create an Object to interact


with Excel Library.

The syntax to create an object is

Set [Object] = CreateObject("Excel.Application")


Set xlapp = CreateObject("Excel.Application")

To Create a new workbook we need to use this syntax. The syntax to add a
workbook is

Set [Variable] = Object.Workbooks.Add


Set wbook = xlapp.Workbooks.Add

To Open an existing workbook we need to use this syntax. The syntax to open an
existing workbook is

Set [Variable] = Object.Workbooks.Open ()


Set wbook = xlapp.Workbooks.Open("F:\TestFolder ")

To create a worksheet in the workbook we use this syntax and the syntax to create
a worksheet is

Set [Variable] = Object.worksheets(id)


Set wsheet = xlapp.worksheets(1)
Set wsheet = xlapp.worksheets("Testing")

Here id can be the sheet id and the index begin with 1. You can also give a string for
the id but should be enclosed in " ".

To save a new workbook in a destination we use this syntax

Variable.SaveAs ()
wbook.SaveAs(("F:\TestFolder\Test.xls")

Every time a workbook is created or opened it should be closed and to close the
workbook we need a Close Method. To close a Work book the syntax is
Variable.Close
wbook.Close

It is a good practice to quit the application once your work is over and to quit the
excel application we need a Quit Method. The syntax is

Object.Quit
Xlapp.Quit

As soon as the application is quit it is required to clear the variables so that it does
not interfere with other scripts. It is important that the worksheet, workbook, excel
application variables should be cleared. To clear the variable used from the memory
we use the Nothing Method. The syntax is

Set [Object] = Nothing


Set wsheet = Nothing
Set wbook = Nothing
Set xlapp = Nothing

To create cells in the worksheet we use this syntax

wsheet.cells(rows,columns)
wsheet.cells(1,1)

Each Cell is identified with Row and Column as (Row, Column)

Check this script to understand how these methods are used.

Script to create a file and add odd line to


second file

Write a Script to create two text files and write some lines in the first file and copy
the odd lines of the first file in to the second file.

Writing a VB Script using WriteLine and ReadLine Methods of FileSystemObject to


generate the required result

'Script to create two text files,


'Write few lines into the first text file.
'Copy all the odd lines from the
'first text file to the second text file
'Create an object variable to interact with the File System Object
Set Fso = CreateObject("Scripting.FileSystemObject")

'Create Two text files using CreateTextFile method


Set fil = Fso.CreateTextFile("F:\Text1.txt")
Fso.CreateTextFile("F:\Text2.txt")

'Write few lines into the first text file


For i = 1 to 100
fil.WriteLine("This is Line "&i)
Next

Set fil = nothing

'Open first text file in read mode and second one in write mode
Set fil1 = fso.OpenTextFile("F:\Text1.txt",1, False)
Set fil2 = fso.OpenTextFile("F:\Text2.txt",2, False)

'Scan text file until we reach the endofstream


'Set the line number for every time scanned the file
'if the line number is odd copy in the second file
Do While Not fil1.AtEndOfStream
Line_number = fil1.line
If Line_number MOD 2 <> 0 Then
fil2.WriteLine(fil1.ReadLine)
Else
fil1.SkipLine
End If
Loop

Set fil = nothing


Set fil1=Nothing
Set fil2 = nothing

Display of File Properties in VB Scrip using


FileSystemObject
Back To File System Object Page

How to display File Properties in VB script?


Using the File System Object method
CreateFile we create a File and Using the
GetFile Method we get the newly created
File. Then we use the name, size etc
methods to get the properties of the file.

'Create a Folder using FSO or FileSystemObject


'Script to print the different properties of a Text File

'Step 1: Create an object variable that interacts with the File


System Object Library
Set Fso = CreateObject("Scripting.FileSystemObject")

'Step 2: use the CreateTextFile to Create a Text File


Fso.CreateTextFile("F:\Text.txt")

'Step 3: Use the GetFile Method to get the information of the


file and set it to a Object Variable
Set F=Fso.GetFile("F:\Text.txt")

'Step 4: Print the Properties of the File using various

MsgBox "The File name is: "&f.name&"" &vbnewline& "The File


Size is: "&f.size&""&vbnewline& "The File Creation Date is:
"&f.DateCreated&""&vbnewline& "The File Last Modified on:
"&f.DateLastModified

Creating a Folder in VB Script using


FileSystemObject
Back To File System Object Page

How to create a Folder using VB script?


Using the File System Object method
CreateFolder we create a Folder and Using
the GetFolder Method we get the newly
created Folder.

'Create a Folder using FSO or FileSystemObject

'Step 1: Create an object variable that interacts with the File System
Object Library

Set Fso = CreateObject("Scripting.FileSystemObject")

'Step 2; Use the CreateFolder method along with the object to create a
Folder at desired location

Fso.CreateFolder("F:\Test Folder")

'Step 3: Use the GetFolder method to get the newly created file and
store in a variable called s

Set s = fso.GetFolder("F:\Test Folder")

'Step 4: Use the name method to get the file name and print it along
with the message

Msgbox "The New Folder Created is "&s.name

Creating multiple Text files in VB Script


using FileSystemObject
Back To File System Object Page

How to create multiple Text Files?


Using the File System Object method
CreateTextFile we create a Text file and
using a For Loop we create any number of
Text files as desired. Using a InputBox we
can also ask the user how many text files to
be created.
Example 1: Assuming we know how many text files to create.

'Create a Text File using FSO or FileSystemObject


'Step 1: Create an object variable that interacts with the File
System Object Library
Set Fso = CreateObject("Scripting.FileSystemObject")
'Step 2: Use For Loop to run the script for 100 times.
For I = 1 to 5
Fso.CreateTextFile("F:\Test"&i&".txt")
var = "" &var&", Test" &i
Next
Msgbox" The Text Files Created are "&Var

Example 2: Asking the user for input to print that many number of files.

Rewrite the code by just adding one line with InputBox function.

'Create a Text File using FSO or FileSystemObject


'Step 1: Create an object variable that interacts with the File
System Object Library
Set Fso = CreateObject("Scripting.FileSystemObject")
'Step 2: Use For Loop to run the script for 100 times.
n=CINT(InputBox("Enter how many files to be created"))
For I = 1 to n
Fso.CreateTextFile("F:\Test"&i&".txt")
var = "" &var&", Test" &i
Next
Msgbox" The Text Files Created are "&Var
Creating a Text File in VB Script using
FileSystemObject
Back To File System Object Page

How to Create a Text File using VB Script?

Using the File System Object method


CreateTextFile we create a Text file and
Using the GetFile Method we get the newly
created file.

'Create a Text File using FSO or FileSystemObject

'Step 1: Create an object variable that interacts with the File System
Object Library.

Set Fso = CreateObject("Scripting.FileSystemObject")

'Step 2: Use the CreateTextFile method along with the object to create
a text file at desired location.

Fso.CreateTextFile("F:\Test.txt")

'Step 3: Use the GetFile method to get the newly created file and store
in a variable called s.

Set s = fso.GetFile("F:\Test.txt")

'Step 4: Use the name method to get the file name and print it along
with the message.
Msgbox "The Text Files Created is "&s.name

Assignment Answer on Functions.


Back to the Previous Page

Write a script in VB to Convert all the


previous written scripts like Fibonacci
series in VB Script, Prime number
Generation in VB Script, Odd number
generation in VB Script, conversion from
centigrade to Fahrenheit in VB Script,
Addition in VB Script, Multiplication in
VB Script etc using functions in VB Script.
In order to write this script first we need to use a inputbox to ask the user the
choice to perform a certain function. Then Use Select Case taking the value from
Inputbox and based on the condition it will select the case in which the function call
is specified.After the Select Case Write down all the Functions for different
operations.

The code looks like this

Here you are asking the user for the choice to perform the operation.

n=Inputbox("Enter your choice"&vbnewline&" "&vbnewline&"1 -


Addition"&vbnewline&
"2 - Subtraction"&vbnewline&"3 - Multiplication"&vbnewline&"4
- Quotient"&vbnewline&
"5 - Fibonacci Series"&vbnewline&"6 - Odd
Numbers"&vbnewline&"7 - Prime Numbers"&vbnewline&"8 -
Degree Conversion")
Here you are selecting the case based on the user input and appropriately calling
the required function.

Select Case n
Case 1
aaaaddfunc x,y
Case 2
aaaminusfunc x,y
Case 3
aaamultiply x,y
Case 4
aaaquotient x,y
Case 5
aaaFibonacci var
Case 6
aaaoddfunc var
Case 7
aaaprime var
case 8
aaaconversion cen, fah
Case Else
aaamsgbox "invalid entry"
End Select

Here you are actually defining the functions for different operations to be
performed.

For Addition of two Numbers

Function addfunc(byval x, byval y)


aaax = CINT(inputbox("Enter 1st number to be added"))
aaay = CINT(inputbox("Enter 2nd number to be added"))
aaamsgbox "The summation of "&x& " and " &y& " is: " &x+y
End Function

For Subtraction of two Numbers

Function minusfunc(byval x, byval y)


aaax = CINT(inputbox("Enter 1st number"))
aaay = CINT(inputbox("Enter 2nd number to be subtracted"))
aaamsgbox "The difference between "&x& " and " &y& " is:
"&x-y
End Function

For Multiplication of two Numbers

Function multiply(byval x, byval y)


aaax = CINT(inputbox("Enter 1st number to be multiplied"))
aaay = CINT(inputbox("Enter 2nd number to be multiplied"))
aaamsgbox "The product of "&x& " and " &y& " is: "&x*y
End Function

For finding quotient of two Numbers

Function quotient (byval x, byval y)


aaax = CINT(inputbox("Enter 1st number to be divided"))
aaay = CINT(inputbox("Enter 2nd number as divisor"))
aaamsgbox "The quotient between "&x& " and " &y& " is:
"&x\y
End Function

For displaying the Fibonacci Series of a given Number

Function Fibonacci (byval var)


aaan = CINT(Inputbox("Enter a range for the Fibonacci
Series"))
aaaf1=0
aaaf2=1
aaaf3=f1+f2
aaavar= f1& ", " &f2
aaaaaado while f3 < n
aaaaaaaaavar =" var&", "&f3
aaaaaaaaaf1=f2
aaaaaaaaaf2=f3
aaaaaaaaaf3=f1+f2
aaaaaaLoop
MsgBox("Fibonacii Series for the limit " &n&" is: " &var)
End Function

For displaying the Odd Numbers of a given Number


Function oddfunc(byval var)
aaan = CINT(Inputbox("Enter the limit for the Odd Numbers"))
aaaaaaFor i = 1 to n
aaaaaaaaaif (i mod 2<>0) then
aaaaaaaaavar = "" &var&", " &i
aaaaaaaaaEnd If
aaaaaanext
aaaMsgBox("Odd numbers within " &n&" numbers = :" &var)
End Function

For displaying the Prime numbers of a given Number

Function prime(byval var)


n = inputbox("Please Enter the limit for Prime Numbers to be
printed")
aaaFor i = 1 to n
aaaaacount = 0
aaaaaa = 1
aaaaaaaDo While a<=i
aaaaaaaaaif i mod a = 0 Then
aaaaaaaaaaacount = count + 1
aaaaaaaaaend if a=a+1
aaaaaaaLoop
aaaaaaaaaIf count = 2 Then
aaaaaaaaaaavar = var&" " &i& ", "
aaaaaaaaaEnd If
aaaNext
aaaMsgBox("Prime numbers within " &n&" numbers = :" &var)
End Function

For converting from and to Centigrade or Fahrenheit of a given Number

Function conversion(byval cen, byval fah)


con = inputbox("Enter 1 for Centigrade to Fahrenheit and 2 for
Fahrenheit to Centigrade")
aaaSelect Case con
aaaaaCase 1
aaaaaaacen=inputbox("Enter the value to be converted")
aaaaaaamsgbox "The converted value of " &cen& " Centigrade
is " &cen\0.55555555556 + 32& " Fahrenhite"
aaaaaCase 2
aaaaaaafah=inputbox("Enter the value to be converted")
aaaaaaamsgbox "The converted value of " &fah& " Fahrenheit
is " &(fah-32) *0.55555555556 & " Centigrade"
aaaaaCase Else
aaaaaaamsgbox "Invalid entry for Conversion"
aaaEnd Select
End Function

Fibonacci Series Code


Click on Back to the Assignment Question Page

Write a script to generate the Fibonacci Series. Again ask the


user for the limit.

In order to generate a Fibonacci Series in VB


Script we make use of the DO WHILE
LOOP Looping Construct.
The code for generating the Fibonacci Series is given below.

n = CINT(Inputbox("Enter a range"))
f1=0
f2=1
f3=f1+f2
var= f1& ", " &f2
do while f3 < n
var = var& ", "&f3
f1=f2
f2=f3
f3=f1+f2
loop

MsgBox "Fibonacii Series for the limit " &n&" is: " &var
Till the condition is satisfied the inner conditions get executed and stored in the var
variable thus giving out the output as 0,1,1,3,5,8,13,21,34,55 and 89 if we take the
range as 100.

Script to print Prime Numbers


Click on Back to the Assignment Question Page

Write a script to print prime numbers based


on the user input for the prime number
limit.
n = Inputbox("Please Enter the limit")
For i = 1 to n
aaaCount = 0
aaaa = 1
aaaaaaDo While a<=i
aaaaaaaaaIf i MOD a = 0 Then
aaaaaaaaaaaaCount = Count + 1
aaaaaaaaaEnd If
aaaaaaa=a+1
aaaaaaLoop
aaaaaaaaaIf Count = 2 Then
aaaaaaaaaaaavar = var&" "&i& ", "
aaaaaaaaaEnd If
Next
aaaMsgBox("Prime numbers within " &n&" numbers = :" &var)

Write a VB Script to Print different


Operations using Select Statement
Click on Back to the Assignment Question Page

This Code gives an idea as to how we can use


FOR loop in our script to make it more
meaningful and reduce the no of lines of
code.
Hope you remember the SELECT CASE statement in which we have looked at a code
where in the user can perform a particular type of operation like addition,
subtraction, multiplication and division. Now using the For loop try to ask the user
how many times the operation should perform. For ex if the user enters 3 then the
code should run for three times.

Look the script for this Select Case Statement

The script for this is given below. What i have done is that before the user to select
the operation before this line we will add few code like an inputbox and a for loop.
The code to be added in the top is like this and at the end of the code add NEXT.
Now we are asking the user how many times the user wants to perform the
operations and taking that value in the variable Varint1 and converting it into
integer. Remember that by default a variant is a string. Then we are passing the
value into the for Loop and incrementing by one value.

Varint1 = CINT(Inputbox("Enter the number of times this operation to


be performed"))
For i = 1 to Varint1 Step 1
Look at the entire code

Varint1 = CINT(Inputbox("Enter the number of times this operation to


be performed"))
For i = 1 to Varint1 Step 1
UserInput = Inputbox("Enter any of the following
options"&vbnewline&" " &vbnewline&"1 for
Addition"&vbnewline&"2 for Subtraction"&vbnewline&"3 for
Multiplication"&vbnewline&"4 for Division")
Var1 = CINT(Inputbox("Enter the First Value"))
Var2 = CINT(Inputbox("Enter the Second Value"))
aaaSelect Case UserInput
aaaCase 1
aaamsgbox"The Sumation of "&Var1& " and " &var2& " is:
"&Var1 + Var2
aaaCase 2
aaamsgbox"The difference between "&Var1& " and " &var2& "
is: "&Var1 - Var2
aaaCase 3
aaamsgbox"The product of "&Var1& " and " &var2& " is:
"&Var1 * Var2
aaaCase 4
aaamsgbox"The quotient between "&Var1& " and " &var2& "
is: "&Var1 \ Var2
aaaCase Else
aaamsgbox "Invalid entry"
aaaEnd Select
Next

You might also like