CitectVBA Reference Guide
CitectVBA Reference Guide
40
CitectVBA Reference Guide
August 2013
Legal Information
DISCLAIMER
Schneider Electric makes no representations or warranties with respect to this manual and, to the maximum extent permitted by law,
expressly limits its liability for breach of any warranty that may be implied to the replacement of this manual with another. Further,
Schneider Electric reserves the right to revise this publication at any time without incurring an obligation to notify any person of the
revision.
The Example Projects are provided to you for the purpose of illustrating how the SCADA software v7.40 could be used in an oper-
ational environment ("the Purpose").Schneider Electric grants you a royalty free, non exclusive, non transferable license to use the exam-
ple projects installed with your SCADA software version v7.40 (“the Example Projects”) for the Purpose only.
The Example Projects are provided by Schneider Electric as part of the SCADA software version v7.40 on an "as is" basis and Schneider
Electric does not guarantee the reliability, serviceability or function of the Example Projects.
Should you modify the Example Projects, you bear the risk of any use of such modified Example Projects.
Schneider Electric gives no express warranties, guarantees or conditions and to the extent permitted under applicable laws, Schneider
Electric disclaims all implied warranties, including any implied warranties of merchantability, fitness for a particular purpose or non-
infringement of third parties’ intellectual property rights.
Schneider Electric shall not be liable for any direct, indirect or consequential damages or costs of any type arising out of any action
taken by you or others related to the Example Projects.
COPYRIGHT
© Copyright 2012 Schneider Electric All rights reserved.
TRADEMARKS
Schneider Electric has made every effort to supply trademark information about company names, products and services mentioned in
this manual.
Citect, CitectHMI, Vijeo Citect, Vijeo Citect Lite PowerSCADA Expert and CitectSCADA are either registered trademarks or trademarks
of Schneider Electric.
Pelco, Spectra, Sarix, Endura, are registered trademarks of Pelco, Inc.
IBM, IBM PC and IBM PC AT are registered trademarks of International Business Machines Corporation.
MS-DOS, Windows, Windows NT, Microsoft, and Excel are either registered trademarks or trademarks of Microsoft Corporation in the
United States and/or other countries.
DigiBoard, PC/Xi and Com/Xi are trademarks of Digi International Inc.
Novell, Netware and Netware Lite are either registered trademarks or trademarks of Novell, Inc. in the United States and other
countries.
dBASE is a trademark of dataBased Intelligence, Inc.
All other brands and products referenced in this document are acknowledged to be the trademarks or registered trademarks of their
respective holders.
GENERAL INFORMATION
Some product names used in this manual are used for identification purposes only and may be trademarks of their respective com-
panies.
August 2013 edition for Vijeo Citect Version v7.40.
Manual Revision Version v7.40.
PLEASE NOTE
Electrical equipment should be installed, operated, serviced, and maintained only by qualified personnel. No responsibility is assumed
by Schneider Electric for any consequences arising out of the use of this material. © 2012 Schneider Electric. All Rights Reserved.
Validity Note
The present documentation is intended for qualified technical personnel responsible for the implementation, operation and main-
tenance of the products described. It contains information necessary for the proper use of the products. However, those who wish to
make a more "advanced" use of our products may find it necessary to consult our nearest distributor in order to obtain additional infor-
mation.
The contents of this documentation are not contractual and in no way constitute an extension to, or restriction of, the con-
tractual warranty clauses.
Legal Information 1
Contents 3
Safety Information 7
3
Contents
Scope of CitectVBA 28
Procedural (local) level scope 28
Modular level scope 29
Global level scope 29
CitectVBA Statements 30
Comments 30
Header information 31
Labels 32
CitectVBA Line Continuation Character 32
Naming 33
Option Statements 34
Option Explicit statement 34
Option Compare statement 35
Option Base statement 35
CitectVBA Data Types 36
Constants 37
Declaration of constants 38
Intrinsic constants 39
Variables 40
Variable declaration 40
Variable initialization values 42
Arrays of Variables 43
Variant Declaration 48
Numbers 50
Numeric Data Types 50
Exponential Notation 51
Floating Point Calculation Rules 52
Rounding Numbers 53
Date and Time Handling 54
Date Constants 55
Formatting Date Values 57
Date and Time Data Constraints 59
Date Data Type Structure 60
Date-values 61
Time-values 61
Dates in Databases Using Different Calendars 62
Operators 63
Assignment Operator 63
Arithmetical (Math) Operators 64
Relational Operators 65
Logical Operators 65
Operator Precedence 66
Strings 67
String Comparisons 68
String Concatenation 68
Control Structures 69
GoTo statement 70
Do statement 70
While statement 71
4
Contents
For statement 71
If statement 72
Select case statement 74
End statement 76
Exit statement 76
OnError statement 77
Stop statement 77
With statement 78
Subroutines and Functions 78
Subroutines 79
Functions 80
Arguments 82
DLLs and APIs 84
Accessing Functions in DLLs 85
Passing Arguments to DLL Functions from CitectVBA 89
OLE Services 90
OLE terminology 90
OLE automation objects 91
Declaration of OLE automation objects 92
Assigning references to OLE automation objects 93
Using OLE automation objects 94
Accessing the object model of OLE automation server applications 95
Understanding object models in OLE automation 96
Using the Microsoft Word object model 99
OLE automation example using the Microsoft Word object 99
Using the Microsoft Excel object model 100
Deleting OLE automation objects 100
File Input/Output with CitectVBA 101
5
Contents
6
Safety Information
Safety Information
Hazard categories and special symbols
The following symbols and special messages may appear in this manual or on the prod-
uct to warn of potential hazards or to call attention to information that clarifies or sim-
plifies a procedure.
Symbol Description
DANGER indicates an imminently hazardous situation, which, if not avoided, will result in
death or serious injury.
WARNING indicates a potentially hazardous situation, which, if not avoided, can result in
death or serious injury.
CAUTION indicates a potentially hazardous situation which, if not avoided, can result in
minor or moderate injury.
NOTICE
NOTICE used without a safety alert symbol, indicates a potentially hazardous situation
which, if not avoided, can result in property or equipment damage.
Please Note
7
Safety Information
Vijeo Citect is a Supervisory Control and Data Acquisition (SCADA) solution. It facil-
itates the creation of software to manage and monitor industrial systems and processes.
Due to Vijeo Citect's central role in controlling systems and processes, you must appro-
priately design, commission, and test your Vijeo Citect project before implementing it in
an operational setting. Observe the following:
Do not use Vijeo Citect or other SCADA software as a replacement for PLC-based control pro-
grams. SCADA software is not designed for direct, high-speed system control.
Failure to follow these instructions can result in death, serious injury, or equip-
ment damage.
LOSS OF CONTROL
l The designer of any control scheme must consider the potential failure modes of con-
trol paths and, for certain critical control functions, provide a means to achieve a safe
state during and after a path failure. Examples of critical control functions are emer-
gency stop and overtravel stop, power outage and restart.
l Separate or redundant control paths must be provided for critical control functions.
l System control paths may include communication links. Consideration must be given
to the implications of unanticipated transmission delays or failures of the link.
l Observe all accident prevention regulations and local safety guidelines. 1
l Each implementation of a control system created using Vijeo Citect must be individ-
ually and thoroughly tested for proper operation before being placed into service.
Failure to follow these instructions can result in death, serious injury, or equip-
ment damage.
1. For additional information, refer to NEMA ICS 1.1 (latest edition) "Safety Guidelines
for the Application, Installation, and Maintenance of Solid State Control", and to NEMA
ICS 7.1 (latest edition) "Safety Standards for Construction and Guide for Selection, Instal-
lation and Operation of Adjustable-Speed Drive Systems" or their equivalent governing
your particular location.
8
Chapter 1: Introducing CitectVBA
CitectVBA is a Visual Basic for Applications (VBA) and VBScript-compatible Basic script-
ing language. Vijeo Citect has embedded support for CitectVBA.
CitectVBA has the following features:
l CitectVBA code is multithreaded and fully scheduled within the Vijeo Citect Kernel.
l CitectVBA uses the same well proven engine that Cicode uses and can be used
wherever Cicode is used.
l CitectVBA has a small footprint of under 400K.
l CitectVBA code is directly callable from Vijeo Citect Command and Expression fields.
l CitectVBA code is callable from Cicode and visa-versa.
l CitectVBA code provides native support for ActiveX objects, Vijeo Citect Variable
Tags and Alarm Tags.
l CitectVBA makes ActiveX object manipulating easier. It allows direct interaction with
the object models from 3rd party applications such as Word, Excel, etc.
Note: You may notice slight differences between CitectVBA and VBA in other
applications; this is normal as each application has a different object model.
The Cicode Editor has been upgraded to fully support CitectVBA. New features of the
editor include:
l Integrated Cicode and CitectVBA compiler
l Integrated Cicode and CitectVBA source code editor
l Integrated Cicode and CitectVBA debugger
See Also
Integrating CitectVBA with Vijeo Citect
9
Chapter 1: Introducing CitectVBA
10
Chapter 2: Integrating CitectVBA into your Project
You can integrate CitectVBA into your Vijeo Citect project in two ways:
l Use CitectVBA code script directly in your Command or Expression fields within
Vijeo Citect.
l Store user-defined CitectVBA script in a separate CitectVBA file.
In either case, all procedures within a CitectVBA script can access (read and write) any
Vijeo Citect variable tag in the same way as Cicode can access Vijeo Citect tags.
See Also
Accessing Cicode Tags with CitectVBA
Note: Project variable tags are defined (in Vijeo Citect) by using the Variable Tags
form in the Citect Project Editor. For details, see Adding a Variable Tag.
For instance, in the following example, two variable tags in your Vijeo Citect project may
be named B1_PUMP_101_SP and B1_PUMP_101_PV respectively, representing the Set
Point and Process Variable values of Pump 101. These variable tag names can be used
within a CitectVBA statement (just as you would use any other variable in CitectVBA).
Both values can be read-from and written-to directly using CitectVBA:
You should note that CitectVBA does not recognize Vijeo Citect variable tags that are
named with an initial digit (0-9).
To access such tags using CitectVBA, you must precede the tag name with a case-insen-
sitive string containing the letters 'V', 'B,' and the underscore character (VB_) as in the
following example:
11
Chapter 2: Integrating CitectVBA into your Project
For details about accessing ActiveX objects using CitectVBA, see Accessing ActiveX
Objects with CitectVBA. For details of using tags that have a number as their first digit
in your Vijeo Citect project, consider using the [General]TagStartDigit Citect.INIparam-
eter.
See Also
Using CitectVBA in Vijeo Citect Command or Expression fields>Calling CitectVBA from
Cicode
Calling CitectVBA from Cicode
CiVBA
TestTag_1 = TestTag_1 + 1
This is known as the language override command. When the Vijeo Citect compiler reads
the keyword CiVBA, it knows to handle that code (within the same Vijeo Citect Com-
mand or Expression field) as CitectVBA script, and compiles it as such. No such over-
ride command is required to use Cicode.
The CiVBA language override statement must be placed first in the Vijeo Citect Com-
mand or Expression field if you want to use CitectVBA script code instead of Cicode in
that Vijeo Citect Command or Expression field.
Note: You must use either Cicode or CitectVBA in a Vijeo Citect Command or Expres-
sion field. You cannot change or swap between the two programming languages
(within the same Vijeo Citect Command or Expression field) once you've started
using one or the other.
You can, however, call a single Cicode function from within CitectVBA script if you
wrap the Cicode call within special CitectVBA functions CicodeCallOpen()and Cicode-
CallReturn(). For details, see Calling Cicode from CitectVBA.
12
Chapter 2: Integrating CitectVBA into your Project
Alternatively, to call a single CitectVBA function (from within the Vijeo Citect Command
or Expression field) after you have already used Cicode in that field, you can wrap the
CitectVBA within three nested special Cicode functions: VbCallOpen(), VbCallRun()and
VbCallReturn(). See Calling Cicode from CitectVBA.
See Also
Accessing Cicode Tags with CitectVBA
Accessing ActiveX Objects with CitectVBA
Multithread Considerations with CitectVBA
Calling CitectVBA from Cicode
Calling Cicode from CitectVBA
In this example, the reference name for the Temperature meter object would be referred to
in CitectVBA as ActiveX_AN125.
All object properties can be accessed and manipulated using CitectVBA in the same way
that object properties can be manipulated using Cicode.
See Also
Accessing Cicode Tags with CitectVBA
13
Chapter 2: Integrating CitectVBA into your Project
If, for example, you were reading or setting some variable or point in a multi-statement
thread, and further processing that data in a later thread,that data might become invalid
or incorrect. For this reason, you should separate every statement onto separate lines in
CitectVBA.
For example, it is better to write:
as
A = Motor1.speed()
A = A + Motor4.speed()
A = A + Motor5.speed()
14
Chapter 2: Integrating CitectVBA into your Project
Note: This does not apply to Cicode because the Cicode engine can pre-empt aggre-
gated code.
See Also
Accessing Cicode Tags with CitectVBA
Using CitectVBA in Vijeo Citect Command or Expression fields
Calling CitectVBA from Cicode
Calling Cicode from CitectVBA
Note: When using the CiVBA language override in a Command field, the compiler
constructs the nested call for you. The same mechanism is used even though it is not
self evident. For details, see Using CitectVBA in Vijeo Citect Command or Expression
fields.
where:
15
Chapter 2: Integrating CitectVBA into your Project
<ReturnValue> = VbCallRun(<CallHandle>)
where:
l <ReturnValue> represents the handle to the opened CitectVBA function passed through
for the <CallHandle>argument.
l <CallHandle> represents the handle to the previously opened CitectVBA function as
returned by the Cicode VbCallOpenfunction.
The Cicode VbCallReturn()function is used to obtain the return value of the completed
CitectVBA function (previously opened with the Cicode VbCallOpenfunction), and requires
the handle returned from the VbCallRunfunction call.
<ReturnValue> = VbCallReturn(<CallHandle>)
where:
l <ReturnValue> represents the value returned by the completed CitectVBA function
(which was previously opened by the Cicode VbCallOpenfunction). The data type of the
return value is dependent upon the data type of the return value for the CitectVBA
function opened.
l <CallHandle> represents the handle to the previously opened CitectVBA function as
returned by the Cicode VbCallRunfunction.
Example
FUNCTION
TestCitectVBA()
INT iRet;
STRING sMsg = "Hello";
INT iVal = 123;
iRet = VbCallReturn(VbCallRun(VbCallOpen("CiVBATest", iVal)));
Message("TestCitectVBA Function", "CiVBATest = " +
16
Chapter 2: Integrating CitectVBA into your Project
IntToStr(iRet), 0);
END
Example
See Also
Calling Cicode from CitectVBA
To call a given Cicode function, use the CicodeCallOpenfunction which will create and
execute a Cicode thread that runs the function. For multitasking purposes, a separate
function CicodeCallReturnis used to obtain the return-value of the completed Cicode func-
tion most recently called by the CicodeCallOpenfunction.
Do not nest the CicodeCallOpen and CicodeCallReturn functions. Nesting these functions
can lead to unintended equipment operation when your program is run.
Failure to follow these instructions can result in death, serious injury, or equip-
ment damage.
The return value is initialized when control is returned to the Vijeo Citect kernel. This
occurs only after completion of the line of CitectVBA code containing CicodeCallOpen. For
details on multithreading in CitectVBA, see Multithread Considerations with CitectVBA.
To call a given Cicode function or subroutine from CitectVBA, use the CicodeCallOpenfunc-
tion. Upon return from CicodeCallOpen, you can call the CicodeCallReturnfunction to
obtain the return value of the Cicode function called.
The CicodeCallOpenfunction is a CitectVBA function used to call a Cicode function from
CitectVBA. It is used to initiate and execute a call to the Cicode function and returns an
integer value representing the success or the type of error encountered by the Cicode-
CallOpen function.
17
Chapter 2: Integrating CitectVBA into your Project
where:
l <ReturnValue> represents the return value of:
l 0 if CicodeCallOpenfunction was successful
l 1 for CicodeCallOpenfunction general error
l 2 for specified Cicode function not found
l 3 for incorrect number of arguments for specified Cicode function passed in
<ArgList>.
l <FunctName> is a string representing the name of the Cicode function being called. The
function name should be enclosed in double quotes.
l <ArgList> represents a variable length comma separated argument list of all the argu-
ments to be passed to the Cicode function being opened (dependant upon which
Cicode function is being called and the arguments that Cicode function requires). The
argument list should not be enclosed within brackets, although when using variable
names as arguments, those variable arguments within the list need to be individually
enclosed within brackets to force the passing of the variable to Cicode by value.
The CicodeCallReturnfunction is a CitectVBA function used to obtain the return value of
the most recently completed Cicode function opened with the CitectVBA
CicodeCallOpenfunction.
<ReturnValue> = CicodeCallReturn()
where:
l <ReturnValue> represents the return value of the Cicode function specified in the most
recent call of the CicodeCallOpenfunction. Note that the return data type of Cicode-
CallReturnwill depend upon the return data type of the Cicode function called in the
most recent call of the CicodeCallOpenfunction.
No arguments are passed to the CicodeCallReturnfunction, as it can only return the result
of the most recent return-value for the Cicode function called by the CitectVBA Cicode-
CallOpenfunction.
CitectVBA
18
Chapter 2: Integrating CitectVBA into your Project
Case = 2
' assign return comment for this case
strReply = "Cicode Function not found"
Case = 3
' assign return comment for this case
strReply = "Wrong number of arguments "_
& "in Cicode CallOpen function call"
Case Else
' assign return comment for this case
strReply = "Unknown error"
End Select
End If
' display return comment for your information
MsgBox strReply
' assign return value for this function
TestCicode = intRet
End Function
See Also
Calling CitectVBA from Cicode
19
Chapter 2: Integrating CitectVBA into your Project
20
Chapter 3: Using the CitectVBA Test Project
You can use the CitectVBA test project to help you learn the basics programming with
CitectVBA. Before you can use the project, you must:
l Create the test project
l Open the test project
l Set up test project communications
l Set up the test project computer
l Add a variable tag to the project
l Set up a graphics page to the project
Note: The name of the project is appended as a sub folder name to the User
folder. Your path will depend upon the actual path of your Vijeo Citect instal-
lation.
21
Chapter 3: Using the CitectVBA Test Project
Note: Vijeo Citect stores the most recently opened project name in the Citect.ini
file, so that the next time Vijeo Citect is started, that project opens automatically
ready for further editing.
See Also
Setting up Test Project Communications
7. Select Next and click the Create a New I/O Device check box.
8. In the Name field, replace the default name IODev with CiVBAIODevice.
9. Click Next and click the Disk I/O Device check box.
10. Click Next to accept the defaultVijeo Citect Generic Protocol.
22
Chapter 3: Using the CitectVBA Test Project
11. ClickNext to accept the default remaining unlinked to any external tag database.
12. Select Next and Finish to create the CitectVBA Project communications.
See Also
Setting up the Test Project Computer
23
Chapter 3: Using the CitectVBA Test Project
5. In the I/O Device Name field, check that the device name selected is CiV-
BAIODevice. (If other I/O Devices have been created for this project, they will display
in this menu.)
6. In the Data Type field, select INT from the menu.
7. In the Address field, typeI1 (the capital letter i and the number one).
8. Click Add.
See Also
Adding a Graphics Page
1. Click Save.
2. In the Page field on the Page tab, replace the default name Untitled1 with Startup.
When you start this project, this page will be displayed by default.
3. Click OK.
See Also
Opening the Graphics Page
24
Chapter 3: Using the CitectVBA Test Project
1. Choose Open from the File menu in Graphics Builder, or click Open.
2. In the Project field on the Page tab, change to the CitectVBA Test project (if not
already selected).
3. In the Page field on the Page tab, select the file named Startup.
4. Click OK.
Note: Double clicking a graphic page icon in the Citect Explorer launches the Citect
Graphics Builder and displays the selected graphics page.
See Also
Accessing Cicode Tags with CitectVBA
25
Chapter 3: Using the CitectVBA Test Project
26
Chapter 4: Understanding CitectVBA Language
Basics
This section describes the basics of the CitectVBA programming language.
CitectVBA Files
CitectVBA code scripts can be saved to file, can include comments, statements, various
representations of numbers, can handle many different data types, and can have mul-
tiple and nested control structures. However, CitectVBA is primarily provided with Vijeo
Citect to interact with ActiveX objects.
CitectVBA files are ASCII text files stored in ANSI format with a BAS extension
(filename.BAS), and are known as file modules.
CitectVBA file modules can be viewed and edited in any text editor program. They can
be used in Vijeo Citect, but must be saved as 'text with linebreaks' with a '.BAS' file exten-
sion or Citect will not be able to open the file.
Cicode Editor
The Cicode Editor is CitectVBA aware and designed to help you create, edit, test, and
debug CitectVBA file modules in your Vijeo Citect project.
The Cicode Editor has features suitable for use with CitectVBA file modules including:
l Ability to create, open, edit, and save CitectVBA file modules
l Customizable coloration of CitectVBA code syntax structure
l Recognition of predefined keywords with tooltip prompting and auto-completion
functionality
l Fully integrated debugging of CitectVBA file modules
l Separate VB Watch window for viewing runtime CitectVBA variable values
A sample CitectVBA file module named Sample.Bas is included in the User\Example
subfolder on the drive on which you installed Vijeo Citect. This module explains most of
the CitectVBA functionality.
27
Chapter 4: Understanding CitectVBA Language Basics
CitectVBA file modules will never be compiled into standalone Windows executable
files; instead, they're included with the compiled Vijeo Citect. As a result, they don't
require a Mainprocedure to be declared. Therefore, CitectVBA file modules are structured
to contain only their header information, modular constant and variable declarations,
then procedures (subroutines, and functions).
CitectVBA file modules are automatically included with a Vijeo Citect project if they are
stored in the same file folder as your project. When saving a CitectVBA file module to
disk, save it to your project folder.
All files with a BAS extension in your project folder appear in the CitectVBA Files folder
of your project in Citect Explorer. To launch the Cicode Editor, double-click the
CitectVBA file you want to edit in Citect Explorer.
Scope of CitectVBA
The scope of an object determines which portions of your code scripts can use that
object.
Note: The use of Global, Public, and Privatekeywords has no effect on scope in
CitectVBA.
Do not use the Global, Public, or Private keywords in your CitectVBA procedures. Using
these keywords in procedures can lead to unintended equipment operation when your pro-
gram is run.
Failure to follow these instructions can result in death, serious injury, or equip-
ment damage.
28
Chapter 4: Understanding CitectVBA Language Basics
Procedural level variables declared using the Dimstatement do not retain their assigned
values when dereferenced. Procedural level variables declared using the Staticstatement,
however, do retain their assigned values between references, even after that procedure
moves out of scope.
29
Chapter 4: Understanding CitectVBA Language Basics
CitectVBA Files
CitectVBA Statements
A statement in CitectVBA is an unbroken sequence of syntactically correct code script
containing at least one CitectVBA keyword instruction. A single statement in CitectVBA
is one complete segment of code script that instructs Vijeo Citect to do something.
In CitectVBA there is no statement terminator. As in other BASIC programming lan-
guages, the end of the line containing the statement is treated as the statement ter-
minator by default.
Most often, a statement consists of a single line of CitectVBA script. However, more than
one statement can be placed on one line of CitectVBA script, provided each statement is
separated by a colon character (:); for example:
Comments
Comments are non-executed sections of code that are ignored by the CitectVBA compiler.
Comments allow programmers to describe the purpose of a section of code to facilitate
code maintenance.
As in other BASIC programming languages, both the apostrophe character ( ' ), and the
keyword REMare recognized as the start of a comment in CitectVBA. All characters fol-
lowing an apostrophe or the keyword REMare ignored by the CitectVBA compiler until it
reaches the end of the line. Line continuation characters do not work inside comments.
REM, like all other keywords and most names in CitectVBA, is not case sensitive.
30
Chapter 4: Understanding CitectVBA Language Basics
Both types of comments can be used on their own separate line, or the apostrophe char-
acter can be used to start a comment at the end of a statement on the same line as a state-
ment.
Everything placed on the same line after an apostrophe is treated by CitectVBA as a com-
ment. If you want to place a comment on the same line as a statement, the comment
must be placed last after all statements on that line. Comments cannot be placed
between multiple statements on the same line.
Not every line of code requires a comment. In fact, CitectVBA should contain under-
standable naming structures and be laid out in such a manner as to make comments
unnecessary. However, where a complex function, equation, or logic structure is not
readily understandable by viewing the code, it is good practice to include a pertinent
comment to make the code more understandable when viewed in isolation.
See Also
Comments
Header information
You should include header information with every file you create or edit. Data such as
the file name, author name, creation date, update date, editing history, and the like
should be included to form the header information. Each function or subroutine should
include a brief comment describing the purpose or function of the procedure.
See Also
Header information
CitectVBA Files
31
Chapter 4: Understanding CitectVBA Language Basics
Labels
Labels can be used to divide a large CitectVBA function or subroutine into logical sub-
sections of code script. Labels are often used in association with the GoTo statement. All
of the CitectVBA script following the label and extending through to another label, or to
the end of the function or subroutine containing the label, is regarded as belonging to
that label. Or more appropriately, the label is said to identify, or be attached to, that par-
ticular section of CitectVBA script.
Labels must begin with a letter, be no longer than 40 characters, and cannot be a
reserved word. Labels must terminate with the colon character (:). Label names can only
contain the letters 'A' to 'Z' and 'a' to 'z', the underscore '_' character, and the digits '0' to
'9'. Label names cannot contain the space character.
Label names (once declared), become a keyword in CitectVBA. Like most keywords in
CitectVBA, label names are not case sensitive. For example, all of the following label
examples are treated identically in CitectVBA:
label1:
Label1:
LABEL1:
Note: Labels as used in CitectVBA are not the same as labels used in Vijeo Citect.
See Also
CitectVBA Files
Pump234.AddPoint _
( 25, 100)
Strings cannot be separated between lines using the line-break character in CitectVBA,
unless the strings are properly enclosed within double quotes on each line, and
appended together as per the following example:
32
Chapter 4: Understanding CitectVBA Language Basics
Naming
Function, subroutine, variable, constant, and label naming in CitectVBA must begin with
a letter, be no longer than 40 characters, and cannot be a reserved word. Names can only
contain the letters 'A' to 'Z' and 'a' to 'z', the underscore '_' character, and the digits '0' to
'9'. Names cannot contain the space character. You cannot use the name of a CitectVBA
predefined function as a name. For a list of predefined functions, see CitectVBA Function
Reference.
Function, subroutine, variable, constant, and label object names (once declared), become
a keyword in CitectVBA. Like most keywords in CitectVBA, these names are not case sen-
sitive. For example, all of the following examples are treated identically in CitectVBA:
pump234.addpoint(25, 100)
Pump234.AddPoint(25, 100)
PUMP234.ADDPOINT(25, 100)
When naming in CitectVBA, make the name an appropriately descriptive term that is
easily recognizable. For example:
X.addpoint(25, 100)
Pump234.AddPoint(25, 100)
Combining upper- and lowercase letters between words in the name is an acceptable
common programming practice, and aids in readability.
Identically named objects cannot be declared more than once per Vijeo Citect project,
even though they may exist in different CitectVBA code file modules. However, if an
object declared locally within a procedure has the same name as an object declared in a
module, CitectVBA will reference the local procedure scope object instead of the modular
scope object.
See Also
Scope of CitectVBA
33
Chapter 4: Understanding CitectVBA Language Basics
CitectVBA Files
Accessing Cicode Tags with CitectVBA
Option Statements
CitectVBA supports the use of file scope Optionstatements which determine the default
behaviour of some CitectVBA functions. For instance, the Option Explicitstatement
causes the CitectVBA compiler to produce compile errors whenever it encounters the use
of previously undeclared variables. The Option Comparestatement sets the default com-
parison method for string comparisons. The Option Basestatement sets the default base
number for CitectVBA variable arrays to either zero or one.
You must declare all optionstatements in CitectVBA at the beginning of your CitectVBA
code files.
See Also
Option Explicit statement
Option Compare statement
Option Base statement
CitectVBA Function Reference
Option Explicit
This causes the CitectVBA compiler to produce a compile error whenever it encounters
an undeclared variable. This can be useful in locating and identifying variable name typ-
ing errors in your CitectVBA code at compile time, thus trapping and minimizing the
likelihood of runtime errors caused by such mistakes.
See Also
Option Explicit statement
Variable declaration
34
Chapter 4: Understanding CitectVBA Language Basics
Option Statements
Note: When comparing strings, CitectVBA compares the ANSI values of each char-
acter in the strings. For example, the character capital 'A' has the ANSI value of 65,
and the character lowercase 'a' has the ANSI value of 97. For a listing of ANSI char-
acter values, see ASCII/ANSI Character Code Listings.
You can use the Option Comparestatement to specify the default case-sensitivity behavior
for CitectVBA functions when making string comparisons.
The Option Comparestatement in CitectVBA has two settings:
l Option Compare Binary: String comparisons are case-sensitive, and this is the
default string-comparison setting.
l Option Compare Text: String comparisons are case-insensitive.
See Also
Strings
Option Statements
35
Chapter 4: Understanding CitectVBA Language Basics
Option Statements
See Also
Numeric Data Types
Numbers
36
Chapter 4: Understanding CitectVBA Language Basics
Variables
CitectVBA Function Reference
Constants
Your CitectVBA code may contain frequently recurring constant values like Pi, or may
contain numbers that are difficult to remember or have no obvious meaning. You can
make your CitectVBA code much easier to read and maintain using constants to rep-
resent those values.
Unlike variables, constants can't be changed once your Vijeo Citect project is compiled
and running. Constants are either symbolic or intrinsic:
l Symbolic or user-defined constants are declared by using the const statement.
l Intrinsic constants are provided in object libraries of ActiveX objects and you cannot
use them in CitectVBA: they cause compile errors as there is no way to provide early-
binding to the object type library.
You can create a constant in CitectVBA named Pi, assign it the numeric value once in
your code, then refer to it by using the constant name, as shown here:
These CitectVBA functions would be called from a Vijeo Citect command or expression
field like this:
CiVBA
TestTag_1 = CircleArea(TestTag_1)
or
CiVBA
TestTag_1 = CircleCircumference(TestTag_1)
See Also
Declaration of constants
37
Chapter 4: Understanding CitectVBA Language Basics
Declaration of constants
CitectVBA constants can only be declared and referenced within CitectVBA file modules.
CitectVBA modular constants have modular scope and cannot be referenced (accessed
and used) from outside their CitectVBA module (file).
Once declared within a CitectVBA module, CitectVBA constants can be referenced and
used in any procedure within the same code module. A constant declared outside a pro-
cedure has modular scope to all procedures within that same CitectVBA module (file).
See Scope of CitectVBA. Constants declared in a Sub or Function procedure have local
scope only within that procedure.
CitectVBA constants are declared with the Conststatement in the following format.
where:
l Const is the required constant declaration statement BASIC keyword
l <ConstantName> represents the required name of the constant being declared
l <DataType> represents the optional CitectVBA data type of the constant being declared
l <expression> represents the required value being assigned to the constant
Note: Do not include the brackets from the explanation in the actual code statement.
If no data type is declared, CitectVBA automatically assigns one of the following data
types to the constant:
l Long (if it is a long or integer).
l Double (if a decimal place is present).
l String (if it contains quote marks).
38
Chapter 4: Understanding CitectVBA Language Basics
Constant statements can only be declared and assigned using simple expressions. Con-
stants cannot be assigned values from variables, user-defined functions, intrinsic
CitectVBA functions (such as Chr), or from any expression that involves an operator. A
constant needs to be defined before it can be used.
Example
Note: The use of Global, Public, and Private keywords has no effect on scope in
CitectVBA.
See Also
Constants
Intrinsic constants
Variables
CitectVBA Data Types
CitectVBA Function Reference
Intrinsic constants
CitectVBA has no predefined intrinsic (built-in and declared) constants, however, does
provide limited support for intrinsic constants provided in object libraries of ActiveX
objects when the object they refer to is loaded using the predefined CitectVBA Create-
Object() function.
39
Chapter 4: Understanding CitectVBA Language Basics
See Also
Declaration of constants
Constants
Variables
Variables are used in CitectVBA to temporarily store data values. Variables let you
assign a descriptive name to the data you are working with. You can create a variable
once only in your code, and reference (refer to) it thereafter as many times as you like, by
using its name in your code in place of the data value. Unlike constants, the value that a
variable holds can be changed during the runtime of the project.
All variables declared within a CitectVBA procedure (subroutine or function) have local
scope to that procedure only. Procedural level variables declared using the Dim statement
do not retain their assigned values when dereferenced. Procedural level variables
declared using the Static statement, however, retain their assigned values between ref-
erences, even after that procedure moves out of scope.
CitectVBA code used within a Vijeo Citect command or expression field is treated as if
the command or expression is a separate CitectVBA procedure. Variables declared
within such a command procedure have procedural scope and lifetime, as described
above.
Variables declared using the staticstatement at the modular level (outside any pro-
cedure) in a CitectVBA file, have modular scope to all procedures within that same
CitectVBA module (file). Modular level staticvariables retain their assigned values for
the entire runtime of the project.
Variables declared (using the dim,global,orpublicstatements) at the modular level (out-
side any procedure) in a CitectVBA file do, however, have global scope within the Vijeo
Citect project.
Note:Global and public statements are redundant at the modular (global) level in
CitectVBA, as they perform the exact same duty as the dim statement.
Variable declaration
In CitectVBA, variables are declared (dimensioned) with the dim statement in the fol-
lowing format.
40
Chapter 4: Understanding CitectVBA Language Basics
where:
l Dim is the required Variable declaration statement BASIC keyword
l <VariableName> represents the required name of the variable being declared (dimen-
sioned)
l <DataType> represents the optional CitectVBA data type of the variable being declared
If no data type is declared, the data type is Variant by default. To declare a variable
other than a Variant, the variable declaration needs to be immediately followed by As
<datatype> (where <datatype> represents one of the 10 data types), or appended by a type
declaration character such as a $, %, &, !, or # for string, integer, long, single, or double
data types respectively. For example:
Be aware that multiple declarations in the same statement require individual data type
assignment if you want them be other than the variant type. In the following example,
only the first variable is not a variant. For example:
The same statement with data type assignment for every variable would look like the fol-
lowing example:
See Also
CitectVBA Data Types
Variable initialization values
41
Chapter 4: Understanding CitectVBA Language Basics
Constants
Variant Declaration
Arrays of Variables
CitectVBA Function Reference
Note: Only implicitly declared variables can be assigned an initial value in the dec-
laration. However, as explicit declaration is preferred practice in CitectVBA, explicit
variables need to be declared before they can be assigned a value.
Every call to a procedure will reinitialize the value of all objects (except static variables)
declared within that procedure.
Note: In CitectVBA, use a static variable, a modular variable, or a Vijeo Citect tag to
store variable values between procedures. For details, see Scope of CitectVBA.
Objects (including variables) declared in CitectVBA are only initialized when referenced
by a running piece of code, and are removed from memory when all references are
closed.
In the Vijeo Citect multithreaded environment, CitectVBA remains active in memory
only so long as a procedure is being processed. At the completion of a CitectVBA pro-
cedure, all objects no longer referenced by that procedure are removed from memory. For
details, see Multithread Considerations with CitectVBA.
See Also
CitectVBA Data Types
Variable initialization values
Constants
Variant Declaration
Arrays of Variables
42
Chapter 4: Understanding CitectVBA Language Basics
Arrays of Variables
Arrays of variables allow you to group like variables together, somewhat similar to the
grouping of like items in fields of a database. An array is an ordered group of variables
of the same name, containing values of the same data type. Individual member elements
of the array are identified by a separate index number. Arrays in CitectVBA start their
indexing sequence by default at zero. This default base value can be changed in a
CitectVBA file module by using the option base statement.
CitectVBA supports single and multi-dimension arrays of variables. CitectVBA creates
single dimension arrays by default. Multi-dimension arrays must be specifically
declared.
CitectVBA allocates memory space for each element of the array. To minimize the
amount of memory used storing arrays, and to minimize the time required to access
array data, arrays should not be declared any larger than required.
All elements in an array must be of the same data type. CitectVBA supports arrays of
bytes, booleans, longs, integers, singles, doubles, strings, and variants. For details about
CitectVBA data types, see CitectVBA Data Types.
Arrays declared in a sub or function procedure have local scope only within that pro-
cedure. An array declared outside a procedure has modular (global) scope to all pro-
cedures within the project.
Note: CitectVBA arrays cannot be used directly in Vijeo Citect command or expres-
sion fields. Also, CitectVBA does not support user-defined data types.
Arrays declared (using the dim statement within procedures,) do not retain their values
between procedure calls in CitectVBA.
See Also
Fixed Size Arrays
Multi-Dimensional Arrays
Dynamic Size Arrays
Arrays of variables are declared within a CitectVBA file module, function, or subroutine,
using the dim statement with parentheses positioned after the array name, in the fol-
lowing syntax:
where:
43
Chapter 4: Understanding CitectVBA Language Basics
Array Subscripts
Arrays can be declared with default or defined boundaries known as bounds. Unless spe-
cifically defined in the array declaration statement, default lower bound settings are
used. The default lower bound is zero, unless set by the module option base statement
setting.
CitectVBA does not have an arbitrary upper bound on array dimensions. The upper
bound of the array dimension must be defined before the array can be used. All bound
values must be whole integers.
Subscripts are contained within one set of parentheses positioned immediately after the
array name in the array declaration statement.
44
Chapter 4: Understanding CitectVBA Language Basics
Subscripts are used to specify the bounds of each dimension of an array when the array
is declared. If a single value is used, for instance (5), this represents the upper bound for
that dimension of the array. If a range is specified, for instance (1 to 9), this specifies
both the lower and upper bounds for that dimension of the array. If more than one sub-
script is used, for instance ( 5, 1 To 9), each subscript must be separated by a comma,
and each subscript represents a separate dimension of the array.
The syntax of an array subscript range consists of a numeric value range separated by
the to clause:
(<LowerBound> To <UpperBound>)
where:
l ( )are the required parentheses to hold an array subscript range (dimensions).
l <LowerBound> represents the lower bound of the subscript range for the array dimen-
sion.
l To is the clause linking the lower and upper bounds of the subscript range.
l <UpperBound> represents the upper bound of the subscript range for the array dimen-
sion.
See Also
Fixed Size Arrays
Multi-Dimensional Arrays
Dynamic Size Arrays
Arrays of Variables
Dim
To declare a fixed size array, the array name must be followed by the upper bound sub-
script enclosed within parentheses. The upper bound must be an integer.
Unless specifically defined in the array declaration statement, default lower bound set-
tings are used. The default lower bound is zero, unless set by the module option base
statement setting. For details, see Array Subscripts.
The first declaration in the previous example creates an array with 11 elements, with
index numbers running from 0 to 10. The second creates an array with 21 elements (if
base 0). One way to specify the lower bound is to provide it explicitly (as an integer in
the range -32,768 to 32,767) using the To clause within the subscript:
45
Chapter 4: Understanding CitectVBA Language Basics
In the preceding example, the index numbers of intCounters run from 1-13, and the
index numbers of strSums run from 100-126.
Loops often provide an efficient way to manipulate arrays. For example, the following
for loop initializes all elements in the array to 5:
Arrays declared (using the dim statement within procedures) do not retain their values
between procedure calls in CitectVBA.
See Also
Multi-Dimensional Arrays
Dynamic Size Arrays
Arrays of Variables
Array Subscripts
Option Base statement
Multi-Dimensional Arrays
Unless specifically defined in the array declaration statement, default lower bound set-
tings are used. The default lower bound is zero, unless set by the module option base
statement setting. For more information on bounds, see "Array Subscripts in CitectVBA."
Reusing the previous example, either or both dimensions can be declared with explicit
lower bounds.
46
Chapter 4: Understanding CitectVBA Language Basics
Arrays can be more than two dimensional. This declaration creates an array that has
three dimensions with sizes 6 elements by 4 elements by 3 elements, using base 0:
Dim ArrTest(5, 3, 2)
You can efficiently process a multi-dimensional array with the use of for loops. In the fol-
lowing statements the elements in a multi-dimensional array are set to a value.
Arrays declared (using the dim statement within procedures,) do not retain their values
between procedure calls in CitectVBA.
See Also
Multi-Dimensional Arrays
Dynamic Size Arrays
Arrays of Variables
Array Subscripts
Option Base statement
Fixed Size Arrays
To declare a dynamic sized array, the array must first be declared using the dim state-
ment with an empty pair of parentheses following the array name. For example:
Once declared as dynamic in this manner, the array can then ONLY be resized within a
function or subroutine using the redim statement.
Note: You cannot resize an array whose size was predefined in its initial declaration.
47
Chapter 4: Understanding CitectVBA Language Basics
In the above examples, the first declaration creates an array with 0 elements. The second
recreates the array to contain 21 elements, with index numbers running from 0 to 20,
unless the option base statement has been set previously in the code module (file), in
which case the array will contain 20 elements with index numbering ranging from 1 to
21.
Unless specifically defined in the array declaration statement, default lower bound set-
tings are used. The default lower bound is zero, unless set by the module option base
statement setting. For more information on bounds, see "Array Subscripts in CitectVBA."
erases all values the array may have held. To preserve the contents of the array
Redim
when resizing, precede the Redim statement with the preserve keyword.
Redimensioning an array to a smaller value, will erase any values it may have con-
tained in the removed portions.
Arrays declared (using the dim statement within procedures,) do not retain their values
between procedure calls in CitectVBA.
See Also
Multi-Dimensional Arrays
Arrays of Variables
Array Subscripts
Option Base statement
Fixed Size Arrays
Variant Declaration
As is the case with Visual Basic, when a variable is introduced in CitectVBA, it is not
necessary to declare it first (see Option Explicit statement for an exception to this rule).
When a variable is used but not declared, it is implicitly created as a variant data type.
Variants can also be declared explicitly using As Variant. Both of the following example
declarations as treated identically in CitectVBA:
The IsEmpty( ) function can be used to find out if a variant variable has been previously
assigned a value.
48
Chapter 4: Understanding CitectVBA Language Basics
The variant data type is capable of storing numbers, strings, dates, and times. When
using a variant, you do not have to explicitly convert a variable from one data type to
another. This data type conversion is handled automatically, and is termed data type
coercion.
Numeric characters inside quotes ("567") will be stored and treated as a string in a var-
iant data type variable. If this string (containing numeric characters) is subsequently
used in a numeric operation, it will be coerced into a numeric data type and treated as a
number in the operation. Conversely, numeric characters stored as a number data type
in a variant variable, and subsequently used in an operation with a string, will be
coerced into a string data type, and treated as a string value in the operation.
Note: To determine the type of a variant variable, use the function VarType( ), which
returns a value that corresponds to the explicit data types. See VarType for return
values.
Numbers in Variants
When storing numbers in variant variables, the data type used is the most compact type
possible. For example, if you first assign a whole number to the variant it will be stored
as an integer or long. If you assign a number with a fractional component, it is stored as
a single or double.
For doing numeric operations on a variant variable, it is sometimes necessary to deter-
mine if the value stored is a valid numeric, thus avoiding an error. This can be done
with the IsNumeric( ) function.
See Also
CitectVBA Data Types
Variables
Constants
Strings
Numbers
49
Chapter 4: Understanding CitectVBA Language Basics
Numbers
CitectVBA supports three representations of numbers: decimal, octal, and hexadecimal.
To indicate the use of octal (base 8) or hexadecimal (base 16) numbers, prefix the number
with &O or &H respectively. If no prefix is included with a number, it is treated as decimal
(base 10). For example:
Most numbers used in CitectVBA formulas are decimal numbers. Decimal numbers con-
sist of integral values (known as integers) positioned to the left of the decimal point, and
fractional values (known as fractions) positioned to the right of the decimal point. If the
decimal point is omitted, the number is treated as an integer (whole number with no frac-
tion).
When using numbers in CitectVBA, consideration needs to be given to the data type of
the variables that hold and store the numbers, as well as to the behaviour of CitectVBA
when dealing with numbers. For details, see Numeric Data Types, Floating Point Cal-
culation Rules, and Rounding Numbers.
See Also
Date Handling
Variant Declaration
Strings
Variables
Constants
CitectVBA Data Types
CitectVBA Function Reference
50
Chapter 4: Understanding CitectVBA Language Basics
l Integer (Integer data type) variables can only store whole number values (no decimal
or fraction values) within the range -32,000 to +32,000. If you use a number outside
this range, the long integer (Long data type) can store whole number values in the
range -2.1 million to +2.1 million.
l Floating point numbers contain both integer and fractional values with a floating dec-
imal point. CitectVBA provides both single precision (Single data type) and Double
Precision (Double data type) variables for handling floating-point numbers.
l Single-precision variables can store floating-point numbers within the range of
approximately 3.4E-38 to 3.4E+38, with 7 significant digits and occupying 4 bytes of
memory.
l Double-precision variables can store floating-point numbers within the range of
approximately 1.79D-308 to 1.79D+308, with 15 significant digits and occupying 8
bytes of memory.
For an explanation of exponential notation, see Exponential Notation.
The principal differences between single and double data types, are the significance they
can represent, the storage they require, and their range. Double data type variables have
a smaller range, but hold more precision and occupy more memory than single data
type variables.
If precision is less of a concern than storage, consider using single for floating-point var-
iables. Conversely, if precision is the most important criterion, use double.
Variant (variant data type) variables in CitectVBA can store numbers by storing them as
integer, long, single, or double data types within the variant structure. See Variant Dec-
laration.
See Also
Numbers
Exponential Notation
CitectVBA can handle very large numbers, up to a value of 1.7976931486232 raised to
the power of 308, (1.7 308). To represent very large numbers such as these, exponential
notation is used.
Commonly, exponential notation uses the letter 'E' in the number, followed by the sign of
the number (+ or -), and then the exponential value (power) of the number. CitectVBA
uses the letter 'E' for Single data type exponential values, and the letter 'D' for Double
data type exponential values. The maximum size number for a double precision data
type, as quoted above, would be represented using exponential notation as
1.7976931486232D+308, or abbreviated to 1.79D+308.
51
Chapter 4: Understanding CitectVBA Language Basics
You can use exponential notation in your CitectVBA calculations, so long as the data
types of all the variables in the calculation are capable of storing floating point values;
i.e.: Single, Double or Variant.
For details about precision, accuracy, and rounding issues with using floating point var-
iables in CitectVBA, see Numeric Data Types, Floating Point Calculation Rules, and
Rounding Numbers.
See Also
Numbers
Numbers
Date Handling
52
Chapter 4: Understanding CitectVBA Language Basics
Rounding Numbers
Rounding occurs when you convert a number of greater precision into a number of
lesser precision. For instance, when converting a floating-point number (single precision,
double precision, or variant data types) into an integer or long data type number. The
possible ways of numeric rounding are discussed below.
Rounding down
The simplest form of rounding is truncation. Any digits after the desired precision are
ignored and dropped. The CitectVBA Fix()function is an example of truncation. For
example, Fix(3.5)is 3, and Fix(-3.5)is -3.
The Int()function rounds down to the highest integer less than the value. Both Int()and
Fix()act the same way with positive numbers (truncating), but give different results for
negative numbers: Int(-3.5)gives -4.
The Fix()function is an example of symmetric rounding because it affects the magnitude
(absolute value) of positive and negative numbers in the same way. The Int()function is
an example of asymmetric rounding because it affects the magnitude of positive and neg-
ative numbers differently.
Rounding up
CitectVBA does not have a specific round-up function. However, for negative numbers,
both Fix() and Int() can be used to round upward, in different ways:
l Fix() rounds towards 0 (up in the absolute sense, but down in terms of absolute mag-
nitude). For example: Fix(-3.5) is -3.5.
l Int() rounds away from 0 (up in terms of absolute magnitude, but down in the abso-
lute sense). For example: Int(-3.5) is -4.
Arithmetic rounding
When continually rounding in one direction (down or up), the resulting number is not
necessarily the closest to the original number. For example, if you round 1.9 down to 1,
the difference is a lot larger than if you round it up to 2. It is easy to see that numbers
from 1.6 to 2.4 should be rounded to 2. However, what about 1.5, which is equidistant
between 1 and 2? By mathematical convention, the half-way number is rounded up.
To implement rounding half-way numbers in a symmetric fashion, -.5 is rounded down
to -1, or in an asymmetric fashion, where -.5 is rounded up to 0.
CitectVBA does not have a function for arithmetic rounding.
Banker's rounding
53
Chapter 4: Understanding CitectVBA Language Basics
When you add rounded values together, always rounding .5 in the same direction
results in a bias that grows with the more numbers you add together. One way to mini-
mize the bias is with banker's rounding.
Banker's rounding rounds .5 up sometimes and down sometimes. The convention is to
round to the nearest even number, so that both 1.5 and 2.5 round to 2, and 3.5 and 4.5
both round to 4. Banker's rounding is symmetric.
In CitectVBA, the CByte(), CInt(), CLng(), CCur(), and Round() numeric functions perform
banker's rounding.
Random rounding
Even banker's rounding can bias totals. You can take an extra step to remove bias by
rounding .5 up or down in a truly random fashion. This way, even if the data is delib-
erately biased, bias might be minimized. However, using random rounding with ran-
domly distributed data might result in a larger bias than banker's rounding. Random
rounding could result in two different totals on the same data.
CitectVBA does not have a function for random rounding.
Alternate rounding
54
Chapter 4: Understanding CitectVBA Language Basics
If you need just the time portion of a date variable, use the TimeValue function. Using this
function, you could write code that checks the time portion of a date variable against a
particular time, like this:
dtmTomorrow = Date()+ 1
Date is a built-in CitectVBA function that returns the date portion (the integer part) of the
current date and time retrieved from the Windows operating system. Adding 1 to that
value returns a date that represents the next day.
The same mechanism works for subtracting two dates. Although CitectVBA supplies the
DateDiff function for finding the interval spanned by two date/time values, if you just
need to know the number of days between the two dates, you can simply subtract one
from the other.
See Also
Date and Time Functions
Date Constants
Formatting Date Values
CitectVBA Function Reference
Date Constants
You can use date/time literals in CitectVBA code by enclosing them with the hash sign
(#), in the same way you enclose string literals with double quotation marks (""). This is
commonly known as declaring date constants.
For example, #2/6/10# represents the Australian date value of 2nd June, 2010 if the short
date setting for the locale was set to d/MM/yyyy. The same date constant would rep-
resent the American date value of February 6, 2010 if the short date setting for the locale
was set to MM/d/yyyy. See Formatting Date Values.
55
Chapter 4: Understanding CitectVBA Language Basics
Note: The system locale settings are determined using Regional Settings in Windows
Control Panel.
Similarly, you can compare a date/time value with a complete date/time literal:
If you don't include a time in a date/time literal, CitectVBA sets the time part of the
value to midnight (the start of the day). If you don't include a date in a date/time literal,
CitectVBA sets the date part of the value to December 30, 1899.
CitectVBA accepts a wide variety of date and time formats in literals. These are all valid
date/time values:
In the same way that you can use the IsNumeric function to determine if a Variant var-
iable contains a value that can be considered a valid numeric value, you can use the
IsDate function to determine if a variant contains a value that can be considered a valid
date/time value. You can then use the CDate function to convert the value into a
date/time value.
For example, the following code tests the Text property of a text box with IsDate. If the
property contains text that can be considered a valid date, CitectVBA converts the text
into a date and computes the days left until the end of the year:
See Also
Date and Time Functions
Formatting Date Values
CitectVBA Function Reference
Date Handling
56
Chapter 4: Understanding CitectVBA Language Basics
Note: Always use long date format whenever possible. Also, please ensure that you
enter and display dates in an unambiguous format. For example, dates in short date
format might be misinterpreted in queries if the year or the day of the month are 12
or less (for example, 3/11/10). Dates in medium date format display only the first few
characters of the month name, which can create ambiguity or an undesirable appear-
ance.
Text
All strings should be surrounded by single quotes, and any single quotes should be
entered as four single quotes in a row:
Value Example
it''''s it's
'Today is 'M/dd/yy' and it''''s 'h:mm Today is 01/22/99 and it's 8:18
Day
The day can be displayed in one of four formats using a lowercase "d".
d Day of the month as digits without leading zeros for single digit days. 5
dd Day of the month as digits with leading zeros for single digit days. 05
57
Chapter 4: Understanding CitectVBA Language Basics
Month
The month can be displayed in one of four formats using capital "M". The letter "M"
must be uppercase to distinguish months from minutes.
Year
The year can be displayed in one of three formats using lowercase "y"..
y Year represented only by the last digit, if the year is less than 10. 9
Years greater than 10 will be given the value of yy.
Period/Era
The period/era string can be displayed in a single format using the letter "g". The letter
"g" must be lowercase. If you include the gg in a date string that does not have any asso-
ciated Era string, the gg is ignored.
Valu- Meaning
e
(Nul- Gregorian dates are used. Does nothing if Gregorian is value of iCalendarType
l)
58
Chapter 4: Understanding CitectVBA Language Basics
Time
The time can be displayed in one of many formats using the letter "h" or "H" to denote
hours, the letter "m" to denote minutes, the letter "s" to denote seconds and the letter "t"
to denote the time marker. The lowercase "h" denotes the 12 hour clock and uppercase
"H" denotes the 24 hour clock. The "m" must be lowercase to denote minutes as opposed
to Months. The "s" for seconds and "t" for the time marker string must also be lowercase.
h Hours without leading zeros for single digit hours (12 hour clock). 1
hh Hours with leading zeros for single digit hours (12 hour clock). 01
H Hours without leading zeros for single digit hours (24 hour clock). 1
HH Hours with leading zeros for single digit hours (24 hour clock). 01
t One character time marker string. This will be the first letter of the A
values in the AM symbol or PM symbol boxes in Regional Options
See Also
Date Handling
Date Constants
Date and Time Data Constraints
59
Chapter 4: Understanding CitectVBA Language Basics
l The value of the month field must be between 1 and 12, inclusive.
l The value of the day field must be in the range from 1 through the number of days in
the month. The number of days in the month is determined from the values of the
year and months fields and can be 28, 29, 30, or 31. (The number of days in the
month can also depend on whether it is a leap year.)
l The value of the hour field must be between 0 and 23, inclusive.
l The value of the minute field must be between 0 and 59, inclusive.
l For the trailing seconds field of interval data types, the value of the seconds field
must be between 0 and 59.9(n), inclusive, where n is the number of digits in the frac-
tional seconds precision.
l For the trailing seconds field of datetime data types, the value of the seconds field
must be between 0 and 61.9(n), inclusive, where n specifies the number of "9" digits
and the value of n is the fractional seconds precision. (The range of seconds allows as
many as two leap seconds to maintain synchronisation of sidereal time.)
See Also
Date Handling
Date Constants
Formatting Date Values
Date Data Type Structure
Dates in Databases Using Different Calendars
60
Chapter 4: Understanding CitectVBA Language Basics
For example, the date and time of 5/22/97 at 3:00 p.m. would be stored in CitectVBA as
35572.625 representing the 35572 days since 12/30/1899, and 3:00 p.m. as 625/1000 of a
full day.
Note: Don't confuse Date data types used in CitectVBA with date and time values
used in Windows, DLLs, Vijeo Citect, or in Cicode. For instance, Vijeo Citect stores
time/date-related variables as a single integer representing the number of seconds
since 01/01/1970.
Date-values
A date-value in CitectVBA is a count of the number of days from December 30, 1899.
December 31, 1899 has the date-value of 1, and the 1st January 1900 is 2. December 30,
1899 has the date value of zero. Negative date-values represent dates prior to December
30, 1899.
A date-value in CitectVBA can actually range from January 1, 0100, to December 31,
9999 inclusive, which is a integer value ranging from -657434 up to +2958465 respec-
tively. Using values outside this range will cause compilererrors in CitectVBA.
The pre-defined CitectVBA Year, Month, and Day functions calculate and return the appro-
priate year, month or day value (as an integer) from a date-value.
Time-values
A time-value in CitectVBA represents the fractional time of day since the previous mid-
night. Unlike a date-value which is simply a count of the number of days, the time-value
is a decimal fraction of a day.
As every day invariably consists of 24 hours, or 1440 minutes, or 86,400 seconds, the
time of day can be readily determined from a time-value using simple math. An hour
has the time-value of one twenty-fourth of one day (0.0416'), one minute has the time-
value of 0.000694', and a second has the time-value of 0.000011574'0'7'. Midday has the
time-value of 0.50. 1AM has the time-value of 0.0416'. 1PM has the time value of
0.5416'.
The pre-defined CitectVBA Hour function, Minute function, and Second function calculates
and returns the appropriate hour, minute or second value (as an integer) from a time-
value.
61
Chapter 4: Understanding CitectVBA Language Basics
See Also
Date Handling
Date Constants
Formatting Date Values
Dates in Databases Using Different Calendars
Date and Time Data Constraints
Always confirm that calendar types in existing databases are compatible with the locality
(regional and language) options of the operating system.
Failure to follow these instructions can result in death, serious injury, or equip-
ment damage.
To avoid problems of this sort, all date references in an external database should be
based on the Gregorian Calendar, or the database tables can be exported to text files
before use in Vijeo Citect. Dates in Microsoft Access database tables exported as text files
are always stored as Gregorian values. If the database calendar is set to Hijri for exam-
ple, automatic Hijri to Gregorian conversion is performed during the export process.
You can't set a database calendar programmatically using CitectVBA.
Note: When you want to use characters for Baltic, Central European, Cyrillic, Greek,
Turkish, and Asian languages, or right-to-left languages (Arabic, Hebrew, Farsi, and
Urdu) the operating system would need to have the corresponding language version
of Windows, or have installed system support for that language.
See Also
Date Handling
62
Chapter 4: Understanding CitectVBA Language Basics
Operators
Variables can be manipulated in CitectVBA using assignment, arithmetic, relational, and
logical operators.
l The assignment operator is used to assign a value to a variable or constant (that
equals this).
l Arithmetic operators are used to mathematically manipulate numeric variables and
numbers (addition, subtraction, multiplication, division, etc.).
l Relational Operators are used to compare the relationship between variables (less
than, greater than, not equal to, etc.).
l Logical operators are used to perform digital logic operations on variables ( AND,
OR, NOT, etc.).
When using multiple operators in a CitectVBA statement, you need to ensure the proper
execution of your code by observing order of precedence rules.
The string concatenation operator is used to join strings together.
See Also
Constants
Variables
Numbers
Strings
Date Handling
CitectVBA Function Reference
Assignment Operator
The CitectVBA assignment operator uses the equals character ( = ) in a CitectVBA state-
ment. The variable named to the left side of the assignment operator is assigned the oper-
and value from the right side of the assignment operator, as shown here:
Only one variable can be assigned at any one time with the assignment operator.
63
Chapter 4: Understanding CitectVBA Language Basics
There must be a space on either side of the assignment operator, or the equals character
may be confused with either the variable name or the value being assigned, and a com-
pile error may occur.
Unless the variable is a variant data type, the value being assigned must be the same
data type as the variable receiving the assigned value. For instance, if you assign a text
string into a long data type variable, you'll cause an error to occur.
The variable must be previously declared before being assigned a value. The value of a
variable can be changed any number of times in a later statements, as in the following
CitectVBA example:
See Also
Operators
^ Exponentiation X=Y^2
- Negation X=-2
* Multiplication X=2*3
64
Chapter 4: Understanding CitectVBA Language Basics
/ Division X = 10 / 2
+ Addition X=2+3
- Addition X=6-4
See Also
Operators
Relational Operators
CitectVBA Relational Operators are used in CitectVBA statements to compare the rela-
tionship between operands (values positioned immediately on either side of the Rela-
tional Operator). The boolean result is either True or False. .
= Equals X=Y
See Also
Operators
Logical Operators
Logical (boolean) operators are used to perform digital logic operations on variables. All
logical operations result in either a boolean True or False.
65
Chapter 4: Understanding CitectVBA Language Basics
Or logical Or If (X = Y) Or (X = Z)
See Also
Operators
Operator Precedence
The operator precedence in CitectVBA runs like this:
() Parenthesis Highest
^ Exponentiation
- Unary minus
/, * division/multplication
Mod Modulo
Or logical disjunction
66
Chapter 4: Understanding CitectVBA Language Basics
See Also
Operators
Strings
Strings can be stored in variables of string and variant. When using variant strings, be
aware of type coercion in CitectVBA. Strings can be compared with each other in
CitectVBA to determine whether they contain the same characters or not. Strings can be
joined together to create longer strings in CitectVBA using the concatenation operator.
Strings can be searched using the:
l InStr()function, which returns the character position of the first occurrence of a string
within another;
l Left()function or Right()function which return a copy of the left or right most char-
acters of a string respectively; and
l Mid() function, which returns the copy of a substring from within another string.
To determine the length of a string, use the Len() function which returns a Long variable
containing the number of characters in the string.
String characters can be converted to ASCII values using the Asc()function, and ASCII
values can be converted to their string characters using the Chr()Function.
String characters can be converted to all lowercase or all uppercase using the Lcase()
Function or the Ucase() Function respectively.
Leading or trailing spaces can be stripped off strings using the Ltrim()function or the
Rtrim()function respectively.
Strings can be created consisting of a specified number of spaces or characters using the
Space() function or the String() function respectively.
67
Chapter 4: Understanding CitectVBA Language Basics
String Comparisons
CitectVBA compares ANSI values of characters when comparing strings. For example,
the character capital 'A' has the ANSI value of 65, and the character lowercase 'a' has
the ANSI value of 97. For a listing of ANSI characters values, see ASCII/ANSI Character
Code Listings.
You can use CitectVBA relational operators (less than, greater than, equal to, not equal
to, and so on) to compare string variables. All relational operators return either true or
false.
With comparisons made using relational operators, the result depends on the option com-
pare string-comparison option setting of the CitectVBA file. Consider the following exam-
ple:
If the file Option string-comparison setting is Option Compare Binary (or not set at all),
the comparison returns true. CitectVBA compares the binary (ANSI) values for each cor-
responding position in the string until it finds two that differ. In this example, the low-
ercase letter "v" corresponds to the ANSI value 118, while the uppercase letter "V"
corresponds to the ANSI value 86. Because 118 is greater than 86, the comparison
returns true.
If the file Option string-comparison setting is Option Compare Text, "Citectvba" >
"CitectVBA" returns false, because the strings are equivalent apart from case.
The built-in CitectVBA StrComp() Function returns a variant containing a value rep-
resenting the result of the comparison of two strings. It has an optional third argument
Comp which can override the file Option string-comparison setting.
See Also
Option Compare statement
Strings
String Concatenation
To concatenate strings in CitectVBA, use the ampersand ( & ) concatenation operator
between the strings. Multiple concatenations can occur in the same CitectVBA statement.
68
Chapter 4: Understanding CitectVBA Language Basics
strFirstName = "Colin"
strLastName = "Ramsden"
strFullName = strFirstName &strSpaceChar &strLastName
' concatenates string values
The & concatenation operator does not perform arithmetic, and will convert variable
data types to strings for concatenation. For instance, if a variant string and a variant
number are concatenated, the result is a string. For more details of variant data types,
see Variant Declaration and CitectVBA Data Types.
See Also
Strings
Operators
Control Structures
Control Structures
CitectVBA provides conditional control functionality, which can be used to conditionally
perform CitectVBA statements or blocks of statements dependant upon the result of the
condition tested. This is known as logical decision making.
The logical decision making control structures available in CitectVBA consist of three
conditional looping or repetitive statements (Do Statement, While Statement, and For
Statement), and two conditional flow control sequence statements (Select Case Statement,
and variations of the If Statement). In addition, CitectVBA provides one unconditional
branching GoTo Statement.
Note: In the control structure syntax examples, every placeholder shown inside
arrow brackets ( <placeholder> ) should be replaced in any actual code with the value
of the item that it describes. The arrow brackets and the word they contain should
not be included in the statement, and are shown here only for your information.
Also, statements shown between square brackets ( [ ]) are optional. The square brack-
ets should not be included in the statement, and are shown here only for your infor-
mation.
See Also
Operators
GoTo statement
Do statement
While statement
For statement
69
Chapter 4: Understanding CitectVBA Language Basics
If statement
Select case statement
End statement
Exit statement
OnError statement
Stop statement
With statement
CitectVBA Function Reference
GoTo statement
The GoTo conditional statement branches unconditionally and without return to the label
specified in the GoTo statement. The label must be located in the same subroutine or func-
tion as the Goto statement.
<statement/s>
If <condition> then
GoToLabel1
Else
GoToLabel2
End If
Label1:
<statement/s>
GoToLabel3
Label2:
<statement/s>
GoToLabel3
Label3:
<statement/s>
In this example, CitectVBA tests the If condition, and jumps to the part of the script that
begins with the label "Label1:" if the condition was true, or jumps to the part of the script
that begins with the label "Label2:" if the condition was false. This could be anywhere in
the same subroutine or function.
See Also
Control Structures
Do statement
The Do...Loop conditional statement allows you to execute a block of statements an indef-
inite number of times. The variations of the Do...Loop are Do While, Do Until, Do Loop
While, and Do Loop Until.
70
Chapter 4: Understanding CitectVBA Language Basics
Do While|Until <condition>
<statement/s>
Loop
Do Until <condition>
<statement/s>
Loop
Do
<statement/s>
Loop While <condition>
Do
<statement/s>
Loop Until <condition>
Do While and Do Until check the condition before entering the loop, thus the block of
statements inside the loop are only executed when those conditions are met. Do Loop
While and Do Loop Until check the condition after having executed the block of state-
ments so that the block of statements is executed at least once.
Any Do statement can be exited using the Exit Do statement.
See Also
Control Structures
While statement
The While...Wend loop conditional statement is similar to the Do While loop statement.
The condition is checked before executing the block of statements comprising the loop.
While <condition>
<statement/s>
Wend
See Also
Control Structures
For statement
The For...Next loop conditional statement repeats its block of statements a set number of
times as determined by the values used with the To clause.
71
Chapter 4: Understanding CitectVBA Language Basics
The counter variable is increased or decreased (by the value stated in the optional Step
parameter), with each reiteration of the loop. The counter default is to increment by one
if the Step parameter is omitted.
See Also
Control Structures
If statement
The If statement in CitectVBA tests an initial condition and then either performs or omits
to perform the statements it contains, dependant upon the logical result of the test con-
dition. The condition can be a comparison or an expression, and must logically evaluate
to either True or False. The If statement has both single line and multiple line syntax
structure.
The single line syntax uses the If <TestCondition> Then <StatementToPerformIfTrue>
structure, however, can only perform a single statement if and only if the test condition
result is True. No 'End If' statement is required:
If the result of the If test condition was True, the program flow continues into and per-
forms the statement following the Then statement, until it reaches the end of the line.
To perform a single statement conditionally upon a False result, use the NOT logical
operator:
To perform multiple statements, use the multiple line syntax structure which ends with
the 'End If' statement:
If <Condition> Then
' Then statement block
' perform only if true
<Statement/s>
End If
If the result of the If test condition was True, the program flow continues into the Then
statement block, and performs the statements following the Then statement, until it
reaches the End If statement.
If the result of the If test condition was False, the program flow jumps over the Then
statement block, which in this case exits the If structure (without performing any state-
ments other than the initial test condition).
72
Chapter 4: Understanding CitectVBA Language Basics
The mutiple line If structure can perform different blocks of statements dependant upon
EITHER a True OR a False result to the test condition, through the use of the Else state-
ment block:
If <Condition> Then
' Then statement block
' perform only if true
<Statement/s>
Else
' Else statement block
' perform only if false
<Statement/s>
End If
If the result of the If test condition was True, the program flow performs the Then block
statements, until it reaches the Else statement. It then jumps over the Else statement
block and exits the If structure (without performing any of the Else statement block state-
ments).
If the result of the If test condition was False, the program flow jumps over the Then
statement block (without performing any of those statements) to the Else statement to per-
form the statements in the Else statement block until it reaches the End If statement.
Further test conditions can be placed into an If structure through the use of the optional
Else If <Condition> statement block. ElseIf statement blocks can only be positioned
within an If structure before the Else statement block.
If <Condition> Then
' Then statement block
' perform only if true
<Statement/s>
ElseIf <Condition>
' Else If statement block
' perform only if true
<Statement/s>
Else
' Else statement block
' perform only if false
<Statement/s>
End If
The ElseIf test condition is only evaluated after the initial If structure test condition
results in False.
If the result of the ElseIf test condition was True, the statements within the ElseIf state-
ment block are performed. The program flow then jumps over the Else statement block
and exits the If structure (without performing any of the Else statement block state-
ments).
73
Chapter 4: Understanding CitectVBA Language Basics
If the result of the ElseIf test condition was False, the program flow jumps over the ElseIf
statement block (without performing any of those statements) to the Else statement to per-
form the statements in the Else statement block until it reaches the End If statement.
There is no apparent limit to the number of Else If statement blocks that any one If struc-
ture can hold, however, the Select Case Statement structure handles multiple condition
result alternatives much more efficiently.
See Also
Control Structures
If the result of the Case test condition was True, the program flow performs the state-
ments contained within that Case statement block, and will then exit the Select Case
structure (without performing any of the Else statement block statements).
If the result of the Case test condition was False, the program flow jumps over the Case
statement block (without performing any of those statements) to the Case Else statement
to perform the statements in the Else statement block until it reaches the End Select state-
ment.
Further test conditions can be placed into a Select Case structure through the optional
use of further Case statement blocks. Case statement blocks can only be positioned
within a Select Case structure before the Case Else statement block.
74
Chapter 4: Understanding CitectVBA Language Basics
Each Case statement block is evaluated in order until the test condition of one results as
True. The program flow performs the statements contained within that Case statement
block, and will then exit the Select Case structure (without performing any other state-
ments).
The statements of ONLY one Case statement block are ever performed, unless all result
in False and there is no Case Else block declared, in which case no Case statement
blocks are performed at all.
The following example may help clarify the logic testing being performed in a Select
Case structure. Lets say that we have a variable named (intDayOfWeek) containing an
integer (ranging from 1 to 7) representing the day of the week, and we wished to display
that value as a string (named strDayOfWeek) containing the name of the day of the
week, assuming in this example, that Sunday is the first day of the week (1). The Select
Case structure would look like this:
75
Chapter 4: Understanding CitectVBA Language Basics
The Select Case structure tends to be easier to read, understand, and follow and should
be used in place of a complicated multi-nested If...ElseIf structure.
See Also
Control Structures
End statement
The End statement Ends a block of statements such as a Sub procedure or Function.
End[{Function | If | Sub}]
Example
See Also
Control Structures
Exit statement
Exits a loop or procedure
Example
' This sample shows Do ... Loop with Exit Do to get out.
Dim Value, Msg ' Declare variables
Do
Value = InputBox("Enter a value from 5 to 10.")
If Value >= 5 And Value <= 10 Then ' Check range
Exit Do ' Exit Do...Loop
Else
Beep ' Beep if not in range
End If
76
Chapter 4: Understanding CitectVBA Language Basics
Loop
See Also
Control Structures
OnError statement
CitectVBA's error-handling routine and specifies the line label of the error-handling rou-
tine. The line parameter refers to a label. That label needs to be present in the code or an
error is generated.
Syntax
Example
See Also
Control Structures
Stop statement
Ends execution of the program. The Stop statement can be placed anywhere in your
code.
Example
Dim x,y,z
For x = 1 to 5
For y = 1 to 5
For z = 1 to 5
Print "Looping",z,y,x
Next z
Next y
Stop
Next x
77
Chapter 4: Understanding CitectVBA Language Basics
See Also
Control Structures
With statement
The With Statement is not supported in CitectVBA. When performing a series of com-
mands on an object, you must explicitly refer to the name of the object with each com-
mand.
See Also
Control Structures
Note: Subroutines and functions can contain statements that call other subroutines
or functions (to perform, before returning to the following statements within the call-
ing subroutine or function).
Both subroutines and functions can similarly be passed values as arguments when they
are called:
l Arguments are passed to subroutines in CitectVBA code following the subroutine
name and separated by space characters.
l Arguments are passed to functions enclosed within parentheses in CitectVBA code,
similarly following the subroutine name and separated by space characters.
Note:Vijeo Citect tag values must be declared by value when passed as argument
78
Chapter 4: Understanding CitectVBA Language Basics
See Also
Subroutines
Functions
Arguments
Subroutines
A CitectVBA subroutine starts with the SUB statement and finishes with the END SUB
statement. All other statements that lie between the SUB and END SUB statements, will
be executed by the subroutine, when called to do so.
Note: In the following subroutine syntax example:
l Every placeholder shown inside arrow brackets ( <placeholder>) should be replaced
in any actual code with the value of the item that it describes. The arrow brackets
and the word they contain should not be included in the statement, and are shown
here only for your information.
l Statements shown between square brackets ( [ ]) are optional. The square brackets
should not be included in the statement, and are shown here only for your infor-
mation.
In CitectVBA, Subroutines are created with the SUB statement in the following format.
where:
l [Byval] is the optional parameter for the argument;
l Sub is the required subroutine statement basic keyword
l <SubName> represents the required name of the subroutine being created
l <Argument/s> represents the optional argument/s of the subroutine
l <statement> represents the executable CitectVBA script statement/s
l End Sub is the subroutine terminating statement
79
Chapter 4: Understanding CitectVBA Language Basics
The name given to the subroutine immediately follows the SUB keyword, and is used to
identify the subroutine to CitectVBA. This name is referred to when the subroutine is
called upon (called) to be executed (perform the statements it contains) by some other
procedure in CitectVBA.
Subroutine names can contain the letters 'A' to 'Z' and 'a' to 'z', the underscore '_' and
digits '0' to '9'. The subroutine name must begin with a letter, be no longer than 40 char-
acters, cannot contain the space character, and cannot be a reserved word. Subroutine
names (once declared), become a keyword in CitectVBA. Like most keywords in
CitectVBA, these names are not case sensitive.
The subroutine name always ends with a pair of parentheses ( ) which may or may not
contain one or more arguments required by (necessary for use in) the subroutine . Mul-
tiple arguments if used, are separated by commas ( , ). See Arguments for more details
and argument syntax.
All the lines located between the SUB and the END SUB statements, contain the state-
ments that will be executed when the subroutine is called in CitectVBA. These state-
ments will be executed one at a time in logical order from top to bottom within the
subroutine.
See Also
Subroutines and Functions
Functions
Arguments
Functions
A CitectVBA function starts with the FUNCTION statement and finishes with the END
FUNCTION statement. All other statements that lie between the FUNCTION and END
FUNCTION statements, will be executed by the function, when called to do so.
Note: In the following function syntax example:
l Every placeholder shown inside arrow brackets ( <placeholder>) should be replaced
in any actual code with the value of the item that it describes. The arrow brackets
and the word they contain should not be included in the statement, and are shown
here only for your information.
l Statements shown between square brackets ( [ ]) are optional. The square brackets
should not be included in the statement, and are shown here only for your infor-
mation.
A typical CitectVBA function is structured like in the following example:
80
Chapter 4: Understanding CitectVBA Language Basics
<statement>
<statement>
<statement>
[ <FunctionName> = <value> ]
End Function
where:
l Function' is the required function statement basic keyword
l [ Byval ] is the optional parameter for the argument;
l <FunctionName> represents the required name of the function being created
l ( <Argument/s> ) represents the optional argument/s of the function
l <ReturnDataType> represents the optional return data type of the function
l <statement> represents the executable CitectVBA script statement/s
l = <value> represents the optional assignment of the return value for the function
l 'End Function' is the function terminating statement
The name given to the function, immediately follows the FUNCTION keyword, and is
used to identify the function to CitectVBA. This name is referred to when the function is
called upon (called) to be executed (perform the statements it contains) by some other
procedure in CitectVBA.
Function names can contain the letters 'A' to 'Z' and 'a' to 'z', the underscore '_' and dig-
its '0' to '9'. The function name must begin with a letter, be no longer than 40 characters,
cannot contain the space character, and cannot be a reserved word. Function names
(once declared), become a keyword in CitectVBA. Like most keywords in CitectVBA,
these names are not case sensitive.
The function name always ends with a pair of parentheses ( ) which may or may not
contain one or more arguments required by (necessary for use in) the function. Multiple
arguments if used, are separated by commas ( , ). See the section titled 'Arguments in
CitectVBA' for more details and argument syntax.
All the lines located between the FUNCTION and the END FUNCTION statements, con-
tain the statements that will be executed when the function is called in CitectVBA. These
statements will be executed one at a time in logical order from top to bottom within the
function.
The return value of the function is optionally assigned within the function in a state-
ment using the function name. This value is often used within the calling procedure to
determine the status of the function. Commonly, this value may be a Boolean True or
False to indicate the successful completion or not of the function.
81
Chapter 4: Understanding CitectVBA Language Basics
See Also
Subroutines and Functions
Arguments
Subroutines
Accessing Functions in DLLs
Arguments
Arguments are used in CitectVBA to pass values into subroutines and functions when
they are being called. Arguments are positioned between parentheses '( )' immediately
after the subroutine or function name in the subroutine or function declaration. If no
arguments are required for the subroutine or function, the parentheses must be included
and left empty in the declaration.
Arguments are optional in the sense that subroutines and functions do not require them.
However, if arguments are to be used in a subroutine or function, the arguments must
first be declared with the subroutine or function declaration, before they can be used. If
declared, they must be used whenever the subroutine or function is called.
CitectVBA does NOT support named arguments so all arguments must be used in dec-
laration order. If omitted, strings default to an empty string (""), and numeric values
default to zero (0). Boolean values in CitectVBA are represented with -1 for TRUE, and 0
for FALSE.
Multiple arguments must be separated by a comma ( , ) placed between the arguments.
The number of arguments that can be used in any single subroutine or function is not
stated, (but likely limited to something like 255). If you are declaring a subroutine or func-
tion with that many arguments, you should probably split your subroutine or function
into smaller separate logical routines with less arguments for each routine. If an argu-
ment is omitted, its place must be declared by the use of a comma in the call.
If you want to use the value in a Vijeo Citect tag as an argument to a function or sub-
routine, you must assign the value of the tag to a CitectVBA variable, and then pass the
variable as the argument. You cannot pass a Vijeo Citect tag name as an argument to a
function or subroutine.
Each argument declaration in a subroutine or function must be structured using the
proper CitectVBA argument syntax as described below.
CitectVBA argument structure syntax in the declaration of functions or subroutines is as
follows:
where:
82
Chapter 4: Understanding CitectVBA Language Basics
Note:Vijeo Citect tag values MUST be declared by value when passed as argument
values to a CitectVBA procedure from within a Vijeo Citect command or expression
field. This is best done by declaring a variable, assigning it the tag value, then pass-
ing the variable by value.
The function or subroutine name always ends with a pair of parentheses ( ) which may
or may not contain one or more arguments required by (necessary for use in) the func-
tion or subroutine. Multiple arguments if used, are separated by commas ( , ).
The optional 'As <DataType>' parameter is used to specify the data type of the argument
variable. The argument data types must be individually declared, or will be of Variant
data type by default. Valid data types for arguments in CitectVBA are: String, Integer,
Double, Long, and Variant (see the section titled 'CitectVBA_Data_Types' for descrip-
tions of data types in CitectVBA).
Example
83
Chapter 4: Understanding CitectVBA Language Basics
TestTag_1 = Z
End Sub
Granted, that's not likely the way you'd actually calculate an area given two fixed values
in a subroutine that calls a function. You could just as easily do the calculation within
the subroutine. However, this example does demonstrate the passing of values from a
subroutine to a function, and the retrieval of a return value from the function back to the
calling subroutine.
Note in the previous example, that the argument names ('longLength' and 'longWidth')
are only used within the function in which they were declared. The values they rep-
resented were passed in with the call to the function in the statement line:
Z = longArea(X, Y)
The values of the variables 'X' and 'Y' were passed into the function 'longArea' and were
handled within the function as its argument names 'longLength' and 'longWidth'. The
result was returned and stored in the variable named 'Z'.
See Also
Subroutines and Functions
Subroutines
Functions
Note: Vijeo Citect itself provides an API for external access to Vijeo Citect I/O
84
Chapter 4: Understanding CitectVBA Language Basics
APIs are traditionally written for C and C++ programmers who are building Windows
applications, however, the functions in a DLL can also be called by other programming
languages, including CitectVBA. Because most DLLs are written and documented pri-
marily for C/C++ programmers, calling a DLL function may differ somewhat from call-
ing a CitectVBA function. In order to work with an API, you need to understand how to
pass arguments from CitectVBA to a DLL function. See Passing Arguments to DLL Func-
tions from CitectVBA.
See Also
Passing variables Byref and Byval
CitectVBA Function Reference
Note: The use of the OPTIONAL components of the Declare statement syntax indi-
cates that they may not be required in all DLL functions. It is not up to you whether
you can optionally use them or not. If included in a DLL function, they MUST be
used when declaring that function to CitectVBA.
The Declare statement in CitectVBA details the name, file location, arguments, intrinsic
constants, and type definitions that the DLL function requires. Here's an example of the
Declare statement for the Windows API GetTempPathA function, which returns the path
to the Windows system temporary folder:
85
Chapter 4: Understanding CitectVBA Language Basics
The Declare keyword indicates to CitectVBA that you intend to call a function belonging
to an external DLL. The Declare keyword must be used first in the declaration statement.
The Function statement consists of the Function keyword, followed by the name that you
will use when calling this function from CitectVBA.
The Lib statement specifies which DLL contains the function you wish to use. The Lib
statement consists of the Lib keyword, followed by the name of the DLL contained
within string double quotes. Some commonly used DLLs in the Windows API for exam-
ple, are Kernel32.dll - which performs low level OS functions like memory management
and resource handling, the User32.dll - which performs Windows message handling,
timers, menus and communication functions, and the GDI32.dll - which performs the
graphics display and font management functions.
86
Chapter 4: Understanding CitectVBA Language Basics
In this example, the name of the API function in the DLL is GetTempPathA, and the
name by which you would call this function from CitectVBA is GetWinTempPath. Note
that the actual name of the DLL function appears contained within string double quotes
positioned after the Alias keyword. This instructs CitectVBA to use the alias function
name when calling the DLL.
Because an alias allows you to name a declared DLL function anything you want in
CitectVBA, you can make the function name conform to your own naming standards.
Note: DLL functions are case sensitive; CitectVBA function names are not. When
declaring DLL functions in CitectVBA, be careful to accurately remain case sensitive
in the declaration.
See Also
Functions
Passing variables Byref and Byval
Passing Arguments to DLL Functions from CitectVBA
DLLs and APIs
87
Chapter 4: Understanding CitectVBA Language Basics
l In the next example, the parameter iVar is passed by value to the function Test-
Function. Since arguments passed to functions must be enclosed in parentheses, an
extra pair is used to force the argument to be passed by value.
TestFunction((iVar))
Note:Vijeo Citect does not support passing by reference, so Vijeo Citect tag values
MUST be declared by value when passed as arguments to a CitectVBA procedure
from within a Vijeo Citect command or expression field. This is best done by
declaring the variable, assigning it the tag value, then passing the variable by
value. (See the Example below.)
Example
Suppose you had a variable tag of integer type named "iTag1" and you need to pass it to
a function. From within a CitectVBA script, or Vijeo Citect command or expression field,
you would use the following code example to pass the variable tag value to a function
named TagArgumentTest:
CiVBA
Dim iVar1 as Integer
iVar1 = iTag1
TagArgumentTest(iVar1)
Note: Cicode does not support passing by reference, so CitectVBA variables passed
to Cicode functions using the CicodeCallOpen function must be enclosed in brackets to
force the passing of those variables by value.
See Also
Passing Arguments to DLL Functions from CitectVBA
DLLs and APIs
Arguments
88
Chapter 4: Understanding CitectVBA Language Basics
Note: Although the Byval keyword appears in front of some arguments of type
String, strings are always passed to Windows API functions by reference, therefore
any DLL function can always modify a string source directly.
DLL functions don't return strings in the same way that CitectVBA functions do.
Because strings are always passed to DLL functions by reference, the DLL function can
modify the value of the string argument. Rather than returning a string as the return
value for the function, as you would probably do in CitectVBA, a DLL function returns a
string into an argument of type String that was passed to the function. The actual return
value for the function is often a long integer specifying the number of bytes that were
written into the string argument.
To call a DLL function that writes to a String variable, you need to take additional steps
to format the string properly. First of all, the String variable must be a null-terminated
string. A null-terminated string ends in a special null character. Secondly, a DLL func-
tion can't change the size of a string once it has been created.
Therefore, you need to make sure that the string that you pass to a function is large
enough to hold the entire return value, and that it terminates with a Null character.
When you pass a string to a DLL function, you'll usually need to specify the size of the
string that you've passed in another argument. Windows keeps track of the length of the
string so that it doesn't overwrite any memory that the string is using.
Note: It's only necessary to pass in a null-terminated string and its size if you're
returning a string from a function. If the function does not return a string into a
string argument, but instead takes a string that provides information to the function,
you can simply pass in a normal CitectVBA String variable.
A Nullstring is a string of value 0 [no Character code]; note that this is not the same as
an empty string ("").
See Also
DLLs and APIs
Arguments
Passing variables Byref and Byval
89
Chapter 4: Understanding CitectVBA Language Basics
OLE Services
OLE (Object Linking and Embedding) services is the term used to generally describe the
integrated use of separate software components (applications) working together to pro-
vide custom software solutions based upon the Microsoft Component Object Model
(COM) architecture.
Note: When considering the use of OLE services, you should be aware that there are dif-
ferent uses of OLE which have developed over the years and which may be confused
with one another. Examples of different OLE services include: object linking, object
embedding, visual editing, drag-and-drop, ActiveX Controls, OLE Automation, OLE DB,
OLE Messaging, and OLE Networking services. See OLE terminology.
Vijeo Citect supports linked and embedded OLE objects in its graphics pages with the
use of ActiveX Controls. See Accessing ActiveX Objects with CitectVBA.
Vijeo Citect can use CitectVBA to perform as an OLE Automation controller. See OLE
automation objects. Vijeo Citect can also exchange data with other applications using
other data transfer technologies.
OLE terminology
OLE superceded the Dynamic Data Exchange protocol. Network DDE was introduced to
afford the same data transfer facility between Windows applications connected across
the same network. Vijeo Citect supports both DDE and Network DDE connectivity.
The differences between linked objects and embedded objects which may affect you, con-
cern where the data is stored, and how it is updated after you place it in the destination
file. With linked OLE objects, the source of the OLE object data remains in the original
data file of the application that was used to create it, and only a copy of the data is ever
displayed in the destination document. The data is updated only when the source file is
modified. Embedded OLE objects duplicate and store a local copy of the source file data
within the destination document data file, and are not linked to the source file. That is,
the data copy in the destination file does not change when you modify the source file.
With both linked and embedded OLE objects, when the OLE object in the destination doc-
ument is double-clicked, the original application (that was used to create the data) of the
OLE object is launched to permit editing of the data using that source program's editor.
Linked OLE objects store their data back in the original source data files, while embed-
ded OLE objects store their data in the destination program data files.
OLE Automation
90
Chapter 4: Understanding CitectVBA Language Basics
'OLE Automation' was developed to permit the (remote) control of other applications on
the same computer. Applications which expose their functionality using OLE Auto-
mation are known as OLE Automation servers, and could be automated by code run-
ning in a completely separate application, known as OLE Automation clients or
controllers.
OLE Automation servers exposed their functionality through structured object models,
which are listings of the internal functions, methods and properties of the application
object. All Microsoft Office applications are OLE Automation servers to some extent, and
can be subsequently controlled by any OLE Automation compliant controller, using the
appropriate syntax to manipulate and control the relevant application object model.
Not all applications that support OLE services support OLE Automation. For example,
many products support drag-and-drop, and object linking and embedding, but do not
support OLE Automation. Linking and embedding allow the user to access the object,
whereas OLE Automation allows one application to control another application, pos-
sibly with minimal or no user interaction.
See Also
OLE Services
91
Chapter 4: Understanding CitectVBA Language Basics
Note: CitectVBA objects cannot be used directly in Vijeo Citect command or expres-
sion fields.
Once declared within a CitectVBA module, CitectVBA objects can be referenced and used
in any procedure within the same code module. An object declared outside of a pro-
cedure has modular scope to all procedures within that same CitectVBA module (file).
Objects declared within a Sub or Function procedure have local scope only within that
procedure.
The object variable must be declared before it can be assigned an object reference. Object
variables are declared by the Dim Statement with the As Object CitectVBA data type
using the following syntax:
where:
l Dim is the required Variable declaration statement BASIC keyword
l <VariableName> represents the required name of the variable being declared (dimen-
sioned)
l As Object declares the variable as a CitectVBA 'object' data type
For example:
Once declared, you can then assign an OLE Automation reference to the object variable
in CitectVBA.
92
Chapter 4: Understanding CitectVBA Language Basics
See Also
Deleting OLE automation objects
Using OLE automation objects
where:
l Set is the required reference assignment statement keyword
l <objVarName> represents the required name of the variable receiving the reference
l CreateObject() function creates the object of the class type specified in the argument
l <objClassName> represents the required name of the class providing the object
The object class name passed as the argument to the CreatObject function usually con-
sists of the fully qualified class name of the object being created, for example "Word.A-
pplication" or "Excel.Application".
Example
Once assigned, you can then use that object variable in your CitectVBA code to manip-
ulate the referenced object model. See Using OLE automation objects.
Dependant objects (which cannot be created independantly) can be "drilled-down" to
and subsequently assigned from existing (externally creatable) independant object s, by
using a method of the higher level object. See Understanding object models in OLE Auto-
mation.
93
Chapter 4: Understanding CitectVBA Language Basics
94
Chapter 4: Understanding CitectVBA Language Basics
due to rounding when converting between different data types. See Rounding Numbers
in CitectVBA.
To make full use of the OLE Automation object models, you should make yourself famil-
iar with Object related terms. See Understanding object models in OLE Automation.
See Also
OLE automation objects
95
Chapter 4: Understanding CitectVBA Language Basics
What is a property?
objWordApp.Documents("MyDoc.doc").TrackRevisions = True
In this example, Documents refers to the collection of open documents, and the name
"MyDoc.doc" identifies a single document in the collection. The TrackRevisions property
is set for that single document.
You can also return information about an object by returning the value of one of its prop-
erties. The following example returns the name of the active Word document.
docName = objWordApp.ActiveDocument.Name
In this example, ActiveDocument refers to the document in the active window in Word.
The name of that document is assigned to the variable "docName".
Note: Some properties cannot be set. The Help topic for each property indicates
96
Chapter 4: Understanding CitectVBA Language Basics
whether you can set that property (read-write), only read the property (read-only), or
only write the property (write-only). Also the Object Browser in the Visual Basic
Editor displays the read-write status at the bottom of the browser window when the
property is selected.
What is a method?
A method is an action that an object can perform. For example, just as a Word document
can be printed, the Document object has a PrintOut method. Methods often have argu-
ments that qualify how the action is performed. The following example prints the first
three pages of the active Word document.
In most cases, methods are actions and properties are qualities. Using a method causes
something to happen to an object, while using a property returns information about the
object or it causes a quality about the object to change.
Returning an object
Most objects return a single object from the collection. For example, the Documents col-
lection contains the currently open Word documents. You use the Documents property of
the Application object (the object at the top of the Word object hierarchy) to return the
Documents collection.
After you've accessed the collection, you can return a single object by using an index
value in parentheses (this is similar to how you work with VBA arrays). The index
value can be either a number or a name.
The following example uses the Documents property to access the Document collection.
The index number is used to return the first document in the Documents collection. The
Close method is then applied to the Document object to close the first document in the
Documents collection.
objWordApp.Documents(1).Close
The following example uses a name (specified as a string) to identify a Document object
within the Documents collection.
objWordApp.Documents("Sales.doc").Close
97
Chapter 4: Understanding CitectVBA Language Basics
Collection objects often have methods and properties which you can use to modify the
entire collection of objects. The Documents object has a Save method that saves all the
documents in the collection. The following example saves the open documents by apply-
ing the Save method.
objWordApp.Documents.Save
The Document object also has a Save method available for saving a single document.
The following example saves the document named Report.doc.
objWordApp.Documents("Report.doc").Save
To return an object that is further down in the Word object hierarchy, you must "drill
down" to it by using properties and methods to return objects.
To see how this is done, in Word, open the Visual Basic Editor and click Object Browser
on the View menu. Click Application in the Classes list on the left. Then click Active-
Document from the list of members on the right. The text at bottom of the Object Browser
indicates that ActiveDocument is a read-only property that returns a Document object.
Click Document at the bottom of the Object Browser; the Document object is auto-
matically selected in the Classes list, and the Members list displays the members of the
Document object. Scroll through the list of members until you find Close. Click the Close
method. The text at the bottom of the Object Browser window shows the syntax for the
method. For more information about the method, press F1 or click the Help button to
jump to the Close method Help topic.
Given this information, you can write the following instruction to close the active doc-
ument.
objWordApp.ActiveDocument.Close SaveChanges:=wdSaveChanges
objWordApp.ActiveDocument.ActiveWindow.WindowState =
wdWindowStateMaximize
The ActiveWindow property returns a Window object that represents the active window.
The WindowState property is set to the maximize constant (wdWindowStateMaximize).
The following example creates a new document and displays the Save As dialog box so
that a name can be provided for the document.
objWordApp.Documents.Add.Save
98
Chapter 4: Understanding CitectVBA Language Basics
The Documents property returns the Documents collection. The Add method creates a
new document and returns a Document object. The Save method is then applied to the
Document object.
As you can see, you use methods or properties to drill down to an object. That is, you
return an object by applying a method or property to an object above it in the object hier-
archy. After you return the object you want, you can apply the methods and control the
properties of that object.
See Also
OLE Services
Sub runWord()
' demonstrating the use of OLE Automation
' to manipulate Word
99
Chapter 4: Understanding CitectVBA Language Basics
objWordApp.Quit
End Sub
See Also
OLE automation example using the Microsoft Word object
Using OLE automation objects
where:
l Set is the required reference assignment/release statement keyword.
l <objVarName> represents the required name of the variable holding the reference.
l Nothing is the keyword used to release the object reference.
When several object variables refer to the same object, they also refer to the memory and
system resources associated with the object. These resources are released only after all of
them have been set to Nothing, either explicitly using Set, or implicitly after the last
object variable set to Nothing goes out of scope.
Example
100
Chapter 4: Understanding CitectVBA Language Basics
See Also
Using OLE automation objects
For details of all predefined CitectVBA functions, see CitectVBA Function Reference.
101
Chapter 4: Understanding CitectVBA Language Basics
102
Chapter 5: CitectVBA Function Reference
CitectVBA includes the following function categories.
Array Functions
CitectVBA array functions are provided to allow you to declare, resize, initialize, pop-
ulate, and erase arrays and their elements.
The array functions predefined in CitectVBA are:
Dim Allocates storage for, and declares the data type of, variables and arrays in a
module.
Lboun- Returns the smallest available subscript for the dimension of the indicated
d array.
ReDim Used to size or resize a dynamic array that has already been declared using
the Dim statement with empty parentheses.
Uboun- Returns the value of the largest usable subscript for the specified dimension of
d an array.
Dim
The Dim statement allocates storage for, and declares the data type of, variables and
arrays in a module.
103
Chapter 5: CitectVBA Function Reference
The To clause in the array subscript range of a Dim statement provides a more flexible
way to control the lower bound of an array. If you don't explicitly set the lower bound
with a To clause, the Option Base setting (if used) comes into affect, or defaults to zero (if
not used).
Syntax
Subscripts:
DataType:
Related Functions
Example
Dim MyArray(1 To 10, 5 To 15, 10 To 20) ' declares the three dimensional array
MyArray and specifies the upper and lower bounds of each dimension
Erase
Reinitialises the elements of a fixed array specified in the ArrayList parameter.
Syntax
104
Chapter 5: CitectVBA Function Reference
Erase(Arraylist)
Arraylist:
Related Functions
Dim | ReDim
Example
Option Base 1
Dim Num(10) As Integer ' Integer array.
Dim StrVarArray(10) As String ' Variable-string array.
Dim StrFixArray(10) As String * 10 ' Fixed-string array.
Dim VarArray(10) As Variant ' Variant array.
Dim DynamicArray() As Integer ' Dynamic array.
ReDim DynamicArray(10) ' Allocate storage space.
Erase Num ' Each element set to 0.
Erase StrVarArray ' Each element set to zero-length string ("").
Erase StrFixArray ' Each element set to 0.
Erase VarArray ' Each element set to Empty.
Erase DynamicArray ' Free memory used by array.
Erase StrVarArray,StrFixArray,VarArray ' Reset three arrays at the same time.
Lbound
Determines the value of the lower bound for the dimension of the array specified in the
arguments.
Lbound expects the required argument ArrayName to be a valid variable array name. The
optional argument ArrayDimension must be a whole long number indicating which
dimension's lower bound is to be returned. Use 1 for the first dimension, 2 for the sec-
ond, and so on.
Syntax
Lbound(ArrayName, ArrayDimension)
ArrayName:
ArrayDimension:
The dimension of the array for which you want to the lower bound. If ArrayDimension is omitted, 1
is assumed.
Return Value
105
Chapter 5: CitectVBA Function Reference
Related Functions
Ubound
Example
Dim Lower
Dim MyArray(1 To 10, 5 To 15, 10 To 20) ' Declare array variables.
Dim AnyArray(10)
Lower = LBound(MyArray, 1) ' Returns 1.
Lower = LBound(MyArray, 2) ' Returns 5.
Lower = LBound(AnyArray) ' Returns 1.
Option Base
Declares the default lower bound for array subscripts.
The Option Base statement is optional. If used, it can appear only once in a CitectVBA
file, and must be used before you declare the dimensions of any arrays.
The To clause in the array subscript range of a Dim statement provides a more flexible
way to control the lower bound of an array. If you don't explicitly set the lower bound
with a To clause, the Option Base setting (if used) comes into affect, or defaults to zero (if
not used).
Syntax
Option BaseNum
Num:
An Integer or expression representing a valid numeric value. The value of the 'number' parameter
must be either 0 or 1. The default is 0.
Related Functions
Dim | ReDim
Example
The example below uses the Option Base statement to override the default base array
subscript value of 0.
106
Chapter 5: CitectVBA Function Reference
Dim NL as String
' Define newline
NL = Chr(10) & Chr(13)
' Create message
Msg = "The lower bound is " & LBound(Arr) & "."
Msg = Msg & NL & "The upper bound is " & UBound(Arr) & "."
' Display message
MsgBox Msg
ReDim
Used to size or resize a dynamic array that has already been declared using the Dim
statement with empty parentheses.
Use the ReDim statement to change the number of elements in an array, but not to
change the number of dimensions in an array or the type of the elements in the array.
Syntax
ReDimVariableName(Subscripts)
VariableName:
Subscripts:
An Integer or expression representing a valid To numeric value range when declaring the dimen-
sions of an variable array. Up to 60 multiple dimensions may be declared.
When not explicitly stated in lower, the lower bound of an array is controlled by the
Option Base statement. The lower bound is zero if no Option Base statement is present
in the CitectVBA file.
Related Functions
Example
107
Chapter 5: CitectVBA Function Reference
Next I
Ubound
Determines the value of the largest subscript for the ArrayDimension of the ArrayName
provided in the argument. Ubound expects the required argument ArrayName to be a
valid variable array name.
The optional argument ArrayDimension must be a whole long number indicating which
dimension's lower bound is to be returned. Use 1 for the first dimension, 2 for the sec-
ond, and so on. If ArrayDimensionis omitted, 1 is assumed.
Syntax
Ubound(ArrayName, ArrayDimension)
ArrayName:
ArrayDimension:
A numeric value or expression that can represent a valid long data type value.
Return Value
Related Functions
Lbound
Example
Dim Upper
Dim MyArray(1 To 10, 5 To 15, 10 To 20) ' Declare array variables.
Dim AnyArray(10)
Upper = UBound(MyArray, 1) ' Returns 10.
Upper = UBound(MyArray, 3) ' Returns 20.
Upper = UBound(AnyArray) ' Returns 10.
Conditional Statements
108
Chapter 5: CitectVBA Function Reference
tion
For Repeats its block of statements a set number of times as determined by the
values used with the To clause.
Goto Branches unconditionally and without return to the label specified in the
GoTo statement.
If Tests an initial condition and then either performs or omits to perform the
statements it contains, dependant upon the logical result of the test con-
dition.
OnError CitectVBAs error-handling routine and specifies the line label of the error-
handling routine.
Do Loop
The Do...Loop conditional statement allows you to execute a block of statements an indef-
inite number of times. The variations of the Do...Loop are Do...While, Do...Until,
Do...Loop While, and Do...Loop Until.
Do While <condition>
<statement/s>
Loop
Do Until <condition>
<statement/s>
Loop
Do
<statement/s>
109
Chapter 5: CitectVBA Function Reference
Do
<statement/s>
Loop Until <condition>
Do...While and Do...Until check the condition before entering the loop, thus the block of
statements inside the loop are only executed when those conditions are met. Do...Loop
While and Do...Loop Until check the condition after having executed the block of state-
ments so that the block of statements is executed at least once.
Any Do statement can be exited using the Exit Do statement.
End Function
The End Function statement ends a program or a block of statements within a function.
A CitectVBA function starts with the FUNCTION statement and finishes with the END
FUNCTION statement. All other statements that lie between the FUNCTION and END
FUNCTION statements will be executed by the function when called to do so.
Syntax
Related Functions
Example
Sub TestColor2
Dim I as integer
For I = 1 to 10
Print GetColor2(I)
Next I
End Sub
110
Chapter 5: CitectVBA Function Reference
Exit
Exits a loop or procedure.
Syntax
Example
' This sample shows Do ... Loop with Exit Do to get out.
Dim Value, Msg ' Declare variables
Do
Value = InputBox("Enter a value from 5 to 10.")
If Value >= 5 And Value <= 10 Then ' Check range
Exit Do ' Exit Do...Loop
Else
Beep ' Beep if not in range
End If
Loop
For
Repeats its block of statements a set number of times as determined by the values used
with the To clause.
Example
Goto
The GoTo conditional statement branches unconditionally and without return to the
label specified in the GoTo statement. The label must be located in the same subroutine
or function as the GoTo statement.
Example
<statement/s>
If <condition> then
GoTo Label1
Else
GoTo Label2
End If
Label1:
111
Chapter 5: CitectVBA Function Reference
<statement/s>
GoTo Label3
Label2:
<statement/s>
GoTo Label3
Label3:
<statement/s>
In this example, CitectVBA tests the If condition, and jumps to the part of the script that
begins with the label "Label1:" if the condition was true, or jumps to the part of the script
that begins with the label "Label2:" if the condition was false. This could be anywhere in
the same subroutine or function.
If
Tests an initial condition and then either performs or omits to perform the statements it
contains, dependant upon the logical result of the test condition. The condition can be a
comparison or an expression, and must logically evaluate to either True or False. The If
statement has both single line and multiple line syntax structure.
The single line syntax uses the If <TestCondition> Then <StatementToPerformIfTrue>
structure, however, can only perform a single statement if and only if the test condition
result is True. No 'End If' statement is required:
Example
If<Condition>Then<Statement>
If the result of the If test condition was True, the program flow continues into and per-
forms the statement following the Then statement, until it reaches the end of the line.
To perform a single statement conditionally upon a False result, use the NOT logical
operator:
To perform multiple statements, use the multiple line syntax structure which ends with
the 'End If' statement:
If <Condition> Then
' Then statement block
' perform only if true
<Statement/s>
End If
112
Chapter 5: CitectVBA Function Reference
If the result of the If test condition was True, the program flow continues into the Then
statement block, and performs the statements following the Then statement, until it
reaches the End If statement.
If the result of the If test condition was False, the program flow jumps over the Then
statement block, which in this case exits the If structure (without performing any state-
ments other than the initial test condition).
The mutiple line If structure can perform different blocks of statements dependant upon
EITHER a True OR a False result to the test condition, through the use of the Else state-
ment block:
If <Condition> Then
' Then statement block
' perform only if true
<Statement/s>
Else
' Else statement block
' perform only if false
<Statement/s>
End If
If the result of the If test condition was True, the program flow performs the Then block
statements, until it reaches the Else statement. It then jumps over the Else statement
block and exits the If structure (without performing any of the Else statement block state-
ments).
Further test conditions can be placed into an If structure through the use of the optional
Else If <Condition> statement block. ElseIf statement blocks can only be positioned
within an If structure before the Else statement block. If the result of the If test condition
was False, the program flow jumps over the Then statement block (without performing
any of those statements) to the Else statement to perform the statements in the Else state-
ment block until it reaches the End If statement.
If <Condition> Then
' Then statement block
' perform only if true
<Statement/s>
ElseIf <Condition>
' Else If statement block
' perform only if true
<Statement/s>
Else
' Else statement block
' perform only if false
<Statement/s>
End If
113
Chapter 5: CitectVBA Function Reference
The ElseIf test condition is only evaluated after the initial If structure test condition
results in False.
If the result of the ElseIf test condition was True, the statements within the ElseIf state-
ment block are performed. The program flow then jumps over the Else statement block
and exits the If structure (without performing any of the Else statement block state-
ments).
If the result of the ElseIf test condition was False, the program flow jumps over the ElseIf
statement block (without performing any of those statements) to the Else statement to per-
form the statements in the Else statement block until it reaches the End If statement.
There is no apparent limit to the number of Else If statement blocks that any one If struc-
ture can hold, however, the Select Case Statement structure handles multiple condition
result alternatives much more efficiently.
OnError
CitectVBA's error-handling routine and specifies the line label of the error-handling rou-
tine. The line parameter refers to a label. That label needs to be present in the code or an
error is generated.
Syntax
Example
Select
The Select Case statement tests the same variable for many different conditions. The test
value provided with the initial Select Case statement is logically tested against the Case
test condition.
The Select Case structure can perform different blocks of statements dependant upon
whichever Case statement test condition (if more than one) first results as True, through
the use of the Case statement block:
114
Chapter 5: CitectVBA Function Reference
Case <Condition>
' Case statement block
' perform only if case true
<Statement/s>
Case Else
' Else statement block
' perform only if all cases false
<Statement/s>
End Select
If the result of the Case test condition was True, the program flow performs the state-
ments contained within that Case statement block, and will then exit the Select Case
structure (without performing any of the Else statement block statements).
If the result of the Case test condition was False, the program flow jumps over the Case
statement block (without performing any of those statements) to the Case Else statement
to perform the statements in the Else statement block until it reaches the End Select state-
ment.
Further test conditions can be placed into a Select Case structure through the optional
use of further Case statement blocks. Case statement blocks can only be positioned
within a Select Case structure before the Case Else statement block.
Each Case statement block is evaluated in order until the test condition of one results as
True. The program flow performs the statements contained within that Case statement
block, and will then exit the Select Case structure (without performing any other state-
ments).
The statements of ONLY one Case statement block are ever performed, unless all result
in False and there is no Case Else block declared, in which case no Case statement
blocks are performed at all.
115
Chapter 5: CitectVBA Function Reference
The following example may help clarify the logic testing being performed in a Select
Case structure. Lets say that we have a variable named (intDayOfWeek) containing an
integer (ranging from 1 to 7) representing the day of the week, and we wished to display
that value as a string (named strDayOfWeek) containing the name of the day of the
week, assuming in this example, that Sunday is the first day of the week (1). The Select
Case structure would look like this:
The Select Case structure tends to be easier to read, understand, and follow and should
be used in place of a complicated multi-nested If...ElseIf structure.
Stop
Ends execution of the program. The Stop statement can be placed anywhere in your
code.
Example
Dim x,y,z
For x = 1 to 5
For y = 1 to 5
For z = 1 to 5
Print "Looping",z,y,x
Next z
Next y
Stop
Next x
While...Wend
116
Chapter 5: CitectVBA Function Reference
Example
While <condition>
<statement/s>
Wend
With
Note: The With statement is not supported in CitectVBA.
When performing a series of commands on an object, you must explicitly refer to the
name of the object with each command.
Conversion Functions
CitectVBA conversion functions are provided to assist with data manipulation and cal-
culation in your formulas. Conversion functions can be used in CitectVBA statements,
and will (like all other functions), return a value to the caller.
Asc
Converts a text string character to its numeric ASCII code value. The Asc function
expects the argument Str to be a valid string expression. If Strcontains no characters, a
runtime error occurs. The Asc function performs the opposite of the Chr function, which
converts a number into its string character ASCII code value.
Syntax
Asc(Str)
Str:
117
Chapter 5: CitectVBA Function Reference
Return Value
Returns the numeric ASCII code value of the first character in Str provided in the argu-
ment.
Related Functions
Chr
Example
Chr
Converts a number into its string character ASCII code value.
The Chr function expects the argument Num to be a valid numeric integer (whole pos-
itive number within the range 0 to 255 inclusive). If Chrcontains no number, a runtime
error occurs.
Note: Values 8, 9, 10, and 13 convert to backspace, tab, linefeed, and carriage return
characters respectively.
The Chr function performs the opposite of the Asc function, which converts a text string
character to it's numeric ASCII code value.
Syntax
Chr(Num)
Num:
Return Value
Returns a single character string representing the ASCII character code value of the
number Num provided in the argument.
Related Functions
Asc
118
Chapter 5: CitectVBA Function Reference
Example
Date conversion
Vijeo Citect uses the following date conversion functions:
CDate
Converts any valid date expression to a Date data type.
The CDate function expects the argument Date to be a date expression (limited to
numbers or strings in any combination) that can represent a date from January 1, 100
through December 31, 9999.
Syntax
CDate(Date)
Date:
A string or expression that can represent a date value. This includes any combination of date lit-
erals, numbers that look like dates, strings that look like dates, and dates from functions.
Return Value
119
Chapter 5: CitectVBA Function Reference
Returns the value of the expression Date provided in the argument as a variant with a
vartype of 7 (date data type).
Related Functions
Example
CDbl
Converts expressions to a double data type.
Syntax
CDbl(Exp)
Exp:
Return Value
Returns the value of the expression Exp provided in the argument as a double data type.
Related Functions
Example
Dim x as integer
Dim z as double
z = CDbl(x)'Converts the integer value of x to a double value in z
CInt
Converts expressions to an integer data type.
Syntax
120
Chapter 5: CitectVBA Function Reference
CInt(Exp)
Exp:
Return Value
Returns the value of the expression Exp provided in the argument as an integer data
type.
Related Functions
Example
Dim x as integer
Dim y as long
x = CInt(y) 'Converts the long value of y to an integer value in x
CLng
Converts expressions to a long data type.
Syntax
CLng(Exp)
Exp:
Return Value
Returns the value of the expression Exp provided in the argument as a long data type.
Related Functions
Example
Dim x as integer
Dim y as long
y = CLng(x) 'Converts the integer value of x to an long value in y
CSng
Converts expressions to a single data type.
121
Chapter 5: CitectVBA Function Reference
Syntax
CSng(Exp)
Exp:
Return Value
Returns the value of the expression Exp provided in the argument as a single data type.
Related Functions
Example
Dim x as integer
Dim s as single
s = CSng(x) 'Converts the integer value of x to a single value in s
CStr
Converts expressions to a string data type.
Syntax
CStr(Exp)
Exp:
Return Value
Returns the value of the expression Exp provided in the argument as a string data type.
Related Functions
Example
Dim x as integer
Dim t as string
t = CStr(x) 'Converts the integer value of x to a string value in t
CVar
Converts expressions to a variant data type.
122
Chapter 5: CitectVBA Function Reference
Syntax
CVar(Exp)
Exp:
Return Value
Returns the value of the expression (Exp) provided in the argument as a variant data
type.
Related Functions
Example
Dim x as integer
Dim v as variant
v = CVar(x) 'Converts the integer value of x to a variant value in v
DateSerial
Constructs a date value from the given Year, Month, and Day arguments passed to the
function. The DateSerial function expects all three parameters to be valid. Date values in
CitectVBA are evaluated using the Gregorian Calendar.
Syntax
DateSerial(year,month,day)
year, month, day:
Return Value
123
Chapter 5: CitectVBA Function Reference
Returns a Variant (of date data type) containing a date value corresponding to the Year,
Month and Day values that were passed in to the function.
Related Functions
TimeSerial
Example
Dim varMyBDate
varMyBDate = DateSerial(1958, 7, 08)
' constructs and stores date value.
TimeSerial
Constructs a time value serially from the given Hrs, Mins, and Secs arguments passed
to the function. The TimeSerial Function expects all three arguments to be valid.
Syntax
TimeSerial(hours,minutes,seconds)
hours, minutes, seconds:
Return Value
Returns a Variant (of date data type) containing a time value corresponding to the Hrs,
Mins, and Secs values that were passed in to the function.
Related Functions
DateSerial
Example
Dim varMyTime
varMyTime = TimeSerial(14, 35, 17)
' stores time as 2:35:17 PM
124
Chapter 5: CitectVBA Function Reference
Format
Formats a string, number, or variant to the format expression fmt. The Format function
expects the argument Exp to be a valid expression to be formatted.
The Format function expects the argument fmt to be a string of characters that specify
how the expression is to displayed, or the name of a commonly used format that has
been predefined in CitectVBA. Do not mix different type format expressions in a single
fmt parameter.
If the fmt parameter is omitted or is zero-length and the expression parameter is a
numeric, Format[$] provides the same functionality as the Str[$] function by converting
the numeric value to the appropriate return data type. Positive numbers convert to
strings using Format[$] lack the leading space reserved for displaying the sign of the
value, whereas those converted using Str[$] retain the leading space.
To format numbers, you can use the commonly used formats that have been predefined
in CitectVBA, or you can create user-defined formats with standard characters that have
special meaning when used in a format expression.
Syntax
Format(Exp [,fmt])
Exp:
Return Value
125
Chapter 5: CitectVBA Function Reference
l Standard - Display number with thousand separator, if appropriate; display two dig-
its to the right of the decimal separator.
l Percent - Display number multiplied by 100 with a percent sign (%) appended to the
right' display two digits to the right of the decimal separator.
l Scientific - Use standard scientific notation.
l True/False - Display False if number is 0, otherwise display True.
User-defined number formats
l Null string - Display the number with no formatting.
l 0 - Digit placeholder.
Display a digit or a zero
If the number being formatted has fewer digits than there are zeros (on either side of the
decimal) in the format expression, leading or trailing zeros are displayed. If the number
has more digits to the right of the decimal separator than there are zeros to the right of
the decimal separator in the format expression, the number is rounded to as many dec-
imal places as there are zeros. If the number has more digits to left of the decimal sep-
arator than there are zeros to the left of the decimal separator in the format expression,
the extra digits are displayed without modification.
l Digit placeholder(#). Displays a digit or nothing. If there is a digit in the expression
being formatted in the position where the # appears in the format string, displays it;
otherwise, nothing is displayed.
l Decimal placeholder(.). The decimal placeholder determines how many digits are dis-
played to the left and right of the decimal separator.
l Percentage placeholder.(%) The percent character (%) is inserted in the position
where it appears in the format string. The expression is multiplied by 100.
l Thousand separator(,). The thousand separator separates thousands from hundreds
within a number that has four or more places to the left of the decimal separator. Use
of this separator as specified in the format statement contains a comma surrounded
by digit placeholders(0 or #). Two adjacent commas or a comma immediately to the
left of the decimal separator (whether or not a decimal is specified) means "scale the
number by dividing it by 1000, rounding as needed."
l Scientific format(E-E+e-e+). If the format expression contains at least one digit place-
holder (0 or #) to the right of E-,E+,e- or e+, the number is displayed in scientific for-
matted E or e inserted between the number and its exponent. The number of digit
placeholders to the right determines the number of digits in the exponent. Use E- or e-
to place a minus sign next to negative exponents. Use E+ or e+ to place a plus sign
next to positive exponents.
l Time separator(:). The actual character used as the time separator depends on the
Time Format specified in the International section of the Control Panel.
126
Chapter 5: CitectVBA Function Reference
l Date separator(/). The actual character used as the date separator in the formatted
out depends on Date Format specified in the International section of the Control
Panel.
l Display a literal character (- + $ ( )). To display a character other than one of those
listed, precede it with a backslash (\).
l Display the next character in the format string (\). The backslash itself isn't dis-
played. To display a backslash, use two backslashes (\\).
Note: Examples of characters that can't be displayed as literal characters are the
date- and time- formatting characters (a,c,d,h,m,n,p,q,s,t,w,y, and /:), the numeric for-
matting characters(#,0,%,E,e,comma, and period), and the string- formatting char-
acters (@,&,<,>, and !).
l Display the string inside the double quotation marks ("String"). To include a string in
fmt from within CitectVBA, you need to use the ANSI code for a double quotation
mark Chr(34) to enclose the text.
l Display the next character as the fill character (*). Any empty space in a field is filled
with the character following the asterisk.
Unless the fmt argument contains one of the predefined formats, a format expression for
numbers can have from one to four sections separated by semicolons.
Two The first section applies to positive values, the second to negative
sections values.
Three The first section applies to positive values, the second to negative
sections values, and the third to zeros.
Four The first section applies to positive values, the second to negative
section values, the third to zeros, and the fourth to Null values.
The following example has two sections: the first defines the format for positive values
and zeros; the second section defines the format for negative values.
"$#,##0; ($#,##0)"
If you include semicolons with nothing between them. the missing section is printed
using the format of the positive value. For example, the following format displays pos-
itive and negative values using the format in the first section and displays "Zero" if the
value is zero.
127
Chapter 5: CitectVBA Function Reference
"$#,##0;;\Z\e\r\o"
Some sample format expressions for numbers are shown below. (These examples
assume the Country is set to United States in the International section of the Control
Panel.) The first column contains the format strings. The other columns contain the out-
put the results if the formatted data has the value given in the column headings.
0 3 -3 1
#,##0 3 -3 1
$#,##0;($#,##0) $3 ($3) $1
Numbers can also be used to represent date and time information. You can format date
and time serial numbers using date and time formats or number formats because
date/time serial numbers are stored as floating-point values.
To format dates and times, you can use either the commonly used format that have been
predefined or create user-defined time formats using standard meaning of each:
General Display a date and/or time. for real numbers, display a date and time.
(e.g. 4/3/93 03:34 PM); If there is no fractional part, display only a
date (e.g. 4/3/93); if there is no integer part, display time only (e.g.
03:34 PM).
128
Chapter 5: CitectVBA Function Reference
Long Date Display a Long Date, as defined in the International section of the Con-
trol Panel.
Medium Display a date in the same form as the Short Date, as defined in the
international section of the Control Panel, except spell out the month
abbreviation.
Short Date Display a Short Date, as defined in the International section of the Con-
trol Panel.
Long Time Display a Long Time, as defined in the International section of the Con-
trol panel. Long Time includes hours, minutes, seconds.
Medium Display time in 12-hour format using hours and minuets and the Time
AM/PM designator.
Short Time Display a time using the 24-hour format (e.g. 17:45)
c Display the date as dddd and display the time as ttttt. in the order.
ddddd Display a date serial number as a complete date (including day , month,
and year).
129
Chapter 5: CitectVBA Function Reference
ttttt Display a time serial number as a complete time (including hour, min-
ute, and second) formatted using the time separator defined by the
Time Format in the International section of the Control Panel. A leading
zero is displayed if the Leading Zero option is selected and the time is
before 10:00 A.M. or P.M. The default time format is h:mm:ss.
AMPM Use the 12-hour clock and display the contents of the 11:59 string
(s1159) in the WIN.INI file with any hour before noon; display the con-
tents of the 2359 string (s2359) with any hour between noon and
11:59 PM. AMPM can be either uppercase or lowercase, but the case of
the string displayed matches the string as it exists in the WIN.INI file.
The default format is AM/PM.
m/d/yy 2/26/65
d-mmmm-yy 26-February-65
d-mmmm 26 February
130
Chapter 5: CitectVBA Function Reference
mmmm-yy February 65
h:nn:ss 18:45:15
Strings can also be formatted with Format[$]. A format expression for strings can have
one section or two sections separated by a semicolon.
Two sec- The first section applies to string data, the second to Null values and zero-
tions length strings.
The following characters can be used to create a format expression for strings:
Related Functions
Example
131
Chapter 5: CitectVBA Function Reference
' time separator (:), and AM/ PM literal, the actual formatted output
' displayed by your system depends on the locale settings on which the code
' is running. When times and dates are displayed in the development
' environment, the short time and short date formats of the code locale
' are used. When displayed by running code, the short time and short date
' formats of the system locale are used, which may differ from the code
' locale. For this example, English/United States is assumed.
' MyTime and MyDate are displayed in the development environment using
' current system short time and short date settings.
MyTime = "08:04:23 PM"
MyDate = "03/03/95"
MyDate = "January 27, 1993"
MsgBox Now
MsgBox MyTime
MsgBox Second( MyTime ) & " Seconds"
MsgBox Minute( MyTime ) & " Minutes"
MsgBox Hour( MyTime ) & " Hours"
MsgBox Day( MyDate ) & " Days"
MsgBox Month( MyDate ) & " Months"
MsgBox Year( MyDate ) & " Years"
' Returns current system time in the system-defined long time format.
MsgBox Format(Time, "Short Time")
MyStr = Format(Time, "Long Time")
' Returns current system date in the system-defined long date format.
MsgBox Format(Date, "Short Date")
MsgBox Format(Date, "Long Date")
MyStr Format(MyTime, "h:n:s") ' Returns "17:4:23".
MyStr Format(MyTime, "hh:nn:ss")' Returns "20:04:22 ".
MyStr Format(MyDate, "dddd, mmm d yyyy")' Returns "Wednesday, Jan 27 1993".
' If format is not supplied, a string is returned.
MsgBox Format(23) ' Returns "23".
' User-defined formats.
MsgBox Format(5459.4, "##,##0.00") ' Returns "5,459.40".
MsgBox Format(334.9, "###0.00") ' Returns "334.90".
MsgBox Format(5, "0.00%") ' Returns "500.00%".
MsgBox Format("HELLO", "<") ' Returns "hello".
MsgBox Format("This is it", ">") ' Returns "THIS IS IT".
Hex
Converts a numeric value to a text string representing the hexadecimal value of the
number.
The Hex function expects the argument Num to be a valid numeric value. It is rounded
to nearest whole number before evaluation.
Syntax
Hex(Num)
Num:
132
Chapter 5: CitectVBA Function Reference
Return Value
Returns a text string containing the hexadecimal value of the numeric Num value pro-
vided in the argument.
Related Functions
Example
Oct
Converts a numeric value to a text string representing the octal value of the number.
The Oct function expects the argument Num to be a valid numeric value. It is rounded to
nearest whole number before evaluation.
Syntax
Oct(Num)
Num:
Return Value
Returns a text string containing the octal value of the numeric Num value provided in
the argument.
Related Functions
Example
Str
133
Chapter 5: CitectVBA Function Reference
Converts a numeric value to a text string containing numeric characters. The Str func-
tion expects the argument Num to be a valid numeric value.
The Str function is often used to prepare a numerical value for display as a string in a
caption, label, string field, or string expression.
The Str function performs the opposite of the Val function, which converts a text string
containing numeric characters to a numeric value.
Note: Please remember the data type coercion considerations with variant data types.
See Variants.
Syntax
Str(Num)
Num:
Return Value
Returns a string containing the numeric character representation of the numeric Num
value provided in the argument.
The Str function reserves the first return string character for the sign of Num. If Num is
positive, a leading space is used and the plus sign is implied.
Related Functions
Example
Val
Converts a text string containing numeric characters to a numeric value. The Val func-
tion expects the argument Str to be a valid string expression. The Val function stops read-
ing the string when it reaches a non numeric character.
134
Chapter 5: CitectVBA Function Reference
Symbols such as dollar signs and commas are not recognised; however, radix prefixes
for octal (&0) and hexadecimal (&H) are. Blanks, tabs and linefeeds are stripped out
from the return.
The Val function performs the opposite of the Str function, which converts a numeric
value to a text string containing numeric characters.
Syntax
Val(Str)
Str:
Return Value
Returns the numeric value of a string of characters extracted from the Str provided in the
argument.
Related Functions
Example
Declarations
CitectVBA declarations allow you to manipulate and control variables and constants.
The Declaration functions and statements predefined in CitectVBA are:
135
Chapter 5: CitectVBA Function Reference
Dim statement Allocates storage for, and declares the data type of, variables and
arrays.
Option Base Declares the default lower bound for array subscripts.
statement
Option Compare Determines the default string comparison method. Forces explicit
statement declaration of all variables.
Static statement Allocates storage for, and declares the data type of, variables and
arrays.
CreateObject
Creates a new OLE Automation object and assigns a reference to the object.
Syntax
objClassName:
The object variable objVarName must be declared before it can be set to reference an OLE
Automation object.
136
Chapter 5: CitectVBA Function Reference
Related Functions
Dim | Set
Example
Const
Assigns a symbolic name to a constant value using the following syntax:
A constant must be defined before it is used. Unlike variables, constants are assigned
values when initialized and retain that same value during the life of the constant.
Constant statements can only be declared and assigned using simple expressions. Con-
stants can NOT be assigned values from variables, user-defined functions, intrinsic
CitectVBA functions (such as Chr), or from any expression that involves an operator.
Constants declared in a Sub or Function procedure are local to that procedure. A con-
stant declared outside a procedure has modular scope to all procedures within the same
CitectVBA file module. See Scope of CitectVBA.
Constants can be used anywhere in your CitectVBA code where you could use a
CitectVBA expression.
If you use Const outside a procedure its scope becomes global.
A type declaration character may also be used. However if none is used, CitectVBA will
automatically assign one of the following data types to the constant: long (if it is a long
or integer); Double (if a decimal place is present); or String (if it is a string).
Syntax
Const(VarName, Exp)
VarName:
Exp:
137
Chapter 5: CitectVBA Function Reference
Related Functions
Example
Declare
The Declare statement is used at module (file) level to declare references to external pro-
cedures in a dynamic-link library (DLL).
Syntax
LibName:
AliasName:
ArgList:
ReturnType:
Related Functions
138
Chapter 5: CitectVBA Function Reference
Dim
Example
Dim
The Dim statement allocates storage for, and declares the data type of, variables and
arrays in a module.
The To clause in the array subscript range of a Dim statement provides a more flexible
way to control the lower bound of an array. If you don't explicitly set the lower bound
with a To clause, the Option Base setting (if used) comes into affect, or defaults to zero (if
not used).
Syntax
Subscripts:
DataType:
Related Functions
Example
139
Chapter 5: CitectVBA Function Reference
Dim MyArray(1 To 10, 5 To 15, 10 To 20) ' declares the three dimensional array
MyArray and specifies the upper and lower bounds of each dimension
IsDate
Determines if an expression can be converted to a date.
The required Date argument is a Variant containing a date expression or string expres-
sion recognizable as a date or time value.
Syntax
IsDate(Date)
Date:
A string or expression that can represent a date value. This includes any combination of date lit-
erals, numbers that look like dates, strings that look like dates, and dates from functions.
Return Value
Related Functions
Example
Dim x As String
Dim MArray As Integer, MCheck
MArray = 345
x = "January 1, 1987"
MCheck = IsDate(MArray)
MChekk = IsDate(x)
MArray1 = CStr(MArray)
MCheck1 = CStr(MCheck)
Print MArray1 & " is a date " & Chr(10) & MCheck
Print x & " is a date" & Chr(10) & MChekk
IsEmpty
Determines if a variant parameter has been initialised.
140
Chapter 5: CitectVBA Function Reference
Syntax
IsEmpty(Exp)
Exp
Related Functions
Related Functions
Example
IsNull
Determines if a Variant contains Null.
IsNull returns True if expression is Null; otherwise, IsNull returns False. If Exp consists
of more than one variable, Null in any constituent variable causes True to be returned
for the entire expression.
The Null value indicates that the Variant contains no valid data. Null is not the same as
Empty, which indicates that a variable has not yet been initialised. It is also not the
same as a zero-length string (" "), which is sometimes referred to as a null string.
Note: Use the IsNull function to determine whether VarName contains a Null value.
Expressions that you might expect to evaluate to True under some circumstances,
141
Chapter 5: CitectVBA Function Reference
such as If Var = Null and If Var <> Null, are always False. This is because any
expression containing a Null is itself Null and, therefore, False.
Syntax
IsNull(Exp)
Exp
Return Value
Related Functions
Example
MyVar = ""
MyCheck = IsNull(MyVar) ' Returns False.
MyVar = Null
MyCheck = IsNull(MyVar) ' Returns True.
IsNumeric
Determines if a variant can be evaluated as a number.
The required Exp argument is a variant containing a numeric expression or string expres-
sion that can be evaluated as a number.
IsNumeric returns False if Exp is a date expression.
Syntax
IsNumeric(Exp)
Exp
Return Value
Related Functions
142
Chapter 5: CitectVBA Function Reference
Example
Nothing
Releases an OLE Automation object reference from a variable of object type. The Nothing
keyword is used in a Set statement.
In the following declaration syntax example, each placeholder shown inside arrow brack-
ets ( <placeholder> ) should be replaced in any actual code with the value of the item
that it describes. The arrow brackets and the word they contain should not be included
in the statement, and are shown here only for your information.
Syntax
SetobjVarName = Nothing
objVarName:
The nothing keyword should be used when you are finished with an object, to clear any
variables that reference the object, so the object can be released from memory.
Related Functions
Example
Option Base
Declares the default lower bound for array subscripts.
143
Chapter 5: CitectVBA Function Reference
The Option Base statement is optional. If used, it can appear only once in a CitectVBA
file, and must be used before you declare the dimensions of any arrays.
The To clause in the array subscript range of a Dim statement provides a more flexible
way to control the lower bound of an array. If you don't explicitly set the lower bound
with a To clause, the Option Base setting (if used) comes into affect, or defaults to zero (if
not used).
Syntax
Option BaseNum
Num:
An Integer or expression representing a valid numeric value. The value of the 'number' parameter
must be either 0 or 1. The default is 0.
Related Functions
Dim | ReDim
Example
The example below uses the Option Base statement to override the default base array
subscript value of 0.
Option Compare
Determines how strings are compared within a CitectVBA module. The optional Option
Compare statement if used, must be placed at the top of the CitectVBA file along with
any other Option declarations.
If an Option Compare statement is not included, the default text comparison method is
Binary.
Syntax
144
Chapter 5: CitectVBA Function Reference
Related Functions
InStr | StrComp
Example
Example
ReDim
Used to size or resize a dynamic array that has already been declared using the Dim
statement with empty parentheses.
Use the ReDim statement to change the number of elements in an array, but not to
change the number of dimensions in an array or the type of the elements in the array.
Syntax
ReDimVariableName(Subscripts)
VariableName:
Subscripts:
An Integer or expression representing a valid To numeric value range when declaring the dimen-
sions of an variable array. Up to 60 multiple dimensions may be declared.
When not explicitly stated in lower, the lower bound of an array is controlled by the
Option Base statement. The lower bound is zero if no Option Base statement is present
in the CitectVBA file.
Related Functions
145
Chapter 5: CitectVBA Function Reference
Example
Set
Assigns an OLE Automation object reference to a variable of object type.
Syntax
objClassName:
Related Functions
CreateObject | Nothing
Example
Static
146
Chapter 5: CitectVBA Function Reference
The Static statement allocates storage for-and declares the data type of-variables and
arrays that will retain their values between subsequent references. Static variables are
more commonly used within procedures (subroutines and functions), and have local
scope.
Syntax
Subscripts:
DataType:
Related Functions
Example
VarType
Determines the data type of a Variant variable.
The required VarName argument is a Variant containing any variable (except user-
defined type).
Syntax
VarType(VarName)
VarName:
147
Chapter 5: CitectVBA Function Reference
Return Value
0 Empty
1 Null
2 Integer
3 Long
4 Single
5 Double
6 Not Applicable
7 Date/Time
8 String
Related Functions
Example
148
Chapter 5: CitectVBA Function Reference
Date function Determines the current system date according to the setting of the com-
puter's system time.
Now function Determines the current date and time according to the setting of the
computer's system date and time.
Time function Determines the current time according to the setting of the computer's
system time.
149
Chapter 5: CitectVBA Function Reference
Date
Gets the current date in string format.
Time/Date functions can only be used with dates between 1980 and 2035. You should
check that the date you are using is valid with Cicode similar to the following:
Syntax
Date([Format])
Format:
If omitted, the default Format is 2. All of these formats follow the Regional Settings found in the
Windows Control Panel.
Return Value
Related Functions
Example
/* If the current system date is 3rd November 1991 and the Windows date format is
dd/mm/yy; */
str = Date();
! Sets str to "3/11/91".
str = Date(2);
! Sets str to "3/11/91".
str = Date(3);
! Sets str to "3rd November 1991".
See Also
Time/Date Functions
Date statement
150
Chapter 5: CitectVBA Function Reference
Syntax
Date = dateVariable
dateVariable:
You must enclose a Date literal within number signs (# #), for example #31/5/1993#.
Related Functions
Time (statement)
Example
Dim varCitectVBAReleaseDate
varCitectVBAReleaseDate = #01/07/2001#
Date = varCitectVBAReleaseDate
' sets system date to CitectVBA Release Date
DateSerial
Constructs a date value from the given Year, Month, and Day arguments passed to the
function. The DateSerial function expects all three parameters to be valid. Date values in
CitectVBA are evaluated using the Gregorian Calendar.
Syntax
DateSerial(year,month,day)
year, month, day:
Return Value
Returns a Variant (of date data type) containing a date value corresponding to the Year,
Month and Day values that were passed in to the function.
Related Functions
TimeSerial
Example
151
Chapter 5: CitectVBA Function Reference
Dim varMyBDate
varMyBDate = DateSerial(1958, 7, 08)
' constructs and stores date value.
DateValue
Calculates a date from the given date argument passed to the function. Date values in
CitectVBA are evaluated using the Gregorian Calendar. The DateValue function expects
the argument value (Date)to be a string or any expression that can represent a date.
Syntax
DateValue(Date)
Date:
A string or expression that can represent a date value. This includes any combination of date lit-
erals, numbers that look like dates, strings that look like dates, and dates from functions.
Return Value
Returns a variant (of date data type) corresponding to the string date expression that
was passed in.
Related Functions
TimeValue
Example
Dim varMyBDate
varMyBDate = DateValue("1958/07/08")
' stores date value.
Day
Calculates the day from the given date argument passed to the function using the Gre-
gorian Calendar.
Syntax
Day(Date)
Date:
A string or expression that can represent a date value. This includes any combination of date lit-
erals, numbers that look like dates, strings that look like dates, and dates from functions.
Return Value
152
Chapter 5: CitectVBA Function Reference
Returns a variant date corresponding to the date expression that was passed in.
Related Functions
Example
Hour
Calculates the hour value from the given time argument passed to the function.
Syntax
Hour(Time)
Time:
A string or expression that can represent a time value. This includes and combination of time lit-
erals, numbers that look like times, strings that look like times, and times from functions.
Return Value
Returns an integer between 0 and 23 that is the hour of the parameter (Time).
Related Functions
Minute | Second
Example
Minute
Calculates the minute value from the given time argument passed to the function.
Syntax
Minute(Time)
Time:
153
Chapter 5: CitectVBA Function Reference
A string or expression that can represent a time value. This includes and combination of time lit-
erals, numbers that look like times, strings that look like times, and times from functions.
Return Value
Returns an integer between 0 and 59 representing the minute of the parameter (Time).
Related Functions
Hour | Second
Example
Month
Calculates the month from the given date argument passed to the function using the Gre-
gorian Calendar.
Syntax
Month(Date)
Date:
A string or expression that can represent a date value. This includes any combination of date lit-
erals, numbers that look like dates, strings that look like dates, and dates from functions.
Return Value
Returns an integer between 1 and 12 inclusive, that represents the month of the year.
Related Functions
Example
Now
154
Chapter 5: CitectVBA Function Reference
Determines the current date and time according to the setting of the computer's system
date and time using the Gregorian Calendar. Unlike other functions, Now does not
require trailing parentheses.
Syntax
Now()
Return Value
The Now function returns a Variant data type containing a date and time value that is
stored internally as a double data type.
The number represents a date and time from January 1, 100 through December 31, 9999.
Numbers to the left of the decimal point represent the date and numbers to the right rep-
resent the time.
Related Functions
Example
Dim vntToday
vntToday = Now
' stores current system date and time.
Second
Calculates the second value from the given time argument passed to the function.
Syntax
Second(Time)
Time:
A string or expression that can represent a time value. This includes and combination of time lit-
erals, numbers that look like times, strings that look like times, and times from functions.
Return Value
Related Functions
Hour | Minute
Example
155
Chapter 5: CitectVBA Function Reference
Time
Gets the current time in string format.
Time/date functions can only be used with dates from 1980 to 2035. You should check
that the date you are using is valid with Cicode similar to the following:
Syntax
Time([Format])
Format:
Return Value
Related Functions
Date
Example
156
Chapter 5: CitectVBA Function Reference
See Also
Time/Date Functions
Time (statement)
Sets the system time.
Syntax
Time = timeVariable
timeVariable:
You must enclose a Time literal within number signs (# #), for example #12:14:00 PM#.
Related Functions
Date statement
Example
Timer
The Timer event is used to track elapsed time or can be displayed as a stopwatch in a
dialog.
Syntax
Timer()
Return Value
Related Functions
Example
Dim TS As Single
Dim TE As Single
Dim TEL As Single
157
Chapter 5: CitectVBA Function Reference
TS = Timer
MsgBox "Starting Timer"
TE = Timer
TT = TE - TS
Print TT
TimeSerial
Constructs a time value serially from the given Hrs, Mins, and Secs arguments passed
to the function. The TimeSerial Function expects all three arguments to be valid.
Syntax
TimeSerial(hours,minutes,seconds)
hours, minutes, seconds:
Return Value
Returns a Variant (of date data type) containing a time value corresponding to the Hrs,
Mins, and Secs values that were passed in to the function.
Related Functions
DateSerial
Example
Dim varMyTime
varMyTime = TimeSerial(14, 35, 17)
' stores time as 2:35:17 PM
TimeValue
Calculates a time. The TimeValue function expects the argument value (Time) to be a
string or any expression that can represent a time value.
Syntax
TimeValue(Time)
Time:
A string or expression that can represent a time value. This includes and combination of time lit-
erals, numbers that look like times, strings that look like times, and times from functions.
Return Value
158
Chapter 5: CitectVBA Function Reference
Returns a variant (of date data type) corresponding to the parameter (Time).
Related Functions
DateValue
Example
Dim varMyTime
varMyTime = TimeValue("2:35:17 PM")
' stores time as 14:35:17
WeekDay
Calculates the weekday value of the given date argument passed to the function. Date
values in CitectVBA are evaluated using the Gregorian Calendar.
Syntax
WeekDay(Date)
Date:
A string or expression that can represent a date value. This includes any combination of date lit-
erals, numbers that look like dates, strings that look like dates, and dates from functions.
Return Value
Returns an integer between the range of 1-7 inclusive representing the whole number for
the weekday:
1 Sunday
2 Monday
3 Tuesday
4 Wednesday
5 Thursday
6 Friday
7 Saturday
Related Functions
159
Chapter 5: CitectVBA Function Reference
Example
Year
Calculates the year from the given date argument passed to the function. Date values in
CitectVBA are evaluated using the Gregorian Calendar.
Syntax
Year(Date)
Date:
A string or expression that can represent a date value. This includes any combination of date lit-
erals, numbers that look like dates, strings that look like dates, and dates from functions.
Return Value
Related Functions
Example
ChDir Changes the system environment current directory on the specified drive.
160
Chapter 5: CitectVBA Function Reference
ChDrive Changes the system environment current drive to the specified drive.
Close Closes the file/s previously opened with the Open statement.
CurDir, Returns the current system environment path for the specified drive (Drv).
CurDir$
Dir Returns a file or directory name that matches the given Fileand Attrib argu-
ments.
EOF Returns a boolean True or False value during file access that indicates
whether the current position of an open file has reached the end of the file.
FreeFile Retrieves the next sequential system file number available for association
with a file.
Input Reads data from a Sequential file and assigns that data to variables. Input
function returns characters from a file opened in Input or Binary mode.
Line Reads a single line from an open sequential file and assigns it to a String var-
Input # iable.
Loc Returns a number indicating the current position within a file opened using
the Open statement.
LOF Returns a number indicating the byte length of a sequential file opened using
the Open statement.
Name Renames the disk file specified in the OldFileNameparameter, to the name
specified in the NewFileName parameter.
161
Chapter 5: CitectVBA Function Reference
Print Displays a message in the Vijeo Citect Kernel and the Cicode Editor output
(func- window.
tion)
Print # Reads data from OutputList and writes that data to a sequential file.
Seek Sets the current position within a file opened using the Open statement,
ready for the next read or write action.
Write # Writes data to a Sequential file opened in output or append mode and reads
that data from a list of variables.
ChDir
ChDir statement changes the system environment current directory on the specified
drive.
The parameter Path must be a string or expression that can represent a valid DOS file
structure path value. The parameter Dir must be a string or expression that can rep-
resent a valid DOS file structure directory name. The Path and Dir parameters together,
must be limited to less than 128 characters. The Path drive letter is optional, unless the
directory is on another drive. The required Dir parameter must be a valid directory
name.
Note: The file system keeps track of the current drive, and the current directory of
every drive. Use the CurDir statement to determine the current directory. The current
drive letter can be extracted from the Left character returned in the CurDir statement.
The ChDir statement changes the current directory but not the current drive. To change
the current drive, use the ChDrive statement.
Syntax
ChDirPath Dir
Path:
A string or expression that can represent a valid DOS file structure path value. This includes a direc-
tory name, and may include a relative or static directory or folder structure and drive letter, in the
order:
[<driveletter>:][\<rootdirectoryname>][\<subdirectory> ...
162
Chapter 5: CitectVBA Function Reference
\<subdirectory>\] directoryname
Note that the path can be relative to the current directory. A single period represents the current
directory (.), and two periods represent the parent directory of the current directory (..). For exam-
ple:
l chdir .. ' changes to the parent directory of the current directory
l chdir ..\test ' changes to the test subdirectory of the parent directory
Dir:
A string or expression that can represent a valid DOS file structure directory name. Dir is not case
sensitive. Dir is often used with the Path parameter.
Related Functions
Example
ChDrive
Changes the system environment current drive to the specified drive.
The parameter Drv must be a string or expression that can represent a valid DOS file
structure drive letter. The Drv may be local to the computer, or mapped from anywhere
on the network connected to the computer. If Drv contains more than one letter, only the
first character is used.
Note: The file system keeps track of the current drive, and the current directory of
every drive. Use the CurDir statement to determine the current directory. The current
drive letter can be extracted from the Left character returned in the CurDir statement.
The ChDrive statement changes the current drive but not the current directory on any
drive. To change the current directory, use the ChDir statement.
Syntax
ChDriveDrv
Drv:
163
Chapter 5: CitectVBA Function Reference
A string or expression that can represent a valid DOS file structure drive letter. Drv is case insen-
sitive and must end with a colon (:). The Drv may be local to the computer, or mapped from any-
where on the network connected to the computer. Drv is often included as part of the Path
parameter.
Related Functions
Example
Close
Closes the file(s) previously opened with the Open statement.
The optional FileNumList parameter can contain one or more valid file associated ref-
erence numbers using the following syntax:
Syntax
CloseFileNumList
FileNumList:
Must contain one or more valid integer or numeric expression values representing associated file
numbers using the following syntax:
[[#]filenumber] [, [#]filenumber] ... where filenumber is any valid number associated with an open
file.
Related Functions
Example
164
Chapter 5: CitectVBA Function Reference
CurDir, CurDir$
Both CurDir and CurDir$ functions return the current system environment path for the
specified drive (Drv).
The parameter Drv must be a string or expression that can represent a valid DOS file
structure drive letter. The Drv may be local to the computer, or mapped from anywhere
on the network connected to the computer. If Drv contains more than one letter, only the
first character is used.
Note: The file system keeps track of the current drive, and the current directory of
every drive. Use the CurDir statement to determine the current directory. The current
drive letter can be extracted from the Left character returned in the CurDir statement.
If no Drv is specified or if Drv is a zero-length string (" "), CurDir functions return the sys-
tem environment path for the current drive.
Syntax
CurDir(Drv)
Drv:
A string or expression that can represent a valid DOS file structure drive letter. Drv is case insen-
sitive and must end with a colon (:). The Drv may be local to the computer, or mapped from any-
where on the network connected to the computer. Drv is often included as part of the Path
parameter.
Return Value
Related Functions
Example
165
Chapter 5: CitectVBA Function Reference
Dir
Dir function returns a file or directory name that matches the given File and Attrib argu-
ments.
l The File argument is optional, and represents a string expression that specifies a
valid file name, and may include a DOS path structure including directory or folder
names, and a drive letter. You must specify File the first time you call the Dir func-
tion, or an error occurs.
l The Attrib argument is optional, and can be a constant or numeric expression whose
sum specifies file attribute values. If you specify file attributes in the function call, File
must be included. If the Volume attribute value (8) is specified, all other attribute
values are ignored.
Dir supports the use of multiple-character (*) and single-character (?) wildcards to spec-
ify multiple files.
Dir returns the first file name that matches both File and Attrib. To get any additional file
names that match, call Dir again with no arguments. When no more file names match,
Dir returns a zero-length string (" "). Once a zero-length string is returned, you must spec-
ify argument/s in the next call (to reset the function), or an error occurs.
Calling Dir with any argument will reset the function, and it will treat the call as a new
call. Previous arguments passed to the Dir function are overwritten and forgotten (reset).
You can reset the function (by supplying arguments in the function call) at any time,
even if it has not yet returned every possible argument match result.
Calling Dir with the Directory attribute (16) does not continually return Directory names.
You will need to check the attribute value of every return result to determine if the return
is a valid directory name. To do so, use the GetAttr function. Because file names are
retrieved in no particular order, you may want to store returned file names in an array
and then sort the array.
Note: The file system keeps track of the current drive, and the current directory of
every drive. Use the CurDir statement to determine the current directory. The current
drive letter can be extracted from the Left character returned in the CurDir statement.
Syntax
Dir(File, Attrib)
File:
166
Chapter 5: CitectVBA Function Reference
A string or expression that can represent a valid file name, and may include a DOS path structure
including directory or folder names, and a drive letter.
Attrib:
A number or expression that can represent a sum of the attribute values of a file . This can be a con-
stant or a numeric expression which includes any combination of attribute numeric values, whose
sum specifies all relevant attributes of a file.
where:
l 0 = Normal
l 1 = Read Only
l 2 = Hidden
l 4 = System
l 8 = Volume
l 16 = Directory or Folder
l 32 = Archive
Possible combinations of values can sum to 0, 1, 2, 3, in fact every number from 0 to 64, each rep-
resenting a unique combination of attribute values. For example, a file attribute value of 6 represents
that the file has both System (4) and Hidden (2) attributes set.
Return Value
Returns a String representing the name of a file, directory, or folder that matches a spec-
ified pattern or file attribute, or the volume label of a drive. If File is not found, a zero-
length string (" ") is returned. If Attrib is omitted, all files are returned that match File.
Related Functions
Example
167
Chapter 5: CitectVBA Function Reference
call
EndIf
Loop Until strFileName = "" ' loop again
ChDir strCurPath 'restore previous current directory
EOF
EOF function returns a Boolean True or False value during file access that indicates
whether the current position of an open file has reached the end of the file. The required
FileNum argument must contain an Integer representing any valid system file number
associated with an open file.
Note: The file system keeps track of all open files and the current position of access
within every file. Every statement or function that accesses the data within a file,
alters the current position within that file. The Loc function can be used to determine
the current position within an open file.
Use the LOF and Loc functions instead of EOF when reading binary files with the Input
function, or use Get when using the EOF function.
Note: An error occurs with files opened for Binary access, when the file is read using
the Input function until EOF returns True.
Syntax
EOF(FileNum)
FileNum:
An Integer or numeric expression representing any valid number in the range 1 to 511 inclusive,
which is referenced by the file system to be associated with an open file.
Return Value
Returns an Integer containing the Boolean value False until the end of the file has been
reached. Returns True when the end of a file opened for Random or sequential Input has
been reached.
Related Functions
Example
168
Chapter 5: CitectVBA Function Reference
FileCopy
Copies a file from Src to Dest.
The required source file (Src) and destination file (Dest) arguments must be valid string
expressions representing valid file names. Src is the file name of the file to copy from.
Dest is the file name to be copied to. Both Src and Dest arguments may contain a DOS
path structure including directory or folder names, and a drive letter.
If the Dest file does not exist, it will be created by the FileCopy statement. If the Dest file
already exists, it will be overwritten.
The FileCopy statement does not work on a currently open file. Both the Src and Dest
files must be closed before using the FileCopy statement. To close an open file, use the
Close statement.
Note: The file system keeps track of the current drive, and the current directory of
every drive. Use the CurDir statement to determine the current directory. The current
drive letter can be extracted from the Left character returned in the CurDir statement.
Syntax
FileCopySrc, Dest
Src:
A string or expression that can represent a valid DOS file structure FileName. Src is case insensitive.
This may include a relative or static Path including directory or folder structure and drive letter. To
specify multiple files, the FileName may consist of multiple-character ( * ) and single-character ( ? )
wildcards in the file name.
Dest:
A string or expression that can represent a valid DOS file structure FileName. Dest is case insen-
sitive. This may include a relative or static Path including directory or folder structure and drive
letter. To specify multiple files, the FileName may consist of multiple-character ( * ) and single-char-
acter ( ? ) wildcards in the file name.
Related Functions
Example
169
Chapter 5: CitectVBA Function Reference
FileLen
FileLen function determines the byte length of a file. The required File argument must be
valid string expression representing a valid file name. File may contain a DOS path
structure including directory or folder names, and a drive letter.
The FileLen function returns the size of a file immediately before it was most recently
opened. To obtain the length of a file that is already open, use the LOF function.
Syntax
FileLen(File)
File:
A string or expression that can represent a valid file name, and may include a DOS path structure
including directory or folder names, and a drive letter.
Return Value
Returns a Long value representing the length of the file measured in bytes.
Related Functions
Example
FreeFile
Retrieves the next sequential system file number available for association with a file. Use
the FreeFile function to retrieve an unassociated file number from the file system. This
number can be used by the Open statement to be associated with a file.
Syntax
FreeFile
Return Value
170
Chapter 5: CitectVBA Function Reference
Returns an Integer reference number ready for being associated with a file.
Related Functions
Example
Get #
Get statement reads data from a disk file into a variable.
The required FileNum argument is a system reference number associated with an open
file. The optional RecNum argument is the byte position where the read starts for files
opened in Binary mode. If you omit RecNum, the next record or byte following the last
Get or Put statement (or pointed to by the last Seek function) is read. You must include
delimiting commas.
The required VarName is the name of the variable where the file data is read (copied) to.
Random mode
For files opened in Random mode, the following rules apply:
l If the length of the data being read is less than the length specified in the Lenclause of
the Open statement, Get reads subsequent records on record-length boundaries. The
space between the end of one record and the beginning of the next record is padded
with the existing contents of the file buffer. Because the amount of padding data can't
be determined with any certainty, it is generally a good idea to have the record length
match the length of the data being read.
l If the variable being read into is a variable-length string, Get reads a 2-byte descriptor
containing the string length and then reads the data that goes into the variable. There-
fore, the record length specified by the Lenclause in the Open statement must be at
least 2 bytes greater than the actual length of the string.
l If the variable being read into is a Variant of numeric type, Get reads 2 bytes iden-
tifying the VarType of the Variant and then the data that goes into the variable. For
example, when reading a Variant of VarType 3, Get reads 6 bytes: 2 bytes identifying
the Variant as VarType 3 (Long) and 4 bytes containing the Long data. The record
length specified by the Lenclause in the Open statement must be at least 2 bytes
greater than the actual number of bytes required to store the variable.
171
Chapter 5: CitectVBA Function Reference
Note: You can use the Get statement to read a Variant array from disk, but you
can't use Get to read a scalar Variant containing an array. You also can't use Get
to read objects from disk.
l If the variable being read into is a Variant of VarType 8 (String), Get reads 2 bytes
identifying the VarType, 2 bytes indicating the length of the string, and then reads the
string data. The record length specified by the Lenclause in the Open statement must
be at least 4 bytes greater than the actual length of the string.
l If the variable being read into is a dynamic array, Get reads a descriptor whose
length equals 2 plus 8 times the number of dimensions, that is, 2 + 8 * Num-
berOfDimensions. The record length specified by the Lenclause in the Open statement
must be greater than or equal to the sum of all the bytes required to read the array
data and the array descriptor. For example, the following array declaration requires
118 bytes when the array is written to disk.
l If the variable being read into is a fixed-size array, Get reads only the data. No
descriptor is read.
l If the variable being read into is any other type of variable (not a variable-length
string or a Variant), Get reads only the variable data. The record length specified by
the Lenclause in the Open statement must be greater than or equal to the length of the
data being read.
Get reads elements of user-defined types as if each were being read individually, except
that there is no padding between elements. On disk, a dynamic array in a user-defined
type (written with Put) is prefixed by a descriptor whose length equals 2 plus 8 times the
number of dimensions, that is, 2 + 8 * NumberOfDimensions. The record length specified
by the Lenclause in the Open statement must be greater than or equal to the sum of all
the bytes required to read the individual elements, including any arrays and their
descriptors.
Binary mode
For files opened in Binary mode, all of the Random rules apply, except:
l The Lenclause in the Open statement has no effect. Get reads all variables from disk
contiguously; that is, with no padding between records.
l For any array other than an array in a user-defined type, Get reads only the data. No
descriptor is read.
Get reads variable-length strings that aren't elements of user-defined types without
expecting the 2-byte length descriptor. The number of bytes read equals the number of
characters already in the string.
Syntax
172
Chapter 5: CitectVBA Function Reference
An Integer or numeric expression representing any valid number in the range 1 to 511 inclusive,
which is referenced by the file system to be associated with an open file.
RecNum:
The byte position where the read starts for files opened in Binary mode. If you omit RecNum, the
next record or byte following the last Get or Put statement (or pointed to by the last Seek function)
is read.
VarName:
Related Functions
Example
GetAttr
GetAttr function returns an Integer representing the attribute settings of a file, directory,
or volume.
The required File argument must be valid string expression representing a valid file
name. File may contain a DOS path structure including directory or folder names, and a
drive letter.
173
Chapter 5: CitectVBA Function Reference
To determine which attributes are set, use the AND operator to perform a bitwise com-
parison of the value returned by the GetAttr function and the value of the individual file
attribute you want. If the result is not zero, that attribute is set for the named file. For
example, the return value of the following AND expression is zero if the Archive attrib-
ute is not set:
Const AttrArchive = 32
Result = GetAttr(FileName) And AttrArchive ' A nonzero value is
returned if the Archive attribute is set.
Syntax
GetAttr(File)
File:
A string or expression that can represent a valid file name, and may include a DOS path structure
including directory or folder names, and a drive letter.
Return Value
Returns an Integer number indicating the sum Attribute value of a file, directory, or
folder for the Fileargument, where:
l 0 = Normal
l 1 = Read Only
l 2 = Hidden
l 4 = System
l 8 = Volume
l 16 = Directory or Folder
l 32 = Archive
Related Functions
Example
Dim intAttrVal
' Assume file TESTFILE has hidden attribute set.
intAttrVal = GetAttr("TESTFILE.txt") ' Returns 2.
' Assume file TESTFILE has hidden and read-only attributes set.
intAttrVal = GetAttr("TESTFILE.txt") Returns 3.
' Assume MYDIR is a directory or folder.
intAttrVal = GetAttr("MYDIR") ' Returns 16.
Input
174
Chapter 5: CitectVBA Function Reference
Input # statement reads data from a Sequential file and assigns that data to variables.
Input function returns characters from a file opened in Input or Binary mode.
The Input # statement has two parameters FileNum and VarList. The required FileNum
argument is the associated file number used in the Open statement when the file was
opened. The required VarList argument is a comma delimited list of variables that are
assigned values read from the file.
The Input function has two parameters: Num and FileNum. The required Num argument
is a number or valid numeric expression specifying the number of characters (bytes) to
be read from the file. FileNum is the associated file number used in the Open statement
when the file was opened.
The file system tracks all open files and the current position of access within every file.
Every statement or function that accesses the data within a file, alters the current posi-
tion within that file. The Loc function can be used to determine the current position
within an open file.
Use the LOF and Loc functions instead of EOF when reading binary files with the Input
function, or use Get when using the EOF function.
An error occurs with files opened for Binary access, when the file is read using the Input
function until EOF returns True.
Data read with the Input # statement has usually been written to a file with the Write #
statement. Data read with the Input function has usually been written to a file with the
Print # or Put statements.
When saving data to a file for future reading with the Input # statement, use the Write #
statement instead of the Print # statement to write the data to the file. Using Write # prop-
erly delimits each separate data field, so it can be read back in using Input #. Using
Write # also formats the data in a manner that will allow correct read operations in most
locales.
Syntax
An Integer or numeric expression representing any valid number in the range 1 to 511 inclusive,
which is referenced by the file system to be associated with an open file.
VarList:
A predefined valid CitectVBA variable name or comma delimited list of valid variable names.
Return Value
175
Chapter 5: CitectVBA Function Reference
Input # statement returns data record by record from a file opened in Input or Binary
mode. Data items in a file must appear in the same order as the variables in VarList and
match variables of the same data type. If a variable is numeric and the data is not
numeric, a value of zero is assigned to the variable.
Input function returns a String containing characters from a file opened in Input or
Binary mode. The Input function returns all of the characters it reads, including com-
mas, carriage returns, linefeeds, quotation marks, and leading spaces.
Related Functions
Example
Kill
Kill statement deletes files from disk.
The required File argument must be valid string expression representing a valid file
name. Filemay contain a DOS path structure including directory or folder names, and a
drive letter.
Kill supports the use of multiple-character (*) and single-character (?) wildcards to spec-
ify multiple files. The Kill statement does not work on a currently open file. To remove a
directory use the RmDir statement.
The file system tracks the current drive and the current directory of every drive. Use the
CurDir statement to determine the current directory. The current drive letter can be
extracted from the Left character returned in the CurDir statement.
Syntax
KillFile
File:
176
Chapter 5: CitectVBA Function Reference
A string or expression that can represent a valid file name, and may include a DOS path structure
including directory or folder names, and a drive letter.
Related Functions
Example
Line Input #
Line Input # statement reads a single line from an open sequential file and assigns it to a
String variable.
The required FileNum argument is a system reference number associated with an open
file. The required VarName is the name of the variable where the file data is read (copied)
to.
The Line Input # statement reads from a file one character at a time until it encounters a
carriage return (Chr(13)) or carriage return-linefeed (Chr(13) + Chr(10)) sequence. Car-
riage return - linefeed sequences are skipped rather than appended to the character
string.
Note: The file system keeps track of all open files and the current position of access
within every file. Every statement or function that accesses the data within a file,
alters the current position within that file. The Loc function can be used to determine
the current position within an open file.
Data read with the Line Input # statement has usually been written to a file with the
Print # statement.
Syntax
An Integer or numeric expression representing any valid number in the range 1 to 511 inclusive,
which is referenced by the file system to be associated with an open file.
177
Chapter 5: CitectVBA Function Reference
VarName:
Related Functions
Example
Loc
Loc function returns a number indicating the current position within a file opened using
the Open statement.
The required FileNum argument must contain an Integer representing any valid number
associated with an open file.
Syntax
Loc(FileNum)
FileNum:
An Integer or numeric expression representing any valid number in the range 1 to 511 inclusive,
which is referenced by the file system to be associated with an open file.
Return Value
Returns a Long representing the current position within a file, the value dependant upon
which file access mode the file was opened with:
l If the file was opened in Random mode, the Loc function will return a number rep-
resenting the last record read from or written to the file.
l If the file was opened in Sequential mode, the Loc function will return a number rep-
resenting the current byte position in the file divided by 128. (However, information
returned by Loc for Sequential files is neither used nor required.)
l If the file was opened in Binary mode, the Loc function will return a number rep-
resenting the position of the last byte read from or written to the file.
Related Functions
178
Chapter 5: CitectVBA Function Reference
Example
LOF
LOF function returns a number indicating the byte length of a sequential file opened
using the Open statement.
The required FileNum argument must contain an Integer representing any valid number
associated with an open file.
Note: The file system keeps track of all open files and the current position of access
within every file. Every statement or function that accesses the data within a file,
alters the current position within that file. The Loc function can be used to determine
the current position within an open file.
The LOF function returns the size of a file that is already open.
To obtain the length of a file that is not open, use the FileLen function.
Use the LOF and Loc functions instead of EOF when reading binary files with the Input
function.
Syntax
LOF(FileNum)
FileNum:
An Integer or numeric expression representing any valid number in the range 1 to 511 inclusive,
which is referenced by the file system to be associated with an open file.
Return Value
Related Functions
179
Chapter 5: CitectVBA Function Reference
Example
MkDir
The MkDir statement creates the directory specified in the Path parameter.
The required parameter Path must be a string or expression that can represent a valid
DOS file structure path value, must contain a directory name, may contain a relative
path structure, and may contain a drive letter. The Path parameter must be limited to
less than 128 characters.
The MkDir statement is relative to the current directory. If no path structure is provided,
the directory is created in the current directory. If no drive is specified, the MkDir state-
ment creates the directory on the current drive.
Note: The file system keeps track of the current drive, and the current directory of
every drive. Use the CurDir statement to determine the current directory. The current
drive letter can be extracted from the Left character returned in the CurDir statement.
Syntax
MkDirPath
Path:
A string or expression that can represent a valid DOS file structure path value. This includes a direc-
tory name, and may include a relative or static directory or folder structure and drive letter, in the
order:
[<driveletter>:][\<rootdirectoryname>][\<subdirectory> ...
\<subdirectory>\] directoryname
The path can be relative to the current directory. A single period represents the current directory (.).
Two periods represent the parent directory of the current directory (..). For example:
Related Functions
Example
180
Chapter 5: CitectVBA Function Reference
Name
The Name statement renames the disk file specified in the OldFileName parameter, to the
name specified in the NewFileName parameter.
The required parameter OldFileName must be valid existing file name, may contain a
path structure, and may contain a drive letter.
The NewFileName parameter must be a string or expression that can represent a valid
DOS file name value, may contain a relative path structure, and may contain a drive
letter. The NewFileName parameter must be limited to less than 128 characters.
The Name statement uses the file system relative to the current directory. If no path struc-
ture is provided, the NewFileName file is expected to be in the current directory. If no
drive is specified, the Name statement expects the file to be on the current drive.
Using Name, you can move a file from one directory or folder to another. If the path in
NewFileName exists and is different from the path in OldFileName, the Name statement
moves the file to the new directory or folder and renames the file, if necessary. If New-
FileName and OldFileName have different paths and the same file name, Name moves the
file to the new location and leaves the file name unchanged.
Name does not support the use of multiple-character ( * ) and single-character (?) wild-
cards to specify multiple files.
The Name statement does not work on a currently open file. You must close an open file
before renaming it.
Note: The file system keeps track of the current drive, and the current directory of
every drive. Use the CurDir statement to determine the current directory. The current
drive letter can be extracted from the Left character returned in the CurDir statement.
Syntax
NameOldFileNameNewFileName
OldFileName:
A string or expression that can represent a valid file name, and may include a DOS path structure
including directory or folder names, and a drive letter.
181
Chapter 5: CitectVBA Function Reference
NewFileName:
A string or expression that can represent a valid file name, and may include a DOS path structure
including directory or folder names, and a drive letter.
Related Functions
Example
Open
Open statement enables input/output (I/O) to a disk file.
The required File argument must be a valid string expression representing a valid file
name. File may contain a DOS path structure including directory or folder names, and a
drive letter.
The required Mode argument must be a valid keyword specifying the file I/O mode:
Append, Binary, Input, Output, or Random. If unspecified, the file is opened for Random
access.
The optional Access argument must be a valid keyword specifying the operations per-
mitted on the open file: Read, Write, or Read Write.
The optional Lock argument must be a valid keyword specifying the operations per-
mitted on the open file by other processes: Shared, Lock Read, Lock Write, and Lock
Read Write.
The required FileNum argument must contain an Integer representing the number that
will be associated with the file. This is the file system reference number supplied by the
FreeFile statement that can be used in functions such as Get #, Input #, Line Input #,
Print #, and Write #. In Binary, Input, and Random modes, you can open a file using a
different file number without first closing the file. In Append and Output modes, you
must close a file before opening it with a different file number.
Note: The file system tracks all open files and the current position of access within
every file. Every statement or function that accesses the data within a file, alters the
182
Chapter 5: CitectVBA Function Reference
current position within that file. The Loc function can be used to determine the cur-
rent position within an open file.
The optional RecLen argument must be a number less than or equal to 32,767 (bytes). For
files opened for Random access, this value is the record length. For sequential files, this
value is the number of characters buffered. The Len clause is ignored if mode is Binary.
You must open a file before any I/O operation can be performed on it. Open allocates a
buffer for I/O to the file and determines the mode of access to use with the buffer. If the
file is already opened by another process and the specified type of access is not allowed,
the Open operation will not succeed and an error message will be generated.
If the file specified by pathname doesn't exist, it is created when a file is opened for
Append, Binary, Output, or Random modes.
Syntax
A string or expression that can represent a valid file name, and may include a DOS path structure
including directory or folder names, and a drive letter.
Mode:
A CitectVBA keyword specifying the file I/O mode: Append, Binary, Input, Output, or Random.
Lock:
A CitectVBA keyword specifying the operations permitted on the open file by other processes:
Shared, Lock Read, Lock Write, and Lock Read Write.
Access:
A CitectVBA keyword specifying the operations permitted on the open file: Read, Write, or Read
Write.
FileNum:
An Integer or numeric expression representing any valid number in the range 1 to 511 inclusive,
which is referenced by the file system to be associated with an open file.
RecLen:
An Integer or numeric expression representing the byte length of a file record as a number less than
or equal to 32,767.
Related Functions
Example
183
Chapter 5: CitectVBA Function Reference
' This example opens the file in Binary mode for writing
operations only.
Open "TESTFILE" For Binary Access Write As #1
' Close before reopening in another mode.
Close #1
' The following example opens the file in Random mode. The file
contains records of the user-defined type Record.
Type Record ' Define user-defined type.
ID As Integer
Name As String * 20
End Type
Dim recRecord As Record ' Declare variable.
Open "TESTFILE" For Random As #1
' Close before reopening in another mode.
Close #1
' This code example opens the file for sequential output; any
process can read or write to file.
Open "TESTFILE" For Output Shared As #1
' Close before reopening in another mode.
Close #1
' This code example opens the file in Binary mode for reading;
other processes can't read file.
Open "TESTFILE" For Binary Access Read Lock Read As #1
' Close before reopening in another mode.
Close #1
Print (function)
Displays a message in the runtime Citect Kernel, and the Cicode Editor output window
if you are in debug mode.
Note: Do not confuse this function with the Print # statement, which prints data to
disk.
Related Functions
Print #
Print # statement reads data from OutputList and writes that data to a sequential file.
184
Chapter 5: CitectVBA Function Reference
The Print # statement has two parameters FileNum and OutputList. The required FileNum
argument is the associated file number used in the Open statement when the file was
opened. The required OutputList argument is a delimited list of expressions whose
values are written to the file.
Note: The number sign hash character ( # ) preceding FileNumis not optional. This
character indicates disk file access with the file referenced by the system file number
that follows it. Do not confuse Print # which prints to disk, with Print which dis-
plays data on the screen.
Data written with Print # is usually read from a file with Line Input # or Input.
Note: If you want to read the data from a file using the Input # statement, use the
Write # statement instead of the Print # statement to write the data to the file. Using
Write #properly delimits each separate data field, so it can be read back in using
Input #. Using Write # also formats the data in a manner that will allow correct read
operations in most locales.
If you omit expressionlist, the Print # statement prints a blank line in the file, but you
must include the comma. Because Print # writes an image of the data to the file, you
must delimit the data so it is printed correctly. If you use commas as delimiters, Print #
also writes the blanks between print fields to the file.
The Print # statement usually writes Variant data to a file the same way it writes any
other data type. However, there are some exceptions:
If the data being written is a Variant of VarType 0 (Empty), Print # writes nothing to the
file for that data item.
If the data being written is a Variant of VarType 1 (Null), Print # writes the literal
#NULL# to the file.
If the data being written is a Variant of VarType 7 (Date), Print # writes the date to the
file using the Short Date format defined in the WIN.INI file. When either the date or the
time component is missing or zero, Print # writes only the part provided to the file.
Syntax
An Integer or numeric expression representing any valid number in the range 1 to 511 inclusive,
which is referenced by the file system to be associated with an open file.
OutputList:
185
Chapter 5: CitectVBA Function Reference
One or more formatted numeric and/or string expressions to be written to the file using the fol-
lowing syntax:
where:
l [ ] square brackets are used for illustrative purposes to indicate in the code
that the arguments they enclose are optionally used in the OutputList. Do
not use the square brackets themselves in your code.
l { } curly braces are required to encompass and delineate the arguments they
enclose, and to separate their contents from the other arguments in the Out-
putList.
l ( | ) vertical line are used for illustrative purposes to indicate in the code
that either side of the line is an alternative argument. You can use the argu-
ment provided on one of the line or the other, but not both arguments at the
same time within the same set of curly braces. Do not include the vertical
line in your code.
l {Spc(s)} argument is optionally used to insert 's' number of space characters
in the output file at the position of the argument in the OutputList. The Spc
argument must be enclosed by curly braces to delineate it from an
expression. The Spc argument can be repeated any number of times to insert
spaces in the file between expressions. The Spc argument is mutually exclu-
sive with the Tab argument when used within the same set of curly braces.
l {Tab(n)} argument is optionally used to position the insertion point to an
absolute column number in the output file at the position of the argument
in the OutputList, where 'n' is the column number. Use Tabwith no argument
to position the insertion point at the beginning of the next print zone. The
Tab argument must be enclosed by curly braces to delineate it from an expres-
sion. The Tab argument can be repeated any number of times to insert tabs
in the file between expressions. The Tab argument is mutually exclusive with
the Spc argument when used within the same set of curly braces.
l expression argument represents a valid numeric or string expression to out-
put to the file. The expression argument can be repeated any number of
times.
l charpos is the character that determines the position of the next character in
the output. A semicolon means the next character is printed immediately
after the last character; a comma means the next character is printed at the
start of the next print zone. Print zones begin every 14 columns. If neither
character is specified, the next character is printed on the next line.
Return Value
186
Chapter 5: CitectVBA Function Reference
Input # statement returns data record by record from a file opened in Input or Binary
mode. Data items in a file must appear in the same order as the variables in VarList and
match variables of the same data type. If a variable is numeric and the data is not
numeric, a value of zero is assigned to the variable.
Related Functions
Example
Put #
Put # statement writes data from a variable to a disk file.
The required FileNum argument is a system reference number associated with an open
file.
187
Chapter 5: CitectVBA Function Reference
The optional RecNum argument is the byte position where the read starts for files opened
in Binary mode. The first record or byte in a file is at position 1, the second record or
byte is at position 2, and so on. If you omit RecNum, the next record or byte following the
last Get or Put statement (or pointed to by the last Seek function) is read. You must
include delimiting commas.
Note: The file system keeps track of all open files and the current position of access
within every file. Every statement or function that accesses the data within a file,
alters the current position within that file. The Loc function can be used to determine
the current position within an open file.
The required VarName is the name of the variable where the file data is read (copied)
from.
Data written with the Put # statement is usually read from a file with the Get # state-
ment.
Random mode
For files opened in Random mode, the following rules apply:
l If the length of the data being written is less than the length specified in the Len
clause of the Open statement, Put writes subsequent records on record-length bound-
aries. The space between the end of one record and the beginning of the next record is
padded with the existing contents of the file buffer. Because the amount of padding
data can't be determined with any certainty, it is generally a good idea to have the rec-
ord length match the length of the data being written. If the length of the data being
written is greater than the length specified in the Len clause of the Open statement,
an error occurs.
l If the variable being written is a variable-length string, Put writes a 2-byte descriptor
containing the string length and then the variable. The record length specified by the
Len clause in the Open statement must be at least 2 bytes greater than the actual
length of the string.
l If the variable being written is a Variant of a numeric type, Put writes 2 bytes iden-
tifying the VarType of the Variant and then writes the variable. For example, when
writing a Variant of VarType 3, Put writes 6 bytes: 2 bytes identifying the Variant as
VarType 3 (Long) and 4 bytes containing the Long data. The record length specified
by the Len clause in the Open statement must be at least 2 bytes greater than the
actual number of bytes required to store the variable.
Note: You can use the Put statement to write a Variant array to disk, but you
can't use Put to write a scalar Variant containing an array to disk. You also can't
use Put to write objects to disk.
188
Chapter 5: CitectVBA Function Reference
l If the variable being written is a Variant of VarType 8 (String), Put writes 2 bytes iden-
tifying the VarType, 2 bytes indicating the length of the string, and then writes the
string data. The record length specified by the Len clause in the Open statement must
be at least 4 bytes greater than the actual length of the string.
l If the variable being written is a dynamic array, Put writes a descriptor whose length
equals 2 plus 8 times the number of dimensions, that is, 2 + 8 * Num-
berOfDimensions. The record length specified by the Len clause in the Open state-
ment must be greater than or equal to the sum of all the bytes required to write the
array data and the array descriptor. For example, the following array declaration
requires 118 bytes when the array is written to disk.
Dim MyArray(1 To 5,1 To 10) As Integer
The 118 bytes are distributed as follows: 18 bytes for the descriptor (2 + 8 * 2), and 100
bytes for the data (5 * 10 * 2).
l If the variable being written is a fixed-size array, Put writes only the data. No descrip-
tor is written to disk.
l If the variable being written is any other type of variable (not a variable-length string
or a Variant), Put writes only the variable data. The record length specified by the
Len clause in the Open statement must be greater than or equal to the length of the
data being written.
Put writes elements of user-defined types as if each were written individually, except
there is no padding between elements. On disk, a dynamic array in a user-defined type
written with Put is prefixed by a descriptor whose length equals 2 plus 8 times the
number of dimensions, that is, 2 + 8 * NumberOfDimensions. The record length specified
by the Len clause in the Open statement must be greater than or equal to the sum of all
the bytes required to write the individual elements, including any arrays and their
descriptors.
Binary mode
For files opened in Binary mode, all of the Random rules apply, except:
l The Len clause in the Open statement has no effect. Put writes all variables to disk
contiguously; that is, with no padding between records.
l For any array other than an array in a user-defined type, Put writes only the data. No
descriptor is written.
l Put writes variable-length strings that aren't elements of user-defined types without
the 2-byte length descriptor. The number of bytes written equals the number of char-
acters in the string. For example, the following statements write 10 bytes to file
number 1:
VarString$ = String$(10," ")
189
Chapter 5: CitectVBA Function Reference
Put writes variable-length strings that are not elements of user-defined types without the
2-byte length descriptor.
Put #1,,VarString$
Syntax
An Integer or numeric expression representing any valid number in the range 1 to 511 inclusive,
which is referenced by the file system to be associated with an open file.
RecNum:
The byte position where the read starts for files opened in Binary mode. The first record or byte in
a file is at position 1, the second record or byte is at position 2, and so on. If you omit RecNum, the
next record or byte following the last Get or Put statement (or pointed to by the last Seek function)
is read.
VarName:
Related Functions
Example
' This example uses the Put statement to write data to a file.
' Five records of the user-defined type Record are written to the file.
Type Record ' Define user-defined type.
ID As Integer
Name As String * 20
End Type
RmDir
The RmDir statement deletes the directory specified in the Path parameter.
190
Chapter 5: CitectVBA Function Reference
The required parameter Path must be a string or expression that can represent a valid
DOS file structure path value, must contain a directory name, may contain a relative
path structure, and may contain a drive letter. The Path parameter must be limited to
less than 128 characters.
The RmDir statement is relative to the current directory. If no path structure is provided,
the directory is expected to be a subdirectory of the current directory. If no drive is spec-
ified, the RmDir statement deletes the directory on the current drive.
The current directory cannot be deleted. To change the current directory to another direc-
tory, use the ChDir statement. The directory to be deleted must be empty and contain no
files or sub-directories. To delete files in a directory, use the Kill statement.
Note: The file system keeps track of the current drive, and the current directory of
every drive. Use the CurDir statement to determine the current directory. The current
drive letter can be extracted from the Left character returned in the CurDir statement.
Syntax
RmDirPath
Path:
A string or expression that can represent a valid DOS file structure path value. This includes a direc-
tory name, and may include a relative or static directory or folder structure and drive letter, in the
order:
[<driveletter>:][\<rootdirectoryname>][\<subdirectory> ...
\<subdirectory>\] directoryname
Note: The path can be relative to the current directory. A single period represents the
current directory (.). Two periods represent the parent directory of the current direc-
tory (..). For example, chdir .. changes to the parent directory of the current directory.
chdir ..\test changes to the test subdirectory of the parent directory
Related Functions
Example
191
Chapter 5: CitectVBA Function Reference
Seek
Sets the current position within a file opened using the Open statement, ready for the
next read or write action.
The required FileNum argument must contain an Integer representing any valid system
file number associated with an open file.
The required Position argument must contain an Integer or expression representing a
valid number.
Note: The file system keeps track of all open files and the current position of access
within every file. Every statement or function that accesses the data within a file,
alters the current position within that file. The Loc function can be used to determine
the current position within an open file.
Syntax
SeekFileNum, Position
FileNum:
An Integer or numeric expression representing any valid number in the range 1 to 511 inclusive,
which is referenced by the file system to be associated with an open file.
Position:
Related Functions
Example
Write #
Write # statement writes data to a Sequential file opened in output or append mode and
reads that data from a list of variables.
192
Chapter 5: CitectVBA Function Reference
The Write # statement has two parameters FileNum and VarList. The required FileNum
argument is the associated file number used in the Open statement when the file was
opened. The required VarList argument is a comma delimited list of variables that are
assigned values read from the file.
Note: The file system keeps track of all open files and the current position of access
within every file. Every statement or function that accesses the data within a file,
alters the current position within that file. The Loc function can be used to determine
the current position within an open file.
Data written to a file with the Write # statement is usually read with the Input # state-
ment.
Note: When saving data to a file for future reading with the Input # statement, use
the Write # statement instead of the Print # statement to write the data to the file.
Using Write # properly delimits each separate data field , so it can be read back in
using Input #. Using Write # also formats the data in a manner that will allow cor-
rect read operations in most locales.
Syntax
An Integer or numeric expression representing any valid number in the range 1 to 511 inclusive,
which is referenced by the file system to be associated with an open file.
VarList:
A predefined valid CitectVBA variable name or comma delimited list of valid variable names.
Related Functions
Example
193
Chapter 5: CitectVBA Function Reference
Math/Trigonometry Functions
CitectVBA math functions are provided to assist with number manipulation and cal-
culation in your formulas. Mathematical functions can be used in CitectVBA statements,
and will (like all other functions), return a value to the caller.
Numeric functions
Vijeo Citect uses the following predefined numeric functions:
Abs
Calculates the absolute (positive) value of a number. The absolute value of a number is
the number without its sign. Abs does not round the number, and ignores the fractional
value of the number.
Syntax
Abs(Num)
Num:
Return Value
Returns the absolute value of the number (Num) provided in the argument.
194
Chapter 5: CitectVBA Function Reference
The data type of the return value is the same as that of the number argument. However,
if the number argument is a Variant of VarType (String) and can be converted to a
number, the return value will be a Variant of VarType (Double). If the numeric expres-
sion results in a null, Abs returns a null.
Related Functions
Sgn
Example
Exp
Calculates the exponential of a number. The exponential is the base of the natural log-
arithm e raised to a power (e^Num). The Exp function complements the Log function and
is sometimes referred to as the antilogarithm.
Syntax
Exp(Num)
Num:
Return Value
Returns the value equivalent to the base of the natural logarithm (e) raised to the power
of the number (Num) provided in the argument.
Related Functions
Log
Example
Fix
Calculates the integer portion of a number. Fix does not round the number, and ignores
the fractional value of the number.
195
Chapter 5: CitectVBA Function Reference
Fix expects the argument (Num) to be a valid numeric value. If the argument value is
positive, rounds the Num down by dropping any fractional value. If the argument value
is negative, rounds the Num up to the next integer number greater than or equal to Num.
Do not confuse Fix with Int , which rounds a negative argument value (Num) down to
the next integer number less than or equal to Num.
Syntax
Fix(Num)
Num:
Return Value
Returns the Integer value of the number (Num) provided in the argument.
Related Functions
Example
Dim vntVar
vntVar = Fix(99.2) ' returns 99
vntVar = Fix(99.8) ' returns 99
vntVar = Fix(-99.8) ' returns -99
vntVar = Fix(-99.2) ' returns -99
Int
Calculates the integer portion of a number. Int does not round the number, and ignores
the fractional value of the number.
Int expects the argument (Num) to be a valid numeric value. If the argument value is pos-
itive, rounds the Num down by dropping any fractional value. If the argument value is
negative, rounds the Num down to the next integer number less than or equal to Num.
Do not confuse Int with Fix, which rounds a negative argument value (Num) up to the
next integer number greater than or equal to Num.
Syntax
Int(Num)
Num:
Return Value
196
Chapter 5: CitectVBA Function Reference
Returns the integer value of the number (Num) provided in the argument. If Num con-
tains a Null, Int returns a Null.
Related Functions
Example
Dim vntVar
vntVar = Int(99.2) ' returns 99
vntVar = Int(99.8) ' returns 99
vntVar = Int(-99.8) ' returns -100
vntVar = Int(-99.2) ' returns -100
Log
Calculates the natural logarithm of a number
Log expects the argument (Num) to be a valid numeric value. The argument value must
be greater than zero.
The natural logarithm is the logarithm to the base e. You can calculate the base-n log-
arithms for any number X by dividing the natural logarithm of X by the natural log-
arithm of n as follows:
Logn (X ) = Log(X ) / Log(n )
Syntax
Log(Num)
Num:
Return Value
Returns the natural log of the number (Num) provided in the argument.
Related Functions
Exp
Example
197
Chapter 5: CitectVBA Function Reference
of 2).
Rnd
Generates a decimal fraction number using the optional argument value (Num) to deter-
mine the sequence of the (random) number generation.
Rnd expects the argument (Num) if supplied, to be a valid numeric value.
If Num is less than zero, Rnd generates the same number every time, using Num as the
seed. If Num is equal than zero, Rnd repeats the most recently generated number. If Num
is greater than zero, Rnd generates the next random number in the sequence. If Num is
not supplied, Rnd generates the next random number in the sequence.
Before calling Rnd, use the Randomize statement without an argument to initialise the
random-number generator with a seed based on the system timer.
Note: The square brackets [ ]in the syntax indicate that the argument is optional.
Do NOT include the square brackets in your code.
Syntax
Rnd[(Num)]
Num:
Return Value
Returns a (random) decimal fraction number influenced by the (Num) provided in the
argument. The return value lies in the range of less than 1 but greater than or equal to 0.
Related Functions
Randomize
Example
Dim vntRndValue
Randomize ' Initialize random-number generator.
vntRndValue = Int((6 * Rnd) + 1) ' returns a value between 1 and 6
Sgn
Indicates the sign of a number. Sgn does not round the number, and ignores the frac-
tional value of the number.
198
Chapter 5: CitectVBA Function Reference
Sgn expects the argument (Num) to be a valid numeric value. If Num is greater than zero,
Sgn returns the value of 1. If Num is equal to zero, Sgn returns the value of 0. If Num is
less than zero, Sgn returns the value of -1.
Syntax
Sgn(Num)
Num:
Return Value
Returns a value indicating the Sign (+ or - ) value of the (Num) provided in the argu-
ment.
Related Functions
Example
Dim vntVal
vntVal = Sgn(99.8) ' returns 1
vntVal = Sgn(-99.8) ' returns -1
vntVal = Sgn(0) ' returns 0
Sqrt
Calculates the square root of a number. Sqrt expects the argument (Num) to be a valid
numeric value greater than or equal to 0.
Syntax
Sqrt(Num)
Num:
Return Value
Returns the square root value of the (Num) provided in the argument.
Related Functions
Example
199
Chapter 5: CitectVBA Function Reference
Variable=Sqrt(4);
! Sets Variable to 2.
Trigonometric functions
Vijeo Citect uses the following trigonometric functions:
Trigonometry uses angles and ratios, axes, degrees, Pi, radians and angular conversions.
CitectVBA supports the use of Decimal numbers by default, as well as Hexadecimal and
Octal numbers. See Numbers.
When using numbers in CitectVBA, you must consider the data type of the variables
that hold and store the numbers, as well as the behaviour of CitectVBA when dealing
with numbers. See Numeric Data Types.
Atn
Calculates the trigonometric Arctangent value of a Tangent number.
The Atn function expects the argument (Num) to be a valid tangent value between the
range of - Pi/2 to + Pi/2 (representing the ratio of the two sides of a right-angle triangle),
and calculates the corresponding angle in radians.
Atn is the inverse trigonometric function of Tan (which takes an angle as its argument,
and returns the ratio of two sides of a right-angle triangle). Do not confuse Atn with the
Cotangent, which is the inverse of a Tangent (1/tangent).
Syntax
Atn(Num)
Num:
Return Value
Returns the Arctangent value of the angle (Num) provided in the argument.
200
Chapter 5: CitectVBA Function Reference
Related Functions
Example
Cos
Calculates the trigonometric Cosine value of an angle.
The Cos function expects the argument (Rad) to be a valid angle value in radians, and
calculates the ratio of the two sides of a right-angle triangle on either side of the angle.
The ratio is the length of the side adjacent to the angle divided by the length of the
hypotenuse.
Syntax
Cos(Rad)
Rad:
Return Value
Returns the Cosine value of the angle (Rad) provided in the argument.
The result lies in the range - 1 to +1.
Cos will return a double.
Related Functions
Example
Sin
201
Chapter 5: CitectVBA Function Reference
Calculates the trigonometric Sine value of an angle. The Sin function expects the argu-
ment (Rad) to be a valid angle value in radians, and calculates the ratio of two sides of a
right-angle triangle. The ratio is the length of the side opposite to the angle divided by
the length of the hypotenuse.
To convert degrees to radians, multiply degrees by Pi/180 . To convert radians to
degrees, multiply radians by 180/Pi. For more information, see Circle Maths.
Syntax
Sin(Rad)
Rad:
Return Value
Returns the Sine value of the angle (Rad) provided in the argument. The result lies in the
range - 1 to + 1.
Related Functions
Example
Tan
Calculates the trigonometric Tangent value of an angle. The Tan function expects the
argument (Rad) to be a valid angle value in radians, and calculates the ratio of two sides
of a right-angle triangle. The ratio is the length of the side opposite to the angle divided
by the length of the side adjacent to the angle.
Syntax
Tan(Rad)
Rad:
Return Value
202
Chapter 5: CitectVBA Function Reference
Returns the Tangent value of the angle (Rad) provided in the argument. Tan will return
as a double.
Example
Miscellaneous Functions
The miscellaneous functions predefined in CitectVBA are:
SendKeys state- Sends keystrokes to the active window as if entered at the key-
ment board.
Beep
The Beep statement sounds a tone through the computer's speaker. The frequency and
duration of the beep depends on the computer's hardware.
Syntax
Beep
Related Functions
SendKeys
Example
Randomize
The Randomize statement initialises the random number generator.
203
Chapter 5: CitectVBA Function Reference
It has one optional parameter number. This parameter can be any valid number and is
used to initialise the random number generator. If you omit the parameter then the value
returned by the Timer event is used as the default parameter to seed the random number
generator.
Syntax
Randomize[number]
Related Functions
Timer
Example
Dim MValue
' Initialise random-number generator
Randomize
MValue = Int((6 * Rnd) + 1)
Print MValue
Rem
Used to include explanatory comments in a program.
Syntax
Rem Comment
Comment:
Example
SendKeys
Sends one or more keystrokes to the active window of the active application as if they
had been entered at the keyboard.
The value of the Wait argument determines when the SendKeys function completes and
returns control to CitectVBA. If omitted, Wait is treated as FALSE by default.
204
Chapter 5: CitectVBA Function Reference
designed to run in Microsoft Windows. Sendkeys also can't send the PRINT SCREEN
key {PRTSC} to any application..
Syntax
SendKeys(keys, wait)
keys:
wait:
If wait is true the keystrokes must be processed before control is returned to the calling procedure.
This argument is optional. If you omit it, it is assumed to be false.
Return Value
None
Example
Procedural Statements
CitectVBA procedural function statements are provided to assist with conditional code
execution and program flow:
Function state- Declares and defines a procedure that can receive arguments and
ment return a value of a specified data type.
205
Chapter 5: CitectVBA Function Reference
Sub statement Declares and defines a Sub procedures name, parameters and
code.
CicodeCallReturn Obtains the return value of the most recently completed Cicode
function function opened with the CitectVBA CicodeCallOpen function.
VbCallRun func- Runs the opened CitectVBA function or subroutine from Cicode.
tion
VbCallReturn func- Obtains the return value of the completed CitectVBA function pre-
tion viously opened with the Cicode VbCallOpen function.
Call
The Call Statement transfers control to a Sub procedure, Function procedure, or dynamic-
link library (DLL) procedure.
The required ProcedureName is the name of the function or subroutine to call. The
optional Parameters is the list of arguments to pass to the called function or subroutine.
You are not required to use the Call statement when calling an CitectVBA subroutine or
a DLL function. Parentheses must be used in the argument list if the Call statement is
being used.
Syntax
Call ProcedureName[Parameter(s)]
Related Functions
Example
Call Beep
206
Chapter 5: CitectVBA Function Reference
CicodeCallOpen
The CicodeCallOpen function is used to call a Cicode function from CitectVBA. It is used
to initiate and execute a call to the Cicode function and returns an integer value rep-
resenting either an error code or the success of this CitectVBA function making the call.
Note: This CitectVBA function does not return the actual return-value of the Cicode
function being called. You can obtain that return value by using the associated
CicodeCallReturn function.
Do not nest the CicodeCallOpen and CicodeCallReturn functions. Nesting these functions
can lead to unintended equipment operation when your program is run.
Failure to follow these instructions can result in death, serious injury, or equip-
ment damage.
Syntax
FunctName:
Arglist:
A variable length comma separated argument list of all the arguments to be passed to the Cicode
function being opened (dependant upon which Cicode function is being called and the arguments
that Cicode function requires). The argument list should not be enclosed within brackets, although
when using variable names as arguments, those variable arguments within the list need to be
individually enclosed within brackets to force the passing of the variable to Cicode by value.
Return Value
207
Chapter 5: CitectVBA Function Reference
Related Functions
CicodeCallReturn
Example
In the following example, a CitectVBA variable is enclosed in brackets to force the pass-
ing of the variable by value. See Passing variables Byref and Byval.
208
Chapter 5: CitectVBA Function Reference
Case Else
' assign return comment for this case
strReply = "Unknown error"
End Select
End If
' display return comment for your information
MsgBox strReply
' assign return value for this function
TestCicode = intRet
End Function
CicodeCallReturn
The CicodeCallReturn function is used to obtain the return value of the most recently
completed Cicode function opened and run with the CitectVBA CicodeCallOpen func-
tion.
No arguments are passed to the CicodeCallReturn function, as it will return the result of
the most recent return-value for the Cicode function called by the CitectVBA Cicode-
CallOpen function.
The CicodeCallReturn function should be used in its own separate line of CitectVBA
code and must not be nested with the CicodeCallOpen function. For details, see Calling
Cicode from CitectVBA.
Syntax
ReturnValue = CicodeCallReturn()
ReturnValue:
The return value of the Cicode function specified in the most recent call of the CicodeCallOpen
function. Note that the return data type of CicodeCallReturn will depend upon the return data type
of the completed Cicode function most recently called by the CicodeCallOpen function.
Return Value
Related Functions
CicodeCallOpen
Example
209
Chapter 5: CitectVBA Function Reference
End Function
End Function
210
Chapter 5: CitectVBA Function Reference
The End Function statement ends a program or a block of statements within a function.
A CitectVBA function starts with the FUNCTION statement and finishes with the END
FUNCTION statement. All other statements that lie between the FUNCTION and END
FUNCTION statements will be executed by the function when called to do so.
Syntax
Related Functions
Example
Sub TestColor2
Dim I as integer
For I = 1 to 10
Print GetColor2(I)
Next I
End Sub
End Sub
The End Sub statement ends a program or a block of statements within a subroutine. A
CitectVBA subroutine starts with the SUB statement and finishes with the END SUB
statement. All other statements that lie between the SUB and END SUB statements, will
be executed by the subroutine, when called to do so.
Syntax
End Sub
Related Functions
Example
211
Chapter 5: CitectVBA Function Reference
Sub TestColor2
Dim I as integer
For I = 1 to 10
Print GetColor2(I)
Next I
End Sub
Function
The Function statement declares and defines a function procedure, its name, parameters,
and code to be enacted upon when the subroutine is called. Functions differ from sub-
routines in that functions return a value, whereas subroutines do not.
The required FunctionName is the name of the function being declared. The optional
ArgList is the list of arguments used within the function.
A CitectVBA function starts with the FUNCTION statement and finishes with the END
FUNCTION statement. All other statements that lie between the FUNCTION and END
FUNCTION statements will be executed by the function when called to do so.
Syntax
Related Functions
Example
212
Chapter 5: CitectVBA Function Reference
If c% > 8 Then
GetColor2 = 16711680 ' 0xFF0000 - Blue
End If
End Function
Sub TestColor2
Dim I as integer
For I = 1 to 10
Print GetColor2(I)
Next I
End Sub
Sub
Declares and defines a subroutine procedure, its name, parameters, and code to be
enacted upon when the subroutine is called. Subroutines differ from functions in that
functions return a value, whereas subroutines do not.
The required SubroutineName is the name of the subroutine being declared.
The optional ArgList is the list of arguments used within the subroutine.
A CitectVBA subroutine starts with the SUB statement and finishes with the END SUB
statement. All other statements that lie between the SUB and END SUB statements, will
be executed by the subroutine, when called to do so.
Syntax
Sub
Related Functions
Example
Sub TestColor2
Dim I as integer
213
Chapter 5: CitectVBA Function Reference
For I = 1 to 10
Print GetColor2(I)
Next I
End Sub
VbCallOpen function
The VbCallOpen function is a Cicode function used to call a CitectVBA function or sub-
routine from Cicode. It is used to initiate a call to the CitectVBA function or subroutine
and returns a handle (of OBJECT data type) to that opened function call.
VbCallOpen is used in conjunction with VbCallRun and VbCallReturn functions, which
can all be nested to implement the entire function set with a single line of Cicode. For fur-
ther information, see the section "Calling CitectVBA from Cicode".
Syntax
FunctName:
ArgList:
A comma separated list of arguments to pass to the function or subroutine being called.
Return Value
VbCallOpen returns an Object data type containing a handle to the CitectVBA function
being called. If the function cannot open the CitectVBA function or subroutine the return
value is zero.
Related Functions
Example
FUNCTION
TestCitectVBA()
INT iRet;
STRING sMsg = "Hello";
INT iVal = 123;
iRet = VbCallReturn(VbCallRun(VbCallOpen("CiVBATest",
214
Chapter 5: CitectVBA Function Reference
iVal)));
Message("TestCitectVBA Function", "CiVBATest = " +
IntToStr(iRet), 0);
END
Example
VbCallReturn function
Used to obtain the return value of the completed CitectVBA function (previously opened
with the Cicode VbCallOpen function), and requires the handle returned from the VbCall-
Run function call.
VbCallReturn is used in conjunction with VbCallOpen and VbCallRun functions, which
can all be nested to implement the entire function set with a single line of Cicode. For fur-
ther information, see the section Calling CitectVBA from Cicode.
Syntax
ReturnValue = VbCallReturn(CallHandle)
ReturnValue:
The value returned by the completed CitectVBA function (which was previously opened by the
Cicode VbCallOpen function). The data type of the return value is dependent upon the data type of
the return value for the CitectVBA function opened.
CallHandle:
The handle to the previously opened CitectVBA function as returned by the Cicode VbCallRun
function
Return Value
VbCallReturn returns the completed return value for the CitectVBA function.
Related Functions
Example
FUNCTION
TestCitectVBA()
INT iRet;
215
Chapter 5: CitectVBA Function Reference
iRet = VbCallReturn(VbCallRun(VbCallOpen("CiVBATest",
iVal)));
Message("TestCitectVBA Function", "CiVBATest = " +
IntToStr(iRet), 0);
END
Example
VbCallRun function
Used to execute the CitectVBA function or subroutine (previously opened with the
Cicode VbCallOpen function), and requires the handle returned from the VbCallOpen
function call.
The VbCallRun function provides an opportunity for the opened CitectVBA function to
complete and return a value in the multi-threaded Citect/SCADA environment. It passes
its argument value (of OBJECT data type) through as its return value upon completion.
VbCallRun is used in conjunction with VbCallOpen and VbCallReturn functions, which
can all be nested to implement the entire function set with a single line of Cicode. For
details, see Calling CitectVBA from Cicode.
Syntax
ReturnValue = VbCallRun(CallHandle)
ReturnValue:
CallHandle:
The handle to the previously opened CitectVBA function as returned by the VbCallOpenfunction.
Return Value
VbCallRun (passes through and) returns a Object data type containing a handle to the
CitectVBA function being called.
Related Functions
Example
216
Chapter 5: CitectVBA Function Reference
FUNCTION
TestCitectVBA()
INT iRet;
STRING sMsg = "Hello";
INT iVal = 123;
iRet = VbCallReturn(VbCallRun(VbCallOpen("CiVBATest",
iVal)));
Message("TestCitectVBA Function", "CiVBATest = " +
IntToStr(iRet), 0);
END
Example
String Functions
CitectVBA strings functions are provided to create, edit and implement strings within
CitectVBA code. The strings functions predefined in CitectVBA are:
Asc Returns a numeric value that is the ASCII code for the first character in a
string.
InStr Returns the character position of the first occurrence of string2 within
string1.
LCase Returns a copy of string in which all characters have been converted to
lowercase.
Line Input Reads a single line from an open sequential file and assigns it to a string
# variable.
217
Chapter 5: CitectVBA Function Reference
StrComp Returns a variant that is the result of the comparison of two strings.
String Create a string that consists of one character repeated a specific number
of times.
Trim Strips any leading and trailing spaces from Str variable.
UCase Returns a copy of string in which all characters have been converted to
uppercase.
Asc
Converts a text string character to its numeric ASCII code value. The Asc function
expects the argument Str to be a valid string expression. If Strcontains no characters, a
runtime error occurs. The Asc function performs the opposite of the Chr function, which
converts a number into its string character ASCII code value.
Syntax
Asc(Str)
Str:
Return Value
Returns the numeric ASCII code value of the first character in Str provided in the argu-
ment.
Related Functions
Chr
Example
218
Chapter 5: CitectVBA Function Reference
Chr
Converts a number into its string character ASCII code value.
The Chr function expects the argument Num to be a valid numeric integer (whole pos-
itive number within the range 0 to 255 inclusive). If Chrcontains no number, a runtime
error occurs.
Note: Values 8, 9, 10, and 13 convert to backspace, tab, linefeed, and carriage return
characters respectively.
The Chr function performs the opposite of the Asc function, which converts a text string
character to it's numeric ASCII code value.
Syntax
Chr(Num)
Num:
Return Value
Returns a single character string representing the ASCII character code value of the
number Num provided in the argument.
Related Functions
Asc
Example
InStr
219
Chapter 5: CitectVBA Function Reference
Returns the character position of the first occurrence of String2 within String1.
Syntax
A numeric expression that sets the starting position for the search. If omitted, search begins at the
first character position. If Num contains Null, an error occurs. An Integer or expression rep-
resenting a valid numeric value.
StringToSearch:
The string expression being searched. A string or expression that can represent a valid text value.
StringToMatch:
The string expression being searched for. A string or expression that can represent a valid text
value.
Return Value
Returns a variant containing a Long data type indicating the result of the string search.
Returns 0 if:
l StringToSearch is of zero length.
l StringToMatch is not found.
l StartPos is longer than StringToMatch.
Returns a value representing the count position where character match was first found.
Returns Null if StringToSearch or StringToMatch contains null.
Related Functions
Example
LCase
220
Chapter 5: CitectVBA Function Reference
Converts all uppercase letters in Str to lowercase letters. All lowercase letters and non-
letter characters remain unchanged.
Syntax
LCase(Str)
Str:
Return Value
Returns a string.
Related Functions
UCase
Example
Left, Left$
Returns the left most Num characters of Str.
The required Str argument is a String expression from which the leftmost characters are
returned. If Str contains Null, Null is returned.
The required Num argument is a Variant (Long) numeric expression indicating how
many characters to return. If 0, a zero-length string (" ") is returned. If greater than or
equal to the number of characters in string, the entire string is returned.
Syntax
Left(Str, Num)
Str:
Num:
Return Value
221
Chapter 5: CitectVBA Function Reference
The Left function returns a variant containing a String data type. The Left$ function
returns a String.
Related Functions
Example
Len
The Len function determines the number of characters in the Str argument. The LenB
function determines the number of bytes in the VarName argument.
l The Str argument can be any valid string expression. If Str contains Null, Null is
returned.
l The VarName argument can be any valid variable name. If VarName contains Null,
Null is returned. If VarName is a Variant, LenB treats it the same as a String and
returns the number of characters it contains.
Syntax
Len(Str)
Str:
Return Value
Returns a Long.
Related Functions
Example
222
Chapter 5: CitectVBA Function Reference
Line Input #
Line Input # statement reads a single line from an open sequential file and assigns it to a
String variable.
The required FileNum argument is a system reference number associated with an open
file. The required VarName is the name of the variable where the file data is read (copied)
to.
The Line Input # statement reads from a file one character at a time until it encounters a
carriage return (Chr(13)) or carriage return-linefeed (Chr(13) + Chr(10)) sequence. Car-
riage return - linefeed sequences are skipped rather than appended to the character
string.
Note: The file system keeps track of all open files and the current position of access
within every file. Every statement or function that accesses the data within a file,
alters the current position within that file. The Loc function can be used to determine
the current position within an open file.
Data read with the Line Input # statement has usually been written to a file with the
Print # statement.
Syntax
An Integer or numeric expression representing any valid number in the range 1 to 511 inclusive,
which is referenced by the file system to be associated with an open file.
VarName:
Related Functions
Example
223
Chapter 5: CitectVBA Function Reference
LTrim
Strips any leading spaces from Str variable.
Syntax
LTrim(Str)
Str:
Return Value
Returns a string.
Related Functions
RTrim| Trim
Example
Mid
The Mid Function extracts a portion of a string from Str.
Note: To determine the number of characters in a string, use the Len function.
The Str argument can be any valid string expression. If Str contains Null, Null is
returned.
The required Num argument is a Long numeric expression that sets the starting position
for the extraction. If Num is greater than the number of characters in string, Mid returns
a zero-length string ("").
224
Chapter 5: CitectVBA Function Reference
The optional Len argument is a Variant containing a Long data type representing the
number of characters to return. If omitted or if there are fewer than Len characters in Str
(including the character at position Num ), all characters from the Num position to the
end of the string are returned.
Syntax
A string or expression that can represent a valid text value. If Str contains Null, Null is returned.
Num:
A Long numeric expression that sets the starting position for the extraction. If Num is greater than
the number of characters in string, Mid returns a zero-length string ("").
Len:
A Variant containing a Long data type representing the number of characters to return. If omitted or
if there are fewer than Len characters in Str (including the character at position Num ), all characters
from the Num position to the end of the string are returned.
Return Value
Related Functions
Example
225
Chapter 5: CitectVBA Function Reference
"Function"
lngPosition = lngNextPosition + 1 ' Move to next word position
lngNextPosition = Instr(lngPosition, strSource," ") ' Locate next space character
lngWordLength = lngNextPosition - lngPosition ' calculate word length
strThirdWord = Mid(strSource, lngPosition, lngWordLength) ' Returns third word
"Demo"
Option Compare
Determines how strings are compared within a CitectVBA module. The optional Option
Compare statement if used, must be placed at the top of the CitectVBA file along with
any other Option declarations.
If an Option Compare statement is not included, the default text comparison method is
Binary.
Syntax
Related Functions
InStr | StrComp
Example
Example
Option Explicit
Forces explicit declaration of all variables.
The optional Option Explicit statement if used, must be placed at the top of the
CitectVBA file. This causes a check of variable declarations at compile time. Setting this
option is a good way to catch misspelling of variables in your code.
Syntax
226
Chapter 5: CitectVBA Function Reference
Option Explicit
Related Functions
Const | Dim
Example
Option Explicit
' various statements go here
' a compile error will occur with the following line
strMyVar = "This string assignment won't work"
'because strMyVar is not explicitly declared
Right
Returns the right most Num characters of Str. The required Str argument is a String
expression from which the rightmost characters are returned. If Str contains Null, Null is
returned.
The required Num argument is a Variant (Long) numeric expression indicating how
many characters to return. If 0, a zero-length string (" ") is returned. If greater than or
equal to the number of characters in string, the entire string is returned.
Note: To determine the number of characters in a string, use the Len function.
Syntax
Right(Str, Num)
Str:
Num:
Return Value
Related Functions
Example
227
Chapter 5: CitectVBA Function Reference
RTrim
Strips any trailing spaces from Strvariable.
Syntax
RTrim(Str)
Str:
Return Value
Returns a String.
Related Functions
LTrim | Trim
Example
Space
Creates a String consisting of the specified number Num of spaces. The Space function is
useful for formatting output and clearing data in fixed-length strings.
Syntax
Space(Num)
Num:
228
Chapter 5: CitectVBA Function Reference
Return Value
Related Functions
String
Example
StrComp
Returns an integer that is the result of the comparison of two strings.
The required String1 argument is any valid string expression. The required String2 argu-
ment is any valid string expression.
The optional Compare argument is a numeric expression that specifies the type of string
comparison. It can be omitted, 0, or 1. Specify 0 (default) to perform a binary com-
parison. Specify 1 to perform a textual comparison. If compare is Null, an error occurs.
Syntax
StrComp(String1, String2)
String1:
String2:
Return Value
Returns a variant containing an integer data type indicating the result of the string com-
pare:
l Returns -1 where String1 is less than String2.
l Returns 0 where String1 is equal to String2.
l Returns 1 where String1 is greater than String2.
l Returns Null where String1 or String2s Null.
Example
229
Chapter 5: CitectVBA Function Reference
String
Creates a string that consists of one character repeated a specific number of times.
The required Num argument is Long numeric expression indicating how many char-
acters to return. If Num contains Null, Null is returned.
The required Character argument is a String expression from which the first character is
repeated and returned, or is a Variant (Long) representing a valid character code. If char-
acter contains Null, Null is returned.
Syntax
String(Num)
Num:
Related Functions
Space
Example
Trim
Strips any leading and trailing spaces from Str variable.
Syntax
230
Chapter 5: CitectVBA Function Reference
Trim(Str)
Str:
Return Value
Returns a String.
Related Functions
LTrim | RTrim
Example
UCase
Converts all lowercase letters in Str to uppercase letters. All uppercase letters and non-
letter characters remain unchanged.
Syntax
UCase(Str)
Str:
Return Value
Returns a string.
Related Functions
UCase
Example
231
Chapter 5: CitectVBA Function Reference
232
Chapter 6: ASCII/ANSI Character Code Listings
The table below shows the Latin 1 ANSI character set.
Codes 0-31 are control codes. The standard ASCII codes are from 32-127 (decimal) and
are common regardless of the ANSI set being used. The remaining codes from 160-255
(decimal) vary between languages dependent upon the ANSI set being used.
{NUL} 0 00
{SOH} 1 01
{STX} 2 02
{ETX} 3 03
{EOT} 4 04
{ENQ} 5 05
{ACK} 6 06
{BEL} 7 07
{BS} 8 08
{HT} 9 09
{LF} 10 0A
{VT} 11 0B
{FF} 12 0C
{CR} 13 0D
{SO} 14 0E
{SI} 15 0F
233
Chapter 6: ASCII/ANSI Character Code Listings
{DLE} 16 10
{DC1} 17 11
{DC2} 18 12
{DC3} 19 13
{DC4} 20 14
{NAK} 21 15
{SYN} 22 16
{ETB} 23 17
{CAN} 24 18
{EM} 25 19
{SUB} 26 1A
{ESC} 27 1B
{FS} 28 1C
{GS} 29 1D
{RS} 30 1E
{US} 31 1F
{SPC} 32 20
! 33 21
" 34 22
# 35 23
$ 36 24
234
Chapter 6: ASCII/ANSI Character Code Listings
% 37 25
& 38 26
' 39 27
( 40 28
) 41 29
* 42 2A
+ 43 2B
, 44 2C
- 45 2D
. 46 2E
/ 47 2F
0 48 30
1 49 31
2 50 32
3 51 33
4 52 34
5 53 35
6 54 36
7 55 37
8 56 38
9 57 39
235
Chapter 6: ASCII/ANSI Character Code Listings
: 58 3A
; 59 3B
< 60 3C
= 61 3D
> 62 3E
? 63 3F
@ 64 40
A 65 41
B 66 42
C 67 43
D 68 44
E 69 45
F 70 46
G 71 47
H 72 48
I 73 49
J 74 4A
K 75 4B
L 76 4C
M 77 4D
N 78 4E
236
Chapter 6: ASCII/ANSI Character Code Listings
O 79 4F
P 80 50
Q 81 51
R 82 52
S 83 53
T 84 54
U 85 55
V 86 56
W 87 57
X 88 58
Y 89 59
Z 90 5A
[ 91 5B
\ 92 5C
] 93 5D
^ 94 5E
_ 95 5F
` 96 60
a 97 61
b 98 62
c 99 63
237
Chapter 6: ASCII/ANSI Character Code Listings
d 100 64
e 101 65
f 102 66
g 103 67
h 104 68
i 105 69
j 106 6A
k 107 6B
l 108 6C
m 109 6D
n 110 6E
o 111 6F
p 112 70
q 113 71
r 114 72
s 115 73
t 116 74
u 117 75
v 118 76
w 119 77
x 120 78
238
Chapter 6: ASCII/ANSI Character Code Listings
y 121 79
z 122 7A
{ 123 7B
| 124 7C
} 125 7D
~ 126 7E
{Delete} 127 7F
128 80
129 81
‚ 130 82
ƒ 131 83
„ 132 84
... 133 85
† 134 86
‡ 135 87
ˆ 136 88
‰ 137 89
Š 138 8A
< 139 8B
Œ 140 8C
141 8D
239
Chapter 6: ASCII/ANSI Character Code Listings
142 8E
143 8F
144 90
` 145 91
' 146 92
" 147 93
" 148 94
· 149 95
- 150 96
- 151 97
˜ 152 98
™ 153 99
š 154 9A
> 155 9B
œ 156 9C
157 9D
158 9E
Ÿ 159 9F
{NBSP} 160 A0
¡ 161 A1
¢ 162 A2
240
Chapter 6: ASCII/ANSI Character Code Listings
£ 163 A3
¤ 164 A4
¥ 165 A5
¦ 166 A6
§ 167 A7
¨ 168 A8
© 169 A9
ª 170 AA
« 171 AB
¬ 172 AC
¯ 173 AD
® 174 AE
¯ 175 AF
° 176 B0
± 177 B1
² 178 B2
³ 179 B3
´ 180 B4
µ 181 B5
¶ 182 B6
· 183 B7
241
Chapter 6: ASCII/ANSI Character Code Listings
¸ 184 B8
¹ 185 B9
º 186 BA
» 187 BB
¼ 188 BC
½ 189 BD
¾ 190 BE
¿ 191 BF
À 192 C0
Á 193 C1
 194 C2
à 195 C3
Ä 196 C4
Å 197 C5
Æ 198 C6
Ç 199 C7
È 200 C8
É 201 C9
Ê 202 CA
Ë 203 CB
Ì 204 CC
242
Chapter 6: ASCII/ANSI Character Code Listings
Í 205 CD
Î 206 CE
Ï 207 CF
Ð 208 D0
Ñ 209 D1
Ò 210 D2
Ó 211 D3
Ô 212 D4
Õ 213 D5
Ö 214 D6
× 215 D7
Ø 216 D8
Ù 217 D9
Ú 218 DA
Û 219 DB
Ü 220 DC
Ý 221 DD
Þ 222 DE
ß 223 DF
à 224 E0
á 225 E1
243
Chapter 6: ASCII/ANSI Character Code Listings
â 226 E2
ã 227 E3
ä 228 E4
å 229 E5
æ 230 E6
ç 231 E7
è 232 E8
é 233 E9
ê 234 EA
ë 235 EB
ì 236 EC
í 237 ED
î 238 EE
ï 239 EF
ð 240 F0
ñ 241 F1
ò 242 F2
ó 243 F3
ô 244 F4
õ 245 F5
ö 246 F6
244
Chapter 6: ASCII/ANSI Character Code Listings
÷ 247 F7
ø 248 F8
ù 249 F9
ú 250 FA
û 251 FB
ü 252 FC
ý 253 FD
þ 254 FE
ÿ 255 FF
245
Chapter 6: ASCII/ANSI Character Code Listings
246
Index
Close statement 164
coercion and variant data types 48
A comments 30
Abs function 194 file header 30
access, file 101 comparing strings 68
Application Programming Interface (API) 84 concatenation 68
arguments 82, 87, 89 Const 137
arithmetical operators 64 Const statement 137
array subscripts 44 constant declaration 38
arrays 43 constant naming 33
declaration 43 constants 33, 37
dimensions 44 date 55
dynamic size 47 declaring 38
fixed size 45 scope 28
multi-dimensional 47 constants, intrinsic 39
subscripts 44 constraints, date and time 59
Asc function 117, 218 control structures 70
assigning references 93 DO statement 70
assignment operators 63 WHILE statement 71
Atn function 200 Cos function 201
CSng function 121
CStr function 122
B
CurDir function 165
Beep statement 203
CVar function 122
bounds 44
ByRef 87
ByVal 87 D
data types 36
arrays 43
C
coercion 48
calendars, in databases 62
default 48
Call 206
numeric 50
Call statement 206
variant as default 48
CDate function 119
databases and calendars 62
CDbl function 120
date 60
character
data type structure 60
line continuation 32
date and time data constraints 59
underscore 32
Date Cicode function 150
ChDir statement 162
date constants 55
ChDrive statement 163
date data type structure 60
Chr function 118, 219
date formatting 57
CInt function 120
date functions 148
CLng function 121
247
Index
248
Index
249
Index
250
Index
251
Index
variant variables 48
VarType function 147
W
WeekDay function 159
WHILE statement 71
WITH statement 78
Write # function 192
Y
Year function 160
252