Must Watch!
MustWatch
What is VBScript?
VBScript (Visual Basic Script) is developed by Microsoft with the intention of developing dynamic web pages.
It is client-side scripting language like JavaScript.
VBScript is a light version of Microsoft Visual Basic.
The syntax of VBScript is very similar to that of Visual Basic.
If you want your webpage to be more lively and interactive, then you can incorporate VBScript in your code.
VBScript is just a scripting language.
So, it cannot run its code on its own.
It needs a bigger programming language to host it.
Right now, there are 3 environments where VB Scripts can run.
IIS (Internet Information Server) – Microsoft’s web server
WSH (Windows Script Host)– The native hosting environment of the Windows OS
IE (Internet Explorer)– The simplest hosting environment we can use to run VBScript
How to Create a Simple VBScript?
You only need 2 simple tools to create and run VBScript code throughout this tutorial:
Internet Explorer - any version, but it is good to use IE6 or above.
Text Editor - You can use normal text editors like Notepad++ or Microsoft Expression Web or even Notepad to write VBScript code.
Let’s start by developing a simple VB Script program.
In this tutorial series, we will embed our VBScript code within a very basic HTML code.
This way, we can see VBScript in action by running the particular HTML file on the Internet Explorer web browser.
VBScript Example:
Open your text editor (Here, Notepad is used.
You can use whichever text editor you want) and add the following lines of code.
<html>
<head>
<title>My First VBScript Code!!!</title>
</head>
<body>
<script type="text/vbscript">
document.write("Yes!!! I have started learning VBScript.")
</script>
</body>
</html>
In this program, the following sections constitute the HTML template.
<html>
<head>
<title>My First VBScript Code!!!</title>
</head>
<body>
<script type="text/vbscript">
document.write("Yes!!! I have started learning VBScript.")
</script>
</body>
</html>
Only the section that starts with <script> comes as part of VB Scripting code.
Whatever string sequence you put in the document.write() will be displayed by IE as page text.
This code will simply output the statement “Yes!!! I have started learning VB Scripting.” on the browser page.
Go to File menu and click” Save” option.
Filename: enter the name as trial.html
Save as type: All Files.
Click the save button
Click the Save button and you will see the file trial.html in the folder where you have saved your file.
To execute the VB Scripting code we have just created, we need to open the trial.html file in Internet Explorer.
If you have set IE as your default browser, you just need to double click the file trial.html.
TroubleShooting
If the code is not working -
Press F12 to open developer tools
In left toolbar scroll down until you see "Emulation" settings page
Change Document Mode from a default ("Edge") to 10
Try using the following code
<html>
<head>
<meta http-equiv="x-ua-compatible" content="IE=10">
<title>My First VBScript Code!!!</title>
</head>
<body>
<script type="text/vbscript">
document.write("Hello World!")
</script>
</body>
</html>
Disadvantage of VBScript
The main disadvantage of VBScript is that most browsers except Internet Explorer will not process VBScript code.
In other words, if your site has visitors who use a web browser other than Internet Explorer like Chrome, Firefox or Opera, then VBScript will not be useful.
Moreover, VBScript will not run on computers that run on operating systems other than Microsoft Windows including Linux, Mac etc.
Like any other scripting language, VBScript has gone through many changes over the years.
Now, VB Script is used as the default scripting language of ASP.
KEY LEARNING:
VB Script is a scripting language developed by Microsoft.
It is a light version of Microsoft Visual Basic and the VBScript syntax is very similar to that of Visual Basic.
VBScript program needs to be hosted on any of these 3 environments:
IIS (Internet Information Server) – Microsoft’s own web server software
WSH (Windows Scripting Host) – The native hosting environment of the Windows OS
IE (Internet Explorer) – The simplest hosting environment we can use to run VBScript
VB Script can only run on Windows machines and Internet Explorer browser.
The simplest tools that you can use to create and run VBScript are IE and any text editor.
VBScript Variable Declaration with Data Types: Dim, String, Boolean
Variables form the basis of programming.
Variables are used to hold value or an expression.
Whenever you have a piece of data to work with, you will have to declare a variable.
For example, if you have to store names of students or salaries of employees, you will be using variables named students or salaries.
Variables can also be used for holding expressions.
Suppose you have stored the marks of a student in English and Mathematics using the variables markE and markM.
You want to find the total marks.
Then, you can use a variable named markT and set its value to markE + markM.
In other words, markT = markE + markM.
Here, markT is a variable which holds an expression.
Declaring Variables
Declaring variables is the same as creating variables because you are instructing the computer to reserve memory space.
You can name the variable the way you want.
It can be short names like x, y or z or more self-describing names like student, Name, salary etc.
Providing clear and meaningful names to variables is considered a good programming practice.
There are certain rules for VBScript variable names.
Variable name must begin with a letter.
Examples: salary, mark etc.
Variables beginning with numbers or special characters are not allowed.
Examples: 1stSchool, 3rdCar, _name etc.
Variable name cannot exceed 255 characters.
Variable name should not contain a period (.).
For declaring variables, you need to use the keyword Dim.
Suppose you plan to use a variable named “salary” in your VBScript program, syntax
Dim salary;
Just declaring the VBS variables will not help you, use it.
You will have to assign a value to it at some point or another and this process is known as initializing the variable.
If you are planning to declare a variably named salary, then you can code like this:
Dim salary
salary = 10000
The important thing you need to make sure is that you should not assign a value to the variable as and when you declare it. Suppose you write a statement like this:
Dim salary = 10000
If you try to output salary using document.write, it will not return any output.
Code Example
Step 1) Open your text editor and add the following lines of code.
<html>
<head>
<title>Variables</title>
</head>
<body>
<script type="text/vbscript">
Dim variable1
variable1="John"
document.write(variable1)
‘Dim variable2 = "Smith"
‘document.write(variable2)
</script>
</body>
</html>
Step 2) Save this file as variable.html in your preferred location and then open this in IE (following the steps specified in the previous chapter).
Now, you will see the value John on the browser.
Step 3) Next, uncomment line # 11 & 12
Again save the file and refresh the IE browser if it is already opened or open the file in the IE browser.
You might be wondered to see nothing; neither John nor Smith.
The problem here is that you tried to assign the value to the variable while declaring it which is not allowed.
Loose Binding
VBScript provides you the freedom to use variables without declaring it (called loose binding).
For example, without having the statement Dim student, you can assign a value to the variable student like – student = "John"
But, it is not at all a good programming practice.
If you use a variable without declaring it and misspell the same variable when you use it again, VBScript will not prompt you of the error.
So to make the code easier to read and to identify the errors, you should use the Option Explicit statement at the beginning of your code so that you will be forced to declare all your variables even if you forget to do so.
To avoid variable type related issues, it is always good to specify the statement Option Explicit at the beginning of your VBScript code.
Code Example:
Step 1) Open your text editor and add the following lines of code.
<html>
<body>
<script type="text/vbscript">
Option Explicit
‘Dim markE, markM, markT
markE=90
markM=86
markT=markE+markM
document.write("Your marks in English is " & markE & "." & "<br />")
document.write("Your marks in Mathematics is " & markM & "." & "<br />")
document.write("Your total marks is " & markT & ".")
</script>
</body>
</html>
Step 2) Save the file as variables.html in your preferred location.
Now open the file in Internet Explorer and your screen is blank.
Why ? because you have used option explicit but not declared variables before using them
Step 3) Now to understand the importance of Option Explicit statement, uncomment Line 5 in the above code
Step 4) Save the variables.html file and refresh your browser.
Note - To concatenate two strings, you need to use “&”.
In above example, its used inside document.write command.
It is obvious that the calculation of total marks is wrong.
Now just add the first statement Option Explicit at the beginning of VBScript code (without the Dim statement).
Save the file and see the output.
You will get nothing as output which indicates that your code has some error.
Here the error is you have not declared variables before using it even after specifying Option Explicit statement.
You can also declare variables using public and private keywords like a public student or private student.
But, you have to be more careful while using these two keywords for declaring variables because it will change the scope of your variables.
You can also store multiple values in a single variable and such variables are known as VBScript array variables.
Suppose, you want to store details like name, marks, address etc of 30 students.
It will be really difficult to create and manage sets of 30 variables for names, marks, addresses and so on.
Instead, you can declare a single variable named students and store the names of all 30 students in this variable.
In such case, you will declare the variable as Dim students(29) (array index starts from zero) and you will assign values as
students(0) = "John"
students(1) = "Hannah"
students(2) = "Kevin"
.......
.......
students(28) = "Rose"
students(29) = "Emma"
Similarly, you can create variables like marks, address etc to store the respective values of all 30 students.
You can also create multidimensional arrays having up to 60 dimensions.
Code Example:
Open your text editor and add the following lines of code.
<html>
<body>
<script type="text/vbscript">
Option Explicit
Dim students(19), marks(19)
students(0) = "John"
marks(0) = 95
students(1) = "Emma"
marks(1) = "83"
students(2) = "Kevin"
marks(2) = 87
document.write(students(0) & " has scored " & marks(0) & ".<br />")
document.write(students(1) & " has scored " & marks(1) & ".<br />")
document.write(students(2) & " has scored " & marks(2) & ".<br />")
</script>
</body>
</html>
Here, we have stored details of only three students.
You can add details of up to 20 students as we have set the size of the array as 20 (as index starts from 0).
VBScript Data Types
In the previous section, you might have noticed that we assigned different types of data to the variables.We have stored numbers (mark and salary), strings (name) etc in different variables.
These numbers, strings etc are known as data types.
In fact, VBScript has only one data type called Variant.
A variant is a special kind of data type which can hold different kinds of information.
If you use Variant in a numeric context, it behaves like a number and when you use it in a string context, it behaves as a string.
In other words, when you specify salary=10000, VBScript assumes that salary is a numeric data type.
A Variant makes specific distinctions about the nature of the data.
For example, you can use variant type to store Boolean values, currency, date and so on.
These different categories of information that can be contained in a Variant are called subtypes.
Though most of the time, Variant behaves in such a way that is most appropriate for the data it contains, you should be aware of different subtypes.
Following is the list of VBScript Data Types.
Empty: A special subtype to represent a variable that has not been assigned with any value yet.
Null: A special subtype to represent a variable assigned with a null value.
Integer: Using 2 bytes to express signed integer in the range -32,768 to 32,767.
Long: Using 4 bytes to express signed integers ranging from -2,147,483,648 to 2,147,483,647.
Single: Using 4 bytes to express real numbers in floating-point format ranging from -3.402823e38 to -1.401298e-45 for negative values, and from 1.401298e-45 to 3.402823e38 for positive value.
Double: Using 8 bytes to express real numbers in floating-point format ranging from -1.79769313486232e308 to -4.94065645841247e-324 for negative values, and from 4.94065645841247e-324 to 1.79769313486232e308 for positive values.
Currency: Using 8 bytes to express real numbers in decimal format ranging from -922,337,293,685,477.5808 to 922,337,293,685,477.5807.
Date: Using 8 bytes to express dates ranging from January 1, 100 to December 31, 9999.
String: Using 1 byte per character to express a sequence of characters that can be up to approximately 2 billion characters.
Object: A special subtype to represent a reference to an object.
Error: A special subtype to represent an error number.
Boolean: Using 2 bytes to contain either True or False.
Byte: Using 1 byte to express integer in the range 0 to 255.
There are two built-in VBScript functions that help you know the subtype of a variable: “varType()” and “typeName()”.
The var type returns the numeric representation and typeName() returns the text representation of the subtype of the variable.
Each subtype has a predefined numeric representation.
Code Example
Open your text editor and add the following lines of code.
<html>
<head>
<script type="text/vbscript">
Option Explicit
Dim a
a = Empty
document.write("a = " & a & "<br />")
document.write("The numeric representation of a is " & VarType(a) & "<br />")
document.write("The variable a is of " & TypeName(a) & " data type." & "<br /><br />")
Dim b
b = Null
document.write("b = " & b & "<br />")
document.write("The numeric representation of b is " & VarType(b) & "<br />")
document.write("The variable b is of " & TypeName(b) & " data type." & "<br /><br />")
Dim c
c = 4
document.write("c = " & c & "<br />")
document.write("The numeric representation of c is " & VarType(c) & "<br />")
document.write("The variable c is of " & TypeName(c) & " data type." & "<br /><br />")
Dim d
d = -2100483648
document.write("d = " & d & "<br />")
document.write("The numeric representation of d is " & VarType(d) & "<br />")
document.write("The variable d is of " & TypeName(d) & " data type." & "<br /><br />")
Dim e
e = -3.402823E38
document.write("e = " & e & "<br />")
document.write("The numeric representation of e is " & VarType(e) & "<br />")
document.write("The variable e is of " & TypeName(e) & " data type." & "<br /><br />")
Dim f
f = "John"
document.write("f = " & f & "<br />")
document.write("The numeric representation of f is " & VarType(f) & "<br />")
document.write("The variable f is of " & TypeName(f) & " data type." & "<br /><br />")
Dim g
g = True
document.write("g = " & g & "<br />")
document.write("The numeric representation of g is " & VarType(g) & "<br />")
document.write("The variable g is of " & TypeName(g) & " data type." & "<br /><br />")
</script>
</head>
<body>
</body>
</html>
Save the file as subtype.html and open it in IE.
NOTE: You can also declare variables using public and private keywords like public student or private student.
But, you have to be more careful while using these two keywords for declaring variables because it will change the scope of your variables.
Summary
Variables are used to hold value or an expression while programming.
Variables are to be declared and initialized separately.
Though you can use variables without declaring, declaring variables before using them is considered as a good programming practice.
A variant is the only data type of VBScript and variant has different subtypes including String, Boolean, Integer, Currency etc.
Troubleshooting
In case you see a blank page after you run the code, do the following
Press F12 to open developer tools
In left toolbar scroll down until you see "Emulation" settings page
Change Document Mode from a default ("Edge") to 10
Add the following code to the head
<meta http-equiv="x-ua-compatible" content="IE=10">
VBScript Operators
An Operator works either on values or variables to perform some task.
Operators are very crucial in programming because you cannot assign values to variables or perform tasks without them.
Suppose, you want to calculate the sum of two variables a and b and save the result in another variable c.
c = a + b
Here, a, b and c are operands and + and = are the operators.
There are mainly three kinds of operators in VBScript: Arithmetic, Comparison and Logical Operators.
VBScript Arithmetic Operators
VBS Arithmetic operators, as the name indicate, are used for arithmetic calculations.
Different arithmetic operators are
+ (addition)
- (subtraction)
* (multiplication)
/ (division)
% (modulus)
^ (exponentiation)
& (concatenation)
You might be familiar with the first four arithmetic operators as we use them commonly.
The modulus operator is used to find the remainder after a division.
For example, 10%3 is equal to 1.
The exponentiation operator is equivalent to “the power of” in mathematics.
For example, 2^3 is equal to 8.
The concatenation operator is used to concatenate two string values.
For example, "Hello" & " John" will return "Hello John".
VBScript Comparison Operators
Comparison operators are used to compare two values.
Different comparison operators are == , <>, < , >, <= and >=.
Suppose, you have two variables a and b with values 5 and 9 respectively, then the results for the following comparison will be like this:
a==b will return false.
a<>b will return true.
a<b will return true.
a>b will return false.
a<=b will return true.
a>=b will return false.
VBScript Logical operators: AND, OR
Logical operators are used for logical operations.
Some of the logical operators are AND, OR, NOT and XOR.
Suppose, you have two variables x and y with values true and false respectively, then the results for the following logical operations will be like this:
x AND y will return false.
x OR y will return true.
NOT(x OR y) will return false.
x XOR y will return true.
Code Example
Step 1) Copy the following code into an editor
<html>
<head>
<script type="text/vbscript">
Dim num1,num2
num1=20
num2=3
document.write(num1 & " + " & num2 & " = " & num1+num2 & "<br />")
document.write(num1 & " - " & num2 & " = " & num1-num2 & "<br />")
document.write(num1 & " * " & num2 & " = " & num1*num2 & "<br />")
document.write(num1 & " / " & num2 & " = " & num1/num2 & "<br />")
document.write(num1 & " ^ " & num2 & " = " & num1^num2 & "<br />")
document.write(num1 & " Mod " & num2 & " = " & num1 Mod num2 & "<br />")
document.write("John" & " & " & "Smith" & " = "& "John" & " Smith" & "<br />")
Dim num3,num4
num3=7
num4=13
If (num3=num4) Then
document.write(num3 & " == " & num4 & " returns true." & "<br />")
Else
document.write(num3 & " == " & num4 & " returns false." & "<br />")
End If
If (num3<>num4) Then
document.write(num3 & " <> " & num4 & " returns true." & "<br />")
Else
document.write(num3 & " == " & num4 & " returns false." & "<br />")
End If
If (num3<num4) Then
document.write(num3 & " < " & num4 & " returns true." & "<br />")
Else
document.write(num3 & " < " & num4 & " returns false." & "<br />")
End If
If (num3>num4) Then
document.write(num3 & " > " & num4 & " returns true." & "<br />")
Else
document.write(num3 & " > " & num4 & " returns false." & "<br />")
End If
If (num3<=num4) Then
document.write(num3 & " <= " & num4 & " returns true." & "<br />")
Else
document.write(num3 & " <= " & num4 & " returns false." & "<br />")
End If
If (num3>=num4) Then
document.write(num3 & " >= " & num4 & " returns true." & "<br />")
Else
document.write(num3 & " >= " & num4 & " returns false." & "<br />")
End If
Dim bool1,bool2
bool1=false
bool2=true
If (bool1 AND bool2) Then
document.write(bool1 & " AND " & bool2 & " returns true." & "<br />")
Else
document.write(bool1 & " AND " & bool2 & " returns false." & "<br />")
End If
If (bool1 OR bool2) Then
document.write(bool1 & " OR " & bool2 & " returns true." & "<br />")
Else
document.write(bool1 & " OR " & bool2 & " returns false." & "<br />")
End If
If NOT(bool1 OR bool2) Then
document.write("NOT (" & bool1 & " OR " & bool2 & " ) returns true." & "<br />")
Else
document.write("NOT (" & bool1 & " OR " & bool2 & " ) returns false." & "<br />")
End If
If (bool1 XOR bool2) Then
document.write(bool1 & " XOR " & bool2 & " returns true." & "<br />")
Else
document.write(bool1 & " XOR " & bool2 & " returns false." & "<br />")
End If
</script>
</head>
<body>
</body>
</html>
Step 2) Save the file as operator.html in your preferred location.
Now open the file
What is Operator Precedence?
When several operators occur in an expression, each part is evaluated in a predetermined order called operator precedence.
When expressions contain operators from more than one category-
arithmetic operators are evaluated first
comparison operators are evaluated next
logical operators are evaluated last
Comparison operators all have equal precedence; that is, they are evaluated in the left-to-right order in which they appear.
Arithmetic operators are evaluated in the following order:
exponentiation
multiplication
division
modulus
addition and subtraction
and finally concatenation.
Logical operators are evaluated in the following order:
NOT
AND
OR
XOR.
You can use parentheses (opening and closing brackets) to change the normal order of precedence to the way you want. Within parentheses, normal operator precedence is maintained.
For example, if you try to calculate the expression a = 5-2*2/5^3, what you expect as the result? The result will be 4.968.
How? The exponentiation comes first, then come multiplication and division and finally comes subtraction.
So the above expression gets calculated like this: 5-2*2/(5^3) --> 5-(2*2)/125 --> 5-(4/125) --> 5-.032 --> 4.968.
Suppose, you want to calculate 5-2 first, then you should write the expression as a = (5-2)*2/5^3.
Now you get the value of as a as 3*2/5^3 --> 3*2/125-->6/125 --> 0.048.
You can try the given below code.
Code Example
Step 1) Copy the following code into an editor
<html>
<head>
<script type="text/vbscript">
Dim a
a = 5-2*2/5^3
document.write(a)
</script>
</head>
<body>
</body>
</html>
Step 2) Save the file as precedence.html in your preferred location.
Now open the file
Step 3) Change the expression a to (5-2)*2/5^3 and save the file.
Now check the output
VBScript Constants
While coding in VBS, you might have to use constants at times.
A constant is a meaningful name that replaces a number or string that will never change.
For example, suppose you want to use the constant ? in your code.
It is obvious that the value of the constant ? will not change.
So, you can create a constant named “pi” and use it wherever you want.
You need to use the keyword “const” in order to declare a constant.
For example, you can declare a constant named pi and assign the value of ? to it like this:
const pi = 3.14
After declaring a constant, if you try to change its value, then you will get an error.
While naming the constants, you need to be careful not to use the predefined VBScript constants.
The best preventive measure is to avoid names starting with vb because all VBScript predefined constants start with vb.
Some examples are vbRed, vbSunday, vbArray and so on.
You can use these predefined VBScript constants in your code as you want.
Try the code given below to make the concept clearer.
Code Example
<html>
<head>
<script type="text/vbscript">
Dim intRadius
intRadius = 20
const pi=3.14
area = pi*intRadius^2
document.write(area)
</script>
</head>
<body>
</body>
</html>
Save the file as constant.html in your preferred location.
Now open the file
Summary
Operators are used to assigning values to variables or perform different kinds of tasks.
There are mainly three kinds of operators in VBScript: Arithmetic, Comparison and Logical Operators.
Operator precedence is the order in which operators are evaluated normally when several operations occur in an expression.
You can use parenthesis to override the operator precedence.
A constant is a meaningful name that replaces a number or string that will never change.
VBScript Conditional Statement: IF Else, ElseIF, Select Case Example
What is Conditional Statement?
While programming, you will have to make certain decisions and perform different actions based on those decisions.
In such situations, you will be using conditional statements.
In VBScript, there are four types of conditional statements: If...Then, If.....Then...Else, If...Then.....ElseIf, and Select Case.
VBScript If Then Statement
You will use the VBScript If-Then statement if you want to execute some code when a specific condition is true.
For example, you want to output the message "Welcome" whenever the value of the variable loggedIn is true.
In this case, you will be using If...Then statement in VBS.
If loggedIn = true Then
document.write("Welcome")
End If
NOTE: If you forget to end the code with End If, you will not get any output.
VBScript If Else Statement
You will be using VBScript If....Then....Else statement, if you want to select one of two blocks of code to execute.
For example, you want to output the message "Hi, Good Morning" when the value of a variable named “time” is less than or equal to ten and output the message "Hi, Good Day" otherwise.
In such a case, you will be using If....Then.....Else statement.
If time <= 10 Then
document.write("Hi, Good Morning")
Else
document.write("Hi, Good Day")
End If
VBScript If Elseif Statement
You will be using If.....Then.......ElseIf statement, if you have to select one of many blocks of code to execute.
For example, if you want to change the output based on the day of the week, then you have to use If.....Then.......ElseIf statement.
If today="Sunday" Then
document.write("Today is Sunday")
ElseIf today="Monday" Then
document.write("Today is Monday")
ElseIf today="Tuesday" Then
document.write("Today is Tuesday")
ElseIf today="Wednesday" Then
document.write("Today is Wednesday")
ElseIf today="Thursday" Then
document.write("Today is Thursday")
ElseIf today="Friday" Then
document.write("Today is Friday")
ElseIf today="Saturday" Then
document.write("Today is Saturday")
End If
VBScript SELECT Case Statement
Similar to If.....Then.......ElseIf statement, VBScript Case statement can also be used if you have to select one of many blocks of code to execute.
The same above code can be written like this using Select Case statement.
Select Case today
Case "Sunday"
document.write("Today is Sunday")
Case "Monday"
document.write("Today is Monday")
Case "Tuesday"
document.write("Today is Tuesday")
Case "Wednesday"
document.write("Today is Wednesday")
Case "Thursday"
document.write("Today is Thursday")
Case "Friday"
document.write("Today is Friday")
Case "Saturday"
document.write("Today is Saturday")
End Select
Try the code given below to make the concept clearer.
If Else If Example
Step 1) Copy the code into your editor
<html>
<head>
<script type="text/vbscript">
Dim age
age = InputBox("Enter your age")
If age<18 Then
document.write("You are too young.")
ElseIf age<45 Then
document.write("You are still young.")
ElseIf age<70 Then
document.write("You are getting older.")
Else
document.write("You are too old.")
End If
</script>
</head>
<body>
</body>
</html>
Step 2) Save the file as condition.html in your preferred location.
Now open the file
Enter a numeric value, say 22.
Enter different values and observe the output.
Summary
IN VBS, Conditional statements are used to make decisions and execute different blocks of code based on the decisions taken.
You will use If...Then statement, if you want to execute some code when a specific condition is true.
You will use If....Then....Else statement, if you want to select one of two blocks of code to execute.
You will use If.....Then.......ElseIf statement and Select Case statement, if you have to select one of many blocks of code to execute.
Why Loops are used in VBScript?
Loops are used to execute the same block of code again and again.
There are a number of VBScript looping statements.
Some of the VBScript looping statements are Do While, Do Until, For.....Next and so on.
So, how will you decide which looping statement to use for your need?
While executing the loops, you might or might not be aware of the number of times you want to execute a set of instructions.
For example, you want to calculate the sum of two numbers ten times.
In this case, you already know you want to repeat a block of code 10 times.
Suppose, you want to calculate the sum of two numbers until a particular variable becomes true.
Here, you do not know how many times the loop is to be executed.
So based on whether you know or do not know the number of executions, you can use different types of looping statements.
For...Next looping statements are used if you want to repeat a block of code a finite number of times, that if you know the number of times if you want to repeat the block of code.
Do While and Do Until looping statements are used when you want to repeat a block of code until a condition becomes true or false, that is when you are not aware of the number of times you want to execute the block of code.
Let’s take a look at these looping statements one by one.
VBScript Do While Loop
If you do not know the number of times you need to execute a block of code, then you will be using Do While loops.
For example, you want to output the message "Welcome" while the value of the variable x is less than 5.
In such case, Do While loop will be used.
<script type="text/vbscript">
Dim x
x=1
Do While x<5
document.write("Welcome.")
x=x+1
Loop
</script>
The block gets executed four times (when x=1,2,3 and 4) and the loop ends when the value of x becomes 5.
If you forget the statement x=x+1, then your loop will become a never-ending one.
This kind of loops is known as infinite loops.
Infinite loops could even crash your system.
So, while using Do While looping statements, you should make sure that there is some code that will make the looping condition true at one point or another.
If you assign the value 7 to the variable x at the beginning, then the code block will not be executed even once.
Suppose you want to execute the block of code at least once regardless of the condition, then you can use Do While loop.
Change the code like this:
VBScript Example:
<script type="text/vbscript">
Dim x
x=7
Do
document.write("Welcome.")
x=x+1
Loop While x<5
</script>
If you execute this code, you will get the message “Welcome” just once.
Here the condition is checked only after executing the loop once.
VBScript Do Until Loop
‘Do Until’ loop is also used when you do not know the number of time you need to execute a block of code.
The first block of code in Do Until loop (Do While x<5) is equivalent to the given below block of code.
<script type="text/vbscript">
Dim x
x=1
Do Until x=5
document.write("Welcome.")
x=x+1
Loop
</script>
This will give you the same output as the first block of code in Do While loop.
You will see the Welcome message four times.
Similar to Do .....Loop While, we have to Do...Loop Until as well.
If you want to exit a Do While or Do Until loop in between, then you can use Exit Do statement.
Suppose you want to exit the block when the value of x becomes 3 in the above program, then you need to code like this:
<script type="text/vbscript">
Dim x
x=1
Do Until x=5
If x=3 Then Exit Do
document.write("Welcome.")
x=x+1
Loop
</script>
VBScript While Loop
While...Wend loop is similar to Do While loop though not used commonly.
As Do While is more structured than While.....Wend loop, programmers usually use Do While statements.
<script type="text/vbscript">
Dim x
x = 1
While x < 5
document.write("Welcome.")
x=x+1
Wend
</script>
VBScript For-Next Loop
The For-Next loop can be used to execute a block of code for a specific number of times.
The “VBScript For loop" specifies the counter variable and its start and end values.
The Next statement increases the counter variable by one.
For i = 1 To 5
document.write("The number is " & i & "
")
Next
VBScript For-Step-Next Loop
By default, the counter variable is incremented by one.
If you want to increase or decrease the counter variable by the value you specify, then you can use For....Step....Next loop.
Suppose in the above code, you want to increment the counter by 2, then modify your code like this:
For i = 1 To 5 Step 2
document.write("The number is " & i & "<br />")
Next
</script>
The output of this code will be:
If you want to exit a For Next or For Step Next loop in between, then you can use Exit for the statement.
Suppose you want to exit the block when the value of i becomes 3 in the above program, then you need to code like this:
<script type="text/vbscript">
For i = 1 To 5 Step 2
If i=3 Then Exit For
document.write("The number is " & i & "<br />")
Next
</script>
VBScript For-Each-Next Loop
If you want to repeat a block of code for each item in a collection or for each element of a VBS array, then you need to use For...Each...Next loop.
<script type="text/vbscript">
Dim students(4)
students(0)="John"
students(1)="Hanah"
students(2)="Sarah"
students(3)="Kevin"
students(4)="Emma"
For Each x In students
document.write(x & "<br />")
Next
</script>
Code Example
<html>
<head>
<script type="text/vbscript">
Dim name, length
name = InputBox("Enter your name")
length = Len(name)’Gives length of the input string
For i = 1 To length
txt = Mid(name,i,1)'Returns a specified number of characters from a string, the first parameter is the string, second parameter is the starting position and third parameter is the number of characters to return
If txt="a" or txt="A" or txt="e" or txt="E" or txt="i" or txt="I" or txt="o" or txt="O" or txt="u" or txt="U" Then
counter = counter+1
End If
Next
document.write("Hi " & name & "!!!Your name contains " & counter & " vowels.")
</script>
</head>
<body>
</body>
</html>
Save the file as loop.html in your preferred location.
Now open the file
Summary
Looping statements are used to execute the same block of code again and again.
You will use Do-While, Do-Until and While-Wend loops when you do not know in advance how many times the block is to be executed.
You will use For-Next, For-Next-Step and For-Each-Next loops if you already know the number of times you need to execute the block of code.
VBScript Procedures
VBScript procedures are used mainly for code organization and reuse.
We have been using simple examples till now as here the purpose is learning VBScript.
But in real-world scenario, the code is not as simple as that.
When you try to implement something that is useful, the code might get more complex.
There could be hundreds of lines stretching across many pages.
If you do not organize the code properly, the whole process of coding, debugging and managing the code will become really complex.
So, you should organize or modularize the code carefully so that your code becomes easily manageable.
Moreover, suppose you have a set of statements that performs a particular action.
You want the same action to be repeated several times.
Then, why should you write the same code again and again? By using effective techniques, you can make your code reusable.
This will help the developers to organize the code beautifully and the testers to identify bugs easily.
In short, code modularization and reuse is very important for making the code more powerful, reliable, and easier to maintain.
Here come procedures into a picture.
Types of Procedures in VBScript
A procedure is a block of code that ideally performs a single function.
A block of code that processes an input or handles a file is a good example of a function.
There are two types of procedures in VBScript.
Sub procedure: The sub-procedure does not return a value.
Function procedure: The function procedure is used if you want to return a value.
Sub Procedures:
If you want to execute a series of statements without returning any value, then you can use sub procedures.
Sub procedures start and end with Sub and End Sub statements respectively.
Sub procedures can take arguments, but cannot return a value.
Sub procedures may or may not take input.
Sub outputMessage()
document.write("Welcome")
End Sub
Just writing this code will not output anything.
Here you have created a Sub procedure named outputMessage.
Next, you need to call it.
call outputMessage()
Combine both these sets of codes inside <script> tag like this.
<script type="text/vbscript">
Sub outputMessage()
document.write("Welcome")
End Sub
call outputMessage()
</script>
VBScript Functions
If you want to execute a series of statements and return a value, then you need to use function procedures, commonly known as function.
Function procedures start and end with Function and End Function statements respectively.
A function procedure may or may not take input.
Function procedures return a value by assigning the value to its name.
<script type="text/vbscript">
Function findArea(radius)
const pi=3.14
area = pi*radius*radius
findArea = area
End Function
document.write("The area of the circle when the radius is 20 is " & findArea(20) &"<br/>")
document.write("The area of the circle when the radius is 10 is " & findArea(10))
</script>
ByRef and ByVal Parameters
You can pass VBScript arguments to the procedures by reference or by value.
If you do not specify anything when you call a procedure, then the argument/arguments are passed by reference by default.
If you the changes made to the arguments to persist even after the procedure is called, then you need to pass the VBScript arguments by reference.
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.
The keywords ByRef and ByVal are used to pass arguments by reference and by value respectively.
To understand the difference, first, execute the given below code and see the output.
Step 1) Copy the code into your editor
<script type="text/vbscript">
Function returnResult(ByRef value)
value = value +1
returnResult = value
End Function
Dim x
x=5
call returnResult(x)
document.write(x)
</script>
Step 2) the output is 6.
Step 3) Change Function returnResult(ByRef value) to Function returnResult(ByVal value)
Step 4) Now your output will be 5.
Summary
VBScript procedures are used mainly for better code organization and reuse.
There are two types of VBS procedures: Sub procedures and Function procedures.
If you want to execute a series of statements without returning any value, then you can use sub procedures.
If you want to execute a series of statements and return a value, then you need to use function procedures.
You can pass arguments to the procedures by reference or by value.
Arguments are passed by reference by default.
If you want to make the changes happened to the arguments persist even after the procedure is called, then you need to pass the arguments by reference and otherwise by value.
Top 25 VBScript Interview Questions & Answers
Following are frequently asked questions in interviews for freshers as well experienced VBScript developer.
1) Mention what is VBScript?
VB Script stands for Visual Basic Script, and it is a light version of Microsoft Visual Basic.
It is a client-side scripting language like JavaScript.
VBScript is very similar to that of Visual Basic.
2) Mention the environments where VBScript could be run?
VBScript could be run into 3 environments,
IIS (Internet Information Server) – Microsoft's web server
WSH (Windows Script Host)– The native hosting environment of the Windows OS
IE (Internet Explorer)– The simplest hosting environment we can use to run VBS
3) Mention what is the technology used by VB Script?
VB Script provides Technology as,
Subroutines
Functions
String manipulation
Data/time
Error Handling, etc.
4) Mention what are the rules to name variable in VBScript?
To name variable in VBScript there are certain rules, you need to use the keyword 'Dim'.
For example, Dim salary.
Also, you need to remember the following things
Variable name must begin with a letter
Variable name cannot exceed 255 characters
Variable name should not contain a period (.)
5) Explain what is loose binding? Why is it not a good practice to use it?
VBScript allows you to use variables without declaring it known as 'loose binding.' It is not an ideal practice to use it.
Because if you misspell the same variable when you use it again then VBScript will not show you of the error.
6) Mention what is variant in VBScript?
A variant in VBScript is a data type.
A Variant can contain either string or numeric information.
A Variant behaves like a string when you use it in a string context and as a number when you use it in a number context.
7) Mention what is VBScript Procedures?
VBScript procedures are primarily used for code organization and reuse.
There are mainly two types of VBScript procedures: Sub procedures and Function procedures.
8) Mention when to use Function procedures and what are its characteristics?
You use Function procedures when you want to execute a series of statements and return a value.
Function procedures start and end with Function and End Function statements
A function procedure may or may not take input.
Function procedures return a value by assigning the value to its name
9) Mention how you can Call VBScript Functions?
To call VBScript Functions, you have to follow below rules.
The mention function name, followed by opening and closing brackets
Mention all arguments between the brackets that the function requires
10) Mention how to assign a date value to a variable?
To assign a date value to a variable, Date and Time variables should be enclosed within a hash symbol(#).
11) Mention how to create a Cookie using VBScript?
The simplest way to create a cookie is to assign a string value to the document.cookie object.
12) Mention how to access Array Data?
Data in an array can be accessed by referring to the name of the array and the element's index number.
13) In HTML file what is an ideal position to include VBScript?
An ideal position to include VBScript in HTML is,
Inside Head Section
Inside Body Section
Inside External File
14) Mention what is ByRef and ByVal Parameters in VBScript?
ByRef and ByVal Parameters in VBScript is used to pass VBScript argument to the procedures by reference or by value
15) Mention what if you do not specify anything when you call a procedure?
If you do not specify anything when you call a procedure, then the argument/arguments are passed by reference by default.
16) Mention what is the use of Option Explicit in VBScript?
The use of Option Explicit statement in VBScript is to initialize all the variable before using them.
It helps to avoid typing error in the code.
17) Mention the rules for using Option Explicit statement?
The Option Explicit statement should be there in a script before any other statements.
If not then, a nontrappable error occurs
In modules where the Option Explicit statement is not declared, any undeclared variables are considered as variants automatically.
Where Option Explicit is declared, all variables must be declared using the Dim, Public, Private, or ReDim statements.
18) Mention what is the difference between VBScript and VBA?
Difference between VBScript and VBA is that,
VBA | VBScript |
In VBA, you can explicitly define the lower bound of an array in the subscripts argument. | In VBScript, this is not permitted; the lower bound of all arrays is always 0. |
VBA supports the WithEvents keyword to allow an object reference to receiving notification of the events fired by its corresponding object. | VBScript, however, does not support the WithEvents keyword. |
VBA supports the New keyword to create early-bound objects. | A new keyword is not supported in a variable declaration statement |
19) Mention characteristics of Sub procedures?
You can use sub procedures if you want to run a series of statement without returning any value.
Subprocedures start with "Sub" and end with "End Sub" statements
Subprocedures can take arguments but cannot return a value
Subprocedures may or may not take input.
20) Mention what is Select Case statement?
Select Case statement is similar to If Then Else but it makes the code more readable.
It works on a single expression and evaluated at the beginning of the Select Case statement.
21) Mention if QTP generates VBScript code as we record actions, can't it possible to directly write using VBScript code when QTP does the same thing too?
No.
it is not possible.
QTP is the engine that runs through it.
The VBScript relies on the QTP UI to perform the actions, such as clicking on a link on a web page.
22) Write a code to print numbers from 5 to 0?
For i=5 To 0 step -1
WScript.Echo i
Next
23) Mention what is the main difference between function and sub-procedure?
The main difference between function and sub-procedure is that function returns a value whereas a Sub-procedure does not.
24) In what way program "hello world" you can write in VBScript?
In VBScript, you can write hello world in two ways, the program will display a message box with text hello world.
MsgBox "Hello World"
Echo "Hello World"
25) Explain about scrrun.dll in VBScript?
Scrrun.dll is used very much in programming VB.
The scripting Runtime library is very important for the functioning of the Visual basic script.
It provides much more functionality such as text operations, file management, and file modification features.