Copyright © 2006-2007 by InduSoft®. All rights reserved worldwide.
No part of this publication may be reproduced or transmitted in any form or by any means without written authorization from InduSoft. InduSoft is a registered trademark of InduSoft. CEView is a trademark of InduSoft.
The information contained within this document is subject to change without notice. InduSoft does not assume responsibility for any errors or inaccuracies that may occur in this publication.
Visual Basic and VBScript are registered trademarks of Microsoft Corporation in the United States and other countries. Other brand or product names are trademarks or registered trademarks of their respective owners.
Table of Contents
About VBScript...5
VBScript Limitations in IWS...7
The Microsoft Visual Basic Family...8
Differences between VBScript and VBA ...9
VBScript Hosting Environments...10
VBScript Language Overview ...11
VBScript Functionality ...11
VBScript Elements ...11
Variable Data Types and Subtypes...12
Data Subtype Identification...12
Data Subtype Conversion...12
Variable Naming Rules & Conventions...13
Variable Scope...13
VBScript Constants...13
Declaring VBScript Variables and Constants ...14
VBScript Keywords...14
Operators ...14
Operator Precedence ...15
Functions ...15
Statements ...18
Objects and Classes ...21
VBScript Object Commands ...23
VBScript User-Defined Class Objects...24
VBScript Objects and Collections ...28
Err Object ...29
Scripting Dictionary Object...30
Scripting FileSystemObject...31
COM Objects and Collections...39
VBScript Configuration and Operation in IWS ...43
Global Procedures...45
Graphics Script ...46
Screen Scripts ...47
Command Dynamic ...49
ActiveX Events...50
Background Task Startup Script...51
Background Task Script Groups...51
Scope of VBScript Procedures and Variables...53
Accessing IWS Tags and IWS Built-in functions ...55
Accessing ActiveX Objects from VBScript...58
IntelliSense ...60
VBScript with Web Thin Clients...62
VBScript Language Reference...63
VBScript Variables ...64
Array Variables...66
Boolean Variables...67
Byte, Integer & Long Variables...69
Currency Variables ...69
Date (and Time) Variables ...70
Empty Variables ...72
Error Variables...72
Null Variables...72
Object Variables ...73
Real (Single, Double) Variables ...73
Strings Variables...74
Data Subtype Identification...76
Data Subtype Conversion...79
VBScript Naming Rules and Conventions...80
Variable Scope...82
VBScript Constants...84
Explicit Constants ...84
Implicit Constants ...86
Declaring Variables, Objects and Constants ...95
VBScript Keywords...97
VBScript Literals ...97
VBScript Operators...98
Arithmetic Operators...98
Assignment Operator ...98
Comparison Operators ...98
String Concatenation Operators...98
Logical Operators...99
Is Operator...99
$ Operator...99
Operator Precedence ...111
VBScript Functions...112
VBScript Derived Functions ...169
VBScript Statements...170
VBScript Objects and Collections ...196
Scripting Type Library...212
FileSystemObject (FSO) ...216
Using VBScript With InduSoft HMI/SCADA Applications
InduSoft Web Studio (IWS) supports both a simple, proprietary scripting language (worksheet style) using one or more Math worksheets, as well as VBScript (new with IWS Version 6.1). Developers can use either scripting language or a combination of both. VBScript code is placed in one of several modules, based on the functionality to be performed and the scope of the code and its variables. This subject is covered more completely in the VBScript Configuration and Operation in IWS section.
Examples of how VBScript can be used:
• To execute a logic sequence or a routine when opening or closing a screen, or while the screen is open • To execute a logic sequence in the background
• Run a simple VBScipt code segment based on an IWS object’s command dynamic • Interaction with IWS Tags and control of IWS built-in functions
• Manipulation of ActiveX Controls and ActiveX Control event handler • Simple file I/O (e.g. text files)
• Database interfaces (e.g. via ADO.NET), especially where use of SQL is required
• Interface to Windows Management Instrumentation (WMI) and Web Services (via WSDL)
• Interface to Microsoft Office applications (e.g. Excel, Access, Word) and Microsoft Office components via OLE Automation
• Run on a Web Thin Client
Where you should use IWS instead of VBScript
• User Interface. IWS does not support Windows Scripting, which typically provides the User Interface for VBScript via Forms.
• Device I/O (e.g. PLC communications). VBScript does not directly support serial or network communications.
About VBScript
Visual Basic Script Language (VBScript) is one of Microsoft’s scripting languages that is commonly
associated with Server-side and Client-side web applications. However, Microsoft has opened up
VBScript to developers and now VBScript can be found in a variety of applications. InduSoft has
standardized on VBScript since it provides a significant subset of Microsoft Visual Basic’s functionality,
and VBScript supports all of Microsoft’s operating system platforms including Windows CE, unlike VBA
(Visual Basic for Applications) which cannot support the Windows CE runtime environment.
VBScript is a programming language that is often viewed as a dialect of VBA (Visual Basic for
Applications), although it is really its own language. The VBScript language attempts to balance
flexibility, capability and ease of use. VBA is a subset of Visual Basic that was developed to automate
Microsoft Office applications, whereas VBScript was originally developed to support Server-side and
Client-side web applications. Although VBScript and VBA provide many of the same features, there are
some differences between them, primarily due to the applications they were each developed to support.
So before we get into details of the VBScripting language, perhaps it is worthwhile to review how
VBScript is used with InduSoft Web Studio (IWS) or alternatively, why VBScript is included with IWS.
IWS provides an easy-to-use development environment that configures predefined objects to support
an HMI/SCADA application. Applications can be built quickly and are relatively easy to support, even by
someone other than the original developer. By comparison, programming languages such as Visual
Basic can be used to develop an HMI/SCADA application, but the lower per-copy licensing cost savings
quickly gets offset by much higher development costs and support costs. A programming development
environment is clearly more flexible than a configuration development environment, but there is a
significant cost associated with programming that makes it an unattractive alternative for HMI/SCADA
applications. By adding VBScript support to IWS, InduSoft lets you chose between configuration and
programming to meet your application needs and develop applications efficiently.
IWS implements Visual Basic Script Edition 5.5 or higher, and functions as the “host” for VBScript. IWS
provides an integrated development environment where the HMI/SCADA application developer can
take advantage of the functionality and ease of use of VBScript, yet have access to all IWS tags and all
built-in functions directly from VBScript. The diagram below illustrates the IWS architecture. Since
VBScript is an interpreted language, the VBScript Engine parses the language at runtime and executes
commands subject to limitations placed by the VBScript Host. InduSoft allows VBScript code to be
located several areas in an IWS application:
• Global Procedures. This is an area for subroutines and functions that can be called by any other
VBScript routine, or by a built-in IWS function (requires IWS Version 6.1 Service Pack 1 or later).
• Graphic Script. Code in this area gets executed whenever any graphics (screens) are active.
• Screen Script. This is where code is executed when an individual screen is active.
• Command Dynamic. When an object has a Command Dynamic, one option is to run VBScript
code.
• ActiveX Events. A VBScript code segment can be run based on an ActiveX event
• Background Task. VBScript code can be running as a background task. One or more VBScript
groups are supported, allowing conditional processing of the various VBScript background tasks.
This subject is covered more completely later in the VBScript Configuration and Operation in IWS
section.
In a Web Thin Client configuration, VBScripts associated with a screen can run either on the
workstation runtime display or on a Web Thin Client station running Microsoft Internet Explorer. The
VBScript routines that can execute on a Web Thin Client include those located in a Screen Script, a
Command Dynamic, and an ActiveX Event. Since VBScript runs on all Microsoft operating system
platforms, there are no limitations to VBScript running on any Microsoft compatible platform.
VBScript Limitations in IWS
Microsoft initially developed VBScript to work with websites (web pages). In the web server
environment, VBScript was designed to work with the Windows Scripting host and ASP, which provide
file access and form generation. On the web client side, VBScript was designed to work with Microsoft
Internet Explorer using HTML and DHTML, which provide display generation. So as a result of the initial
design goals, VBScript does not have much in the way of built-in language support for Forms, File I/O,
Communications or direct Printing control. Additionally, IWS has its own built-in web server and does
not use ASP.
By using IWS built-in functions, ActiveX controls and Microsoft Office Applications (or components),
there are several methods for workarounds to these limitations as well as to extend VBScript’s
capability.
The following are some of VBScript’s limitations and workarounds.
Item
VBScript
Workarounds
Forms Does not support Use IWS objects for user interface, pass parameters to IWS. Can also use ActiveX Controls.
File I/O Limited support directly Use Scripting Objects and/or IWS built-in functions. Can also use ActiveX Controls.
Communications Does not directly support Use IWS built-in functions or 3rd party ActiveX controls Printing Does not directly support Use Microsoft Office Applications or IWS built-in functions Charting/Graphing Does not directly support Use IWS trending, Microsoft Office Applications, Microsoft
Office Components, or 3rd party ActiveX controls
DDE Does not support Supported in IWS built-in commands (not under Windows CE).
Basic, VB (Visual Basic), VB.NET, VBA and VBScript – The Evolution
Most everyone is familiar with Basic, the Beginner’s All-purpose Symbolic Instruction Code that has been around since 1964. Originally designed to teach non-science students about computers, it was one of the first high-level programming languages ported to the PC in the 1980’s. It has continued to evolve with programming and operating system technology. Here is a quick summary of the different versions today:
• Basic A simple high-level programming language developed in 1964. Migrated to the PC platform in the 1980’s, with many versions developed.
• VB Visual Basic. An event-driven programming version of Basic, supporting graphical user interfaces (GUI), database access and ActiveX controls that was introduced in 1991. VB Version 6 was the last version released (1998).
• VB.NET The successor to VB launched in 2002. Supports Microsoft .NET framework architecture and is a true object-oriented programming language.
• VBA Visual Basic for Applications is a version of VB (most compatible with Version 6) that is built into Microsoft Office products (Word, Excel, Access, Outlook, PowerPoint) and into some other 3rd party products. Unlike VB or VB.NET, VBA does not run stand-alone and only runs from a host application, usually within a Microsoft Office application. VBA can control an second application while running in a host application. VBA works on Windows XP/2000/NT platforms only.
• VBScript VBScript is considered a dialect of VBA and is the default language for website Active Server Pages (ASP). Like VBA, VBScript does not run stand-alone and only runs from a host application. It is run by the operating system’s Windows Script Host and can be used for Server-side Windows scripting or Client-side Web Page scripting using Microsoft Internet Explorer. A key advantage of VBScript is that it is supported under Windows CE.
The Microsoft Visual Basic Family
VBScript is part of a family of Microsoft programming languages that support object-oriented
programming. This family of products is derived from the Basic programming language, first developed
in 1964. Once study recently indicated that over 50% of all programmers are familiar with VB (Visual
Basic) programming.
Differences between VBScript and VBA
Since other HMI/SCADA products support VBA, it might be worth highlighting some of the key
differences between VBScript and VBA. For HMI/SCADA applications, these differences are relatively
minor. However, VBScript support for the Windows CE operating system is a major differentiator
between the two products. For additional details or a complete listing of the differences, please
reference the MSDN website at http://msdn.microsoft.com.
Key differences between VBScript vs. VBA
Item
VBA
VBScript
Primary Purpose Automation of MS Office Applications Automation of Web Services
Support for Windows CE No Yes
Data Types Stronger Type Declaration. Many data types supported. (e.g. String, Integer, Date, Boolean)
Typeless, uses Variant Type. The final data subtype will be determined at runtime based on use. Supports same data subtypes as VBA and VB (e.g. String, Integer, Date, Boolean, etc) Dimension Statement Dim Var as Type Dim Var
(Cannot specify Type, but it is determined at runtime based on use) Class Block declaration Must use separate Class Module Class Block Declaration supported
Object Clipboard
Collection
Not supported
Object Manipulation TypeOf Not supported
Eval function Not supported Expression evaluation supported Execute function Not supported Allows interpreted code to be executed
on the fly.
RegExp No Allows creation of regular expressions
Error Handling Several different types Supported but more limited Arrays Lower bound can be <>0 Lower bound is 0
File I/O Supported Not directly supported but VBScript can
use FileSystemObject and can access IWS built-in I/O functions
DDE Supported Not supported
Financial functions Supported Not supported
Strings Fixed length strings Variable length only
Debugging Debug, Print, End, Stop Use MsgBox or IWS built-in functions
VBScript Hosting Environments
While much of the material contained in the document covers the VBScript language and its use for
IWS applications, it is important to understand conceptually how VBScript works in an IWS environment.
If you browse the web for information on VBScript, you will likely find a plethora of information, but
many of the examples are for running VBScript with ASP using the Windows Scripting Host.
VBScript was developed using a Microsoft technology called ActiveX scripting, which is a COM-based
specification that allows the development of runtime engines for virtually any scripting language. Other
scripting languages include JScript. VBScript can create an instance, or instantiate, a COM object, and
thus through VBScript, many system features can be controlled such as ActiveX Controls, the
FIleSystemObject (providing access to the Windows file system), Microsoft Office Automation (COM),
and ActiveX Database Objects (ADO).
The VBScript Scripting Engine runs on a host, and there are several hosts that can run VBScript (or
any ActiveX Scripting-compliant engines) including Windows Scripting Host and Microsoft Internet
Explorer. VBScript can be used in conjunction with Windows Scripting Host (WSH) to automate system
administration tasks. WSH is part of the Microsoft operating system and treats a VBScript application
like a powerful batch file. VBScript applications can also be found with Web-based shell views. Most
frequently, VBScript is used with Active Server Pages (ASP) for Server-side web applications and
Microsoft Internet Explorer for Client-side web applications.
Stating with Version 6.1, IWS is now a host for the VBScript Scripting Engine. When used in
conjunction with IWS, IWS becomes the only host for the VBScript Scripting Engine that is used. WSH
is not used by IWS, even though WSH may be resident on the PC running the IWS application.
InduSoft has placed implemented VBScript host environment in a manner that is logically consistent
with the current IWS application development environment and licensing method. What this means is
that there are multiple locations in the development environment where VBScript code segments can
be located (so the code is located close to its use), and restrictions placed on the scope of procedures
and variables. In IWS, there is no such thing as a Global Variable that is accessible by any VBScript
code segment. The IWS tags and built-in procedures can be accessed by any VBScript code segment.
The restrictions and interaction with IWS tags and built-in functions implemented by the IWS VBScript
Host are covered in more detail in the VB Configuration and Operation in IWS section.
The VBScript Scripting Engine performs a few key functions. It performs syntax checking in the
development environment (e.g. right mouse click on a VBScript Interface, then select Check Script). It
also interacts with IntelliSense, an auto-completion tool that provides reference to available functions
(VBScript and IWS), IWS tags and ActiveX Controls (name, Properties and Methods). And most
importantly, it executes the VBScript code at runtime, providing error messages if an error occurs. It
should be noted that unlike most programming languages, VBScript is not compiled; it runs in an
interpreted mode. The VBScript Scripting Engine (vbscript.dll) is responsible for interpreting (via the
VBScript Parser, a part of the VBScript Scripting Engine) and executing the VBScript statements, and it
does so quite efficiently. IWS uses Version 5.6 or later of the Microsoft VBScript Scripting Engine.
There are no limitations on the number of VBScript variables supported in IWS, however the amount of
storage for VBScript variables is determined by the amount of memory available in your system.
VBScript Language Overview
This section contains a short summary of the VBScript Language. A more complete reference of the
VBScript language can be found in the Appendix at the end of these materials.
VBScript Functionality
VBScript has inherited much of VB & VBA’s functionality including support for math operations, string
manipulation, arrays, flow control, data conversion, procedures, COM objects, and date/time functions.
Since VBScript was initially designed for Web applications, direct support for file I/O and user interface
functions was not included. However, VBScript can use the FileSystemObject COM object (scrrun.dll)
to manipulate local files and folders.
VBScript does not support explicitly declared data types. This was eliminated to speed up the runtime
performance of the VBScript Scripting Engine. All variables are type Variant and their subtype (e.g.
Integer, Real, etc.) is determined at runtime.
VBScript Elements
There are several VBScript elements, but the most important ones are variables, constants and types.
A variable is an item holding data that can change during the execution of the VBScript program. A
constant is an item that holds data but cannot change during the execution of the VBScript program.
The data that variables and constants hold can be classified into types.
Note that with IWS, you can check the VBScript syntax for errors by choosing the Check VBScript
command (right mouse click when in a VBScript interface). VBScript is always checked when saving
the Script interface.
The VBScript elements that are covered in this material (and the Appendix) include:
• Variables (Type, Declaration, Scope)
• Constants (Explicit, Implicit)
• Keywords
• Errors (Runtime, Syntax)
• Operators
• Functions and Procedures
• Statements
• Objects and Collections
• Example VBScript Applications
The Check Script function can be invoked following a right mouse click when the cursor is on the VBScript Interface. Note that Comments are in Green, VBScript Functions and KeyWords are in Blue, Variables are in Black
Variable Data Types and Subtypes
All variables in VBScript are a data type called Variant. This means that you do not (and cannot)
explicitly declare the variable type. In fact, with VBScript you do not need the Dim statement to allocate
storage for a variable. At runtime, the Parser in the VBScript Scripting Engine determines the Variant
data subtype to be used. These correspond to the more traditional classifications of data types (see
chart below).
Variant data subtypes
Subtype Description
Boolean Either True or False
Byte Contains integer in the range 0 to 255
Currency Floating-point number in the range -922,337,203,685,477.5808 to 922,337,203,685,477.5807 Date(Time) Contains a number that represents a date between January 1, 100 to December 31, 9999
Double Contains a doubleprecision, floatingpoint number in the range 1.79769313486232E308 to -4.94065645841247E-324 for negative values; -4.94065645841247E-324 to
1.79769313486232E308 for positive values Empty Uninitialized Variant
Error Contains an error number used with runtime errors Integer Contains integer in the range -32,768 to 32,767
Long Contains integer in the range -2,147,483,648 to 2,147,483,647 Null A variant containing no valid data
Object Contains an object reference
Single Contains a single-precision, floating-point number in the range -3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values
String Contains a variable-length string that can be up to approximately 2 billion characters in length.
The Parsers choice of data subtype will depend on how the variable is used in a statement or function.
Note that a variable’s subtype can change within a code segment.
Data Subtype Identification
If it is important to determine the Variant data subtype used at runtime, you may use any of the three
categories of functions to determine the data subtype:
•
The VarType(variable) function which returns a code based on the Variant data subtype used
•
Various IsXxxx(variable) functions which return boolean values indicating whether the variable
is of a specific data subtype.
•
A TypeName(variable) function which returns a string based indicating the data subtype
Example:
If varType(a) = vbInteger Then
Msgbox “a is an Integer”
EndIf
Data Subtype Conversion
VBScript provides several functions that convert a variable from one data subtype to another. Since
VBScript uses the Variant data type, these functions are not generally required. However, when
passing data between IWS (or CEView) and VBScript, or calling built-in IWS functions from VBScript
where variables need to be put into the proper argument format, these VBScript data subtype
conversion functions can be very useful.
Example:
a = 4.2
Variable Naming Rules & Conventions
VBScript has four primary rules for naming. These are:
1. Variable names must begin with an alpha character (a..z, A...Z) or an underscore character
2. After the first character, the variable name can contain letters, digits and underscores
3. Variable names must be less than 255 characters in length
4. The variable name must be unique in the scope in which they are declared
VBScript variable names are not case sensitive. Microsoft recommends following their naming
convention for variables, which puts attaches different prefixes to the variable name based on the data
subtype.
Variable Scope
Variables have “scope” which defines a variable’s visibility or accessibility from one procedure (or
VBScript Interface) to another, which is principally determined by where you declare the variable.
Generally, when you declare a variable within a procedure, only code within that procedure can access
or change the value of that variable. This is called local scope and is for a procedure-level variable.
If you declare a variable outside a procedure, you make it recognizable to all the procedures in your
Script. This is a Script-level variable, and it has Script-level scope. However, as previously noted,
InduSoft enforces certain restrictions on the scope of Variables and Procedures.
VBScript Constants
VBScript supports both explicit and implicit constants. Constants should never be used as variable
names.
Explicit constants are defined by the programmer. Explicit constants have a defined value which, unlike
a variable, is not allowed to change during the life of the script.
Implicit constants are pre-defined by VBScript. VBScript implicit constants usually begin with a vb
prefix. VBScript implicit constants are available to the VBScript programmer without having to define
them. Other objects, such as those used by ADO.NET, also have implicit constants predefined, usually
with different prefixes. However, the implicit constants for these objects may not be know to VBScript
and if not, will have to be defined as an explicit constant.
VBScript defines the following categories of implicit Constants:
Intrinsic Constant Category Intrinsic Constant Category Color Constants File Attribute Constants Comparison Constants File Input/Output Constants Date and Time Constants MsgBox Constants
Date Format Constants MsgBox Function Constants Days of Week Constants SpecialFolder Constants New Years Week Constants String Constants
Error Constants Tristate Constants
VBScript Runtime Errors VarType Constants VBScript Syntax Errors Locale ID (LCID)
Declaring VBScript Variables and Constants
VBScript does not require the explicit declaration of scalar variables, i.e. those variables with only one
value assigned at any given time. Arrays, Objects (except Err) and Constants must be declared. While
it may initially be convenient not to declare variables, any typing (spelling) errors of the variable or
constant names may produce unexpected results at runtime.
VBScript Keywords
VBScript has many keywords. Keywords are merely the names or symbols used with built-in VBScript
functions. Keywords are reserved, i.e. they may not be used by the programmer as names of variables
or constants. VBScript keywords can be grouped into categories which include:
• Constants & Literals
• Operators
• Functions
• Statements
• Objects
Operators
VBScript defines various operators that perform operations based on the Variant subdata type(s).
Arithmetic operators are used to perform operations on two or more numbers.
Arithmetic
Comparison
Symbol Definition + Add - Subtract * Multiply / Divide \ Integer Divide ^ Exponentiation MOD Modulus DivisionLogical
String
Symbol Definition AND And OR, | Or XOR Exclusive OR Eqv Equivalence Imp Implication Not NOTObject
IWS
Symbol Definition Is Is (compare) Symbol Definition < Less than<= Less than or equal > Greater than
>= Greater than or equal = Equal or assignment <> Not equal
Symbol Definition
&, + Concatenation
Symbol Definition
Operator Precedence
When several operations occur in an expression, each part is evaluated and resolved in a
predetermined order called operator precedence. Parentheses can be used to override the order of
precedence and force some parts of an expression to be evaluated before other parts. Operations
within parentheses are always performed before those outside. Within parentheses, however, normal
operator precedence is maintained.
When expressions contain operators from more than one category, arithmetic operators are evaluated
first, comparison operators are evaluated next, and 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 and logical operators are evaluated in the following order of precedence:
When multiplication and division occur together in an expression, each operation is evaluated as it
occurs from left to right. Likewise, when addition and subtraction occur together in an expression, each
operation is evaluated in order of appearance from left to right.
The string concatenation operator (&) is not an arithmetic operator, but its precedence does fall in after
all arithmetic operators and before all comparison operators. The Is operator is an object reference
comparison operator. It does not compare objects or their values; it only checks to determine if two
object references refer to the same object.
Operator Precedence
Arithmetic Comparison Logical
Negation (-) Equality (=) Not
Exponentiation (^) Inequality (<>) And
Multiplication and division (*, /) Less than (<) Or
Integer division (\) Greater than (>) Xor
Modulus arithmetic (Mod) Less than or equal to (<=) Eqv Addition and subtraction (+, -) Greater than or equal to (>=) Imp
String concatenation (&, +) Is &
Functions
VBScript contains a number of built-in functions (not to be confused with the Function Procedure).
These functions may or may not have arguments. These functions are called in a statement and may
return a result that can be assigned to a variable. VBScript’s functions are grouped as follows:
Array Functions
Array Functions Description
Array Returns a variant containing an array
Filter Returns a zero-based array that contains a subset of a string array based on a filter criteria IsArray Returns a Boolean value that indicates whether a specified variable is an array
Join Returns a string that consists of a number of substrings in an array LBound Returns the smallest subscript for the indicated dimension of an array
Split Returns a zero-based, one-dimensional array that contains a specified number of substrings UBound Returns the largest subscript for the indicated dimension of an array
Data Conversion Functions
Function Description
Abs Returns the absolute value of a specified number
Asc Converts the first letter in a string to its ASCII decimal representation CBool Converts an expression to a variant of subtype Boolean
CByte Converts an expression to a variant of subtype Byte CCur Converts an expression to a variant of subtype Currency
CDate Converts a valid date and time expression to the variant of subtype Date CDbl Converts an expression to a variant of subtype Double
Chr Converts the specified ANSI code to a character CInt Converts an expression to a variant of subtype Integer CLng Converts an expression to a variant of subtype Long CSng Converts an expression to a variant of subtype Single CStr Converts an expression to a variant of subtype String Fix Returns the integer part of a specified number Hex Returns the hexadecimal value of a specified number Int Returns the integer part of a specified number Oct Returns the octal value of a specified number Round Returns a rounded number
Sgn Returns the integer portion of a number
Date and Time Functions
Function Description
CDate Converts a valid date and time expression to the variant of subtype Date Date Returns the current system date
DateAdd Returns a date to which a specified time interval has been added DateDiff Returns the number of intervals between two dates
DatePart Returns the specified part of a given date
DateSerial Returns the date for a specified year, month, and day DateValue Returns a date
Day Returns a number that represents the day of the month (between 1 and 31, inclusive) FormatDateTime Returns an expression formatted as a date or time
Hour Returns a number that represents the hour of the day (between 0 and 23, inclusive) IsDate Returns a Boolean value that indicates if the evaluated expression can be converted to a
date
Minute Returns a number that represents the minute of the hour (between 0 and 59, inclusive) Month Returns a number that represents the month of the year (between 1 and 12, inclusive) MonthName Returns the name of a specified month
Now Returns the current system date and time
Second Returns a number that represents the second of the minute (between 0 and 59, inclusive) Time Returns the current system time
Timer Returns the number of seconds since 12:00 AM
TimeSerial Returns the time for a specific hour, minute, and second TimeValue Returns a time
Weekday Returns a number that represents the day of the week (between 1 and 7, inclusive) WeekdayName Returns the weekday name of a specified day of the week
Year Returns a number that represents the year
Expression Functions
Expressions Description
Eval Evaluates an expression and returns the result RegExp Provides simple regular expression support.
Format Functions
Function Description
FormatCurrency Returns an expression formatted as a currency value FormatDateTime Returns an expression formatted as a date or time FormatNumber Returns an expression formatted as a number FormatPercent Returns an expression formatted as a percentage
I/O Functions
Input/Output Description
InputBox Displays a prompt in a dialog box, waits for the user to input text or click a button, and returns the contents of the text box.
MsgBox Displays a message in a dialog box, waits for the user to click a button, and returns a value indicating which button the user clicked.
LoadPicture Returns a picture object
Math Functions
Function Description
Abs Returns the absolute value of a specified number Atn Returns the arctangent of a specified number Cos Returns the cosine of a specified number (angle) Exp Returns e raised to a power
Hex Returns the hexadecimal value of a specified number Int Returns the integer part of a specified number Fix Returns the integer part of a specified number Log Returns the natural logarithm of a specified number Oct Returns the octal value of a specified number Randomize Initializes the random-number generator
Rnd Returns a random number less than 1 but greater or equal to 0 Sgn Returns an integer that indicates the sign of a specified number Sin Returns the sine of a specified number (angle)
Sqr Returns the square root of a specified number Tan Returns the tangent of a specified number (angle)
Miscellaneous Functions
Miscellaneous Description
GetLocale Returns the current locale ID
RGB Returns a whole number representing an RGB color value SetLocale Sets the current locale ID
Script Engine Functions
Script Engine ID Description
ScriptEngine Returns a string representing the scripting language in use ScriptEngineBuildVersion Returns the build version number of the scripting engine in use ScriptEngineMajorVersion Returns the major version number of the scripting engine in use ScriptEngineMinorVersion Returns the minor version number of the scripting engine in use
String Functions
Function Description
InStr Returns the position of the first occurrence of one string within another. The search begins at the first character of the string
InStrRev Returns the position of the first occurrence of one string within another. The search begins at the last character of the string
LCase Converts a specified string to lowercase
Left Returns a specified number of characters from the left side of a string Len Returns the number of characters in a string
LTrim Removes spaces on the left side of a string
Mid Returns a specified number of characters from a string
Replace Replaces a specified part of a string with another string a specified number of times Right Returns a specified number of characters from the right side of a string
RTrim Removes spaces on the right side of a string
Space Returns a string that consists of a specified number of spaces
StrComp Compares two strings and returns a value that represents the result of the comparison String Returns a string that contains a repeating character of a specified length
StrReverse Reverses a string
Trim Removes spaces on both the left and the right side of a string UCase Converts a specified string to uppercase
Variant Identification Functions
Variant Function
Description
IsArray Returns a Boolean value indicating whether a variable is an array
IsDate Returns a Boolean value indicating whether an expression can be converted to a date IsEmpty Returns a Boolean value indicating whether a variable has been initialized.
IsNull Returns a Boolean value that indicates whether an expression contains no valid data (Null). IsNumeric Returns a Boolean value indicating whether an expression can be evaluated as a number IsObject Returns a Boolean value indicating whether an expression refers to a valid Automation
object.
TypeName Returns a string that provides Variant subtype information about a variable VarType Returns a value indicating the subtype of a variable
Statements
VBScript statements are used to perform fundamental operations such as decision making, repetition
(looping) and assignments. Statements combined with Operators are the building blocks for more
complex code.
Multiple statements can appear on the same line as long as they are separated by a colon (:). For
purposes of code readability, it is recommended to use one statement per line.
Assignment Statements
Many of VBScripts assignment statements have already been covered. For consistency purposes, they
are listed here. Please refer to the Appendix for a more detailed description of their use.
Assignment Statements
Statement Description
Const Declares constants for use in place of literal values Dim Declares variables and allocates storage space
Erase Reinitializes the elements of fixed-size arrays, deallocates dynamic-array storage space. Option Explicit Forces explicit declaration of all variables in the script
Private Declares private variables and allocates storage space Public Declares public variables and allocates storage space
Comment Statements
Comment statements are used to provide documentation comments with the code.
Comment Statements
Comments Description
Rem Includes explanatory remarks in a program
‘
Includes explanatory remarks in a program (single quote)Control Flow Statements
By default, VBScript sequentially moves (flows) through the script from statement to statement. As is
typical with virtually all high-level programming languages, control flow statements can alter this flow by
branching to other code sections based upon logic conditions, inputs, errors, etc.
One of the most commonly used control flow statement is the If..Then..Else statement. This control
flow statement takes the following format:
{simple format}
If condition Then statement(s) [Else elsestatement(s) ]
{block format}
If condition Then
[statement(s)]
[ElseIf condition-n Then
[elseifstatement(s)]] . . .
[Else
[elsestatement(s)]]
End If
The condition can be a boolean constant or boolean variable, or a numeric or string expression that
evaluates to True or False.
Refer to the Appendix for a detail description of these functions.
Control Flow Statements
Function Description
Do…Loop Repeats a block of statements while a condition is True or until a condition becomes True Execute Executes one or more specified statements
Execute Global Executes one or more specified statements in the global namespace of a script
Exit Do Exit a Do Loop Function. Transfers control to the statement following the Loop statement. Exit For Exit a For Loop Function (For…Next or For Each…Next loop). Transfers control to the
statement following the Next statement.
For...Next Repeats a group of statements a specified number of times
For Each…Next Repeats a group of statements for each element in an array or collection
If…Then…Else Conditionally executes a group of statements, depending on the value of an expression Select Case Executes one of several groups of statements, depending on the value of an expression While…Wend Executes a series of statements as long as a given condition is True
Procedure Statements
There are two types of procedure statements; the Sub procedure and the Function procedure. Both of
these procedure statements are intended to encapsulate a set of statements that provide functionality
that can be repeatedly called, but the difference between the two is how arguments are passed and
results returned.
The Sub procedure is a series of VBScript statements (enclosed by Sub and End Sub statements) that
perform actions but don't return a value as part of the Sub name. A Sub procedure can take arguments
(constants, variables, or expressions that are passed by a calling procedure). A resultant value or set of
values can be returned through the arguments. If a Sub procedure has no arguments, its Sub
statement must include an empty set of parentheses ().
The Function procedure is a series of VBScript statements enclosed by the Function and End
Function statements. A Function procedure is similar to a Sub procedure, but can also return a value
in the Function name. A Function procedure can take arguments (constants, variables, or expressions
that are passed to it by a calling procedure). If a Function procedure has no arguments, its Function
statement must include an empty set of parentheses. A Function returns a value by assigning a value
to its name in one or more statements of the procedure. The return type of a Function is always a
Variant.
Procedure Statements
Function Description
Call Transfers control to a Sub or Function procedure End Function Immediately exits a Function procedure
End Sub Immediately exits a Sub procedure
Exit Function Exit a Function, generally as a result of a condition Exit Sub Exit a Subroutine, generally as a result of a condition
Function Declares the name, arguments, and code that form the body of a Function procedure GetRef Associates an event handler with a specific function
Sub Declares the name, arguments, and code that form the body of a Sub procedure (Subroutine).
Objects and Classes
Traditional programming is made up of a collection of subroutines and functions that are typically
processed in a sequential or looping manner. In contrast, object oriented programming is a different
programming methodology where a program is viewed as being composed of a collection of individual
objects. These objects process data and can interact with other objects directly without having to be
explicitly programmed to do so. The advantages claimed by object-oriented program include code
reusability, rapid deployment of large-scale complex tasks, and ease of use/debugging. Today,
object-oriented programming is widely used and is supported with both programming languages (e.g. VB.NET,
C++, Visual C++) and operating systems (e.g. Microsoft’s .NET architecture). Object-oriented
programming has also become popular within scripting languages, such as VBScript. Beginning with
VBScript 5.0, developers have been able to use user-defined Classes.
The key concepts with object-oriented programming include:
• Class
The class is the highest level that defines a unit (set) of data and its behavior. Classes form the
basis for modularity and structure in an object-oriented program. The class should sufficiently
describe the set of data, and the code for a class should be contained within it and be
self-sufficient (except for operating system support). While the terms classes and objects often get
used interchangeably, classes describe the structure of objects. One way to think of a class is
that it is a container for code. It can also be viewed as a template for an object. When a class is
declared (instantiated) by the Set statement, it then becomes an object and memory is allocated
for it.
• Object
An object is an in-memory instance of a class. In computer science terms, it is a run-time
manifestation (instantiation) of a particular exemplar of a class. Each object has its own data,
but the code within a class can be shared (for efficiency). Programs generally have multiple
objects. Multiple copies (objects) of a given class can be created. Objects are temporary, i.e.
they can be created and removed at will, depending on the programming needs.
• Encapsulation
Encapsulation wraps the data and functions into a single unit, ensuring that the object can be
changed only through established interfaces. Encapsulation is sometimes referred to as
information hiding. Some of these common interfaces are:
o Fields
Fields are simply public variables stored within the object, as defined by the class. These
variables store items of information about an object.
o Properties
Properties, like fields, also store items of information on an object. But Properties use
Property procedures to control how values are set or returned. VBScript has two primary
Property procedures; Let and Get. The Get property procedure retrieves a Property
value, while the Let Property procedure assigns a value to the property value. A third
Property procedure Set is used with an Object inside of the Class block.
o Methods
Methods are a collection of subroutines (Sub) and function procedures (Function)
declared within a class.
o Events
An event is a message sent by an object announcing that something important has
happened.
Access of an object’s methods, properties and fields are made by referring to the object,
followed by a period, then the particular method, property or field of interest. E.g.
Object.Method
Object.Property
Object.Property.Item
• Dynamism
Dynamism relates to the method of allocating computer resources and definition resources
required to run an object-oriented program. There are different types, but VBScript used
late-bound (late-binding) dynamic typing. This means that the VBScript engine will make the object
type determination at runtime and allocate sufficient memory at that time. Note that VBScript
and VB.NET are slightly different in their approach to dynamism, and therefore they can declare
some variables and objects in different manners (although many forms of declaration are the
same).
• Outlet Connections
At times, Objects will connect together and this connection needs to be defined. With IWS, an
example of a connection would be between a VBScript object (e.g. ADODB) and a Database
Provider (a Provider is a front-end to a database). This connection needs to be defined, and
then the connection string (of parameters) between the objects gets defined. When the need for
the connection is finished, the connection should be closed.
While a full treatment of object-oriented programming is beyond the scope of these materials, the
fundamental concepts of Objects and Classes are important to understand. VBScript supports
COM-based Objects (Component Object Module, a Microsoft standard) such as the ActiveX controls,
ADO.NET, FileSystemObject, and Microsoft Office Automation objects. VBScript also supports
user-defined classes, or Class Objects.
VBScript COM objects and VBScript Class objects differ from each other in several important respects.
These differences lead to each type of object having its unique strengths:
•
VBScript classes are more flexible than VBScript COM objects. Class Objects have an abstract
subtype that encapsulates the data you want and the functions you need to work with that data.
VBScript COM objects have only basic subtypes (integer or string).
•
VBScript classes are slightly more efficient than COM objects. The VBScript parser can execute
the classes' code directly instead of asking the COM object to execute a method.
•
COM objects are binary modules. VBScript classes are ASCII files.
•
You can use any scripting language to write COM objects. You can only use VBScript to write
VBScript classes.
•
You can use COM objects from within any development environment that supports COM
automation. VBScript classes can only be used within development and runtime environments
that support VBScript (e.g IWS and Microsoft Internet Explorer).
VBScript Object Commands
VBScript includes several Functions and Statements that can be used to access objects, including their
methods and properties. There are a large variety of objects available to VBSript, including
user-defined objects, intrinsic objects and extrinsic objects.
VBScript Object Functions
Function Description
CreateObject Creates and returns a reference to an Automation object GetObject Returns a reference to an Automation object from a file
IsObject Returns a Boolean value indicating whether an expression references a valid Automation object.
Object Statements
Error Handling Statements
Statement Description
On Error Enables or disables error-handling Object & Collection Summary
Objects & Collections Description
Debug The Debug object is an intrinsic global object that can send an output to a script debugger, such as the Microsoft Script Debugger.
Dictionary An associative array that can store any type of data. Data is accessed by a key. Drive An object that refers to a specific Drive
Drives A collection of Drive objects.
Err Contains information about the last run-time error. Accepts the Raise and Clear methods for generating and clearing run-time errors.
File An object that refers to a specific File Files A collection of File objects.
FileSystemObject An object model used to access the Windows file system Folder An object that refers to a specific Folder
Folders A collection of Folder objects.
Match Provides access to the read-only properties of a regular expression match. Matches Collection of regular expression Match objects.
RegExp Provides simple regular expression support. Submatches A collection of regular expression submatch strings. TextStream An object that refers to a text File
Statement Description
Class Declares the name of a class, as well as a definition of the variables, properties, and methods that comprise the class
Exit Property Forces an exit from inside a Property Set function.
For Each…Next Repeats a group of statements for each element in an array or a collection.
Property Get Declares, in a Class block, the name, arguments, and code that form the body of a Property procedure that gets (returns) the value of a property
Property Let Declares, in a Class block, the name, arguments, and code that form the body of a Property procedure that assigns (sets) the value of a property
Property Set Sets a reference to an object
Set Assigns an object reference to a variable or property, or associates a procedure reference with an event. Usually used to instantiate an object.
VBScript User-Defined Class Objects
To define a user-defined Class Object, you use the Class statement to declare a class. The End Class
statement defines the termination of the Class. Together, these statements form a Class construct, or
Class block. E.g.
Class objName
‘ Place the Class variables, Properties and Methods here
End Class
In this syntax, objName is the name given to the Class Object. The class object name must follow
standard VBScript variable naming conventions. Class Objects are usually declared in the variable
definition sections. You can have multiple Class blocks in a single VBScript file, but each block must
contain the Class …End Class statements. Classes cannot be nested.
Once you have defined the Class Object, you need to create an instance of the Class, similar to how
other objects are created. When the Class Object is instantiated, memory is allocated for the Class
Object. The Set statement is used with the New keyword to assign an instance of the class to a
variable. With VBScript, this is the only time the New keyword is used (i.e. to instantiate a user-defined
Class). E.g.
Dim MyObj
Set MyObj = New objName
The Object name MyObj is the Object variable name, and must follow standard VBScript variable
naming conventions. The Object variable name is a reference (address) of the Object stored in
memory, it is not the Object itself.
Inside the Class block, any Class variables, Properties, Methods and Events can be defined by the
developer. The developer does not have to use all of the capabilities of the Class construct, i.e. Classes
can be created without Methods or Properties. The design of the Class Object is completely up to the
developer.
Class variables are created within the Class structure by using the Dim, Public, or Private statements.
Variables defined within the Class structure by any of these statements must follow the standard
VBScript variable naming conventions. Variables can be simple variables or arrays. E.g.
Class className
Dim var1, var2
Public var3, var4
Private var5, var6
End Class
The choice of the Dim, Public, or Private statements determine whether the variable is accessible
outside of the Class Object. Variables are public by default, i.e. they are accessible outside of the Class
Object. Both the Dim and the Public statements create public variables, while the Private statement
creates variables that are not public. As a general rule, it is good programming practice to make all
Class variables private, since the developer will want to tightly control when these variables are
changed.
VBScript does not support Class-level Constants, i.e. named constants declared at the Class level. You
cannot use the Const statement at the Class-level so that a constant can be used throughout a Class,
but you can use the Const statement within a Property or Method. However, the constant will only have
local scope within the Property or Method.
Class Object variables are accessible to VBScript code outside the Class through Class Properties.
Class Properties “wrap” the Private variables of a Class. Inside the Class block, the Properties are
defined by Property Get [|Let|Set] … End Property statement(s). For VBScript code outside the
Class, the Property is accessed by referencing the Object Name.Property.
There are different type of Class Properties, depending on whether the Class variable is to be read,
written to, or the Class variable is itself a Class Object. These Properties can be declared Public or
Private.
Property Get
The Property Get procedure is used to access (return) private variables inside of the Class
structure that are used as a read-only Property, or the read portion of a read-write Property. For
VBScript code outside the Class, this type of Class Object Property is generally assigned to a
variable or used in a conditional expression. The Property Get procedure returns a value to the
calling code, and is general not used with any arguments. [Note: VBScript will let you add
arguments to the Property Get procedure, but if you do so you must add the additional
argument to the corresponding Property Let or Property Set procedure, since Property
Let/Property Set must have one more argument than the corresponding Property Get
procedure. It is generally considered bad programming form to have arguments in the Property
Get procedure].
Property Let
The Property Let procedure is used to access (assign) private variables inside of the Class
structure that are used as a write-only Property or are the write portion of a read-write Property.
For VBScript code outside of the Class, this type of Class Object Property is usually assigned
by a variable or a constant.
Property Set
The Property Set procedure is exclusively used when the Class Object needs to store
Properties that are object-based instead of numeric, date, boolean or string subtype variables.
Property Set replaces the Property Let procedure. While Property Set and Property Let are
functionally similar, there are two key differences:
1. With the Property Set procedure, in the VBScript code segment (outside the Class block)
you must use the syntax
Set Object1.Property = Object2
This is because VBScript does not let you use the assignment operator (=) to assign objects
without the Set command.
2. The Property Set procedure makes it clear that the Property is an object-based Property
Example:Class FileSpec ‘ Define a Class block
Private master_file Private master_FSO
Public Property Let FileName(strName) ‘ Define a Public Property to assign the file name master_file = strName
End Property
Public Property Get FileName ‘ Define a Public Property to retrieve a file name FileName = master_file
End Property
Public Property Set FSO(m_FSO) ‘ Define a Public Property for an object Set master_FSO = m_FSO
End Property End Class
Rem Below is the VBScript code
Dim objFSO ‘ Declare variables and objects
Dim objFilePointer, cur_file
Set objFSO = CreateObject(“Scripting.FileSystemObject”) ‘ Instantiate the COM object Set objFilePointer = New FileSpec ‘ Instantiate the Class Object
objFilePointer.FileName = “Myfile.mdb” ‘ Assigns “Myfile.mdb” as the file name
cur_file = objFilePointer.FileName ‘ Retrieves the current file name “Myfile.MDB” Set objFilePointer.FSO = objFSO ‘ Assigns an Object to the Property
Set objFilePointer = Nothing ‘ Keyword Nothing releases the object memory
A couple notes on the example above. The CreateObject command is used to instantiate an Object
that is known at the system level (e.g. a COM object). Also, so far this example only shows how to
assign and retrieve property values. It is generally the Method(s) that control the action an object
performs, not the properties.
A Property can be made read-only by only providing a Property Get procedure, or by declaring the
Property Let procedure as Private instead of Public. A Property can be made write-only by only
providing the Property Let procedure, or by declaring the Property Get procedure as Private instead of
Public.
Class Methods are really just Functions and Subroutines inside of a Class block. These functions and
subroutines can be either Private or Public. If they are public, they will be accessible to a VBScript code
segment outside of the Class block by referencing the obj.Method. If they are private, they will only be
available to code within the Class block.
An example of Class Methods is as follows:
Class FileSpecPrivate master_file
Private master_FSO Private master_file
Private Sub Class_Initialize ‘ Class Object initialization code ‘ code goes here
End Sub
Private Sub Class_Terminate ‘ Class Object termination code ‘ code goes here
End Sub
Public Property Let FileName(strName) ‘ Define a Public Property to assign the file name master_file = strName
End Property
Public Property Get FileName ‘ Define a Public Property to retrieve a file name FileName = master_file
End Property
Public Property Set FSO(m_FSO) ‘ Define a Public Property for an object Set master_FSO = m_FSO
End Property
Public Sub Delete ‘Method to delete the master file master_FSO.DeleteFile (master_file)
End Sub End Class
Rem Below is the VBScript code
Dim objFSO ‘ Declare variables and objects
Dim objFilePointer, cur_file
Set objFSO = CreateObject(“Scripting.FileSystemObject”) ‘ Instantiate the COM object Set objFilePointer = New FileSpec ‘ Instantiate the Class Object
objFilePointer.FileName = “Myfile.mdb” ‘ Assigns “Myfile.mdb” as the file name
cur_file = objFilePointer.FileName ‘ Retrieves the current file name “Myfile.MDB” Set objFilePointer.FSO = objFSO ‘ Assigns an Object to the Property
objFilePointer.Delete ‘ Executes a Method to delete a file
Set objFilePointer = Nothing ‘ Keyword Nothing releases the object memory
VBScript Class Objects automatically supports two type of Class Events; Class_Initialize and
Class_Terminate Events. The code inside the Class_Initialize event executes once when an Object
based on the Class is first instantiated. Any code put in this event is optional, and is typically used for
initialization. Code inside the Class_Terminate event executes once just before the Object based on the
Class is destroyed (i.e. Set to Nothing, or the Object goes out of scope). Usage is as follows:
Class FileSpec
Private master_file
Private master_FSO Private master_file
Private Sub Class_Initialize ‘ Class Object initialization code ‘ code goes here
End Sub
Private Sub Class_Terminate ‘ Class Object termination code ‘ code goes here
End Sub
Public Property Let FileName(strName) ‘ Define a Public Property to assign the file name master_file = strName
End Property
Public Property Get FileName ‘ Define a Public Property to retrieve a file name FileName = master_file
End Property
Public Property Set FSO(m_FSO) ‘ Define a Public Property for an object Set master_FSO = m_FSO
End Property End Class