Professional Documents
Culture Documents
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.
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
Variant Subtypes
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)
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.
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.
Operator Precedence
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
If <expression1> Then
< other code goes here >
ElseIf <expression2> Then
Else
< some other code goes here >
End If
Case Else
< other code goes here >
End Select
Make the best decision between If.. End If and Select Case.. End Select
Looping logic
For.. Next
Do.. While
While.. Wend
For…Next
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.
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
While.. Wend
While <expression>
<some code here>
Wend
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
End Sub
Function Syntax
End Function
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.
Value = Value + 1
End Sub
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
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:
Runtime Errors:
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 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
Errors from other sources- namely, scripting hosts such as IIS and
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
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.
Err
Methods:
Clear()
Raise()
Properties:
On Error Statements
On Error GoTo 0
Err.Number
On Error GoTo 0
Err.Raise
Report and error when there is some problem in your script or in something outside of your
script.
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
‘ Methods.
Dim c
Set c = New Customer
c.CustomerName = “Fabrikam, Inc.”
MsgBox (c.CustomerName)
c.IncreaseOrders(5)
c.IncreaseOrders(3)
MsgBox (c.OrderCount)
Creating Objects
Elements of Objects
The “With” Keyword
Objects can have multiple references
Object Lifetime and Destroying Objects
Array Vs Dictionary
Creating a Folder-
2 different ways
Set FSO=CreateObject(“Scripting.Filesystemobject”)
Set objFolder=FSO.GetFolder(“C:\”)
objFolder.SubFolders.Add “Test1″
Copying a File
Copying a Folder
Reading a Text File
ReadAll()
Read()
ReadLine()
Writing to a Text File
forWriting
forAppending
Regular Expressions
Building on Simplicity
Properties:
Global Property
IgnoreCase Property
Pattern Property
Methods:
Execute Property
Replace Property
Test Property
Matching a whole class of characters
Replacing Digits
^ used outside of []
\b
“\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
Backreferencing
Example
Test Method
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()