You are on page 1of 17

VBScript

What is VBScript?

An interpreted programming language primarily used to write relatively short programs that
access operating system and application objects.
The VBScript commands are a subset of the more complete, compiled Visual Basic language.
Different from compiled code.

Why VBScript?

VBScript is an easy to learn language and thus is a good candidate for a brief introduction to
programming.
VBScript can be used to automate tasks in web pages, MS Excel spreadsheets, MS Access
Databases, and other MS applications.
VBScript can be used to automate administrative tasks such as moving or copying files,
creating user accounts, tweak the registry etc.

Advantages of using VBScript

It can be embedded with other types of code.


Shorter edit-debugging cycle.
Ideally suited for quick-ad hoc solutions.
Good platform coverage.

Disadvantages of using VBScript

It’s going to be slower than programming language


No protection from snooping and change
Syntax errors aren’t caught until runtime
Harder to debug since no development environment is available by default
Variables and Variable Declaration

A variable is a place in the computer memory where your script holds a piece (or pieces) of
information, or data.
Behind the scenes, the variable is a reserved section of the computer’s memory for storing
data.
VBScript does not require variable declaration by default.
Variables in VBScript can be declared anywhere in a program as long as it is before that
variable is referenced.
Unlike most languages, variables declared in VBScript are “variant” and do not assume a type
(string, long, double, integer, Boolean) until the first time they are assigned a value.
Variables in VBScript can be declared using:

1. dim or dimension
2. public
3. private
4. const or constant

Data Types

VBScript is loosely Typed


Variant- An all-purpose, universal, super data type. But a full range of Variant “subtypes” is
available.
A Variant variable automatically chooses its subtype whenever you place a new value into it.
It does this by examining the value placed into it and making its best guess about what the
appropriate subtype is.
A Variant variable has exactly one subtype; in other words, the Variant’s subtype can only be
one type at a time.

Variant Subtypes

Testing for and Coercing Subtypes:


VarType() and TypeName() built-in VBScript functions allow to check the subtype of an
Variant variable.
Implicit Type Coercion is when a Variant variable changes its subtype automatically
Avoiding Trouble with Implicit Type Coercion

Built-in VBScript Functions


Arrays as Complex Data Types

Array is a matrix of data


Array can have up to 60 dimensions
The lower bound of an array is always zero
Array Bounds
1. LBound
2. UBound

Working with arrays

How to declare and populate an array


Dim Names(9) ‘ Declare an array with 10 elements.
Dim Names() ‘ Declare a dynamic array.
Dim A
A = Array(10,20,30)
B = A(2) ’ B is now 30

How to add dimensions and elements to an array dynamically

The ReDim statement is used to size or resize a dynamic array that has already been formally
declared using a Private, Public, or Dim statement with empty parentheses (without
dimension subscripts). You can use the ReDim statement repeatedly to change the number of
elements and dimensions in an array.

If you use the Preserve keyword, you can resize only the last array dimension, and you can’t
change the number of dimensions at all. For example, if your array has only one dimension,
you can resize that dimension because it is the last and only dimension. However, if your
array has two or more dimensions, you can change the size of only the last dimension and
still preserve the contents of the array.

The following example shows how you can increase the size of the last dimension of a
dynamic array without erasing any existing data contained in the array.
ReDim X(10, 10, 10)
ReDim Preserve X(10, 10, 15)

How to loop through an array and access all of its contents


Dim A
A = Array(10,20,30)
For i = 0 To UBound(A)
MsgBox A(i)
Next

Dim A
A = Array(10,20,30)
For Each element in A
MsgBox element
Next
Erasing arrays
Dim NumArray(9)
Dim DynamicArray()
ReDim DynamicArray(9) ‘ Allocate storage space.
Erase NumArray ‘ Each element is reinitialized.
Erase DynamicArray ‘ Free memory used by array.

Using VarType with arrays.


Dim A
A = Array(10,20,30)
MsgBox VarType(A)

The VarType function never returns the value for Array by itself. It is always added to some
other value to indicate an array of a particular type. The value for Variant is only returned
when it has been added to the value for Array to indicate that the argument to the VarType
function is an array. For example, the value returned for an array of integers is calculated as
12 + 8192, or 8204.

Operators and Operator Precedence

Operator Precedence

The operations are normally performed from left to right


1. ∩, −, (*, /), \, Mod, (+, −)
2. &
3. =, <>, <, >, <=, >=, Is
4. Not, And, Or, Xor, Eqv, Imp

Importance of parentheses
Math Operations

String Concatenation

Strings in VBScript can be concatenated (connected) using either the + or & operators

A = “Hello”
B = “World”
MsgBox A & ” ” & B & “!”
A = “Hello”
B = “World”
MsgBox A + ” ” + B + “!”
A = InputBox(“Enter your first name”)
B = InputBox(“Enter your last name”)
MsgBox A & ” ” & B

Control of Flow

Branching logic

If.. End If

Select.. End Select

If <expression1> Then
< other code goes here >
ElseIf <expression2> Then

< some other code goes here >

Else
< some other code goes here >

End If

Use Nested If’s, but with caution!

Select Case < expression >

Case <possibility 1>


< code goes here >

Case <possibility 2>


< other code goes here >

Case <possibility n>


< other code goes here >

Case Else
< other code goes here >

End Select

Be cautious of Nested Select Case too!!

Make the best decision between If.. End If and Select Case.. End Select

Looping logic

For.. Next

For Each.. Next

Do.. While

While.. Wend

For…Next

Ideal for two situations:

When you want to execute a block of code repeatedly a known, finite number of times.

When you want to execute a block of code once for each element in a complex data structure
such as an array, file, or database table.

Examples with the keyword ‘Step’

For i = 10 To 0 Step -2

MsgBox i

Next

Step – Amount counter is changed each time through the loop. If not specified, step defaults
to one.

For Each…Next

The For Each…Next loop is a special kind of loop that is specifically used for traversing
collections

Do Loop

The Do loop is the most versatile of all the loop constructs. You can easily make it loop as
many times as you like based on any criteria you like.
Executing the Block at Least Once

Testing a Precondition

Choosing Between Until and While

Breaking out of a Do Loop

While.. Wend

While <expression>
<some code here>
Wend

Points to remember in While…Wend statement:

1. No option of using either WHILE of UNTIL

2. No equivalent to EXIT FOR or EXIT DO

Procedures and Functions:

Procedures and functions allow you to modularize the code in your script into named blocks
that perform specific functions.

Modularization allows you to think about a more complex problem in a structured way,
increases the readability and understandability of your code.

Creates opportunities to reuse the same code multiple times in the same script.

Procedure Syntax

[Public|Private] Sub Name ([Argument1],[ArgumentN])

[ code inside the procedure ]

End Sub

Function Syntax

[Public|Private] Function Name ([Argument1],[ArgumentN])

[ code inside the function ]

End Function

Usage of ByRef and ByVal

In a Sub or Function declaration, each parameter can be specified as ByRef or ByVal. If


neither is specified, the default is ByRef.

If ByVal is specified, the corresponding argument is always passed by value when the
subroutine is called.
If ByRef (or neither) is specified, the argument can be passed by reference or by value when
the subroutine is called. The argument is passed by value if it is enclosed in parentheses, and
if the parentheses do not apply to the parameter list. The argument is also passed by value if
the variable sent as an argument is in a class. Otherwise, it is passed by reference.

Sub IncrementByRef(ByRef Value)

Value = Value + 1

End Sub

Sub IncrementByVal(ByVal Value)

Value = Value + 1

End Sub

Dim Num
Num = 10
MsgBox “Num : ” & Num
IncrementByRef(Num) : MsgBox “IncrementByRef(Num) : ” & Num
IncrementByRef Num : MsgBox “IncrementByRef Num : ” & Num
IncrementByVal(Num) : MsgBox “IncrementByVal(Num) : ” & Num
IncrementByVal Num : MsgBox “IncrementByVal Num : ” & Num

Error Handling

Error handling is the programmer’s main line of defense against unpredictability.

The term error handling refers not only to how a program responds when an error occurs,
but also to how it prevents errors from happening in the first place.

Types of Errors

Syntax Errors:

Halt the execution of the script.

Runtime Errors:

Occur when a command attempts to perform an action that is invalid

Logic Errors:

Produce undesirable results- contaminating data, confusing users, causing other logic and
runtime errors to occur or obscuring the real source of a problem

Syntax Errors
Syntax errors tend to pop up in several circumstances:
When something is missing from the code — parentheses, keywords (especially those that
define blocks), parameters — or when some element of this code is simply out of place

When a keyword, statement, or procedure call is misspelled or used incorrectly

When you try to use a Visual Basic or VBA keyword or function that is not implemented by
VBScript

When you use keywords that are not supported by a particular version of the script engine.

Runtime Errors

The error does not offend the VBScript runtime engine during compilation; rather, the
runtime engine has a problem with the execution of the code

Divided into 3 categories:

Native VBScript runtime errors

Examples for divide by zero and assigning Null value

Non-VBScript runtime errors

Errors from other sources- namely, scripting hosts such as IIS and

Variable declaration runtime errors related to the Option Explicit directive

Errors Related to Option Explicit; with the usage of Option Explicit directive, one needs to
declare all the variable before using them

Logic Errors

The best way to deal with them is to avoid them in the first place

Develop Defensive Programming

Handling Errors

Taking an active, rather than passive, approach when responding to errors, including having
extra code built into your script to deal with errors in case they occur.

Elements necessary for handling errors

Err

Intrinsic object with global scope

Methods:
Clear()
Raise()

Properties:
On Error Statements

Switch that controls the error control settings

Flipping the Error Handling Switch

On Error Resume Next

On Error GoTo 0

Setting Traps for Errors

On Error Resume Next

Err.Number

On Error GoTo 0

Generating Custom Errors

Err.Raise

When Not to Use Err.Raise

Distinguish between an error and a problem message

Report and error when there is some problem in your script or in something outside of your
script.

E.g. Divide by zero error

When to Generate Custom Errors

When a rule is broken; an assumption fails. Generate an error.

Class
In object-oriented programming, a class is a construct that is used as a blueprint (or
template) to create objects of that class. This blueprint describes the state and behavior that
the objects of the class all share. An object of a given class is called an instance of the class.
The class that contains (and was used to create) that instance can be considered as the type of
that object, e.g. an object instance of the “Fruit” class would be of the type “Fruit”.

Class Customer
Private m_CustomerName
Private m_OrderCount
Private Sub Class_Initialize
m_CustomerName = “”
m_OrderCount = 0
End Sub

‘ CustomerName property.
Public Property Get CustomerName
CustomerName = m_CustomerName
End Property

Public Property Let CustomerName(custname)


m_CustomerName = custname
End Property

‘ OrderCount property (read only).


Public Property Get OrderCount
OrderCount = m_OrderCount
End Property

‘ Methods.

Public Sub IncreaseOrders(valuetoincrease)


m_OrderCount = m_OrderCount + valuetoincrease
End Sub
End Class

Dim c
Set c = New Customer
c.CustomerName = “Fabrikam, Inc.”
MsgBox (c.CustomerName)
c.IncreaseOrders(5)
c.IncreaseOrders(3)
MsgBox (c.OrderCount)

The Scripting Runtime Objects

Creating Objects
Elements of Objects
The “With” Keyword
Objects can have multiple references
Object Lifetime and Destroying Objects

The Dictionary Object


A Dictionary object is the equivalent of a PERL associative array. Items can be any form of
data, and are stored in the array. Each item is associated with a unique key. The key is used
to retrieve an individual item and is usually an integer or a string, but can be anything except
an array.

Array Vs Dictionary

Example to create a Dictionary object

Dim d ‘ Create a variable.


Set d = CreateObject(“Scripting.Dictionary”)
d.Add “a”, “Athens” ‘ Add some keys and items.
d.Add “b”, “Belgrade”
d.Add “c”, “Cairo”
a = d.Items ‘ Get the keys.
For i = 0 To d.Count -1 ‘ Iterate the array.
msgbox a(i)
Next
a = d.Items ‘ Get the items.
For i = 0 To d.Count -1 ‘ Iterate the array.
msgbox a(i)
Next

Three Different Ways to Add

Be careful with the ITEM property

The FileSystemObject Library


Examples

Creating a Folder-
2 different ways

Set FSO=CreateObject(“Scripting.Filesystemobject”)
Set objFolder=FSO.GetFolder(“C:\”)
objFolder.SubFolders.Add “Test1″

Copying a File

FSO.CopyFile “\\A_Network_Folder\*.xls”, _ “C:\MyFolder\Spreadsheets\”, True

Copying a Folder
Reading a Text File
ReadAll()
Read()
ReadLine()
Writing to a Text File
forWriting
forAppending

Regular Expressions

Provide powerful facilities for character pattern-matching and replacing.

Building on Simplicity

String manipulation functions vs Regular Expressions.

The RegExp Object

Properties:

Global Property
IgnoreCase Property
Pattern Property

Methods:
Execute Property
Replace Property
Test Property
Matching a whole class of characters

Replacing Digits

Replacing everything but Digits

Anchoring and Shorting a Pattern

3 special characters that anchor a patter:

^ used outside of []

\b

Using Repeat Counts

Example with and without repeat counts

Note: re.Global=True is not an alternative for repeat counts

Specifying a Minimum Number or Range of Matches

“\d+”

“\d*”

“\d?”

Remembered Matches
Is simply part of a pattern

Useful when you want to use some or all of the text that matched your pattern as part of the
replacement text.

Execute Method

Replace Method

Can also replace subexpressions in the pattern.

Backreferencing

Example

Test Method

The Matches Collection

-Contains regular expression Match objects

-Each Match object provides access to three things:

The string found by the regular expression

The length of the string

An index to where the match was found

Note: Remember to set the Global property to True

Matches Properties

1. Count
2. Item

Miscellaneous

String Functions
Instr()
InstrRev()
Join()
Left()
Right()
Mid()
Split()
Ltrim()
Rtrim ()
StrComp()
Len()

Date Functions:
Now()
Date()
Day()
Month()
Year()
Hour()
Minute()
Second()
Time()

You might also like