VBScript - Interview Questions

Dear readers, these VBScript Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of VBScript. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer:
Microsoft VBScript (Visual Basic Script) is a general-purpose, lightweight and active scripting language developed by Microsoft that is modelled on Visual Basic. Nowadays, VBScript is the primary scripting language for Quick Test Professional (QTP), which is a test automation tool.
Following are the advantages of VBScript −
VBScript is a lightweight scripting language, which has a lightning fast interpreter.
VBScript is a lightweight scripting language, which has a lightning fast interpreter.
VBScript, for the most part, is case insensitive. It has a very simple syntax, easy to learn and to implement.
VBScript, for the most part, is case insensitive. It has a very simple syntax, easy to learn and to implement.
Unlike C++ or Java, VBScript is an object-based scripting language and NOT an Object-Oriented Programming language.
Unlike C++ or Java, VBScript is an object-based scripting language and NOT an Object-Oriented Programming language.
It uses Component Object Model (COM) in order to access the elements of the environment in which it is executing.
It uses Component Object Model (COM) in order to access the elements of the environment in which it is executing.
Successful execution of VBScript can happen only if it is executed in Host Environment such as Internet Explorer (IE), Internet Information Services (IIS) and Windows Scripting Host (WSH).
Successful execution of VBScript can happen only if it is executed in Host Environment such as Internet Explorer (IE), Internet Information Services (IIS) and Windows Scripting Host (WSH).
Following are the disadvantages of VBScript −
VBscript is used only by IE Browsers. Other browsers such as Chrome, Firefox DONOT Support VBScript. Hence, JavaScript is preferred over VBScript.
VBscript is used only by IE Browsers. Other browsers such as Chrome, Firefox DONOT Support VBScript. Hence, JavaScript is preferred over VBScript.
VBScript has a Limited command line support.
VBScript has a Limited command line support.
Since there is no development environment available by default, debugging is difficult.
Since there is no development environment available by default, debugging is difficult.
No! VBScript is a case-insensitive language. This means that language keywords, variables, function names and any other identifiers need NOT be typed with a consistent capitalization of letters.
So identifiers int_counter, INT_Counter and INT_COUNTER have the same meaning within VBScript.
Variable is a named memory location used to hold a value that can be changed during the script execution. VBScript has only ONE fundamental data type, Variant.
Rules for Declaring Variables −
Variable Name must begin with an alphabet.
Variable Name must begin with an alphabet.
Variable names cannot exceed 255 characters.
Variable names cannot exceed 255 characters.
Variables Should NOT contain a period(.)
Variables Should NOT contain a period(.)
Variable Names should be unique in the declared context.
Variable Names should be unique in the declared context.
Variables are declared using "dim" keyword.
No! Since there is only ONE fundamental data type, all the declared variables are variant by default. Hence, a user NEED NOT mention the type of data during declaration.
The numeric values should be assigned without double quotes.
The String values should be enclosed within doublequotes(").
Date and Time variables should be enclosed within hash symbol(#).
Following are the scopes of variable in VBScript −
Dim
Dim
Public
Public
Private
Private
Variables declared using "Dim" keyword at a Procedure level are available only within the same procedure. Variables declared using "Dim" Keyword at script level are available to all the procedures within the same script.
Variables declared using "Public" Keyword are available to all the procedures across all the associated scripts. When declaring a variable of type "public", Dim keyword is replaced by "Public".
Variables that are declared as "Private" have scope only within that script in which they are declared. When declaring a variable of type "Private", Dim keyword is replaced by "Private".
Constants are declared using "const" keyword.
The Public constants are available for all the scripts and procedures.
Private Constants are available within the procedure or Class.
 VBScript language supports following types of operators −
Arithmetic Operators
Arithmetic Operators
Comparison Operators
Comparison Operators
Logical (or Relational) Operators
Logical (or Relational) Operators
Concatenation Operators
Concatenation Operators
MOD opeator is used to get the modulus of two numbers.
Example −
Dim a : a = 5
Dim b : b = 10
Dim c
c = b MOD a
Document.write ("Modulus Result is " &c)
^ opeator is used to get the exponent of two numbers.
Example −
Dim a : a = 5
Dim b : b = 10
Dim c
c = b ^ a
Document.write ("Exponentiation Result is " &c)
<> operator is used to check if two numbers are equal or not.
Example −
Dim a : a = 5
Dim b : b = 10
Dim c
c = b <> a
Document.write ("Equality Check is " &c)
XOR Called Logical Exclusion operator. It is used to do an XOR operation.
Example −
A. Dim a : a = 5
Dim b : b = 10
Dim c
c = b XOR a
Document.write ("XOR Check is " &c)
+ operator adds two Values as Variable Values are Numeric. So A + B will give 15.
+ operator concatenates two Values if values are string. So A + B will give VBScript.
& operator concatenates two values. So A + B will give 510.
& operator concatenates two values. So A & B will give VBScript.
VBScript can also manipulate cookies using the cookie property of the Document object. JavaScript can read, create, modify, and delete the cookie or cookies that apply to the current web page.
The simplest way to create a cookie is to assign a string value to the document.cookie object, which looks like this −
Syntax −
document.cookie = "key1 = value1; key2 = value2; expires = date";
Here expires attribute is optional. If you provide this attribute with a valid date or time then cookie will expire at the given date or time and after that cookies' value will not be accessible.
Reading a cookie is just as simple as writing one, because the value of the document.cookie object is the cookie. So you can use this string whenever you want to access the cookie.
The document.cookie string will keep a list of name=value pairs separated by semicolons, where name is the name of a cookie and value is its string value.
You can use strings' split() function to break the string into key and values.
Sometimes you will want to delete a cookie so that subsequent attempts to read the cookie return nothing. To do this, you just need to set the expiration date to a time in the past.
Using CDbl function, which converts a given number of any variant subtype to double.
Example −
x = 123
y = 123.882
document.write("x value after converting to double - " & CDbl(x) & "<br />")
Using CInt function, which converts a given number of any variant subtype to Integer.
Example −
x = 123
y = 123.882
document.write("y value after converting to Int - " & CInt(y) & "<br />")
Using CLng function, which converts a given number of any variant subtype to Long.
Example −
x = 123
y = 123.882
document.write("x value after converting to Long -" & CLng(x) & "<br />")
Using CSng function, which converts a given number of any variant subtype to Single.
Example −
x = 123
y = 123.882
document.write("x value after converting to Single -" & CSng(x) & "<br />")
Using Hex function, which converts a given number of any variant subtype to Hexadecimal.
Example −
x = 123
y = 123.882
document.write("y value after converting to Hex -" & Hex(y) & "<br />") 
Using FormatNumber function, which would return an expression formatted as a number.
Example −
Dim num : num = -645.998651
document.write(FormatNumber(num, 3))& "<br/>"     '-645.999
Using FormatPercent function, which would return an expression formatted as a percent.
Example −
Dim num : num = -645.998651
document.write(FormatPercent(num, 2))& "<br/>"    '-64,599.86%
Using Int function, which returns the integer part of the given number.
Example −
Dim num : num = -645.998651
document.write("int Result of num is : " & int(num))& "<br/>"  '-646
Using Log function, which returns the natural logarithm of the given number.
Example −
Dim num : num = 210
document.write("Log Result of num2 is : " & Log(num2))& "<br/>" '5.34710753071747
Using Oct function, which returns the octal value of the given number.
Example −
Dim num : num = -645.998651
document.write("Oct Result of num is : " & Oct(num))& "<br/>" '37777776572
Using Hex function, which returns the hexadecimal value of the given number.
Example −
Dim num : num = -645.998651
document.write("Hex Result of num is : " & Hex(num))& "<br/>" 'FFFFFD7A
Using Rnd function,which returns a random number between 0 and 1.
Example −
Dim num : num = -645.998651
document.write("Rnd Result of num is : " & Rnd(num))& "<br/>" '0.5130115
Using Sqr function, which returns the square root of the given number.
Example −
Dim num : num = -210
document.write("Sqr Result of num is : " & Sqr(num))& "<br/>" '14.4913767461894
Using Abs function, which returns the absolute value of the given number.
Example −
Dim num : num = -645.998651
document.write("Abs Result of num is : " & Abs(num))& "<br/>" '645.998651
Using Exp function, which returns the value of e raised to the specified number.
Example −
Dim num : num = -645.998651
document.write("Exp Result of num is : " & Exp(num))& "<br/>" '2.79479883633128E-281
Using InStr function, which returns the first occurrence of one string within another string. The search happens from left to right.
Using InStrRev function, which returns the first occurrence of one string within another string. The search happens from right to left.
Using Lcase function, which returns the lower case of the specified string.
Using Ucase function, which returns the upper case of the specified string.
Using Ltrim function, which returns a string after removing the spaces on the left side of the specified string.
Using Rtrim function, which returns a string after removing the spaces on the left side of the specified string.
Using Trim function, which returns a string value after removing both leading and trailing blank spaces.
Using Len function, which returns the length of the given string.
Using Replace function, which returns a string after replacing a string with another string.
Using Space function, which fills a string with the specified number of spaces.
Using StrComp function, which returns an integer value after comparing the two specified strings.
The StrComp Function returns an integer value after comparing the two given strings. It can return any of the three values -1, 0 or 1 based on the input strings to be compared.
If String 1 < String 2 then StrComp returns -1
If String 1 < String 2 then StrComp returns -1
If String 1 = String 2 then StrComp returns 0
If String 1 = String 2 then StrComp returns 0
If String 1 > String 2 then StrComp returns 1
If String 1 > String 2 then StrComp returns 1
Using String function, which returns a String with a specified character the specified number of times.
Using StrReverse function, whihc returns a String after reversing the sequece of the characters of the given string.
rrays are declared the same way a variable has been declared except that the declaration of an array variable uses parenthesis. In the below example, the size of the array is mentioned in the brackets.
Example −
'Method 1 : Using Dim
Dim arr1() 'Without Size
'Method 2 : Mentioning the Size
Dim arr2(5)  'Declared with size of 5
'Method 3 : using 'Array' Parameter
Dim arr3
arr3 = Array("apple","Orange","Grapes")
The values are assigned to the array by specifying array index value against each one of the values to be assigned.
Example −
Dim arr(5)
arr(0) = "VBScript"    'String
document.write("Value stored in Array index 0 : " & arr(0) & "<br />")
Using ReDim statement, we can declare dynamic-array variables and allocate or reallocate storage space.
Using LBound function, which returns an integer that corresponds to the smallest subscript of the given arrays.
Using UBound function, which returns an integer that corresponds to the largest subscript of the given arrays.
Using Split function, which returns an array that contains a specified number of values. Splitted based on a Delimiter.
Using Join function, which returns a String that contains a specified number of substrings in an array. This is an exact opposite function of Split Method.
Using Filter function, returns a zero based array that contains a subset of a string array based on a specific filter criteria.
Using IsArray function, which returns a boolean value that indicates whether or not the input variable is an array.
Using Erase Function, which recovers the allocated memory for the array variables.
The most common way to define a function in VBScript is by using the Function keyword, followed by a unique function name and it may or may not carry a list of parameters and a statement with a End Function keyword, which indicates the end of the function.
To invoke a function somewhere later in the script, you would simple need to write the name of that function with the Call keyword.
To return a value from a function, simply assign the value to the function name itself.
Yes! A function can return multiple values separated by comma as an array assigned to the function name itself.
Sub Procedures are similar to functions but there are few differences.
Sub procedures DONOT Return a value while functions may or may not return a value.
Sub procedures DONOT Return a value while functions may or may not return a value.
Sub procedures Can be called without call keyword.
Sub procedures Can be called without call keyword.
Sub procedures are always enclosed within Sub and End Sub statements.
Sub procedures are always enclosed within Sub and End Sub statements.
If ByVal is specified, then the arguments are sent as by value when the function or procedure is called.
If ByRef is specified, then the arguments are sent as by reference when the function or procedure is called.
we need to declare the object and instantiate it using Set Keyword.
Example −
Dim obj  
Set obj = CreateObject("Scripting.Dictionary")
In order to destroy the objects, we need to use Set Keyword followed by the object name and point it to Nothing.
Example −
Dim obj  
Set obj = CreateObject("Scripting.Dictionary")
Set obj = Nothing
Class is a construct that is used to define a unique type. Like Object Oriented Programming, VbScript 5.0 supports the creation of classes and it is very similar to writing COM objects with VB.
Class is simply the template for an object and we instantiate an object to access the properties and methods of it. Classes can contain variables, properties, methods or events.
VBScript classes are enclosed within Class .... End Class
'Defining the Class
Class classname    'Declare the object name
...
End Class
' Instantiation of the Class
Set objectname = new classname
Classes can contain variables, which can be of private or public. Variables within classes should follow VBScript naming conventions. By default, the variables in class are Public. That is why they can be accessed outside the class.
Example −
Dim var1 , var2.
Private var1 , var2.
Public var1 , var2.
Class properties, such as Property Let, which handles the process of data validation and assigning the new value to the private variable. Property set, which assigns the new property value to the private object variable.
Read-only properties have only a Property Get procedure while write-only properties (which are rare) have only a Property Let or a Property Set procedure.
Example −
Class Comp
   
   Private modStrType
   Private OS
 
   Public Property Let ComputerType(strType)
      modStrType = strType
   End Property
 
   Public Property Get ComputerType()
      ComputerType = modStrType
   End Property
 
   Public Property Set OperatingSystem(oObj)
      Set OS = oObj
   End Property
 
   Public Property Get OperatingSystem()
      Set OperatingSystem = OS
   End Property
 
End Class
Methods allow the class to perform the operation that the developer wants. The Methods are nothing but Functions or Subroutines.
Example −
Class Car
   
   Private Model
   Private Year
 
   Public Start()
      Fuel = 2.45
   Pressure =  4.15
   End Function
 
End Class
There are two events that are automatically associated with every class by default. Class_Initialize and Class_Terminate.
Class_Initialize is triggered whenever you instantiate an object based on the class. Class_Terminate event is fired when the object goes out of scope or when the object is set to Nothing.
Example −
In the below example, we will make you understand how the events work in VBScript.
'Instantation of the Object
Set objectname = New classname 
   
Private Sub Class_Initialize(  )
 Initalization code goes here
End Sub
'When Object is Set to Nothing
Private Sub Class_Terminate(  )
 Termination code goes here
End Sub
This class provides file system objects which help the developers to work with drives, folders and files.
Example −
Dim oFS, drive
Set oFS = CreateObject("Scripting.FileSystemObject")
Set drive = oFS.GetDrive(oFS.GetDriveName("C:\"))
Document.write drive.VolumeName
Drive contains methods and properties that allow you to gather information about a drive attached to the system.
File contains methods and properties that allow developers to create, delete or move a file.
Files provides a list of all files contained within a folder.
Folder provides methods and properties that allow developers to create, delete or move folders.
Folders provides a list of all the folders within a Folder.
TextStream enables developers to read and write text files.
RegExp object helps the developers to match the pattern of strings and the properties and methods help us to work with Regular Expressions easily.
Following are the properties of RegExp object −
Pattern − The Pattern method represents a string that is used to define the regular expression and it should be set before using the regular expression object.
Pattern − The Pattern method represents a string that is used to define the regular expression and it should be set before using the regular expression object.
IgnoreCase − A Boolean property that represents if the regular expression should be tested against all possible matches in a string if true or false. If not specified explicitly, IgnoreCase value is set to False.
IgnoreCase − A Boolean property that represents if the regular expression should be tested against all possible matches in a string if true or false. If not specified explicitly, IgnoreCase value is set to False.
Global − A Boolean property that represents if the regular expression should be tested against all possible matches in a string. If not specified explicitly, Global value is set to False.
Global − A Boolean property that represents if the regular expression should be tested against all possible matches in a string. If not specified explicitly, Global value is set to False.
The Test method takes a string as its argument and returns True if the regular expression can successfully be matched against the string, otherwise False is returned.
The Replace method takes 2 parameters. If the search is successful then it replaces that match with the replace-string, and the new string is returned. If there are no matches then the original search-string is returned.
The Execute method works like Replace, except that it returns a Matches collection object, containing a Match object for each successful match. It doesn't modify the original string.
If we want to capture the error, then Err Object is used.
Use Err.Raise to throw an error.
Example −
Err.Raise 6   ' Raise an overflow error.
Err.Number gives the error number and Err.Description gives error description.
Example −
Err.Raise 6   ' Raise an overflow error.
MsgBox "Error # " & CStr(Err.Number) & " " & Err.Description
Err.Clear clear an error.
Example −
Err.Raise 6   ' Raise an overflow error.
MsgBox "Error # " & CStr(Err.Number) & " " & Err.Description
Err.Clear   ' Clear the error.
Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong.
Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-)

    63 Lectures 
     4 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page