VBScripting Manual - Rev 2013
VBScripting Manual - Rev 2013
VBScripting Manual - Rev 2013
Scripting Manual
Infolytica Corporation
We welcome your comments regarding Infolytica Corporation documents. Please send comments or corrections to
the following addresses:
email: [email protected]
All rights reserved. No part of this document may be reproduced, translated to another language, stored in
a retrieval system, or transmitted in any form or by any means, electronic, photocopying, recording, or
otherwise, without written permission from Infolytica Corporation.
Appendix A 42
JScript ............................................................................................................................................ 42
References ..................................................................................................................................... 42
Script Forms ................................................................................................................................... 42
5
Chapter 1: Introduction
USER SCRIPTS
Within the various Infolytica applications, scripts can be executed within MagNet, ElecNet,
and ThermNet.
Scripts are text files that contain a series of scripting commands. Script files, which can be
created or modified in any text editor, can be automatically generated using the Infolytica
application and later modified by the user. Alternately, new scripts may be written entirely
from scratch in a text editor. Note that when editing or creating a user script in a text editor,
one must make sure to save the file in text format with the .vbs extension, in order to have it
recognized by the Infolytica application. There are two methods to creating scripts. The first
method requires no additional coding from the user. The script can be used to build or solve
models within any of the products.
In order to automatically create a user script, select Start Recording User Script from the
Scripting Menu and save the script. The application then records all of the commands and
actions carried out by the user until the user stops or pauses the script (Note: Any actions
carried out by any of the Infolytica Extensions are not recorded.). One can then run the script
by selecting Run Script from the Scripting menu and choosing the desired script file.
These recorded user script files can be used as a starting point in generating scripts that are
more functional.
6 M AGNET/ELECNET/THERMNET SCRIPTING M ANUAL CHAPTER 1
Session log
MagNet, ElecNet and ThermNet automatically generate a script file
(MagNetSessionLog.vbs ,ThermNetSessionLog.vbs or ElecNetSessionLog.vbs) every
time they are accessed. This session log, located, by default, in the LogFiles folder of the
application, can also be used as a user script and run from within the application. The file
contains a log of all the activities from the moment one enters the program until the program
is closed (Note: The session log is backed up for up to ten times that the application is
opened before the file is removed. The phrase Backup- followed by a number is appended
to the front of the session log file name). One can view the contents of the session log file by
selecting View Session Log from the help menu.
The second method of implementing script files involves customizing existing scripts. A
script file can be modified using a text editor, such as Word or Notepad. The values in the
script can later be altered and used in some of the code or whole sections of code can be
eliminated altogether. In addition, variables and program coding can be added to increase the
functionality of the script. One can add selected portions from multiple scripts together in
order to increase the functionality of a script or create an entirely new script.
Scripts can be written in either VBScript or in JScript. The coding language of both the user
scripts and the session log for MagNet, ElecNet and ThermNet is in VBScript. Therefore, this
manual will focus on VBScript programming syntax.
7
PROGRAMMING CONVENTIONS
Program Comments
Comments are lines of text in code, which are ignored by the program once it is run.
Comments are single lines preceded by an apostrophe or by the statement REM. The user
could implement comments in order to write notes to himself or place apostrophes at the
beginning of lines of code, commenting them out when error checking, effectively erasing the
lines of code to the program. If comments are not preceded by an apostrophe or a REM
statement, the program would try to interpret the text and an error would be indicated when
the program is run.
It is a good programming practice to put comments throughout code. Comments could
indicate which parts of the code are responsible for which functions such that the user can
readily understand the function of the different elements of the code and modify it easily.
Case-Sensitivity
It is important to note that VBScript language is not case-sensitive. Therefore, if one were to
write Parameter1, parameter1 or PARAMETER1 within the code, the program would
interpret all of them as referring to the same variable. This trait is true for key words in
VBScript (such as Sub and If) as well as user defined terms, such as function and variable
names. Capitalization of letters within the code is strictly optional and is done only to make
the code more easily readable to the user. However, when comparing two similar text strings
with each other, case sensitivity does become an issue. The two strings, String1 and
string1 for example, would not be considered equal by the program unless the
capitalization was identical.
8 M AGNET/ ELECNET/THERMNET SCRIPTING M ANUAL CHAPTER 2
If a MagNet, ElecNet or ThermNet file is already open, the program will prompt for the file to be
saved before continuing.
4. On the Tools Menu, click Keyboard Input Bar.
5. On the Draw menu, click Line.
9
into functional sections such that each subroutine is responsible for a different aspect of the
whole. This makes the code easier to read for the user; thus, the code can be more easily
modified.
Call Statement
The call statement is one way to transfer control from the currently executing section of code,
to a new sub or function. Often, when writing scripting code, one sees the call statement
being used to call subs or functions. The call statement merely transfers control to the listed
subroutine or function. However, it is important to note that when used with functions, the
return value is then omitted, effectively turning the function into a subroutine.
Call SubName(parameters) Call FunctionName(parameters)
The call statement can be used to invoke both Infolytica scripting APIs and subs and
functions written in VBScript. In the session logs, Infolytica scripting APIs are invoked using
the call statement. When accessing Infolytica scripting APIs, it is best to use the call
statement for all subroutines since they do not return a value, or function calls in instances
where the return value is not needed.
Dim
In order to declare a variable, one uses the Dim command. The Dim command reserves space
in memory such that the variable can store any type of data.
Dim Variable
The variable here is automatically declared as a variant such that it can store a string,
numerical data, an array or any other variable type. Therefore, in order to store information,
the following statements would be used:
Dim XValue
XValue = 10
The variable XValue would then contain a value of 10.
Option Explicit
In VBScript, one may use variables without first defining them. Therefore, in the statement
above, one may use the command XValue = 10 without first using the Dim statement and
obtain the same results. In order to have a program that only allows the use of variables that
have been previously declared, the Option Explicit command must be used.
The Option Explicit command is placed before all other statements in a user script, apart
from any sub or function. The following series of statements
Option Explicit
Sub Undeclared
XValue = 10
End Sub
will fail, generating an error message when the program is run, since the variable XValue is
not defined prior to its being used. The variable must first be defined using the Dim
statement, in order to be recognized by the program.
The advantage to using the Option Explicit command is that it prevents one from misspelling
the names of variables. In the following program excerpt, if the Option Explicit command is
not used, then the program would execute, but the variable XValue would not contain any
useful information.
Dim ValueX
ValueX = 10
Evaluate (XValue)
As written, the variable XValue is passed on to the sub Evaluate, although it has not been
initialized and contains no useful data. It is accidentally passed on to the sub instead of the
variable ValueX. This may cause the sub Evaluate to fail since it does not have the expected
input. With the Option Explicit command, the program alerts the user to the use of the
incorrect variable name.
Declaring Arrays
An array is a special type of variable in that it can hold several different values at once. In
order to declare an array that can hold a given number of values, one need only enter the
index of the last element in the array in parentheses directly after the variable declaration.
Since the first element in the array has an index value of zero, one would declare a value one
15
less than the total number of elements in the array. Therefore, to declare an array with 10
values, the following statement would be used:
Dim ArrayName(9)
The indices of the data within the array would range from zero to nine inclusive, a total of 10
separate values.
ReDim
Once an array is declared with a given number of inputs, the same array name can later be
declared again with a different number of indices using the ReDim command. Furthermore,
the ReDim command can be used to declare a previous variant variable as an array.
A) Dim ArrayA(4) B) Dim ArrayB C) Dim ArrayC()
ReDim ArrayA(9) ReDim ArrayB(9) ReDim ArrayC (9)
Figure 1 The different methods for declaring an array with the ReDim statement
a) Resizing an existing array; b) Converting from a variant to an array;
c) Adding the dimension of an empty array
When inputting values into an array, one need only declare the name of the array and the
index and equate it to a value. The statement
ArrayName(0) = 4
places the number 4 in the first position of the array. Each index of a given array can contain
values of different types such as strings, integers, dates, etc.
When resizing an array with the ReDim command, all of the information contained in an
array is lost. In order to preserve the contents of an array while it is being resized, the
Preserve command would need to be used.
ReDim Preserve ArrayName(15)
This function call resizes an already existing array to another size while keeping all of the
information that was previously stored in the array. Note that this statement can only be used
to increase the size of an array and not to decrease it.
In order to use UBound and LBound to return the bounds of other columns, a second,
optional parameter must be passed to the function, indicating which column one desires the
bounds for
Dim ArrayName(10, 20, 30)
Column1 = UBound(ArrayName, 1)
Column2 = UBound(ArrayName, 2)
Column3 = UBound(ArrayName, 3)
In the above example, the values of Column1, Column2 and Column3 are 10, 20 and 30
respectively. Note that the columns are numbered starting from 1 and not from 0.
Erase
In order to delete the contents of an array, one would use the Erase command. The syntax for
the Erase command is
Erase ArrayName
The dimensions of the array remain unchanged after the erase command is executed.
Array Command
One must take care not to name arrays Array. This is because Array is a function that is
defined within VBScript that generates an array from a given list of elements. The statement
Count = Array(0,1,2,3,4,5)
creates an array called Count, which contains six elements 0, 1, 2, 3, 4 and 5. These
elements are placed in the array, in the listed order. Note that the array can contain values of
different types such as strings, integers and dates.
VARIABLE MANIPULATION
When a program contains a variable, this variable can be manipulated by the program code.
In addition to equating different values to a variable, in the case of strings, different strings
can be concatenated to form one long string. In the case of variable containing numerical
values, one can perform mathematical operations.
In order to concatenate two or more strings, merely use the & or the + symbol between the
individual strings in order to add them together.
String1 = "Matter cannot be created" String2 = " or destroyed."
String3 = String1 & String2
The effect of this is that String3 contains the value Matter cannot be created or destroyed.
Alternatively, one could have written
String2 = String1 & " or destroyed."
In this instance, the long string is stored in the variable String2. Note that the string or
destroyed. starts with a space instead of with text. This is because when strings are
concatenated, spaces are not placed between the strings. Therefore, when coding, the user has
to account for this and enter spaces between concatenated strings wherever necessary.
Strings can be concatenated with other strings as well as to any other type of variable such as
integers and dates. All concatenated information will be stored as a string by the program.
Note that when variables are concatenated to strings, they are not placed in quotation marks.
17
For numerical inputs, the variables can be manipulated using arithmetic operations. In
addition to the basic mathematical operations, VBScript also contains a range of
mathematical functions which one can use to calculate values.
Symbol Function
+ Addition
- Subtraction
* Multiplication
/ Division
\ Integer Division (removes all values beyond the decimal point)
Mod Returns the modulus (remainder) of a division
^ Exponent (e.g. 2^3 = 23)
Cos(value) Cosine Input value is in radians
Sin(value) Sine Input value is in radians
Tan(value) Tangent Input value is in radians
Atn(value) Arctangent Input value is in radians
Log(value) Natural Logarithm
Exp(value) Exponential function (evalue)
Sqr(value) Square Root
Abs(value) Absolute Value
18 M AGNET/ELECNET/THERMNET SCRIPTING M ANUAL CHAPTER 3
Symbol Function
StrReverse(String) This function takes a string and returns its reverse.
Len(String) Returns the length of a string.
DateAdd(interval, This function returns the date with a given interval of time added. The
amount, date) interval is a string indicating the unit of time to add:
yyyy adds a year, q adds a quarter, m for month, ww for week,
d for day, h for hour, n for minute, and s for second. The second
input parameter is the amount of time one wishes to add. The last input
parameter indicates to which date or time the given amount it added.
DateDiff(interval, This function determines the amount of time elapsed between two dates,
date1, date2) measured in units of time specified by the interval input parameter. The
interval values are the same as those for the DateAdd function.
SCOPE OF A VARIABLE
If a single variable or a constant needs to be accessed by more than one subroutine, then the
variable can be declared outside of all subroutines. Variables that are defined outside all subs
and functions are said to have a scope that includes the entire program and are referred to as
global variables. The scope of a variable indicates the region in which the variable can be
accessed. Variables and constants that are defined within one sub cannot be accessed in
another sub unless it is passed as an input parameter.
Sub Subroutine1 Sub Subroutine2
Dim Number Dim Value
Number = 4 Value = Number + 4
End Sub End Sub
If one were to try running the above code and call on Subroutine2, an error would result
because Subroutine2 does not have access to a variable Number and as such, would be
unable to initialize the variable Value. In order to be accessible to both subroutines, the
variable would have to be declared globally, or the value of Number would have to be passed
as a parameter from one sub to the other.
Another issue with the scope of the variable is with passing parameters from one subroutine
to another. All modifications done to a parameter within a subroutine are local unless the
routine is a function and passes the modifications along to the point in the program from
which it was called.
Sub Subroutine1 Sub Subroutine2 (Number)
Dim Number Number = Number + 4
Number = 4 End Sub
Subroutine2 (Number)
MsgBox (Number * Number)
End Sub
In the above code, when Subroutine1 is called, the output of MsgBox will be 16 and not
64. This is because all input parameters to a subroutine, be it function or sub, are merely
copies of the original. Therefore, Subroutine2 only makes changes to its own copy of the
variable Number while the original remains unchanged. In order to get the value 64 the
following changes need to be made.
19
Command Function
CBool(VariableName) This function converts a value into a Boolean variable (either True or
False. This works with numerical values and with the strings True and
False.
CDate(VariableName) This function converts the input value into a date.
CDbl(VariableName) This function returns the input value and regards it as a double-precision
floating-point number.
CInt(VariableName) This function returns the input value and treats it as an integer. If the
number entered is a float, this function would round to the nearest
integer.
CLng(VariableName) This function converts the input into a long variable. If the number
entered is a float, this function would round to the nearest long value.
CSng(VariableName) This function returns the input value and regards it as a single-precision
floating-point number.
CStr(VariableName) This function converts the input into a string. Inputs in text boxes and
input boxes are interpreted as strings by default.
These pre-defined functions can convert a variable from one type to another. However, if a
series of letters were input into a text box and then the CInt or CDbl command were to be
tried, the program would be incapable of interpreting this information. The program would
register an error and would cease to execute the code, notifying the user of an error in the
code that needs to be rectified.
20 M AGNET/ELECNET/THERMNET SCRIPTING M ANUAL CHAPTER 3
Input box
An input box is one of the features of VBScript and it can only take in one input at a time
from a user. An input box is a function that outputs a screen to the user and returns the users
input. In order to request input from a user using an input box, the following syntax would be
used:
VariableName = InputBox ("Please enter the material name")
The value input by the user is held in VariableName and can then be manipulated by the
code once the user hits OK. If the user hits on the Cancel button, then an empty string, , is
returned.
Alternatively, one does not have to equate a variable name to the input. As with other
functions, the input box could be manipulated as though it were a value itself. However, if a
function is used in this manner, the return value can only be used once, since it is not stored
and cannot be accessed again. For example, the following code verifies an input string:
If (InputBox("Please enter your name. ") = "Bob") Then
MsgBox ("Good Afternoon, Bob ")
Else
MsgBox ("You are not authorized to use this system.")
End If
Note that when comparing two strings to each other, the capitalization of letters is taken into
account.
In order to change the title of the input box from the default (Visual Basic), a second string
needs to be included in the declaration of the input box. If one wishes to declare the input box
with default text written within as input, then a third input parameter must be added to the
declaration.
VariableName = InputBox ("String Message ", "Input Box title ", "Default input")
In the above declaration, unless the input in the box is changed by the user, the value of
VariableName will be Default input. Both the title and the default input are optional
parameters. If the input box was declared without any parentheses, then it is interpreted as a
sub instead of a function and it does not return a value, producing the same effect as using the
call statement.
InputBox "String Message" same as Call InputBox("String Message")
21
Message Box
When a message box appears, it suspends all activity of an application. Therefore, other
elements of a given program cannot be accessed until a message box is closed by clicking on
one of its buttons.
Apart from the default type of message box, in all other types of message boxes there is more
than one button that the user may click. In this instance, it is important to note which button
the user presses and have the program respond accordingly.
In order to call these different types of message boxes, the following function call could be
used:
RtrnVal = MsgBox(Message String, MsgBoxType, Message Box Title)
The second field in the declaration determines the type of buttons that appear on the message
box. The last field in the statement is optional and it changes the title of the message box (the
default title is Visual Basic). The different types of message boxes are outlined in the table
below.
If the message box is declared without parentheses about the input parameters, it would be
interpreted as a sub and it would not return a value.
In addition, with the different types of buttons, different symbols can be added into the boxes,
such as exclamation marks and question marks. In order to add these symbols in a message
box, the symbol must be declared after the button type of the message box. Only one symbol
can be declared per message box.
RtrnVal = MsgBox(Message String, MsgBoxType & SmblType, Message Box Title)
VbCritical
VbExclamation
VbInfomation
In order to append a character returned from the Chr function, one needs only use string
concatenation. For example, the code
MsgBox ("This is an example of " & Chr(10) & "a multi-line message box")
gives rise to the following message box
The opposite of the Chr function is the Asc function. This array takes as an input argument a
single character and returns the numerical ASCII code for the given input. If an entire string
is given as an argument to the Asc function, only the ASCII code for the first character is
returned for the string. Therefore the two following function calls
ReturnValue = Asc("I") ReturnValue = Asc("Input string")
would return the same value, 73, the ASCII code for the letter I.
The control statement is a statement that can evaluate to either True or False. The conditional
code will be executed only if the control statement evaluates to True, otherwise, the code
specified in the else section of the structure will be executed. Within control statements, the
most commonly used symbols are mathematical expressions of equality and inequality.
Symbol Meaning
< Less than
> Greater than
<= Less than and equal to
>= Greater than and equal to
<> Not equal to
= Equal to
Mathematical Symbols
The equality symbol can be used to compare two strings of text as well as two numerical
values.
In instances where more than one criterion must be met, two or more statements can be
compounded using the compound operators found in the table below:
Compound
Property
Operators
And In a control statement, it is True if both statements are True
In a control statement, it is True if either of the two statements preceding
Or
is True.
Exclusive Or. In a control statement, it is True only if exactly one of the
Xor
two statements is True.
This is True only when the statement that it precedes is False. It toggles
Not
the value of a Boolean statement.
Together, these mathematical and compound operators can be used to form control statements
for the If-Then-Else statement. The structure of the statement is
If (Data >0 And Data <> 10) Then
Data = Data 1
Else
Data = Data + 2
End If
This structure allows for two alternative series of actions. Only one of these alternates can be
executed at a time. If it is found that the control statement Data > 0 and Data <> 10 is True,
then the statements following the If clause are executed. If the control statement is False,
then the statements following the Else clause is executed. Therefore, only one of the sets of
statements is executed when the script is run, dependent upon the Boolean value of the
control statement.
25
This structure is additionally flexible in that the Else clause of the statement is optional. In
these instances, there is no alternative code to be executed. In these cases, the syntax of the
statement is
If (Control Statement) Then
Code
End If
In addition to the mathematical symbols used in control statements, calls to functions that
return Boolean (True or False) values can also be used in control statements.
Sub UseFunction() Function ReturnBoolean()
If (ReturnBoolean) Then ReturnBoolean = True
Code End Function
End If
End Sub
If there are more than two possible outcomes, one can nest the If-Then-Else statements within
each other. However, this can become rather bulky since each If statement needs a
corresponding End If statement. Instead of using several Else clauses followed by separate
If clauses, the term ElseIf can be used instead. This eliminates the need to use several
End If statements that can be hard to keep track of.
26 M AGNET/ELECNET/THERMNET SCRIPTING M ANUAL CHAPTER 3
An alternative to nesting several If-Then-Else statements together is to use the select case
statement. The select case statement is a special type of statement that allows for multiple
outcomes. In the If-Then-Else structure, control statements evaluate to True or False allowing
a maximum of two different possibilities, one set of actions if the control statement evaluates
to True and another if it evaluates to False. However, a select case statement can have several
different alternatives.
The syntax for the Select Case statement is as follows:
Select Case variable
Case value1
Statements1
Case value2
Statements2
Case value3
Statements3
End Select
This statement will execute one of three different sections of code depending on whether
variable is equal to value1, value2 or value3. If it is not equal to any of these three values,
the code is ignored and the statement after the select case statement is executed.
Alternatively, a Case Else statement may be added as the last clause. The Case Else clause
27
is executed when the variable is not equal to of the cases listed in the statement. The select
case statement eliminates the need to use nested If-Then-Else statements as demonstrated by
the following code (the Case Else clause of the statement is optional).
Note that in the select case statement, there may be multiple inputs that trigger the same
event. However, in cases where a range of values is used as a point of comparison (e.g. X >
17 And X <= 24), one must use the If-Then-Else statement instead.
28 M AGNET/ELECNET/THERMNET SCRIPTING M ANUAL CHAPTER 3
CONTROL LOOPS
Control loops are similar to If-Then-Else statements in that they contain a control statement
and they are only executed when certain criteria are met. However, unlike the previous
structures, control loops will repeat the series of statements until the criterion is no longer
met. There are many different types of control loops as outlined in the table below:
Loop
Syntax Properties
Structures
The body of the loop executes the number
of times indicated in the first line of the for
For counter = 1 To 20 statement or until an exit statement is
For-Next Value = Value + 1 reached.
Next
The Exit For statement may be included
within the loop.
This body of the loop executes once for
each value in an array or until an exit
For Each Value in ArrayName statement is reached.
For Each-Next MsgBox (Value) Within the loop, each array element, in
Next turn, is assigned to the variable Value.
The Exit For statement may be included
within the loop.
Do In this loop, the exit statement must be
Value = Value +1 included within the statements in the loop
If (Value > 20) Then or else the loop would continue infinitely.
Do-Loop
Exit Do This is accomplished in the example by
End If using an if statement to test for the exit
condition.
Loop
The body of this loop executes at least
Do once until the control statement at the end
Do-Loop Until Value = Value 1 of the loop evaluates to True.
Loop Until (Value <20) The Exit Do statement may be used
within the Do-Until loop.
This loop executes until the control
Do While (Value < 20) statement is evaluated as False.
Do- Loop While Value = Value + 1
The Exit Do statement may be used
Loop
within the Do-While loop.
While (Value < 20)
This loop executes until the control
While-Wend Value = Value + 1
statement is evaluated as False.
Wend
Control loops
29
Do-Loops
The Do-Loops are very flexible control statements, not only because of the different
variations, but also because the Do-While Loop and the Do-Until loop can be set up such that
the control statement is evaluated either at the end or at the beginning of the loop. The
difference between these two different arrangements is that once the control statement is
placed at the beginning of the loop, the loop verifies the control statement first before
proceeding. However, once the control statement is placed at the end, the control loop will
execute at least once before evaluating the control statement.
Nesting Loops
Further control can be added to a program by nesting loops. Nested loops occur when one
loop is found within another. This technique can be carried out with loops of similar or
dissimilar types.
An interesting point about VBScript is that it can use integers as True and False values. All
integers other than 0 are considered to be True and 0 is considered to be False. Therefore,
integers can then be used in control statements for the various loops. If one were to input a
number called Divisor in an input box, code could be written to verify that Divisor is not
zero.
Divisor = CInt (InputBox ("Enter a divisor for 12."))
If (Divisor) Then
MsgBox (12 /Divisor)
Else
MsgBox ("You cannot divide by zero.")
End If
This code first reads the input text as an integer and then it verifies that the integer is not zero.
If it is zero, then in cannot be used as a divisor. Alternatively, the control statement could
have been (Divisor <> 0).
30
ERROR HANDLING
There are three different types of coding errors that one can make: syntactic errors, semantic
errors and run time errors. Syntactic errors are errors that use incorrect syntax in the code,
such as forgetting to write Then in an If-Then-Else loop or misspelling a function name.
Semantic errors are those that arise from incorrect logic. Often, the program will still run but
give erroneous output. These often arise in arrays and lists when one forgets that the index of
the first item is 0 instead of 1. The third type of error is the run time error. These are errors
that arise when the program is run and are typically the result of the program being unable to
handle incorrect inputs and other unexpected situations that the programmer didnt account
for when coding.
Syntax Errors
Syntax errors are picked up by the program as soon as one tries to run it. Often, an error can
remain undetected if it is located in a line of code that only need to be accessed rarely such as
an else clause within an If-Then-Else statement in a sub that is rarely called. Therefore, the
program can run several times without registering an error. However, once the program
comes upon this line of code and tries to interpret it, the program would cease to run and the
program would indicate that there is an error in the code. Syntax errors are easily fixed by
checking the syntax of the statements in the code at the location indicated by the error
message. Misspelled variables can be detected by using the Option Explicit command in the
code. For more information concerning this command, please refer to page 14.
Semantic Errors
Semantic errors are harder to notice and they are usually discovered only through vigilant
observation. If the erroneous output is never noticed, the program would run without
generating any error messages. If one notices a semantic error, one can determine where in
the code the errors are generated by placing message boxes throughout the code and using
them to output some of the values and parameters that the program is working with.
Therefore, one could look at the input, output in a systematic manner, determine where in the
code the logical flaw is located, and then correct it.
Examples of semantic errors include trying to access an element from outside the range of an
array or improperly accessing the fields from within an array.
Dim ArrayName(9) Dim ArrayName(9)
Dim Count Dim Count
For Count = 1 To 10 For Count = 1 To 9
ArrayName(Count) = Count ArrayName(Count) = Count
Next Next
31
In both of the above examples, the error is in the assumption that the first element in the array
is 1. The code to the left will result in an error message because the largest index of the array
is 9, even though it contains 10 elements. Similarly, the code to the right assumes that the
number used in the declaration indicates the number of elements that are to be found in the
array instead of indicating the index of the last element in the array.
The first semantic error will cause the program to cease running as soon as the variable Count
reaches the value 10. The second error, however, may never generate an error if the array is
always accessed in the same manner. However, as soon as one accesses and tries to
manipulate the value in ArrayName(0), which is not initialized, then the script may stop and
generate an error message, depending on the manipulation.
Often, semantic errors arise in control statements for loops and If statements, as shown below
If (X < 0 And X > 100) Then
Code
End If
In the above code, the code in the loop will never execute because a value can never be less
than 0 and greater than 100 at the same time. Or needs to be used in the control statement
rather than And.
invalid input.
These are just some of the problems that one may run into when running a script that requires
user inputs. In order to make the program resistant to these possibilities, all of the likely
errors and misuses must be taken into account and code written that deals with all of them.
Therefore, one method of correcting the code would be as follows:
Call Division
Sub Division
Dim Op1, Op2
'The following statement verifies that the inputs can be interpreted as
'numbers. This handles problems 2 and 3.
Op1 = InputBox ("Enter operand 1")
Op2 = InputBox ("Enter operand 2")
If (IsNumeric (Op1) And IsNumeric (Op2)) Then
Op1 = CDbl (Op1)
Op2 = CDbl (Op2)
Else
MsgBox ("Please enter numbers in the operand fields")
Exit Sub
End If
'The following statement handles problem 1. If the value is 0, the If
'statement is ignored and the program goes on to the Else clause of the statement.
If (Op2) Then
MsgBox (Op1/Op2)
Else
MsgBox ("You cannot divide by zero")
End If
End Sub
Exit Statement
The Exit statement is used to exit subs, functions and loops before they would ordinary
terminate. Above, the Exit Sub command is used to exit the sub once an error is
encountered. The exit statement is particularly helpful with error handling because once an
erroneous input or value is obtained, typically the program cannot continue to run and must
be exited in order to prevent the program from crashing. The Exit Function statement is
used to exit functions.
is correct or not. The On Error Resume Next command turns on the error handling which
can be subsequently turned off with the On Error GoTo 0 command.
It is important to note that the Error statement must be invoked in every sub or function in
which one wishes an error to be skipped. If another subroutine is called, then the status of the
error handler is not carried over to the called subroutine. In the following example, a run time
error is generated when the function DivideByZero is called.
Sub SkipError Function DivideByZero(input)
On Error Resume Next DivideByZero = input/0
Dim Three, Answer End Function
Three = 3
Answer = DivideByZero(Three)
On Error GoTo 0
End Sub
Since the Error statement is not invoked in the DivideByZero function, when the sub
SkipError is run, a run time error message would still be generated and the program will be
halted.
The run time error handler can be used in order to debug code. If one wants to verify the
output of the code and keeps running into an error, instead of fixing it immediately,
problematic code can simply be skipped in order to continue with the program and verify the
overall structure.
34 M AGNET/ ELECNET/THERMNET SCRIPTING M ANUAL CHAPTER 5
When the On Error Resume Next statement is used, after every error, the Err object is
created. Two properties of the Err object that help determine the type of error are Err.Number
and Err.Description. Err.Number is the number by which the error is defined. Err.Description
gives a short description of the error. These values are reinitialized every time that an error
occurs. In the event that there is no error, Err.Number is 0 and Err.Description contains an
empty string. Using the run time error handler, the division subroutine on page 31 can again
be rewritten as follows:
Call Division
Sub Division
On Error Resume Next
Dim Op1, Op2
Op1 = InputBox ("Enter operand 1")
' Verify if the first operand generates a type mismatch error
If (Err.Number = 13) Then
MsgBox ("Please enter a number in the operand fields")
Exit Sub
End If
Op2 = InputBox ("Enter operand 2")
' Verify if the second operand generates a type mismatch error
If (Err.Number = 13) Then
MsgBox ("Please enter a number in the operand fields")
Exit Sub
End If
MsgBox (Op1/Op2)
' Verify that there is no division by zero
If (Err.Number = 11) Then
MsgBox("You cannot divide by zero")
End If
On Error GoTo 0
End Sub
In the above code, the Err.Number property is used to verify the user input. If one were to use
the Err.Description property for each error number, 11 would generate a description
Division by zero and 13 would generate Type mismatch.
For a complete list of VBScript run time error numbers visit the webpage:
http://msdn.microsoft.com/en-us/library/xe43cc8d.aspx
Since the output of Err.Number is zero when there is no error, instead of including the
statement If (Err.Number = 11) Then , one could simply use the code, If (Err.Number)
Then . The problem with this is that there could be many other errors present in the code
that can result in the genesis of an error number. In this instance, if the error number is not
specified in the If statement, the message box You cannot divide by zero will always be
generated, no matter what values are input by the user.
35
Information on the individual scripting commands used in this chapter can be found in the on-
line help. Note that the syntax for the various commands listed below is subject to change
without notice. The updated scripting syntax listed in the on-line help of the Infolytica
products should be used at all times.
SCRIPTING INTERFACES
An interface is a collection of logically related scripting functions. In the on-line help,
clicking on the Scripting Hierarchy button gives a list of all available interfaces.
The main interface in all Infolytica applications is the Application interface. Other
interfaces found in the application are subsets of this main one. In order to access a given
interface, interfaces are chained together in a script command. For example, to access the
field interface in the hierarchy above, one would use the command
Set Field = getDocument.getSolution.getSystemField()
The interface of all parent interfaces must be included when accessing a given interface.
However, handles to the various interfaces can be created using the Set command. One can
create the field object listed above as follows:
Set Document = getDocument
Set Solution = Document.getSolution
Set Field = Solution.getSystemField()
In this way, one can avoid creating long interface chains when scripting. Note that the Set
command must be used when creating a handle to a scripting interface.
ReDim ArrayName(0)
Set Solution = getDocument.getSolution
Set Field = Solution.getSystemField()
' The application is able to resize the array
' and places the value of the field at the
' specified point in the array ArrayName
Call Field.getFieldAtPoint(0,0,0, ArrayName)
Since there is little extra overhead when creating a variant and then using the ReDim
command to create an array, it is recommended that all scripts that call Infolytica APIs define
the arrays in this way.
39
1
All Infolytica APIs listed in this section are universal to MagNet, ElecNet and ThermNet. Additional
information on the syntax of the scripting APIs mentioned in this section can be found in the help of the
various applications.
40 M AGNET/ ELECNET/THERMNET SCRIPTING M ANUAL CHAPTER 5
ProcessCommand API
There are several APIs in MagNet that pass parameters by reference instead of by value.
There are some applications which do not support the passing of parameters by reference and
therefore, the commands cannot be called directly from within their interface. The
processCommand API is a powerful scripting API included with the Infolytica package that
can navigate around this problem.
The processCommand API is a member of the application interface. This API takes in a
string and executes the string as a VBScript command. The two snippets of code written
below behave in the same manner when executed from within an Infolytica application.
Dim X, Y, Z Call processCommand("Dim X, Y, Z")
X=4 Call processCommand("X = 4")
Y=5 Call processCommand("Y = 5")
Z=X*Y Call processCommand("Z = X * Y")
Call MsgBox (CStr(Z)) Call processCommand("Call MsgBox (CStr(Z)) ")
Running VBScript Code Using the processCommand API to execute the same
VBScript Code
Note that when using the processCommand statement, the values assigned to the variable
remains in memory, such that Z is assigned the value 20.
Using the MATLAB application as an example and MagNet as a remote server, the above
code could be executed using the following command sequence (note that in MATLAB,
strings are enclosed in single quotes 2).
MagNet = actxserver('MagNet.Application'); % Create a handle to the MagNet application
Set (MagNet, 'Visible', 'True'); % Make the application visible
Invoke(MagNet, 'processCommand', 'Dim X, Y, Z');
Invoke(MagNet, 'processCommand', 'X = 4');
Invoke(MagNet, 'processCommand', 'Y = 5');
Invoke(MagNet, 'processCommand', 'Z = X * Y');
Invoke(MagNet, 'processCommand', 'Call MsgBox(CStr(Z)) ');
This workaround allows the power of both applications to be harnessed with a single script.
In this way, one can call APIs that contain parameters that are passed by reference which
otherwise could not be executed from MATLAB.
2
For more information on the MATLAB syntax, please refer to the MATLAB documentation or refer to
the MathWorks website at http://www.mathworks.com
41
application or the other can be stored in this global array and then the value can be transferred
to another application.
The getVariant API takes two input values an index describing where the value should be
stored or retrieved from, and a string indicating the category of the variants. The setVariant
API takes an additional input, the value to be stored in this global array. For example, the
following code stores two different values in the global Variant array. Both inputs are stored
at index 0, however, they have two different categories, one labeled StringInput and the
other labeled NumericalInput
Call setVariant(0. "Value", "StringInput")
Call setVariant(0, 4, "NumericalInput")
In this way, values that are calculated using the processCommand API can then be stored in
the Variant array can then be retrieved using the getVariant API.
RunScript API
The runScript API can take a text file and run it as though it were a .vbs script file. The API
takes a file path as an input and executes the named file. With this functionality, values can
be calculated or manipulated in one application, and then based on these calculations a text
file containing Infolytica API and VBScript commands can be written out. The file can then
be executed using runScript.
42 M AGNET/ ELECNET/THERMNET SCRIPTING M ANUAL CHAPTER 5
Appendix A
JSCRIPT
In MagNet, ElecNet and ThermNet, using JScript commands and syntax, instead of VBScript
is an option. All that must be done to effect the change in programming language is to change
the Active Engine of the script from VBScript to JScript.
Most of the commands and structures for VBScript have analogous structures in JScript
although the exact syntax differs. Furthermore, the structure for writing subs, functions and
event handlers is different. However, while the syntax for the statements may be different, the
programming principles detailed in this manual still apply. Note that the program session log
and the user session log are recorded exclusively in VBScript.
REFERENCES
There are many programming references on VBScript on the internet and in print. The most
up to date information is found on the Microsofts website at (http://msdn.microsoft.com/en-
us/library/d1wf56tt.aspx). This site contains examples and references on how to program in
VBScript.
For more information on the different commands, references for Microsofts Visual Basic can
be used. VBScript is a subset of Visual Basic and as such, most commands are identical.
However, some of the commands for Visual Basic cannot be used in VBScript.
For examples on how to script specifically in MagNet, ElecNet and ThermNet, please refer to
the Live Docs, our web-based documentation system which can be found on Infolyticas
Online Customer Support Center (OCSC) website (http://www.infolytica.com/en/support/).
Almost every section of Live Docs has a Tools section which contains custom scripts. There
is also a Scripting section which contains more code examples and additional explanations.
The script commands in the scripts are readily accessible and can be modified or used in the
generation of new scripts. In addition, there are Excel spreadsheets and Matlab programs
that demonstrate software interaction. In order to access Live Docs, you must have an active
maintenance contract which has an associated OCSC username and password. To obtain this
info, please contact your sales representative ([email protected]).
SCRIPT FORMS
Script forms are no longer supported in Infolytica products. This is due to Microsoft
discontinuing support for them. Please see Release notes for more information at:
http://www.infolytica.com/secured/customer/downloads/release-
notes/magnet7.3.aspx#VBScript forms