You are on page 1of 220

Version 7.

VBA Reference Guide

September 2007

DISCLAIMER
Schneider Electric SA 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 SA reserves
the right to revise this publication at any time without incurring an obligation to notify any person of the revision.
COPYRIGHT
Copyright 2007 Schneider Electric SA. All rights reserved.
TRADEMARKS
Schneider Electric SA has made every effort to supply trademark information about company names, products and services mentioned in this manual.
Citect, CitectHMI, and CitectSCADA are registered trademarks of Citect Pty. Ltd.
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 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 NOTICE
Some product names used in this manual are used for identification purposes only and may be trademarks of their respective companies.
September 2007 edition for Vijeo Citect Version 7.0
Manual Revision Version 7.0.

For further information, contact your local Schneider Electric representative.

Contents
Chapter 1

Introducing CitectVBA

Chapter 2

Integrating CitectVBA with Vijeo Citect


Accessing Cicode Tags with CitectVBA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Using CitectVBA in Vijeo Citect Command or Expression fields . . . . . . . . . . . . . . . . 4
Accessing ActiveX Objects with CitectVBA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Multithread Considerations with CitectVBA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Calling CitectVBA from Cicode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Calling Cicode from CitectVBA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

Chapter 3

Using the CitectVBA Test Project


Creating the Test Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Opening the Test Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Setting up Test Project Communications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Setting up the Test Project Computer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Adding a Variable Tag . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Adding a Graphics Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Saving Your Graphics Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Opening the Graphics Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

Chapter 4

Understanding CitectVBA Language Basics


CitectVBA Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Cicode Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Scope of CitectVBA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Procedural (local) level scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Modular level scope. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Global level scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
CitectVBA Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Header information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Labels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
CitectVBA Line Continuation Character . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
Naming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Option Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Option Explicit statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Option Compare statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

iv

Contents
Option Base statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
CitectVBA Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Declaration of constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Intrinsic constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
Variable declaration. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
Variable initialization values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Arrays of Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Variable Array Declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Array Subscripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
Fixed Size Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
Multi-Dimensional Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
Dynamic Size Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
Variant Declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
Variant Data Types and Coercion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
Numbers in Variants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Numeric Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Exponential Notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
Floating Point Calculation Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Rounding Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Rounding down . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Rounding up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Arithmetic rounding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Banker's rounding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Random rounding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Alternate rounding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Date Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Date Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
Formatting Date Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Day . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Month. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Year . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Period/Era . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Time. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Date and Time Data Constraints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
Date Data Type Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
Date-values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
Time-values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
Dates in Databases Using Different Calendars . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
Assignment Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
Arithmetical (Math) Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51

Contents
Relational Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
Logical Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
Operator Precedence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
String Comparisons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
String Concatenation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
Control Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
GoTo statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
Do statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
While statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
For statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
If statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
Select case statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
End statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
Exit statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
OnError statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
Stop statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
With statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
Subroutines and Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
Subroutines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
DLLs and APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
Accessing Functions in DLLs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
Declare statement structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
Declare - Function Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
Declare - Lib Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
Declare - Alias Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
Passing variables Byref and Byval . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
Passing Arguments to DLL Functions from CitectVBA . . . . . . . . . . . . . . . . . . . . . . . 72
OLE Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
OLE terminology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
OLE Linking and Embedding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
OLE Automation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
OLE automation objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
Declaration of OLE automation objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
Assigning references to OLE automation objects . . . . . . . . . . . . . . . . . . . . . 75
Using OLE automation objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
Accessing the object model of OLE automation server applications. . . . . . . 77
Understanding object models in OLE automation . . . . . . . . . . . . . . . . . . . . . 78
What are objects and collections? . . . . . . . . . . . . . . . . . . . . . . . . . . 78
What is a property? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
What is a method? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
Returning an object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
Using the Microsoft Word object model. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80

vi

Contents
OLE automation example using the Microsoft Word object. . . . . . . . . . . . . .
Using the Microsoft Excel object model. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Deleting OLE automation objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
File Input/Output with CitectVBA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Chapter 5

81
81
81
82

Function and Statement Categories


Array Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
Conditional Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
Conversion Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
ASCII character code conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
Date conversion. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
Date and time formatting/conversion. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
Number and string conversion. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
Date and Time Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
File I/O Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
Math/Trigonometry Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
Numeric functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
Trigonometric functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
Miscellaneous Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
Procedural Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
String Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92

Chapter 6

CitectVBA Function Reference


Abs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
Asc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
Atn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
Beep . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
Call . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
CDate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
CDbl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
ChDir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
ChDrive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
Chr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
CicodeCallOpen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
CicodeCallReturn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
CInt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
CLng . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
Close . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
Const . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
Cos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
CreateObject . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
CSng . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109

Contents
CStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
CurDir, CurDir$ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
CVar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Date . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Date statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
DateSerial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
DateValue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Day . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Declare . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Dim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Dir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Do Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
End Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
End Sub . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
EOF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Erase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Exit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Exp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
FileCopy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
FileLen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Fix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
For . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
FreeFile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Get # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
GetAttr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Goto . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Hex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Hour . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
If . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
InStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Int . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
IsDate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
IsEmpty . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
IsNull . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
IsNumeric . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Kill . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Lbound . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
LCase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Left, Left$ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Len . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Line Input # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Loc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

110
110
111
112
112
112
113
113
114
115
115
118
118
119
120
120
121
121
122
123
123
124
124
131
131
132
134
135
136
137
137
139
141
142
142
143
144
144
145
146
146
147
148
148
149

vii

viii

Contents
LOF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Log . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
LTrim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Mid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Minute . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
MkDir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Month . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Nothing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Now . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Oct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
OnError . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Open . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Option Base . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Option Compare . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Option Explicit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Print (function) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Print # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Put # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Randomize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ReDim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Rem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Right . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
RmDir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Rnd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
RTrim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Second . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Seek . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Select . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
SendKeys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Sgn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Sin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Space . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Sqrt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Static . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Stop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Str . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
StrComp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Sub . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Tan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Time (statement) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Timer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

150
151
151
152
153
154
155
155
156
157
158
158
159
161
162
162
163
163
166
169
169
170
170
171
172
173
173
174
174
176
177
178
178
179
179
180
181
181
182
183
183
184
185
185
185

Contents
TimeSerial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
TimeValue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Trim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Ubound . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
UCase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Val . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
VarType . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
VbCallOpen function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
VbCallRun function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
VbCallReturn function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
WeekDay . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
WhileWend . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
With . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Write # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Year . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Appendix A
Index

ASCII/ANSI Character Code Listings

186
186
187
187
188
188
189
190
191
192
193
194
194
194
195

197
205

ix

Contents

Chapter 1: Introducing CitectVBA


CitectVBAisaVisualBasicforApplications(VBA)andVBScriptcompatible
Basicscriptinglanguage.VijeoCitecthasembeddedsupportforCitectVBA.
CitectVBAhasthefollowingfeatures:

CitectVBAcodeismultithreadedandfullyscheduledwithintheVijeoCitect
Kernel.

CitectVBAusesthesamewellprovenenginethatCicodeusesandcanbe
usedwhereverCicodeisused.

CitectVBAhasasmallfootprintofunder400K.

CitectVBAcodeisdirectlycallablefromVijeoCitectCommandand
Expressionfields.

CitectVBAcodeiscallablefromCicodeandvisaversa.

CitectVBAcodeprovidesnativesupportforActiveXobjects,VijeoCitect
VariableTagsandAlarmTags.

CitectVBAmakesActiveXobjectmanipulatingeasier.Itallowsdirect
interactionwiththeobjectmodelsfrom3rdpartyapplicationssuchasWord,
Excel,etc.
Note:YoumaynoticeslightdifferencesbetweenCitectVBAandVBAin
otherapplications;thisisnormalaseachapplicationhasadifferentobject
model.

TheCicodeEditorhasbeenupgradedtofullysupportCitectVBA.Newfeatures
oftheeditorinclude:

See Also

IntegratedCicodeandCitectVBAcompiler

IntegratedCicodeandCitectVBAsourcecodeeditor

IntegratedCicodeandCitectVBAdebugger

IntegratingCitectVBAwithVijeoCitect

Chapter 2: Integrating CitectVBA with Vijeo


Citect
YoucanintegrateCitectVBAintoyourVijeoCitectprojectintwoways:

UseCitectVBAcodescriptdirectlyinyourCommandorExpressionfields
withinVijeoCitect.

StoreuserdefinedCitectVBAscriptinaseparateCitectVBAfile.

Ineithercase,allprocedureswithinaCitectVBAscriptcanaccess(readand
write)anyVijeoCitectvariabletaginthesamewayasCicodecanaccessVijeo
Citecttags.
See Also

AccessingCicodeTagswithCitectVBA

Accessing Cicode Tags with CitectVBA


CitectVBAcanuseyourVijeoCitectprojectvariabletagandalarmtagvariables
inthesamewayascouldCicode(exceptforsyntaxdifferences).Both
programminglanguagesrefertoaprojectsvariabletagsbyusingthenameof
thetagsasdefinedintheproject.
Note:Projectvariabletagsaredefined(inVijeoCitect)byusingtheVariable
TagsformintheCitectProjectEditor.Fordetails,seeAddingaVariableTag.
Forinstance,inthefollowingexample,twovariabletagsinyourVijeoCitect
projectmaybenamedB1_PUMP_101_SPandB1_PUMP_101_PVrespectively,
representingtheSetPointandProcessVariablevaluesofPump101.These
variabletagnamescanbeusedwithinaCitectVBAstatement(justasyouwould
useanyothervariableinCitectVBA).Bothvaluescanbereadfromandwritten
todirectlyusingCitectVBA:
' set pump speed to 500rpm
B1_PUMP_101_SP = 500
' calculate pump speed error
Dim varPumpSpeedError
varPumpSpeedError = B1_PUMP_101_PV - B1_PUMP_101_SP

YoushouldnotethatCitectVBAdoesnotrecognizeVijeoCitectvariabletags
thatarenamedwithaninitialdigit(09).
ToaccesssuchtagsusingCitectVBA,youmustprecedethetagnamewitha
caseinsensitivestringcontainingthelettersV,B,andtheunderscorecharacter
(VB_)asinthefollowingexample:

4
Vijeo Citect Tag Name:"123Pump"
CitectVBA reference "VB_123Pump"

totheVijeoCitecttag.
FordetailsaboutaccessingActiveXobjectsusingCitectVBA,seeAccessing
ActiveXObjectswithCitectVBA.Fordetailsofusingtagsthathaveanumber
astheirfirstdigitinyourVijeoCitectproject,considerusingthe
[General]TagStartDigit Citect.INIparameter.
See Also

UsingCitectVBAinVijeoCitectCommandorExpressionfields
CallingCitectVBAfromCicode
CallingCitectVBAfromCicode

Using CitectVBA in Vijeo Citect Command or Expression fields


VijeoCitectexpectsthatallcodecontainedwithinaVijeoCitectCommandor
ExpressionfieldtobeCicodebydefault.WhenusingCitectVBAcodescript
directlyinaVijeoCitectCommandorExpressionfieldwithinVijeoCitect,you
mustprecedetheCitectVBAscriptwiththekeywordCiVBA,asshownhere:
CiVBA
TestTag_1 = TestTag_1 + 1

Thisisknownasthelanguageoverridecommand.WhentheVijeoCitect
compilerreadsthekeywordCiVBA,itknowstohandlethatcode(withinthe
sameVijeoCitectCommandorExpressionfield)asCitectVBAscript,and
compilesitassuch.NosuchoverridecommandisrequiredtouseCicode.
TheCiVBAlanguageoverridestatementmustbeplacedfirstintheVijeoCitect
CommandorExpressionfieldifyouwanttouseCitectVBAscriptcodeinstead
ofCicodeinthatVijeoCitectCommandorExpressionfield.
Note:YoumustuseeitherCicodeorCitectVBAinaVijeoCitectCommandor
Expressionfield.Youcannotchangeorswapbetweenthetwoprogramming
languages(withinthesameVijeoCitectCommandorExpressionfield)once
youvestartedusingoneortheother.
Youcan,however,callasingleCicodefunctionfromwithinCitectVBAscriptif
youwraptheCicodecallwithinspecialCitectVBAfunctionsCicodeCallOpen()
andCicodeCallReturn().Fordetails,seeCallingCicodefromCitectVBA.
Alternatively,tocallasingleCitectVBAfunction(fromwithintheVijeoCitect
CommandorExpressionfield)afteryouhavealreadyusedCicodeinthatfield,
youcanwraptheCitectVBAwithinthreenestedspecialCicodefunctions:
VbCallOpen(),VbCallRun()andVbCallReturn().SeeCallingCicodefrom
CitectVBA.
See Also

AccessingCicodeTagswithCitectVBA
AccessingActiveXObjectswithCitectVBA
MultithreadConsiderationswithCitectVBA

5
CallingCitectVBAfromCicode
CallingCicodefromCitectVBA

Accessing ActiveX Objects with CitectVBA


ActiveXobjectswhichhavebeenaddedtoagraphicspageinyourVijeoCitect
projectcanbereferredtoinCitectVBAbyconstructingauniquereferencename
usingthepagename,theunderscorecharacter,thelettersAN,andthe
animationnumberoftheobject.
ThisreferencenameiscalledtheEventClassnameinVijeoCitect.Toviewthe
referencename,doubleclicktheActiveXobject,selecttheAccesstab,thenclick
theIdentificationtab.

Inthisexample,thereferencenamefortheTemperaturemeterobjectwouldbe
referredtoinCitectVBAasActiveX_AN125.
AllobjectpropertiescanbeaccessedandmanipulatedusingCitectVBAinthe
samewaythatobjectpropertiescanbemanipulatedusingCicode.
See Also

AccessingCicodeTagswithCitectVBA
UsingCitectVBAinVijeoCitectCommandorExpressionfields

Multithread Considerations with CitectVBA


Cicodeispreemptedandexecutedonaninstructionbyinstructionbasis.This
meansthatexecutionofasimpleunnestedCicodethreadcanonlyswitchto
anotherthreadafterthecurrentCicodeinstructionhascompletedexecution.
CitectVBAcodeispreemptedandexecutedonalinebylinebasis(asopposed
toaninstructionbyinstructionbasis),andpreemptingcanonlyoccurafterthe
currentlinehascompletedexecution.
EachlineofCitectVBAscriptishandledasaseparatethreadinVijeoCitect.
Thereforemultipleproceduresplacedononelinemaynotcompletebefore
anothersubsequentthreadisprocessedinamultithreadingenvironment.This

6
couldcauseunpredictableresultsandconsequences,includingdatainvalidation
andcorruption.
If,forexample,youwerereadingorsettingsomevariableorpointinamulti
statementthread,andfurtherprocessingthatdatainalaterthread,thevalidity
ofthedatacouldnotbeguaranteed.Forthisreason,youshouldseparateevery
statementontoseparatelinesinCitectVBA.
Forexample,itisbettertowrite:
A = Motor1.speed() + Motor4.speed() + Motor5.speed()

as
A = Motor1.speed()
A = A + Motor4.speed()
A = A + Motor5.speed()

insituationswherethemethodspeed()maytakealongtimetoexecute.
Inthefirstexampleabove,theCitectVBAthreadexecutesforthreetimeslonger
beforeitcanbepreemptedthaninthelatterexample.
Note:ThisisnotanissuewithCicodebecausetheCicodeenginecanpreempt
aggregatedcode.
ForinformationonmultithreadinginVijeoCitect,seeMultitasking.
See Also

AccessingCicodeTagswithCitectVBA
UsingCitectVBAinVijeoCitectCommandorExpressionfields
CallingCitectVBAfromCicode
CallingCicodefromCitectVBA

Calling CitectVBA from Cicode


ThreenewCicodefunctionsallowCitectVBAcodetobecalledfromwithin
Cicodescript,andbepreemptivelymultitaskedbyVijeoCitect.Thesecalls
VbCallOpen(),VbCallRun(),andVbCallReturn()canbenestedtoimplement
theentirefunctionsetwithasinglelineofCicode.
Note:WhenusingtheCiVBAlanguageoverrideinaCommandfield,the
compilerconstructsthenestedcallforyou.Thesamemechanismisusedeven
thoughitisnotselfevident.Fordetails,seeUsingCitectVBAinVijeoCitect
CommandorExpressionfields.
ForinformationonmultithreadinginCitectVBA,seeMultithread
ConsiderationswithCitectVBA.
TocallagivenCitectVBAfunctionorsubroutinefromCicode,usethe
VbCallOpenfunction.Thisreturnsahandlewhichcanthenbeusedtoexecute
thecallbypassingittotheVbCallRunfunction.UponreturnfromVbCallRun,

7
youcancalltheVbCallReturnfunctiontogetthereturnvalueoftheCitectVBA
functioncalled.
TheCicodeVbCallOpen()functionisusedtoinitiateacalltotheCitectVBA
functionorsubroutine,andreturnsahandletotheopenfunction.
<ReturnValue> = VbCallOpen(<FunctName>, <ArgList>)

where

<ReturnValue>representsthehandletotheopenedfunction.

<FunctName>representsthenameoftheCitectVBAfunctionorsubroutine

beingcalled.

<ArgList>representsacommaseparatedlistofargumentstopasstothe
openedCitectVBAfunctionorsubroutinenamedin<FunctName>.

TheCicodeVbCallRun()functionisusedtoexecutetheCitectVBAfunctionor
subroutine(previouslyopenedwiththeCicodeVbCallOpenfunction),and
requiresthehandlereturnedfromtheVbCallOpenfunctioncall.TheVbCallRun
functionprovidesanopportunityfortheopenedCitectVBAfunctionto
completeandreturnavalueinthemultithreadedVijeoCitectenvironment.It
passesitsargumentvalue(ofOBJECTdatatype)throughasitsreturnvalue
uponcompletion.
<ReturnValue> = VbCallRun(<CallHandle>)

where:

<ReturnValue>representsthehandletotheopenedCitectVBAfunction
passedthroughforthe<CallHandle>argument.

<CallHandle>representsthehandletothepreviouslyopenedCitectVBA
functionasreturnedbytheCicodeVbCallOpenfunction.

TheCicodeVbCallReturn()functionisusedtoobtainthereturnvalueofthe
completedCitectVBAfunction(previouslyopenedwiththeCicodeVbCallOpen
function),andrequiresthehandlereturnedfromtheVbCallRunfunctioncall.
<ReturnValue> = VbCallReturn(<CallHandle>)

where:

<ReturnValue>representsthevaluereturnedbythecompletedCitectVBA
function(whichwaspreviouslyopenedbytheCicodeVbCallOpen

function).Thedatatypeofthereturnvalueisdependentuponthedatatype
ofthereturnvaluefortheCitectVBAfunctionopened.

<CallHandle>representsthehandletothepreviouslyopenedCitectVBA
functionasreturnedbytheCicodeVbCallRunfunction.

8
Example

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

Function CiVBATest(Value As Integer) As Integer


CiVBATest = Value * 2
End Function

See Also

CallingCicodefromCitectVBA

Calling Cicode from CitectVBA


CallingaCicodefunctionfromCitectVBAisaccomplishedbytwoCitectVBA
functions:CicodeCallOpen()andCicodeCallReturn().
TocallagivenCicodefunction,usetheCicodeCallOpenfunctionwhichwill
createandexecuteaCicodethreadthatrunsthefunction.Formultitasking
purposes,aseparatefunctionCicodeCallReturnisusedtoobtainthereturn
valueofthecompletedCicodefunctionmostrecentlycalledbythe
CicodeCallOpenfunction.
CallstoCicodeCallOpenandCicodeCallReturnmustnotbenested.The
returnvalueisinitializedwhencontrolisreturnedtotheVijeoCitectkernel.
ThisoccursonlyaftercompletionofthelineofCitectVBAcodecontaining
CicodeCallOpen.FordetailsonmultithreadinginCitectVBA,seeMultithread
ConsiderationswithCitectVBA.
TocallagivenCicodefunctionorsubroutinefromCitectVBA,usethe
CicodeCallOpenfunction.UponreturnfromCicodeCallOpen,youcancallthe
CicodeCallReturnfunctiontoobtainthereturnvalueoftheCicodefunction

called.
TheCicodeCallOpenfunctionisaCitectVBAfunctionusedtocallaCicode
functionfromCitectVBA.ItisusedtoinitiateandexecuteacalltotheCicode
functionandreturnsanintegervaluerepresentingthesuccessorfailureofthis
CitectVBAfunctionmakingthecall.
<ReturnValue> = CicodeCallOpen(<FunctName>, <ArgList>)

where:

<ReturnValue>representsthereturnvalueof:

0ifCicodeCallOpenfunctionwassuccessful

1forCicodeCallOpenfunctionfailure

2forspecifiedCicodefunctionnotfound

3forincorrectnumberofargumentsforspecifiedCicodefunction
passedin<ArgList>.

<FunctName>isastringrepresentingthenameoftheCicodefunctionbeing

called.Thefunctionnameshouldbeenclosedindoublequotes.

<ArgList>representsavariablelengthcommaseparatedargumentlistof
alltheargumentstobepassedtotheCicodefunctionbeingopened
(dependantuponwhichCicodefunctionisbeingcalledandthearguments
thatCicodefunctionrequires).Theargumentlistshouldnotbeenclosed
withinbrackets,althoughwhenusingvariablenamesasarguments,those
variableargumentswithinthelistmustbeindividuallyenclosedwithin
bracketstoforcethepassingofthevariabletoCicodebyvalue.

TheCicodeCallReturnfunctionisaCitectVBAfunctionusedtoobtainthe
returnvalueofthemostrecentlycompletedCicodefunctionopenedwiththe
CitectVBACicodeCallOpenfunction.
<ReturnValue> = CicodeCallReturn()

where:

<ReturnValue>representsthereturnvalueoftheCicodefunctionspecified
inthemostrecentcalloftheCicodeCallOpenfunction.Notethatthereturn
datatypeofCicodeCallReturnwilldependuponthereturndatatypeof
theCicodefunctioncalledinthemostrecentcalloftheCicodeCallOpen

function.
NoargumentsarepassedtotheCicodeCallReturnfunction,asitwillalways
returntheresultofthemostrecentreturnvaluefortheCicodefunctioncalled
bytheCitectVBACicodeCallOpenfunction.
Note:Inthefollowingexample,aCitectVBAvariableisenclosedinbracketsto
forcethepassingofthevariablebyvalue.SeePassingvariablesByrefand
Byval.
CitectVBA
' declare modular variant variable to store function results
Dim vntRet as Variant
Function TestCicode() As Integer
' declare local variables
Dim intRet As Integer
Dim strReply as String
Dim intMaxScale as Integer
' copy current tag value to variable
' uses the project variable tag named MAX_SCALE
intMaxScale = MAX_SCALE
' call Cicode function

10
' for example: TrnSetScale( AN, Pen, Percent, Scale)
intRet = CicodeCallOpen( "TrnSetScale", 53, -1, 100, (IntMaxScale) )
' Note the syntax used:
'- brackets around the CitectVBA function argument list
'(Only necessary when the CitectVBA function is preceded by an equals (=) sign .)
' - double quotes around the Cicode function name
'- no brackets around the Cicode function argument list
'- brackets around individual variable arguments
' test results
If intRet = 0 Then
'
' insert code for successful completion here
'
vntRet = CicodeCallReturn()
strReply = "CicodeCallOpen Function successfully called"
Else
'
' insert code for unsuccessful completion here
'
Select Case intRet
Case = 1
' assign return comment for this case
strReply = "CicodeCallOpen Function call failed"
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

CallingCitectVBAfromCicode

11

Chapter 3: Using the CitectVBA Test Project


YoucanusetheCitectVBAtestprojecttohelpyoulearnthebasicsprogramming
withCitectVBA.Beforeyoucanusetheproject,youmust:

Createthetestproject

Openthetestproject

Setuptestprojectcommunications

Setupthetestprojectcomputer

Addavariabletagtotheproject

Setupagraphicspagetotheproject

Creating the Test Project


Creatingtheprojectrequiresyoutospecifythedestinationfolderforthetest
projectsothatVijeoCitectcanfindit.
TocreatetheCitectVBAtestproject
1

StartVijeoCitect(ifnotalreadystarted).

ClicktheCitectExplorerbutton.

ChooseNewProjectfromtheFilemenu,orclicktheNewProjectbutton.

IntheNamefield,typeCitectVBATest.

IntheLocationfield,checkthatthepathisdisplayingtheprojectnameasa
subfoldernamebeneaththeUserfolder.TheUserfolderistheparentfolder
whereVijeoCitectexpectsallprojectstobestoredinseparatesubfolders.
Note:Thenameoftheprojectshouldbeappendedasasubfoldernameto
theUserfolder.
Yourpathmaydifferfromthatshownhere(C:\Citect\)dependinguponthe
actualpathofyourVijeoCitectinstallation.

14

6
See Also

ClickOK.Thetestprojecthasbeencreated.

OpeningtheTestProject

Opening the Test Project


YouopenthetestprojectfromCitectExplorer.
ToopentheCitectVBAtestproject
1

StartVijeoCitect(ifnotalreadystarted).

ClicktheCitectExplorerbutton.

FromtheProjectList,clickonthefoldernamedCitectVBATest.
Note:VijeoCitectstoresthemostrecentlyopenedprojectnameinthe
Citect.inifile,sothatthenexttimeVijeoCitectisstarted,thatprojectopens
automaticallyreadyforfurtherediting.

See Also

SettingupTestProjectCommunications

15

Setting up Test Project Communications


Youonlyneedtoperformthisprocedureonceforthetestproject.
Tosetuptestprojectcommunications
1

Openthetestproject.

ClicktheCitectExplorerbutton.

DoubleclicktheCommunicationsfolder.

DoubleclicktheExpressI/ODeviceSetupbutton.

SelectNextandclicktheCreateaNewI/OServercheckbox.

IntheNamefield,replacethedefaultnameIOServer_1with
CiVBAIOServer.
Note:VijeoCitectstoresthecommunicationdetailsasrecordsinadatabase.
Eachrecordnameislimitedtoamaximumof16characters.Theserecords
areaccessiblewiththeCitectProjectEditor.

SelectNextandclicktheCreateaNewI/ODevicecheckbox.

IntheNamefield,replacethedefaultnameIODevwithCiVBAIODevice.

ClickNextandclicktheDiskI/ODevicecheckbox.

10 ClickNexttoacceptthedefaultVijeoCitectGenericProtocol.
11 ClickNexttoacceptthedefaultremainingunlinkedtoanyexternaltag
database.
12 SelectNextandFinishtocreatetheCitectVBAProjectcommunications.
See Also

SettinguptheTestProjectComputer

Setting up the Test Project Computer


Youneedtosetupthetestprojectcomputeronlyoncefortheproject.
TosetuptheCitectVBAtestprojectcomputer
1

OpentheCitectVBATestProject.

ClicktheCitectExplorerbutton.

Intheprojectlistcolumn,clicktherootcomputericonnamedMyProjects.

DoubleclicktheComputerSetupWizardbutton.(Youcanalsoclickthe
ComputerSetupbutton,orchooseComputerSetupfromtheToolsmenu.).

SelectNextacceptingtheExpressSetupdefault.

SelectNextacceptingtheStandaloneComputerServerandDisplay
Clientdefault.

16

See Also

FromtheProjectNamelist,selectCitectVBATestandclickNext.

ClickNextandthenFinishtocompletetheCitectVBAproject
communicationssetup.

AddingaVariableTag

Adding a Variable Tag


Youneedtoaddavariabletagonlyoncefortheproject.
ToaddavariabletagtotheCitectVBAtestproject
1

OpentheCitectVBAtestproject.

ClicktheProjectEditorbutton.

ClicktheVariableTagsbutton.

IntheVariableTagNamefield,replacethedefaultnameTag_1with
TestTag_1.
Note:VijeoCitectstoresthecommunicationdetailsasrecordsinadatabase.
Eachrecordnameislimitedtoamaximumof16characters.

See Also

IntheI/ODeviceNamefield,checkthatthedevicenameselectedis
CiVBAIODevice.(IfotherI/ODeviceshavebeencreatedforthisproject,
theywilldisplayinthismenu.)

IntheDataTypefield,selectINTfromthemenu.

IntheAddressfield,typeI1(thecapitalletteriandthenumberone).

ClickAdd.

AddingaGraphicsPage

Adding a Graphics Page


Addingatestpagetoyourtestprojectallowsyoutoviewthefeaturesofthe
CitectGraphicsBuilder.
ToaddagraphicspagetotheCitectVBAtestproject
1

InCitectExplorer,doubleclicktheGraphicsfolder.

DoubleclicktheCreateanewpagebuttoninthePagesfolder,orclickthe
GraphicsBuilderbutton.

ClickNew,andthenclickPage.
TheGraphicsBuilderappearsshowingthetemplatesthatareavailable.
AcceptthedefaulttemplateandclickOK.

See Also

SavingYourGraphicsPage

17

Saving Your Graphics Page


Tosaveagraphicspage,youmustgiveitaname.
Tosavethegraphicspage

See Also

ClickSave.

InthePagefieldonthePagetab,replacethedefaultnameUntitled1with
Startup.Whenyoustartthisproject,thispagewillbedisplayedbydefault.

ClickOK.

OpeningtheGraphicsPage

Opening the Graphics Page


Openingthegraphicspageallowsyoutoeditthepage.
ToopentheCitectVBAtestprojectgraphicspage
1

ChooseOpenfromtheFilemenuinGraphicsBuilder,orclickOpen.

IntheProjectfieldonthePagetab,changetotheCitectVBATestproject(if
notalreadyselected).

InthePagefieldonthePagetab,selectthefilenamedStartup.

ClickOK.

Note:DoubleclickingagraphicpageiconintheCitectExplorerlaunchesthe
CitectGraphicsBuilderanddisplaystheselectedgraphicspage.
See Also

AccessingCicodeTagswithCitectVBA

Chapter 4: Understanding CitectVBA


Language Basics
ThischapterdescribesthebasicsoftheCitectVBAprogramminglanguage.

CitectVBA Files
CitectVBAcodescriptscanbesavedtofile,canincludecomments,statements,
variousrepresentationsofnumbers,canhandlemanydifferentdatatypes,and
canhavemultipleandnestedcontrolstructures.However,CitectVBAis
primarilyprovidedwithVijeoCitecttointeractwithActiveXobjects.
CitectVBAfilesareASCIItextfilesstoredinANSIformatwithaBASextension
(filename.BAS),andareknownasfilemodules.
CitectVBAfilemodulescanbeviewedandeditedinanytexteditorprogram.
TheycanbeusedinVijeoCitect,butmustbesavedastextwithlinebreakswith
a.BASfileextension.

Cicode Editor
TheCicodeEditorisCitectVBAawareanddesignedtohelpyoucreate,edit,
test,anddebugCitectVBAfilemodulesinyourVijeoCitectproject.
TheCicodeEditorhasfeaturessuitableforusewithCitectVBAfilemodules
including:

Abilitytocreate,open,edit,andsaveCitectVBAfilemodules

CustomizablecolorationofCitectVBAcodesyntaxstructure

Recognitionofpredefinedkeywordswithtooltippromptingandauto
completionfunctionality

FullyintegrateddebuggingofCitectVBAfilemodules

SeparateVBWatchwindowforviewingruntimeCitectVBAvariablevalues

AsampleCitectVBAfilemodulenamedSample.Basisincludedinthe
User\ExamplesubfolderonthedriveonwhichyouinstalledVijeoCitect.This
moduleexplainsmostoftheCitectVBAfunctionality.
CitectVBAfilemoduleswillneverbecompiledintostandaloneWindows
executablefiles;instead,theyreincludedwiththecompiledVijeoCitect.Asa
result,theydontrequireaMainproceduretobedeclared.Therefore,CitectVBA
filemodulesarestructuredtocontainonlytheirheaderinformation,modular

20
constantandvariabledeclarations,thenprocedures(subroutines,and
functions).
CitectVBAfilemodulesareautomaticallyincludedwithaVijeoCitectprojectif
theyarestoredinthesamefilefolderasyourproject.WhensavingaCitectVBA
filemoduletodisk,saveittoyourprojectfolder.
AllfileswithaBASextensioninyourprojectfolderappearintheCitectVBA
FilesfolderofyourprojectinCitectExplorer.TolaunchtheCicodeEditor,
doubleclicktheCitectVBAfileyouwanttoeditinCitectExplorer.

Scope of CitectVBA
Thescopeofanobjectdetermineswhichportionsofyourcodescriptscanuse
thatobject.
Note:TheuseofGlobal,Public,andPrivatekeywordshasnoeffectonscopein
CitectVBA.

Procedural (local) level


scope

Variablesandconstantsdeclared(usingtheDim,Static,orConststatements)
withinaCitectVBAprocedure(subroutineorfunction)havelocalscopetoonly
thatwithintheprocedure.Thismeansthatprocedurallevelvariablesand
constantscannotbereferenced(accessedandused)fromanywhereoutsideof
thatprocedure.
TheGlobal,Public,andPrivatekeywordsarenotsupportedbyCitectVBAatthe
procedurallevelandshouldnotbeusedwithinaprocedure.
ProcedurallevelvariablesdeclaredusingtheDimstatementdonotretaintheir
assignedvalueswhendereferenced.Procedurallevelvariablesdeclaredusing
theStaticstatement,however,doretaintheirassignedvaluesbetween
references,evenafterthatproceduremovesoutofscope.

Modular level scope

Constantsdeclared(usingtheConststatement)andvariablesdeclared(using
theStaticstatement)atthemodularlevel(outsideanyprocedure)ina
CitectVBAfilehavemodularscopetoallprocedureswithinthatsame
CitectVBAmodule(file).Thismeansthatmodularconstantsandstaticvariables
canonlybereferencedfromaprocedurelocatedwithinthesamefilemodule,
andcannotbereferencedfromoutsideofthatfilemodule.Thishasnoeffectin
CitectVBA,evenifdeclaredusingtheGlobalkeyword.
Modularlevelconstantsandstaticvariablesretaintheirassignedvaluesforthe
entireruntimeoftheproject.

Global level scope

Variablesdeclared(usingtheDim,Global,orPublicstatements)atthemodular
level(outsideanyprocedure)inaCitectVBAmodule(file),haveglobalscope
withintheVijeoCitectproject.ThismeansthatmodularCitectVBAvariables

21
(exceptstatics)canbereferencedfrombothinsideandoutsideoftheirfile
module.
GloballevelvariablescanbeuseddirectlywithinVijeoCitectcommandor
expressionfields.
Procedures(subroutinesorfunctions)declaredwithinaCitectVBAfilemodule,
likeglobalvariables,haveglobalscopewithinaVijeoCitectproject.Theycanbe
referencedorcalledfromanyCitectVBAmodule,aswellasfromanyVijeo
Citectcommandorexpressionfield.
Equallyimportant,allVijeoCitectvariabletags,alarmtags,andActiveXobjects
areaccessibletoallCitectVBAfilemodules(andtheirprocedures)withinthat
project,inthesamemannerastheyhavealwaysbeenaccessibletoproject
Cicodefiles.ForinformationaboutreferencingVijeoCitectprojecttagsusing
CitectVBA,seeIntegratingCitectVBAwithVijeoCitect.
Globallevelvariableswillalsoretaintheirassignedvaluesbetweensubsequent
references,behavingsomewhatsimilarlytothevaluesstoredinVijeoCitect
tags.Inthisregard,GlobalandPublicstatementsareredundantatthe
modular(global)levelinCitectVBA,astheyperformtheexactsamedutyasthe
Dimstatement.
See Also

MultithreadConsiderationswithCitectVBA
CitectVBAFiles

CitectVBA Statements
AstatementinCitectVBAisanunbrokensequenceofsyntacticallycorrectcode
scriptcontainingatleastoneCitectVBAkeywordinstruction.Asinglestatement
inCitectVBAisonecompletesegmentofcodescriptthatinstructsVijeoCitectto
dosomething.
InCitectVBAthereisnostatementterminator.AsinotherBASICprogramming
languages,theendofthelinecontainingthestatementistreatedasthe
statementterminatorbydefault.
Mostoften,astatementconsistsofasinglelineofCitectVBAscript.However,
morethanonestatementcanbeplacedononelineofCitectVBAscript,provided
eachstatementisseparatedbyacoloncharacter(:);forexample:
Pump234.AddPoint( 25, 100): Pump234.AddPoint( 0, 75)

isequivalentinCitectVBAto:
Pump234.AddPoint( 25, 100)
Pump234.AddPoint( 0, 75)

UsingcomplexmultistatementlinesofCitectVBAscriptisnotrecommendedin
VijeoCitect.Multithreadingshouldbeconsideredwhenusingmorethanone

22
statementperlineinCitectVBA.Fordetails,seeMultithreadConsiderations
withCitectVBA.

Comments
CommentsarenonexecutedsectionsofcodethatareignoredbytheCitectVBA
compiler.Commentsallowprogrammerstodescribethepurposeofasectionof
codetofacilitatecodemaintenance.
AsinotherBASICprogramminglanguages,boththeapostrophecharacter(),
andthekeywordREMarerecognizedasthestartofacommentinCitectVBA.All
charactersfollowinganapostropheorthekeywordREMareignoredbythe
CitectVBAcompileruntilitreachestheendoftheline.Linecontinuation
charactersdonotworkinsidecomments.
REM,likeallotherkeywordsandmostnamesinCitectVBA,isnotcase
sensitive.
' This whole line is
rem This whole line
Rem This whole line
REM This whole line

a comment
is a comment
is a comment
is a comment

Bothtypesofcommentscanbeusedontheirownseparateline,orthe
apostrophecharactercanbeusedtostartacommentattheendofastatementon
thesamelineasastatement.
Pump234.AddPoint( 25, 100 ' Add point to pump 234

EverythingplacedonthesamelineafteranapostropheistreatedbyCitectVBA
asacomment.Ifyouwanttoplaceacommentonthesamelineasastatement,
thecommentmustbeplacedlastafterallstatementsonthatline.Comments
cannotbeplacedbetweenmultiplestatementsonthesameline.
Noteverylineofcoderequiresacomment.Infact,CitectVBAshouldcontain
understandablenamingstructuresandbelaidoutinsuchamannerastomake
commentsunnecessary.However,whereacomplexfunction,equation,orlogic
structureisnotreadilyunderstandablebyviewingthecode,itisgoodpractice
toincludeapertinentcommenttomakethecodemoreunderstandablewhen
viewedinisolation.
See Also

Header information

See Also

Comments
Youshouldincludeheaderinformationwitheveryfileyoucreateoredit.Data
suchasthefilename,authorname,creationdate,updatedate,editinghistory,
andthelikeshouldbeincludedtoformtheheaderinformation.Eachfunctionor
subroutineshouldincludeabriefcommentdescribingthepurposeorfunction
oftheprocedure.
Headerinformation

23
CitectVBAFiles
CitectVBAfileheaderexample
'
'
'
'

FILE IDENTIFICATION
CitectVBA example named CitectVBA.bas
Created by Citect Documentation Team
Created in April 2001

Labels
LabelscanbeusedtodividealargeCitectVBAfunctionorsubroutineinto
logicalsubsectionsofcodescript.Labelsareoftenusedinassociationwiththe
GoTostatement.AlloftheCitectVBAscriptfollowingthelabelandextending
throughtoanotherlabel,ortotheendofthefunctionorsubroutinecontaining
thelabel,isregardedasbelongingtothatlabel.Ormoreappropriately,thelabel
issaidtoidentify,orbeattachedto,thatparticularsectionofCitectVBAscript.
Labelsmustbeginwithaletter,benolongerthan40characters,andcannotbea
reservedword.Labelsmustterminatewiththecoloncharacter(:).Labelnames
canonlycontainthelettersAtoZandatoz,theunderscore_character,
andthedigits0to9.Labelnamescannotcontainthespacecharacter.
Labelnames(oncedeclared),becomeakeywordinCitectVBA.Likemost
keywordsinCitectVBA,labelnamesarenotcasesensitive.Forexample,allof
thefollowinglabelexamplesaretreatedidenticallyinCitectVBA:
label1:
Label1:
LABEL1:

Note:LabelsasusedinCitectVBAarenotthesameaslabelsusedinVijeoCitect.
See Also

CitectVBAFiles

CitectVBA Line Continuation Character


TheunderscoreisthelinecontinuationcharacterinCitectVBA.Theremustbea
spacebeforeandafterthelinecontinuationcharacter.Linecontinuation
charactersdonotworkinsidecomments.
ThefollowingsamplecodestatementsaretreatedidenticallyinCitectVBA:
Pump234.AddPoint _
( 25, 100)
Pump234.AddPoint( 25, 100)

24
Stringscannotbebrokenbetweenlinesusingthelinebreakcharacterin
CitectVBA,unlessthestringsareproperlyenclosedwithindoublequoteson
eachline,andappendedtogetherasperthefollowingexample:
Dim strSample as String
strSample = "This sentence on the first line in my code. " _
& "This sentence is on the second line in my code. " _
& "Yet all would display on the same line " _
& "if the display were wide enough."

Naming
Function,subroutine,variable,constant,andlabelnaminginCitectVBAmust
beginwithaletter,benolongerthan40characters,andcannotbeareserved
word.NamescanonlycontainthelettersAtoZandatoz,theunderscore_
character,andthedigits0to9.Namescannotcontainthespacecharacter.You
cannotusethenameofaCitectVBApredefinedfunctionasaname.Foralistof
predefinedfunctions,seeCitectVBAFunctionReference.
Function,subroutine,variable,constant,andlabelobjectnames(oncedeclared),
becomeakeywordinCitectVBA.LikemostkeywordsinCitectVBA,these
namesarenotcasesensitive.Forexample,allofthefollowingexamplesare
treatedidenticallyinCitectVBA:
pump234.addpoint(25, 100)
Pump234.AddPoint(25, 100)
PUMP234.ADDPOINT(25, 100)

WhennaminginCitectVBA,makethenameanappropriatelydescriptiveterm
thatiseasilyrecognizable.Forexample:
X.addpoint(25, 100)

doesntmakeasmuchsenseas:
Pump234.AddPoint(25, 100)

Combiningupperandlowercaselettersbetweenwordsinthenameisan
acceptablecommonprogrammingpractice,andaidsinreadability.
IdenticallynamedobjectscannotbedeclaredmorethanonceperVijeoCitect
project,eventhoughtheymayexistindifferentCitectVBAcodefilemodules.
However,ifanobjectdeclaredlocallywithinaprocedurehasthesamenameas
anobjectdeclaredinamodule,CitectVBAwillreferencethelocalprocedure
scopeobjectinsteadofthemodularscopeobject.
See Also

ScopeofCitectVBA
CitectVBAFiles
AccessingCicodeTagswithCitectVBA

25

Option Statements
CitectVBAsupportstheuseoffilescopeOptionstatementswhichdeterminethe
defaultbehaviourofsomeCitectVBAfunctions.Forinstance,theOption
ExplicitstatementcausestheCitectVBAcompilertoproducecompileerrors
wheneveritencounterstheuseofpreviouslyundeclaredvariables.TheOption
Comparestatementsetsthedefaultcomparisonmethodforstringcomparisons.
TheOption BasestatementsetsthedefaultbasenumberforCitectVBAvariable
arraystoeitherzeroorone.
YoumustdeclarealloptionstatementsinCitectVBAatthebeginningofyour
CitectVBAcodefiles.
See Also

Option Explicit
statement

OptionExplicitstatement
OptionComparestatement
OptionBasestatement
CitectVBAFunctionReference
AsinotherBASICprogramminglanguages,CitectVBAsupportsthedeclaration
ofvariablesbothimplicitlyandexplicitly.Anunfortunateconsequenceof
implicitvariabledeclarationisthepossiblemisspellingofthevariablenamein
subsequentcodewriting,withunreliableprogrambehaviourandunpredictable
consequences.
Topreventimplicitdeclaration,andtofostergood(consistentandreliable)
programmingstandards,youshouldusetheoptionexplicitstatementatthe
beginningofallyourCitectVBAfiles:
Option Explicit

ThiscausestheCitectVBAcompilertoproduceacompileerrorwheneverit
encountersanundeclaredvariable.Thiscanbeusefulinlocatingandidentifying
variablenametypingerrorsinyourCitectVBAcodeatcompiletime,thus
trappingandpreventingruntimeerrorscausedbysuchmistakes.
See Also

Option Compare
statement

OptionExplicitstatement
Variabledeclaration
OptionStatements
TheOptionComparestatementdetermineshowstringsarecomparedwithina
CitectVBAfile,andlikeotherOptionstatementsinCitectVBA,shouldbe
declaredatthebeginningofyourCitectVBAcodefiles.
WhenstringsarecomparedusingCitectVBAfunctionssuchasStrComp()or
InStr(),CitectVBAdetermineswhethertheycontainequivalentcharactersand
howtheydifferiftheydonotmatch.
Note:Whencomparingstrings,CitectVBAcomparestheANSIvaluesofeach
characterinthestrings.Forexample,thecharactercapitalAhastheANSIvalue

26
of65,andthecharacterlowercaseahastheANSIvalueof97.Foralistingof
ANSIcharactervalues,seeASCII/ANSICharacterCodeListings.
YoucanusetheOptionComparestatementtospecifythedefaultcase
sensitivitybehaviorforCitectVBAfunctionswhenmakingstringcomparisons.
TheOption ComparestatementinCitectVBAhastwosettings:

See Also

Option Base statement

OptionCompareBinary:Stringcomparisonsarecasesensitive,andthisis
thedefaultstringcomparisonsetting.

OptionCompareText:Stringcomparisonsarecaseinsensitive.

Strings
OptionStatements
TheOptionBasestatementdeterminesthedefaultbasenumberfortheindexing
ofvariablearrayscreatedwithinaCitectVBAfile,andlikeotherOption
statementsinCitectVBA,shouldbedeclaredatthebeginningofyourCitectVBA
codefiles.
TherearetwosettingsfortheOptionBasestatementinCitectVBA:

OptionBase0:Variablearraysareindexedfromnumberzero,andthisis
thedefaultsetting.

OptionBase1:Variablearraysareindexedfromnumberone.

ForanexampleofusingtheOptionBasestatement,seeFixedSizeArrays
See Also

ArraysofVariables
OptionStatements

27

CitectVBA Data Types


CitectVBAusestenpredefineddatatypes:
Variable

Char

Type Declaration

Size

Value Range

Byte

Dim bytVar As Byte

1 byte (8 bits)

0 to 255

Boolean

Dim binVar As Boolean

2 bytes

True or False
0 to 65,535 characters

String

Dim strVar As String

Integer
Long Integer
Single precision
Double Precision
Variant

%
&
!
#

Dim intVar As Integer


Dim lngVar As Long
Dim sglVar As Single
Dim dblVar As Double
Dim vntVar As Any

10 bytes + 1 byte per


character
2 bytes
4 bytes
4 bytes
8 bytes
16 bytes

Dim objVar As Object


Dim dtmVar As Date

4 bytes
8 bytes

Object
Date/Time

-32,768 to 32,767
-2,147,483,648 to 2,147,483,647
3.4E-38 to 3.4E+38
1.79D-308 to 1.79D+308
Same ranges as data types
stored
Any OLE Object reference
Jan 1, 100 to Dec 31, 9999

Note:CitectVBAdoesnotsupportuserdefineddatatypes.
See Also

NumericDataTypes
Numbers
Variables
CitectVBAFunctionReference

Constants
AconstantinCitectVBAreferstoavaluethatdoesnotchange(remains
constant),suchasthenumericvaluePi(3.14159).Youcancreateaconstantin
CitectVBAnamedPi,assignitthenumericvalueonceinyourcode,thenreferto
itbyusingtheconstantname,asshownhere:
'modular level constant declaration
Const Pi = 3.1415926
Function CircleArea(Byval Radius)
' calculate and return area of circle
' using radius passed in as argument
CircleArea = Pi * (Radius * Radius)
End Function
Function CircleCircumference(Byval Radius)
' calculate and return circumference of circle
' using radius passed in as argument
CircleCicumference = Pi * Radius * 2
End Function

28
TheseCitectVBAfunctionswouldbecalledfromaVijeoCitectcommandor
expressionfieldlikethis:
CiVBA
TestTag_1 = CircleArea(TestTag_1)

or
CiVBA
TestTag_1 = CircleCircumference(TestTag_1)

See Also

Declarationofconstants
PassingvariablesByrefandByval
IntegratingCitectVBAwithVijeoCitect
YourCitectVBAcodemaycontainfrequentlyrecurringconstantvalueslikePiin
theaboveexample,ormaycontainnumbersthataredifficulttorememberor
havenoobviousmeaning.YoucanmakeyourCitectVBAcodemucheasierto
readandmaintainusingconstantstorepresentthosevalues.
Unlikevariables,constantscantbechangedonceyourVijeoCitectprojectis
compiledandrunning.Constantsareeithersymbolicorintrinsic:

See Also

Declaration of
constants

Symbolicoruserdefinedconstantsaredeclaredbyusingtheconst
statement.

IntrinsicconstantsareprovidedinobjectlibrariesofActiveXobjectsandyou
cannotusetheminCitectVBA:theycausecompileerrorsasthereisnoway
toprovideearlybindingtotheobjecttypelibrary.

Intrinsicconstants
ScopeofCitectVBA
CitectVBAFunctionReference
CitectVBAconstantscanonlybedeclaredandreferencedwithinCitectVBAfile
modules.CitectVBAmodularconstantshavemodularscopeandcannotbe
referenced(accessedandused)fromoutsidetheirCitectVBAmodule(file).
Note:CitectVBAconstantscannotbeuseddirectlyinVijeoCitectcommandor
expressionfields.
OncedeclaredwithinaCitectVBAmodule,CitectVBAconstantscanbe
referencedandusedinanyprocedurewithinthesamecodemodule.Aconstant
declaredoutsideaprocedurehasmodularscopetoallprocedureswithinthat
sameCitectVBAmodule(file).SeeScopeofCitectVBA.Constantsdeclaredin
aSuborFunctionprocedurehavelocalscopeonlywithinthatprocedure.
CitectVBAconstantsaredeclaredwiththeConststatementinthefollowing
format.
Const <ConstantName> [ As <DataType> ] = <expression>

29
where:

ConstistherequiredconstantdeclarationstatementBASICkeyword

<ConstantName>representstherequirednameoftheconstantbeing

declared

<DataType>representstheoptionalCitectVBAdatatypeoftheconstant

beingdeclared

<expression>representstherequiredvaluebeingassignedtotheconstant

Note:Donotincludethebracketsfromtheexplanationintheactualcode
statement.
Ifnodatatypeisdeclared,CitectVBAautomaticallyassignsoneofthefollowing
datatypestotheconstant:

Long(ifitisalongorinteger).

Double(ifadecimalplaceispresent).

String(ifitcontainsquotemarks).

Constantstatementscanonlybedeclaredandassignedusingsimple
expressions.Constantscannotbeassignedvaluesfromvariables,userdefined
functions,intrinsicCitectVBAfunctions(suchasChr),orfromanyexpression
thatinvolvesanoperator.Aconstantmustbedefinedbeforeitcanbeused.
Example

' Correct declaration examples


Const Seven = 7
' long assignment
Const Pi = 3.14159
' double assignment
Const Lab = "Laboratory"
' string assignment
' Incorrect declaration examples. Note that the following
declarations demonstrate incorrect assignments because each
contains an operator
Const conPi = 4 * Atn(1)
' will cause a CitectVBA compile error
Const conDegToRad = (conPi / 180)
' will cause a CitectVBA compile error

ForanexampleofusingconstantsinCitectVBA,seeConstants.
Note:TheuseofGlobal,Public,andPrivatekeywordshasnoeffectonscopein
CitectVBA.
See Also

Constants

30
Intrinsicconstants
Variables
CitectVBADataTypes
CitectVBAFunctionReference

Intrinsic constants

See Also

CitectVBAhasnopredefinedintrinsic(builtinanddeclared)constants,
however,doesprovidelimitedsupportforintrinsicconstantsprovidedinobject
librariesofActiveXobjectswhentheobjecttheyrefertoisloadedusingthe
predefinedCitectVBACreateObject()function.
Declarationofconstants
Constants

Variables
VariablesareusedinCitectVBAtotemporarilystoredatavalues.Variableslet
youassignadescriptivenametothedatayouareworkingwith.Youcancreatea
variableonceonlyinyourcode,andreference(referto)itthereafterasmany
timesasyoulike,byusingitsnameinyourcodeinplaceofthedatavalue.
Unlikeconstants,thevaluethatavariableholdscanbechangedduringthe
runtimeoftheproject.
AllvariablesdeclaredwithinaCitectVBAprocedure(subroutineorfunction)
havelocalscopetothatprocedureonly.Procedurallevelvariablesdeclared
usingtheDimstatementdonotretaintheirassignedvalueswhendereferenced.
ProcedurallevelvariablesdeclaredusingtheStaticstatement,however,retain
theirassignedvaluesbetweenreferences,evenafterthatproceduremovesoutof
scope.
CitectVBAcodeusedwithinaVijeoCitectcommandorexpressionfieldis
treatedasifthecommandorexpressionisaseparateCitectVBAprocedure.
Variablesdeclaredwithinsuchacommandprocedurehaveproceduralscope
andlifetime,asdescribedabove.
Variablesdeclaredusingthestaticstatementatthemodularlevel(outsideany
procedure)inaCitectVBAfile,havemodularscopetoallprocedureswithinthat
sameCitectVBAmodule(file).Modularlevelstaticvariablesretaintheir
assignedvaluesfortheentireruntimeoftheproject.
Variablesdeclared(usingthedim,global,orpublicstatements)atthemodular
level(outsideanyprocedure)inaCitectVBAfiledo,however,haveglobalscope
withintheVijeoCitectproject.
Note:Globalandpublicstatementsareredundantatthemodular(global)
levelinCitectVBA,astheyperformtheexactsamedutyasthedimstatement.

Variable declaration

InCitectVBA,variablesaredeclared(dimensioned)withthedimstatementin
thefollowingformat.

31
Dim <VariableName> [ As <DataType> ]

where:

DimistherequiredVariabledeclarationstatementBASICkeyword

<VariableName>representstherequirednameofthevariablebeing

declared(dimensioned)

<DataType>representstheoptionalCitectVBAdatatypeofthevariable

beingdeclared
Note:Inthevariabledeclarationstatement:

Everyplaceholdershowninsidearrowbrackets(<placeholder>)should
bereplacedinanyactualcodewiththevalueoftheitemthatitdescribes.
Thearrowbracketsandthewordtheycontainshouldnotbeincludedinthe
statement,andareshownhereonlyforyourinformation.

Statementsshownbetweensquarebrackets([ ])areoptional.Thesquare
bracketsshouldnotbeincludedinthestatement,andareshownhereonly
foryourinformation.

Ifnodatatypeisdeclared,thedatatypeisVariantbydefault.Todeclarea
variableotherthanaVariant,thevariabledeclarationmustbeimmediately
followedbyAs<datatype>(where<datatype>representsoneofthe10data
types),orappendedbyatypedeclarationcharactersuchasa$,%,&,!,or#for
string,integer,long,single,ordoubledatatypesrespectively.Forexample:
Dim
Dim
Dim
Dim

intVar As Integer
dblVar As Double
vntVar' as variant by default
strName$, Age%' multiple declarations on one line

Beawarethatmultipledeclarationsinthesamestatementrequireindividual
datatypeassignmentifyouwantthembeotherthanthevarianttype.Inthe
followingexample,onlythefirstvariableisnotavariant.Forexample:
Dim strName As String, vntAge, vntAddress

Thesamestatementwithdatatypeassignmentforeveryvariablewouldlook
likethefollowingexample:
Dim strName As String, intAge As Integer, strAddress As String

See Also

CitectVBADataTypes
Variableinitializationvalues
Constants
VariantDeclaration
ArraysofVariables
CitectVBAFunctionReference

32

Variable initialization
values

CitectVBAvariablesareinitializedwhenfirstdeclared.Numericvariablesare
initializedto0(zero).Variablelengthstringsareinitializedtozerolength
strings().Fixedlengthstringsarefilledwithzeros.Variantvariablesare
initializedtoEmpty.
Tobesureofthecontentsofavariable,avalidvalueshouldbeassignedtoit
beforeitisusedasaoperandinaCitectVBAstatement.Fordetails,see
AssignmentOperator.
Note:Onlyimplicitlydeclaredvariablescanbeassignedaninitialvalueinthe
declaration.However,asexplicitdeclarationispreferredpracticeinCitectVBA,
explicitvariablesmustbedeclaredbeforetheycanbeassignedavalue.
Everycalltoaprocedurewillreinitializethevalueofallobjects(exceptstatic
variables)declaredwithinthatprocedure.
Note:InCitectVBA,useastaticvariable,amodularvariable,oraVijeoCitecttag
tostorevariablevaluesbetweenprocedures.Fordetails,seeScopeof
CitectVBA.
Objects(includingvariables)declaredinCitectVBAareonlyinitializedwhen
referencedbyarunningpieceofcode,andareremovedfrommemorywhenall
referencesareclosed.
IntheVijeoCitectmultithreadedenvironment,CitectVBAremainsactivein
memoryonlysolongasaprocedureisbeingprocessed.Atthecompletionofa
CitectVBAprocedure,allobjectsnolongerreferencedbythatprocedureare
removedfrommemory.Fordetails,seeMultithreadConsiderationswith
CitectVBA.

See Also

CitectVBADataTypes
Variableinitializationvalues
Constants
VariantDeclaration
ArraysofVariables

Arrays of Variables
Arraysofvariablesallowyoutogrouplikevariablestogether,somewhatsimilar
tothegroupingoflikeitemsinfieldsofadatabase.Anarrayisanorderedgroup
ofvariablesofthesamename,containingvaluesofthesamedatatype.
Individualmemberelementsofthearrayareindentifiedbyaseparateindex
number.ArraysinCitectVBAstarttheirindexingsequencebydefaultatzero.
ThisdefaultbasevaluecanbechangedinaCitectVBAfilemodulebyusingthe
option basestatement.
CitectVBAsupportssingleandmultidimensionarraysofvariables.CitectVBA
createssingledimensionarraysbydefault.Multidimensionarraysmustbe
specificallydeclared.

33
CitectVBAallocatesmemoryspaceforeachelementofthearray.Tominimize
theamountofmemoryusedstoringarrays,andtominimizethetimerequiredto
accessarraydata,arraysshouldnotbedeclaredanylargerthanrequired.
Allelementsinanarraymustbeofthesamedatatype.CitectVBAsupports
arraysofbytes,booleans,longs,integers,singles,doubles,strings,andvariants.
FordetailsaboutCitectVBAdatatypes,seeCitectVBADataTypes.
Arraysdeclaredinasuborfunctionprocedurehavelocalscopeonlywithinthat
procedure.Anarraydeclaredoutsideaprocedurehasmodular(global)scopeto
allprocedureswithintheproject.
Note:CitectVBAarrayscannotbeuseddirectlyinVijeoCitectcommandor
expressionfields.Also,CitectVBAdoesnotsupportuserdefineddatatypes.
Arraysdeclared(usingthedimstatementwithinprocedures,)donotretaintheir
valuesbetweenprocedurecallsinCitectVBA.
See Also

FixedSizeArrays
MultiDimensionalArrays
DynamicSizeArrays

Variable Array Declaration


ArraysofvariablesaredeclaredwithinaCitectVBAfilemodule,function,or
subroutine,usingthedimstatementwithparenthesespositionedafterthearray
name,inthefollowingsyntax:
Dim <ArrayName>( [<Subscripts>] ) [As <DataType>]

where:

dimistherequiredvariabledeclarationstatementBASICkeyword.

<ArrayName>representstherequirednameofthearraybeingdeclared

(dimensioned).

( )aretherequiredparenthesestoholdthearraysubscriptrange
(dimensions).
<Subscripts>representstheoptionalsubscriptrangesanddimensionsfor

thearray.

AsistheoptionalAsstatementkeyworddeclaringthearraydatatype.

<DataType>representstheoptionalCitectVBAdatatypedeclarationforthe

array.
Inthevariablearraydeclarationstatement:

Everyplaceholdershowninsidearrowbrackets(<placeholder>)should
bereplacedinanyactualcodewiththevalueoftheitemthatitdescribes.

34
Thearrowbracketsandthewordtheycontainshouldnotbeincludedinthe
statement,andareshownhereonlyforyourinformation.

See Also

Statementsshownbetweensquarebrackets([ ] )areoptional.Thesquare
bracketsshouldnotbeincludedinthestatement,andareshownhereonly
foryourinformation.

FixedSizeArrays
MultiDimensionalArrays
DynamicSizeArrays
ArraySubscripts
ArraysofVariables
Dim

Array Subscripts
Arrayscanbedeclaredwithdefaultordefinedboundariesknownasbounds.
Unlessspecificallydefinedinthearraydeclarationstatement,defaultlower
boundsettingsareused.Thedefaultlowerboundiszero,unlesssetbythe
moduleoptionbasestatementsetting.
CitectVBAdoesnothaveanarbitraryupperboundonarraydimensions.The
upperboundofthearraydimensionmustbedefinedbeforethearraycanbe
used.Allboundvaluesmustbewholeintegers.
Subscriptsarecontainedwithinonesetofparenthesespositionedimmediately
afterthearraynameinthearraydeclarationstatement.
Subscriptsareusedtospecifytheboundsofeachdimensionofanarraywhen
thearrayisdeclared.Ifasinglevalueisused,forinstance(5),thisrepresentsthe
upperboundforthatdimensionofthearray.Ifarangeisspecified,forinstance
(1to9),thisspecifiesboththelowerandupperboundsforthatdimensionofthe
array.Ifmorethanonesubscriptisused,forinstance(5,1To9),eachsubscript
mustbeseparatedbyacomma,andeachsubscriptrepresentsaseparate
dimensionofthearray.
Thesyntaxofanarraysubscriptrangeconsistsofanumericvaluerange
separatedbythetoclause:
(<LowerBound> To <UpperBound>)

where:

( )aretherequiredparenthesestoholdanarraysubscriptrange
(dimensions).

<LowerBound>representsthelowerboundofthesubscriptrangeforthe
arraydimension.

Toistheclauselinkingthelowerandupperboundsofthesubscriptrange.

35

See Also

<UpperBound>representstheupperboundofthesubscriptrangeforthe
arraydimension.

FixedSizeArrays
MultiDimensionalArrays
DynamicSizeArrays
ArraysofVariables
Dim

Fixed Size Arrays


Todeclareafixedsizearray,thearraynamemustbefollowedbytheupper
boundsubscriptenclosedwithinparentheses.Theupperboundmustbean
integer.
Dim ArrayName(10) As Integer
Dim Sum(20) As Double

Unlessspecificallydefinedinthearraydeclarationstatement,defaultlower
boundsettingsareused.Thedefaultlowerboundiszero,unlesssetbythe
moduleoptionbasestatementsetting.Fordetails,seeArraySubscripts.
Thefirstdeclarationinthepreviousexamplecreatesanarraywith11elements,
withindexnumbersrunningfrom0to10.Thesecondcreatesanarraywith21
elements(ifbase0).Onewaytospecifythelowerboundistoprovideit
explicitly(asanintegerintherange32,768to32,767)usingtheToclausewithin
thesubscript:
Dim intCounters (1 To 13) As Integer
Dim strSums (100 To 126) As String

Intheprecedingexample,theindexnumbersofintCountersrunfrom113,and
theindexnumbersofstrSumsrunfrom100126.
Note:AnarrayinCitectVBAmustbedeclaredbeforeitcanbereferenced.
Loopsoftenprovideanefficientwaytomanipulatearrays.Forexample,the
followingforloopinitializesallelementsinthearrayto5:
Dim int As IntegerDim Counters(1 To 20) As Integer
For int = 1 To 20
Counters(int) = 5
Next int

Arraysdeclared(usingthedimstatementwithinprocedures)donotretaintheir
valuesbetweenprocedurecallsinCitectVBA.
See Also

MultiDimensionalArrays
DynamicSizeArrays
ArraysofVariables
ArraySubscripts
OptionBasestatement

36

Multi-Dimensional Arrays
CitectVBAsupportsmultidimensionalarrays,declaredusingmultiple
subscripts.Eachsubscriptmustbeseparatedbyacomma,andeachsubscript
representsaseparatedimensionofthearray.
Thefollowingexampledeclaresatwodimensionalarray.
Dim dblMat(20, 20) As Double

Unlessspecificallydefinedinthearraydeclarationstatement,defaultlower
boundsettingsareused.Thedefaultlowerboundiszero,unlesssetbythe
moduleoptionbasestatementsetting.Formoreinformationonbounds,see
ArraySubscriptsinCitectVBA.
Reusingthepreviousexample,eitherorbothdimensionscanbedeclaredwith
explicitlowerbounds.
Dim dblMat(1 To 10, 1 To 10) As Double

Arrayscanbemorethantwodimensional.Thisdeclarationcreatesanarraythat
hasthreedimensionswithsizes6elementsby4elementsby3elements,using
base0:
Dim ArrTest(5, 3, 2)

Youcanefficientlyprocessamultidimensionalarraywiththeuseofforloops.
Inthefollowingstatementstheelementsinamultidimensionalarrayaresetto
avalue.
Dim L As Integer, J As Integer
Dim TestArray(1 To 10, 1 to 10) As Double
For L = 1 to 10
For J = 1 to 10
TestArray(L,J) = I * 10 + J
Next J
Next L

Arraysdeclared(usingthedimstatementwithinprocedures,)donotretaintheir
valuesbetweenprocedurecallsinCitectVBA.
See Also

MultiDimensionalArrays
DynamicSizeArrays
ArraysofVariables
ArraySubscripts
OptionBasestatement
FixedSizeArrays

37

Dynamic Size Arrays


Todeclareadynamicsizedarray,thearraymustfirstbedeclaredusingthedim
statementwithanemptypairofparenthesesfollowingthearrayname.For
example:
Dim ArrayName( ) As Integer

Oncedeclaredasdynamicinthismanner,thearraycanthenONLYberesized
withinafunctionorsubroutineusingtheredimstatement.
ReDim ArrayName(20) As Integer

Note:Youcannotresizeanarraywhosesizewaspredefinedinitsinital
declaration.
Intheaboveexamples,thefirstdeclarationcreatesanarraywith0elements.The
secondrecreatesthearraytocontain21elements,withindexnumbersrunning
from0to20,unlesstheoptionbasestatementhasbeensetpreviouslyinthecode
module(file),inwhichcasethearraywillcontain20elementswithindex
numberingrangingfrom1to21.
Unlessspecificallydefinedinthearraydeclarationstatement,defaultlower
boundsettingsareused.Thedefaultlowerboundiszero,unlesssetbythe
moduleoptionbasestatementsetting.Formoreinformationonbounds,see
ArraySubscriptsinCitectVBA.
Redimerasesallvaluesthearraymayhaveheld.Topreservethecontentsofthe
arraywhenresizing,precedetheRedimstatementwiththepreservekeyword.
Preserve ReDim ArrayName(20) As Integer

Redimensioninganarraytoasmallervalue,willeraseanyvaluesitmayhave
containedintheremovedportions.
Arraysdeclared(usingthedimstatementwithinprocedures,)donotretaintheir
valuesbetweenprocedurecallsinCitectVBA.
See Also

MultiDimensionalArrays
ArraysofVariables
ArraySubscripts
OptionBasestatement
FixedSizeArrays

Variant Declaration
AsisthecasewithVisualBasic,whenavariableisintroducedinCitectVBA,itis
notnecessarytodeclareitfirst(seeOptionExplicitstatementforanexception
tothisrule).Whenavariableisusedbutnotdeclared,itisimplicitlycreatedasa

38
variantdatatype.VariantscanalsobedeclaredexplicitlyusingAsVariant.Both
ofthefollowingexampledeclarationsastreatedidenticallyinCitectVBA:
Dim vntVar' implicit variant declaration
Dim vntVar As Variant ' explicit variant declaration

TheIsEmpty( )functioncanbeusedtofindoutifavariantvariablehasbeen
previouslyassignedavalue.

Variant Data Types and Coercion


Thevariantdatatypeiscapableofstoringnumbers,strings,dates,andtimes.
Whenusingavariant,youdonothavetoexplicitlyconvertavariablefromone
datatypetoanother.Thisdatatypeconversionishandledautomatically,andis
termeddatatypecoercion.
' declares variant variable
Dim vntVar
' assign numeric 10 to variant
vntVar = 10
' add numeric 8 to numeric variant value
vntVar = vntVar + 8
' convert variant to string value and concatenates strings
vntVar = "F" & vntVar
' print string "F18"
print vntVar

Numericcharactersinsidequotes(567)willbestoredandtreatedasastringin
avariantdatatypevariable.Ifthisstring(containingnumericcharacters)is
subsequentlyusedinanumericoperation,itwillbecoercedintoanumericdata
typeandtreatedasanumberintheoperation.Conversely,numericcharacters
storedasanumberdatatypeinavariantvariable,andsubsequentlyusedinan
operationwithastring,willbecoercedintoastringdatatype,andtreatedasa
stringvalueintheoperation.
Note:Todeterminethetypeofavariantvariable,usethefunctionVarType( ),
whichreturnsavaluethatcorrespondstotheexplicitdatatypes.SeeVarType
forreturnvalues.

Numbers in Variants
Whenstoringnumbersinvariantvariables,thedatatypeusedisalwaysthe
mostcompacttypepossible.Forexample,ifyoufirstassignawholenumberto
thevariantitwillbestoredasanintegerorlong.Ifyouassignanumberwitha
fractionalcomponent,itisstoredasasingleordouble.
Fordoingnumericoperationsonavariantvariable,itissometimesnecessaryto
determineifthevaluestoredisavalidnumeric,thusavoidinganerror.Thiscan
bedonewiththeIsNumeric( )function.

39
See Also

CitectVBADataTypes
Variables
Constants
Strings
Numbers
CitectVBAFunctionReference

Numbers
CitectVBAsupportsthreerepresentationsofnumbers:decimal,octal,and
hexadecimal.
Toindicatetheuseofoctal(base8)orhexadecimal(base16)numbers,prefixthe
numberwith&Oor&Hrespectively.Ifnoprefixisincludedwithanumber,itis
treatedasdecimal(base10).Forexample:
Dim vntVar as Variant
vntVar = 12345' assign decimal value
vntVar = &o12345' assign octal value
vntVar = &h12345' assign hexadecimal value

MostnumbersusedinCitectVBAformulasaredecimalnumbers.Decimal
numbersconsistofintegralvalues(knownasintegers)positionedtotheleftof
thedecimalpoint,andfractionalvalues(knownasfractions)positionedtothe
rightofthedecimalpoint.Ifthedecimalpointisomitted,thenumberistreated
asaninteger(wholenumberwithnofraction).
WhenusingnumbersinCitectVBA,considerationmustbegiventothedatatype
ofthevariablesthatholdandstorethenumbers,aswellastothebehaviourof
CitectVBAwhendealingwithnumbers.Fordetails,seeNumericDataTypesin
CitectVBA,FloatingPointCalculationRulesinCitectVBA,andRounding
NumbersinCitectVBA.
See Also

DateHandling
VariantDeclaration
Strings
Variables
Constants
CitectVBADataTypes
CitectVBAFunctionReference

Numeric Data Types


NumbersareexpressedinCitectVBAindecimalformatbydefault,andcanbe
storedinvariablesofdifferentnumericdatatypesinteger,long,single,double,
andvariantprovidingdifferentlevelsofnumericaccuracy.

Integer(Integerdatatype)variablescanonlystorewholenumbervalues(no
decimalorfractionvalues)withintherange32,000to+32,000.Ifyouusea

40
numberoutsidethisrange,thelonginteger(Longdatatype)canstorewhole
numbervaluesintherange2.1millionto+2.1million.

Floatingpointnumberscontainbothintegerandfractionalvalueswitha
floatingdecimalpoint.CitectVBAprovidesbothsingleprecision(Single
datatype)andDoublePrecision(Doubledatatype)variablesforhandling
floatingpointnumbers.

Singleprecisionvariablescanstorefloatingpointnumberswithinthe
rangeofapproximately3.4E38to3.4E+38,with7significantdigitsand
occupying4bytesofmemory.

Doubleprecisionvariablescanstorefloatingpointnumberswithinthe
rangeofapproximately1.79D308to1.79D+308,with15significantdigits
andoccupying8bytesofmemory.

Foranexplanationofexponentialnotation,seeExponentialNotation.
Theprincipaldifferencesbetweensingleanddoubledatatypes,arethe
significancetheycanrepresent,thestoragetheyrequire,andtheirrange.Double
datatypevariableshaveasmallerrange,butholdmoreprecisionandoccupy
morememorythansingledatatypevariables.
Ifprecisionislessofaconcernthanstorage,considerusingsingleforfloating
pointvariables.Conversely,ifprecisionisthemostimportantcriterion,use
double.
Variant(variantdatatype)variablesinCitectVBAcanstorenumbersbystoring
themasinteger,long,single,ordoubledatatypeswithinthevariantstructure.
SeeVariantDeclaration.
See Also

Numbers

Exponential Notation
CitectVBAcanhandleverylargenumbers,uptoavalueof1.7976931486232
raisedtothepowerof308,(1.7308).Torepresentverylargenumberssuchas
these,exponentialnotationisused.
Commonly,exponentialnotationusestheletterEinthenumber,followedby
thesignofthenumber(+or),andthentheexponentialvalue(power)ofthe
number.CitectVBAusestheletterEforSingledatatypeexponentialvalues,
andtheletterDforDoubledatatypeexponentialvalues.Themaximumsize
numberforadoubleprecisiondatatype,asquotedabove,wouldberepresented
usingexponentialnotationas1.7976931486232D+308,orabbreviatedto
1.79D+308.
YoucanuseexponentialnotationinyourCitectVBAcalculations,solongasthe
datatypesofallthevariablesinthecalculationarecapableofstoringfloating
pointvalues;i.e.:Single,DoubleorVariant.

41
Fordetailsaboutprecision,accuracy,androundingissueswithusingfloating
pointvariablesinCitectVBA,seeNumericDataTypesinCitectVBA,Floating
PointCalculationRulesinCitectVBA,andRoundingNumbersinCitectVBA.
See Also

Numbers

Floating Point Calculation Rules


Oftenprecision,rounding,andaccuracyinfloatingpointcalculationscan
generateunexpectedresults.Toavoidthissituation,followtheserules:

See Also

Inacalculationinvolvingbothsingleanddoubleprecision,theresultwill
notusuallybeanymoreaccuratethansingleprecision.Ifdoubleprecisionis
required,becertainalltermsinthecalculation,includingconstants,are
specifiedindoubleprecision.

Neverassumethatasimplenumericvalueisaccuratelyrepresentedinthe
computer.Mostfloatingpointvaluescantbepreciselyrepresentedasa
finitebinaryvalue.Forexample.1is.0001100110011...inbinary(itrepeats
forever),soitcantberepresentedwithcompleteaccuracyonacomputer
usingbinaryarithmetic,whichincludesallPCs.

Neverassumethattheresultisaccuratetothelastdecimalplace.Thereare
alwayssmalldifferencesbetweenthetrueanswerandwhatcanbe
calculatedwiththefiniteprecisionofanyfloatingpointprocessingunit.

Nevercomparetwofloatingpointvaluestoseeiftheyareequalornot
equal.Thisisacorollarytorulethree.Therearealmostalwaysgoingtobe
smalldifferencesbetweennumbersthatshouldbeequal.Instead,always
checktoseeifthenumbersarenearlyequal.Thatis,checktoseeifthe
differencebetweenthemisverysmallorinsignificant.

Numbers
DateHandling

Rounding Numbers
Roundingoccurswhenyouconvertanumberofgreaterprecisionintoanumber
oflesserprecision.Forinstance,whenconvertingafloatingpointnumber
(singleprecision,doubleprecision,orvariantdatatypes)intoanintegerorlong
datatypenumber.Thepossiblewaysofnumericroundingarediscussedbelow.

Rounding down

Thesimplestformofroundingistruncation.Anydigitsafterthedesired
precisionareignoredanddropped.TheCitectVBAFix()functionisan
exampleoftruncation.Forexample,Fix(3.5)is3,andFix(-3.5)is3.
TheInt()functionroundsdowntothehighestintegerlessthanthevalue.Both
Int()andFix()actthesamewaywithpositivenumbers(truncating),butgive
differentresultsfornegativenumbers:Int(-3.5)gives4.

42
TheFix()functionisanexampleofsymmetricroundingbecauseitaffectsthe
magnitude(absolutevalue)ofpositiveandnegativenumbersinthesameway.
TheInt()functionisanexampleofasymmetricroundingbecauseitaffectsthe
magnitudeofpositiveandnegativenumbersdifferently.

Rounding up

CitectVBAdoesnothaveaspecificroundupfunction.However,fornegative
numbers,bothFix()andInt()canbeusedtoroundupward,indifferent
ways:

Fix()roundstowards0(upintheabsolutesense,butdownintermsof

absolutemagnitude).Forexample:Fix(3.5)is3.5.

Arithmetic rounding

Int()roundsawayfrom0(upintermsofabsolutemagnitude,butdownin
theabsolutesense).Forexample:Int(3.5)is4.

Whencontinuallyroundinginonedirection(downorup),theresultingnumber
isnotnecessarilytheclosesttotheoriginalnumber.Forexample,ifyouround
1.9downto1,thedifferenceisalotlargerthanifyourounditupto2.Itiseasy
toseethatnumbersfrom1.6to2.4shouldberoundedto2.However,whatabout
1.5,whichisequidistantbetween1and2?Bymathematicalconvention,thehalf
waynumberisroundedup.
Toimplementroundinghalfwaynumbersinasymmetricfashion,.5is
roundeddownto1,orinanasymmetricfashion,where.5isroundedupto0.
CitectVBAdoesnothaveafunctionforarithmeticrounding.

Banker's rounding

Whenyouaddroundedvaluestogether,alwaysrounding.5inthesame
directionresultsinabiasthatgrowswiththemorenumbersyouaddtogether.
Onewaytominimizethebiasiswithbankersrounding.
Bankersroundingrounds.5upsometimesanddownsometimes.The
conventionistoroundtothenearestevennumber,sothatboth1.5and2.5
roundto2,and3.5and4.5bothroundto4.Bankersroundingissymmetric.
InCitectVBA,theCByte(),CInt(),CLng(),CCur(),andRound()numeric
functionsperformbankersrounding.

Random rounding

Evenbankersroundingcanbiastotals.Youcantakeanextrasteptoremovebias
byrounding.5upordowninatrulyrandomfashion.Thisway,evenifthedata
isdeliberatelybiased,biasmightbeminimized.However,usingrandom
roundingwithrandomlydistributeddatamightresultinalargerbiasthan
bankersrounding.Randomroundingcouldresultintwodifferenttotalsonthe
samedata.
CitectVBAdoesnothaveafunctionforrandomrounding.

Alternate rounding

Alternateroundingisroundingbetween.5upand.5downonsuccessivecalls.
CitectVBAdoesnothaveafunctionforalternaterounding.

43
See Also

Numbers

Date Handling
CitectVBAhasseveralpredefineddateandtimefunctionsthatreturndate/time
values.Therearethreefunctionsenablingyoutodeterminethecurrentdateand
timesetinWindows.TheNowfunction,Datefunction,andTimefunctioncheck
yoursystemclockandreturnallorpartofthecurrentsetting.
Toretrievethedateportionofadate/timevalue,usethepredefinedDateValue
function.Thisfunctiontakesineitherastringoradatevalueandreturnsonly
thedateportion.
UsingDateValue,youcancomparethedateportionofadatevariabletoa
specificdatevalue,likethis:
If DateValue(dtmSomeDate) = #5/14/70# Then
' You know the date portion of dtmSomeDate is 5/14/70
End If

Ifyouneedjustthetimeportionofadatevariable,usetheTimeValuefunction.
Usingthisfunction,youcouldwritecodethatchecksthetimeportionofadate
variableagainstaparticulartime,likethis:
If TimeValue(dtmSomeDate) > #1:00 PM# Then
' You know the date variable contained a date portion
' with a time after 1:00 PM.
End If

Youcanperformarithmeticormathematics(math)ondate/timevaluesbecause
CitectVBAstoresdatesinternallyasserialvalues.Addingorsubtracting
integersaddsorsubtractsdays,whilstaddingorsubtractingfractionsaddsor
subtractstime.Therefore,adding20toadatevalueinCitectVBAadds20days,
whilesubtracting1/24subtractsonehour.Forexample,togettomorrowsdate,
youcouldjustadd1totodaysdate,likethis:
dtmTomorrow = Date() + 1
DateisabuiltinCitectVBAfunctionthatreturnsthedateportion(theinteger

part)ofthecurrentdateandtimeretrievedfromtheWindowsoperatingsystem.
Adding1tothatvaluereturnsadatethatrepresentsthenextday.
Thesamemechanismworksforsubtractingtwodates.AlthoughCitectVBA
suppliestheDateDifffunctionforfindingtheintervalspannedbytwodate/
timevalues,ifyoujustneedtoknowthenumberofdaysbetweenthetwodates,
youcansimplysubtractonefromtheother.
See Also

DateandTimeFunctions
DateConstants
FormattingDateValues
CitectVBAFunctionReference

44

Date Constants
Youcanusedate/timeliteralsinCitectVBAcodebyenclosingthemwiththe
hashsign(#),inthesamewayyouenclosestringliteralswithdoublequotation
marks().Thisiscommonlyknownasdeclaringdateconstants.
Forexample,#2/6/10#representstheAustraliandatevalueof2ndJune,2010if
theshortdatesettingforthelocalewassettod/MM/yyyy.Thesamedate
constantwouldrepresenttheAmericandatevalueofFebruary6,2010ifthe
shortdatesettingforthelocalewassettoMM/d/yyyy.SeeFormattingDate
ValuesinCitectVBA.
Note:ThesystemlocalesettingsaredeterminedusingRegionalSettingsin
WindowsControlPanel.
Similarly,youcancompareadate/timevaluewithacompletedate/timeliteral:
If SomeDate > #3/6/99 1:20pm# Then

Ifyoudontincludeatimeinadate/timeliteral,CitectVBAsetsthetimepartof
thevaluetomidnight(thestartoftheday).Ifyoudontincludeadateinadate/
timeliteral,CitectVBAsetsthedatepartofthevaluetoDecember30,1899.
CitectVBAacceptsawidevarietyofdateandtimeformatsinliterals.Theseare
allvaliddate/timevalues:
SomeDate
SomeDate
SomeDate
SomeDate

=
=
=
=

#3-6-93 13:20#
#March 27, 1993 1:20am#
#Apr-2-93#
#4 April 1993#

InthesamewaythatyoucanusetheIsNumericfunctiontodetermineifa
Variantvariablecontainsavaluethatcanbeconsideredavalidnumericvalue,
youcanusetheIsDatefunctiontodetermineifavariantcontainsavaluethat
canbeconsideredavaliddate/timevalue.YoucanthenusetheCDatefunction
toconvertthevalueintoadate/timevalue.
Forexample,thefollowingcodeteststheTextpropertyofatextboxwithIsDate.
Ifthepropertycontainstextthatcanbeconsideredavaliddate,CitectVBA
convertsthetextintoadateandcomputesthedaysleftuntiltheendoftheyear:
Dim SomeDate, daysleft
If IsDate(Text1.Text) Then
SomeDate = CDate(Text1.Text)
daysleft = DateSerial(Year(SomeDate) + _
1, 1, 1) - SomeDate
Text2.Text = daysleft & " days left in the year."
Else
MsgBox Text1.Text & " is not a valid date."
End If

See Also

DateandTimeFunctions

45
FormattingDateValues
CitectVBAFunctionReference
DateHandling

Formatting Date Values


DatevaluesinCitectVBAcanbeformattedanddisplayedasstringscontaining
anycombinationofthefollowinglistsofvalues,allofwhicharecasesensitive.
MostCitectVBAdateandtimefunctionsarelocaleawareandrecognisethe
orderforday,month,andyearaccordingtotheshortdateformatintheRegional
SettingssectionofWindowsControlPanel.
Note:Alwaysuselongdateformatwheneverpossible.Forreliablebehavior,
enteranddisplaydatesinanunambiguousformat.Forexample,datesinshort
dateformatmightbemisinterpretedinqueriesiftheyearorthedayofthe
monthare12orless(forexample,3/11/10).Datesinmediumdateformatdisplay
onlythefirstfewcharactersofthemonthname,whichcancreateambiguityor
anundesirableappearance.

Text

Day

Allstringsshouldbesurroundedbysinglequotes,andanysinglequotesshould
beenteredasfoursinglequotesinarow:
Value

Example

it''''s
'Today is 'M/dd/yy' and it''''s 'h:mm

it's
Today is 01/22/99 and it's 8:18

Thedaycanbedisplayedinoneoffourformatsusingalowercased.
Value

Meaning

Example

Day of the month as digits without


leading zeros for single digit days.
Day of the month as digits with leading
zeros for single digit days.
Day of the week as a three letter
abbreviation.
Day of the week as its full name.

dd
ddd
dddd

Month

05
Mon
Monday

ThemonthcanbedisplayedinoneoffourformatsusingcapitalM.Theletter
Mmustbeuppercasetodistinguishmonthsfromminutes.
Value

Meaning

Month as digits without leading zeros for 1


single digit months.
Month as digits with leading zeros for 01
single digit months.

MM

Example

46

Year

Value

Meaning

Example

MMM
MMMM

Month as a three letter abbreviation.


Month as its full name.

Jan
January

Theyearcanbedisplayedinoneofthreeformatsusinglowercasey..
Value

Meaning

Year represented only by the last digit, if 9


the year is less than 10. Years greater
than 10 will be given the value of yy.
Year represented only by the last two
09
digits.
Year represented by the full 4 digits.
1909

yy
yyyy

Period/Era

Theperiod/erastringcanbedisplayedinasingleformatusingtheletterg.The
lettergmustbelowercase.Ifyouincludethegginadatestringthatdoesnot
haveanyassociatedErastring,theggisignored.
Value

Meaning

(Null)

Gregorian dates are used. Does nothing if Gregorian is value of


iCalendarType
Period/era string. This is used by Windows to calculate the year when an
optional calendar is selected. See iCalendarType for optional Calendars.

gg

Time

Example

ThetimecanbedisplayedinoneofmanyformatsusingtheletterhorHto
denotehours,thelettermtodenoteminutes,theletterstodenoteseconds
andtheletterttodenotethetimemarker.Thelowercasehdenotesthe12
hourclockanduppercaseHdenotesthe24hourclock.Themmustbe
lowercasetodenoteminutesasopposedtoMonths.Thesforsecondsandt
forthetimemarkerstringmustalsobelowercase.
Value

Meaning

h
hh
H
HH
m
mm
s
ss
t

Hours without leading zeros for single digit hours (12 hour clock).
Hours with leading zeros for single digit hours (12 hour clock).
Hours without leading zeros for single digit hours (24 hour clock).
Hours with leading zeros for single digit hours (24 hour clock).
Minutes without leading zeros for single digit minutes.
Minutes with leading zeros for single digit minutes.
Seconds without leading zeros for single digit seconds.
Seconds with leading zeros for single digit seconds.
One character time marker string. This will be the first letter of the values in
the AM symbol or PM symbol boxes in Regional Options
Multi-character time marker string. This will be values in the AM symbol or
PM symbol boxes in Regional Options

tt

Example
1
01
1
01
9
09
5
05
A
AM

47
See Also

DateHandling
DateConstants
DateandTimeDataConstraints

Date and Time Data Constraints


CitectVBAhasseveralconstraintsondateandtimevaluesbaseduponthe
GregorianCalendar:

See Also

Thevalueofthemonthfieldmustbebetween1and12,inclusive.

Thevalueofthedayfieldmustbeintherangefrom1throughthenumber
ofdaysinthemonth.Thenumberofdaysinthemonthisdeterminedfrom
thevaluesoftheyearandmonthsfieldsandcanbe28,29,30,or31.(The
numberofdaysinthemonthcanalsodependonwhetheritisaleapyear.)

Thevalueofthehourfieldmustbebetween0and23,inclusive.

Thevalueoftheminutefieldmustbebetween0and59,inclusive.

Forthetrailingsecondsfieldofintervaldatatypes,thevalueoftheseconds
fieldmustbebetween0and59.9(n),inclusive,wherenisthenumberof
digitsinthefractionalsecondsprecision.

Forthetrailingsecondsfieldofdatetimedatatypes,thevalueoftheseconds
fieldmustbebetween0and61.9(n),inclusive,wherenspecifiesthenumber
of9digitsandthevalueofnisthefractionalsecondsprecision.(Therange
ofsecondsallowsasmanyastwoleapsecondstomaintainsynchronisation
ofsiderealtime.)

DateHandling
DateConstants
FormattingDateValues
DateDataTypeStructure
DatesinDatabasesUsingDifferentCalendars

Date Data Type Structure


ThedatedatatypestructureinCitectVBAisajunctionoftwoverydifferent
methodsofdatastorage.Itisformedfromtheserialconcatenationofadate
valuefollowedbyatimevalue,separatedbyafloatingpoint,andstoredinan8
bytefloatingpointdatedatatypevalue.

Theinteger(whole)portionofthevaluerepresentsthenumberofdays
elapsedsinceDecember30,1899.

Theremainder(fractional)portionofthevaluerepresentstheelapsed
portionofthedaysincemidnight.

48
Theinteger(datevalue)portion(totheleftofthefloatingpoint)andthe
remainder(timevalue)portion(totherightofthefloatingpoint)mustbe
handleddifferentlyastheyarestructuredverydifferently.CitectVBAhasa
numberofpredefineddateandtimefunctionstoconvertbetweentheinternal
floatingpointdatedatatypeformatandvisiblyrecognisabledatesandtimes.
Note:DatesinCitectVBAarebasedupontheGregorianCalendar.
Forexample,thedateandtimeof5/22/97at3:00p.m.wouldbestoredin
CitectVBAas35572.625representingthe35572dayssince12/30/1899,and3:00
p.m.as625/1000ofafullday.
Note:DontconfuseDatedatatypesusedinCitectVBAwithdateandtime
valuesusedinWindows,DLLs,VijeoCitect,orinCicode.Forinstance,Vijeo
Citectstorestime/daterelatedvariablesasasingleintegerrepresentingthe
numberofsecondssince01/01/1970.

Date-values
AdatevalueinCitectVBAisacountofthenumberofdaysfromDecember30,
1899.December31,1899hasthedatevalueof1,andthe1stJanuary1900is2.
December30,1899hasthedatevalueofzero.Negativedatevaluesrepresent
datespriortoDecember30,1899.
AdatevalueinCitectVBAcanactuallyrangefromJanuary1,0100,toDecember
31,9999inclusive,whichisaintegervaluerangingfrom657434upto+2958465
respectively.UsingvaluesoutsidethisrangewillcauseerrorsinCitectVBA.
ThepredefinedCitectVBAYear,Month,andDayfunctionscalculateandreturn
theappropriateyear,monthordayvalue(asaninteger)fromadatevalue.

Time-values
AtimevalueinCitectVBArepresentsthefractionaltimeofdaysincethe
previousmidnight.Unlikeadatevaluewhichissimplyacountofthenumber
ofdays,thetimevalueisadecimalfractionofaday.
Aseverydayinvariablyconsistsof24hours,or1440minutes,or86,400seconds,
thetimeofdaycanbereadilydeterminedfromatimevalueusingsimplemath.
Anhourhasthetimevalueofonetwentyfourthofoneday(0.0416),one
minutehasthetimevalueof0.000694,andasecondhasthetimevalueof
0.00001157407.Middayhasthetimevalueof0.50.1AMhasthetimevalueof
0.0416.1PMhasthetimevalueof0.5416.
ThepredefinedCitectVBAHourfunction,Minutefunction,andSecond
functioncalculatesandreturnstheappropriatehour,minuteorsecondvalue(as
aninteger)fromatimevalue.
See Also

DateHandling

49
DateConstants
FormattingDateValues
DatesinDatabasesUsingDifferentCalendars
DateandTimeDataConstraints

Dates in Databases Using Different Calendars


Ifyouuseanexistingdatabasewithdatereferencesofadifferentcalendartype
thanyourcurrentoperationsystemlocalitysettings,CitectVBAcouldreporta
varietyoferrorsorotherunexpectedbehaviours.Forexample,ifyouhaveused
HijriCalendardatesinyourdatabase,asyntaxerrormessagewilloccurif
CitectVBAmakesreferencetoGregoriandatesthatareinvalidHijridates(for
example,the31stofanymonthwillproduceasyntaxerrorbecausenoHijri
monthhas31days).
Toavoidproblemsofthissort,alldatereferencesinanexternaldatabaseshould
bebasedontheGregorianCalendar,orthedatabasetablesmustbeexportedto
textfilesbeforeuseinVijeoCitect.DatesinMicrosoftAccessdatabasetables
exportedastextfilesarealwaysstoredasGregorianvalues.Ifthedatabase
calendarissettoHijriforexample,automaticHijritoGregorianconversionis
performedduringtheexportprocess.
YoucantsetadatabasecalendarprogrammaticallyusingCitectVBA.
Note:WhenyouwanttousecharactersforBaltic,CentralEuropean,Cyrillic,
Greek,Turkish,andAsianlanguages,orrighttoleftlanguages(Arabic,Hebrew,
Farsi,andUrdu)theoperatingsystemmusthavethecorrespondinglanguage
versionofWindows,orhaveinstalledsystemsupportforthatlanguage.
See Also

DateHandling

Operators
VariablescanbemanipulatedinCitectVBAusingassignment,arithmetic,
relational,andlogicaloperators.

Theassignmentoperatorisusedtoassignavaluetoavariableorconstant
(thatequalsthis).

Arithmeticoperatorsareusedtomathematicallymanipulatenumeric
variablesandnumbers(addition,subtraction,multiplication,division,etc.).

RelationalOperatorsareusedtocomparetherelationshipbetweenvariables
(lessthan,greaterthan,notequalto,etc.).

Logicaloperatorsareusedtoperformdigitallogicoperationsonvariables(
AND,OR,NOT,etc.).

50
WhenusingmultipleoperatorsinaCitectVBAstatement,anorderof
precedenceisrequiredtoensuretheoperationsoccurinaconsistentand
predictablemanner.
Thestringconcatenationoperatorisusedtojoinstringstogether.
See Also

Constants
Variables
Numbers
Strings
DateHandling
CitectVBAFunctionReference

Assignment Operator
TheCitectVBAassignmentoperatorusestheequalscharacter(=)ina
CitectVBAstatement.Thevariablenamedtotheleftsideoftheassignment
operatorisassignedtheoperandvaluefromtherightsideoftheassignment
operator,asshownhere:
' declares integer variable named X
Dim X As Integer
' declares integer variable named Y
Dim Y as Integer
X = 123' assigns numeric value 123 to variable X
Y = X' assigns value of variable X to variable Y

Onlyonevariablecanbeassignedatanyonetimewiththeassignmentoperator.
Theremustbeaspaceoneithersideoftheassignmentoperator,ortheequals
charactermaybeconfusedwitheitherthevariablenameorthevaluebeing
assigned,andacompileerrormayoccur.
Unlessthevariableisavariantdatatype,thevaluebeingassignedmustbethe
samedatatypeasthevariablereceivingtheassignedvalue.Forinstance,ifyou
assignatextstringintoalongdatatypevariable,youllcauseanerrortooccur.
Thevariablemustbepreviouslydeclaredbeforebeingassignedavalue.The
valueofavariablecanbechangedanynumberoftimesinalaterstatements,as
inthefollowingCitectVBAexample:
' declare integer variable named X
' and assign an initial numeric value of 123 to it
Dim X = 123 As Integer
' <statement>
' <statement>
' <statement>
' reassign X to store the numeric value 456
X = 456
' <statement>
' <statement>

51
' <statement>
' reassign X to store the numeric value 789
X = 789

See Also

Operators

Arithmetical (Math) Operators


CitectVBAarithmeticoperatorsareusedinCitectVBAstatementsto
mathematicallymanipulatenumericvariablesandnumbers.Theresultantis
oftenassignedtoathirdvariableusingtheassignmentoperator.
Thearithmeticoperationasdeterminedbythearithmeticoperatorisperformed
betweenthevaluesoftheoperands(variablesornumberspositioned
immediatelyoneithersideofthearithmeticoperator).

See Also

Operator

Function

Usage

^
*
/
Mod
+
-

Exponentiation
Negation
Multiplication
Division
Modulo
Addition
Addition

X=Y^2
X=-2
X=2*3
X = 10 / 2
X = Y MOD Z
X=2+3
X=64

Operators

Relational Operators
CitectVBARelationalOperatorsareusedinCitectVBAstatementstocompare
therelationshipbetweenoperands(valuespositionedimmediatelyoneither
sideoftheRelationalOperator).ThebooleanresultiseitherTrueorFalse..

See Also

Operator

Function

Usage

<
<=
=
>=
>
<>

Less than
Less than or equal to
Equals
Greater than or equal to
Greater than
Not equal to

X<Y
X <= Y
X=Y
X >= Y
X>Y
X <> Y

Operators

52

Logical Operators
Logical(boolean)operatorsareusedtoperformdigitallogicoperationson
variables.AlllogicaloperationsresultineitherabooleanTrueorFalse..

See Also

Operator

Function

Usage

Not
And
Or

logical negation
logical And
logical Or

if not X
If (X> Y) And (X < Z)
If (X = Y) Or (X = Z)

Operators

Operator Precedence
TheoperatorprecedenceinCitectVBArunslikethis:.

See Also

Operator

Description

Order

()
^
/, *
Mod
+, -, &
=, <>, <, >,<=,>=
Not
And
Or
Xor
Eqv
Imp

Parenthesis
Exponentiation
Unary minus
division/multplication
Modulo
addition, subtraction, concatenation
Relational
Logical negation
Logical conjunction
logical disjunction
logical exclusion
logical equivalence
logical implication

Highest

Lowest

Operators

Strings
StringscanbestoredinCitectVBAvariablesofstringandvariant.Whenusing
variantstrings,beawareoftypecoercioninCitectVBA.Stringscanbecompared
witheachotherinCitectVBAtodeterminewhethertheycontainthesame
charactersornot.Stringscanbejoinedtogethertocreatelongerstringsin
CitectVBAusingtheconcatenationoperator.
StringscanbesearchedinCitectVBAusingthe:

InStr()function,whichreturnsthecharacterpositionofthefirst

occurrenceofastringwithinanother;

53

Left()functionorRight()functionwhichreturnacopyoftheleftorright
mostcharactersofastringrespectively;and

Mid()function,whichreturnsthecopyofasubstringfromwithinanother

string.
Todeterminethelengthofastring,usetheCitectVBALen()functionwhich
returnsaLongvariablecontainingthenumberofcharactersinthestring.
StringcharacterscanbeconvertedtoASCIIvaluesusingtheCitectVBAAsc()
function,andASCIIvaluescanbeconvertedtotheirstringcharactersusingthe
Chr()Function.
Stringcharacterscanbeconvertedtoalllowercaseoralluppercaseusingthe
CitectVBALcase()FunctionortheUcase()Functionrespectively.
LeadingortrailingspacescanbestrippedoffstringsinCitectVBAusingthe
Ltrim()functionortheRtrim()functionrespectively.

Stringscanbecreatedconsistingofaspecifiednumberofspacesorcharacters
usingtheSpace()functionortheString()functionrespectively.
ForsyntaxdetailsofusingstringfunctionsinCitectVBA,seeStringFunctions.
See Also

Operators
Numbers
ControlStructures

String Comparisons
CitectVBAcomparesANSIvaluesofcharacterswhencomparingstrings.For
example,thecharactercapitalAhastheANSIvalueof65,andthecharacter
lowercaseahastheANSIvalueof97.ForalistingofANSIcharactersvalues,
seeASCII/ANSICharacterCodeListings.
YoucanuseCitectVBArelationaloperators(lessthan,greaterthan,equalto,not
equalto,andsoon)tocomparestringvariables.Allrelationaloperatorsreturn
eithertrueorfalse.
Withcomparisonsmadeusingrelationaloperators,theresultdependsonthe
option comparestringcomparisonoptionsettingoftheCitectVBAfile.

Considerthefollowingexample:
"Citectvba" > "CitectVBA"

IfthefileOptionstringcomparisonsettingisOptionCompareBinary(ornotset
atall),thecomparisonreturnstrue.CitectVBAcomparesthebinary(ANSI)
valuesforeachcorrespondingpositioninthestringuntilitfindstwothatdiffer.
Inthisexample,thelowercaselettervcorrespondstotheANSIvalue118,
whiletheuppercaseletterVcorrespondstotheANSIvalue86.Because118is
greaterthan86,thecomparisonreturnstrue.

54
IfthefileOptionstringcomparisonsettingisOptionCompareText,Citectvba
>CitectVBAreturnsfalse,becausethestringsareequivalentapartfromcase.
ThebuiltinCitectVBAStrComp()Functionreturnsavariantcontainingavalue
representingtheresultofthecomparisonoftwostrings.Ithasanoptionalthird
argumentCompwhichcanoverridethefileOptionstringcomparisonsetting.
See Also

OptionComparestatement
Strings

String Concatenation
ToconcatenatestringsinCitectVBA,usetheampersand(&)concatenation
operatorbetweenthestrings.Multipleconcatenationscanoccurinthesame
CitectVBAstatement.
Dim strFirstName As String
Dim strLastName As String
Dim strFullName As String
Const strSpaceChar = " "
' note the space character between the quotes
strFirstName = "Colin"
strLastName = "Ramsden"
strFullName = strFirstName & strSpaceChar & strLastName
' concatenates string values

The&concatenationoperatordoesnotperformarithmetic,andwillconvert
variabledatatypestostringsforconcatenation.Forinstance,ifavariantstring
andavariantnumberareconcatenated,theresultisastring.Formoredetailsof
variantdatatypes,seeVariantDeclarationandCitectVBADataTypes.
See Also

Strings
Operators
ControlStructures

Control Structures
CitectVBAprovidesconditionalcontrolfunctionality,whichcanbeusedto
conditionallyperformCitectVBAstatementsorblocksofstatementsdependant
upontheresultoftheconditiontested.Thisisknownaslogicaldecisionmaking.
ThelogicaldecisionmakingcontrolstructuresavailableinCitectVBAconsistof
threeconditionalloopingorrepetitivestatements(DoStatement,While
Statement,andForStatement),andtwoconditionalflowcontrolsequence
statements(SelectCaseStatement,andvariationsoftheIfStatement).In
addition,CitectVBAprovidesoneunconditionalbranchingGoToStatement.
Note:Inthecontrolstructuresyntaxexamples,everyplaceholdershowninside
arrowbrackets(<placeholder>)shouldbereplacedinanyactualcodewiththe

55
valueoftheitemthatitdescribes.Thearrowbracketsandthewordtheycontain
shouldnotbeincludedinthestatement,andareshownhereonlyforyour
information.Also,statementsshownbetweensquarebrackets([ ] )are
optional.Thesquarebracketsshouldnotbeincludedinthestatement,andare
shownhereonlyforyourinformation.
See Also

GoTo statement

Operators
GoTostatement
Dostatement
Whilestatement
Forstatement
Ifstatement
Selectcasestatement
Endstatement
Exitstatement
OnErrorstatement
Stopstatement
Withstatement
CitectVBAFunctionReference
TheGoToconditionalstatementbranchesunconditionallyandwithoutreturnto
thelabelspecifiedintheGoTostatement.Thelabelmustbelocatedinthesame
subroutineorfunctionastheGotostatement.
<statement/s>
If <condition> then
GoTo Label1
Else
GoTo Label2
End If
Label1:
<statement/s>
GoTo Label3
Label2:
<statement/s>
GoTo Label3
Label3:
<statement/s>

Inthisexample,CitectVBAteststheIfcondition,andjumpstothepartofthe
scriptthatbeginswiththelabelLabel1:iftheconditionwastrue,orjumpsto
thepartofthescriptthatbeginswiththelabelLabel2:iftheconditionwas
false.Thiscouldbeanywhereinthesamesubroutineorfunction.
See Also

ControlStructures

56

Do statement

TheDo...Loopconditionalstatementallowsyoutoexecuteablockofstatements
anindefinitenumberoftimes.ThevariationsoftheDo...LoopareDoWhile,Do
Until,DoLoopWhile,andDoLoopUntil.
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>

DoWhileandDoUntilchecktheconditionbeforeenteringtheloop,thusthe
blockofstatementsinsidetheloopareonlyexecutedwhenthoseconditionsare
met.DoLoopWhileandDoLoopUntilchecktheconditionafterhaving
executedtheblockofstatementstherebyguaranteeingthattheblockof
statementsisexecutedatleastonce.
AnyDostatementcanbeexitedusingtheExitDostatement.
See Also

While statement

ControlStructures
TheWhile...WendloopconditionalstatementissimilartotheDoWhileloop
statement.Theconditionischeckedbeforeexecutingtheblockofstatements
comprisingtheloop.
While <condition>
<statement/s>
Wend

See Also

For statement

ControlStructures
TheFor...Nextloopconditionalstatementrepeatsitsblockofstatementsaset
numberoftimesasdeterminedbythevaluesusedwiththeToclause.
For <CounterName> = <BeginValue> To <EndValue> [Step <StepValue>]
<statement/s>
Next

Thecountervariableisincreasedordecreased(bythevaluestatedinthe
optionalStepparameter),witheachreiterationoftheloop.Thecounterdefault
istoincrementbyoneiftheStepparameterisomitted.
See Also

ControlStructures

57

If statement

TheIfstatementinCitectVBAtestsaninitialconditionandtheneitherperforms
oromitstoperformthestatementsitcontains,dependantuponthelogicalresult
ofthetestcondition.Theconditioncanbeacomparisonoranexpression,and
mustlogicallyevaluatetoeitherTrueorFalse.TheIfstatementhasbothsingle
lineandmultiplelinesyntaxstructure.
ThesinglelinesyntaxusestheIf<TestCondition>Then
<StatementToPerformIfTrue>structure,however,canonlyperformasingle
statementifandonlyifthetestconditionresultisTrue.NoEndIfstatementis
required:
If <Condition> Then <Statement>

IftheresultoftheIftestconditionwasTrue,theprogramflowcontinuesinto
andperformsthestatementfollowingtheThenstatement,untilitreachesthe
endoftheline.
ToperformasinglestatementconditionallyuponaFalseresult,usetheNOT
logicaloperator:
If NOT <Condition> Then <Statement>

Toperformmultiplestatements,usethemultiplelinesyntaxstructurewhich
endswiththeEndIfstatement:
If <Condition> Then
' Then statement block
' perform only if true
<Statement/s>
End If

IftheresultoftheIftestconditionwasTrue,theprogramflowcontinuesintothe
Thenstatementblock,andperformsthestatementsfollowingtheThen
statement,untilitreachestheEndIfstatement.
IftheresultoftheIftestconditionwasFalse,theprogramflowjumps
completelyovertheThenstatementblock,whichinthiscaseexitstheIf
structure(withoutperforminganystatementsotherthantheinitialtest
condition).
ThemutiplelineIfstructurecanperformdifferentblocksofstatements
dependantuponEITHERaTrueORaFalseresulttothetestcondition,through
theuseoftheElsestatementblock:
If <Condition> Then
' Then statement block
' perform only if true
<Statement/s>
Else
' Else statement block

58
' perform only if false
<Statement/s>
End If

IftheresultoftheIftestconditionwasTrue,theprogramflowperformsthe
Thenblockstatements,untilitreachestheElsestatement.Itthenjumps
completelyovertheElsestatementblockandexitstheIfstructure(without
performinganyoftheElsestatementblockstatements).
IftheresultoftheIftestconditionwasFalse,theprogramflowjumps
completelyovertheThenstatementblock(withoutperforminganyofthose
statements)totheElsestatementtoperformthestatementsintheElsestatement
blockuntilitreachestheEndIfstatement.
FurthertestconditionscanbeplacedintoanIfstructurethroughtheuseofthe
optionalElseIf<Condition>statementblock.ElseIfstatementblockscanonlybe
positionedwithinanIfstructurebeforetheElsestatementblock.
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

TheElseIftestconditionisonlyevaluatedaftertheinitialIfstructuretest
conditionresultsinFalse.
IftheresultoftheElseIftestconditionwasTrue,thestatementswithintheElseIf
statementblockareperformed.Theprogramflowthenjumpscompletelyover
theElsestatementblockandexitstheIfstructure(withoutperforminganyofthe
Elsestatementblockstatements).
IftheresultoftheElseIftestconditionwasFalse,theprogramflowjumps
completelyovertheElseIfstatementblock(withoutperforminganyofthose
statements)totheElsestatementtoperformthestatementsintheElsestatement
blockuntilitreachestheEndIfstatement.
ThereisnoapparentlimittothenumberofElseIfstatementblocksthatanyone
Ifstructurecanhold,however,theSelectCaseStatementstructurehandles
multipleconditionresultalternativesmuchmoreefficiently.
See Also

ControlStructures

59

Select case statement

TheSelectCasestatementteststhesamevariableformanydifferentconditions.
ThetestvalueprovidedwiththeinitialSelectCasestatementislogicallytested
againsttheCasetestcondition.
TheSelectCasestructurecanperformdifferentblocksofstatementsdependant
uponwhicheverCasestatementtestcondition(ifmorethanone)firstresultsas
True,throughtheuseoftheCasestatementblock:
Select Case <TestValue>
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

IftheresultoftheCasetestconditionwasTrue,theprogramflowperformsthe
statementscontainedwithinthatCasestatementblock,andwillthenexitthe
SelectCasestructure(withoutperforminganyoftheElsestatementblock
statements).
IftheresultoftheCasetestconditionwasFalse,theprogramflowjumps
completelyovertheCasestatementblock(withoutperforminganyofthose
statements)totheCaseElsestatementtoperformthestatementsintheElse
statementblockuntilitreachestheEndSelectstatement.
FurthertestconditionscanbeplacedintoaSelectCasestructurethroughthe
optionaluseoffurtherCasestatementblocks.Casestatementblockscanonlybe
positionedwithinaSelectCasestructurebeforetheCaseElsestatementblock.
Select Case <TestValue>
Case <Condition>
' Case statement block
' perform only if case true
<Statement/s>
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

EachCasestatementblockisevaluatedinorderuntilthetestconditionofone
resultsasTrue.Theprogramflowperformsthestatementscontainedwithinthat

60
Casestatementblock,andwillthenexittheSelectCasestructure(without
performinganyotherstatements).
ThestatementsofONLYoneCasestatementblockareeverperformed,unlessall
resultinFalseandthereisnoCaseElseblockdeclared,inwhichcasenoCase
statementblocksareperformedatall.
Thefollowingexamplemayhelpclarifythelogictestingbeingperformedina
SelectCasestructure.Letssaythatwehaveavariablenamed(intDayOfWeek)
containinganinteger(rangingfrom1to7)representingthedayoftheweek,and
wewishedtodisplaythatvalueasastring(namedstrDayOfWeek)containing
thenameofthedayoftheweek,assuminginthisexample,thatSundayisthe
firstdayoftheweek(1).TheSelectCasestructurewouldlooklikethis:
Dim strDayOfWeek As String
Select Case intDayOfWeek
Case = 1
StrDayOfWeek = "Sunday"
Case = 2
StrDayOfWeek = "Monday"
Case = 3
StrDayOfWeek = "Tuesday"
Case = 4
StrDayOfWeek = "Wednesday"
Case = 5
StrDayOfWeek = "Thursday"
Case = 6
StrDayOfWeek = "Friday"
Case = 7
StrDayOfWeek = "Saturday"
Case Else
StrDayOfWeek = "Invalid"
End Select

TheSelectCasestructuretendstobeeasiertoread,understand,andfollowand
shouldbeusedinplaceofacomplicatedmultinestedIf...ElseIfstructure.
See Also

End statement

ControlStructures
TheEndstatementEndsablockofstatementssuchasaSubprocedureor
Function.
End[{Function | If | Sub}]

Example

Dim Var1 as String


Var1 = "hello"
' Calling Test
Test Var1
MsgBox Var1

61
Sub Test(wvar1 as string)
MsgBox wvar1
wvar1 = "goodbye"
End
End Sub

See Also

Exit statement

ControlStructures
Exitsalooporprocedure
Exit {Do | For | Function | Sub }

Example

See Also

OnError statement

' 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

ControlStructures
CitectVBAserrorhandlingroutineandspecifiesthelinelabeloftheerror
handlingroutine.Thelineparameterreferstoalabel.Thatlabelmustbepresent
inthecodeoranerrorisgenerated.
On Error { GoTo line | Resume Next | GoTo 0 }

ExampleExample

See Also

Stop statement

On Error GoTo errHandler


Dim x as object
x.draw ' Object not set
jpe ' Undefined function call
print 1/0 ' Division by zero
Err.Raise 6' Generate an "Overflow" error
Exit Sub
errHandler:
Print Err.Number, Err.Description
Resume Next

ControlStructures
Endsexecutionoftheprogram.TheStopstatementcanbeplacedanywherein
yourcode.

Example

Dim x,y,z
For x = 1 to 5
For y = 1 to 5

62
For z = 1 to 5
Print "Looping",z,y,x
Next z
Next y
Stop
Next x

See Also

With statement

ControlStructures
TheWithStatementisnotsupportedinCitectVBA.Whenperformingaseriesof
commandsonanobject,youmustexplicitlyrefertothenameoftheobjectwith
eachcommand.

See Also

ControlStructures

Subroutines and Functions


CommonlyusedsequencesofCitectVBAstatementscanbegroupedtogether
intofunctionsandsubroutines,sothattheycanbekeyedinonce,andused
manytimesinmanyplaces,bycallingthenameofthesubroutineorfunctionin
code.
Asubroutineorfunctionisagrouporlistofsequentialstatementsthat
CitectVBAcanperform(execute)inthelogicalorderthattheyexistwithinthe
subroutineorfunctionfromtoptobottomintheordertheyarelistedwithinthe
functionorsubroutine.
Ifthegroupofstatementsreturnsavalue,itmustbedeclaredasafunction.Ifit
doesnotreturnavalue,itmustbedeclaredasasubroutine.Asubroutineor
functioniscalledbyplacingthenameofthesubroutineorfunctioninacode
statementwhereyouwanttheactionofthesubroutineorfunctiontooccur.
Note:Subroutinesandfunctionscancontainstatementsthatcallother
subroutinesorfunctions(toperform,beforereturningtothefollowing
statementswithinthecallingsubroutineorfunction).
Bothsubroutinesandfunctionscansimilarlybepassedvaluesasarguments
whentheyarecalled:

ArgumentsarepassedtosubroutinesinCitectVBAcodefollowingthe
subroutinenameandseparatedbyspacecharacters.

Argumentsarepassedtofunctionsenclosedwithinparenthesesin
CitectVBAcode,similarlyfollowingthesubroutinenameandseparatedby
spacecharacters.

Note:VijeoCitecttagvaluesmustbedeclaredbyvaluewhenpassedas
argumentvaluestoaCitectVBAprocedurefromwithinaVijeoCitectcommand
orexpressionfield(seePassingvariablesByrefandByval).
See Also

Subroutines

63
Functions
Arguments

Subroutines

ACitectVBAsubroutinestartswiththeSUBstatementandfinisheswiththe
ENDSUBstatement.AllotherstatementsthatliebetweentheSUBandEND
SUBstatements,willbeexecutedbythesubroutine,whencalledtodoso.
Note:Inthefollowingsubroutinesyntaxexample:

Everyplaceholdershowninsidearrowbrackets(<placeholder>)shouldbe
replacedinanyactualcodewiththevalueoftheitemthatitdescribes.The
arrowbracketsandthewordtheycontainshouldnotbeincludedinthe
statement,andareshownhereonlyforyourinformation.

Statementsshownbetweensquarebrackets([])areoptional.Thesquare
bracketsshouldnotbeincludedinthestatement,andareshownhereonly
foryourinformation.

InCitectVBA,SubroutinesarecreatedwiththeSUBstatementinthefollowing
format.
Sub <SubName> ( [ Byval ] [ <Argument/s> ] [ <As Data Type> ])
<statement>
<statement>
<statement>
End Sub

where:

[Byval]istheoptionalparameterfortheargument;

Subistherequiredsubroutinestatementbasickeyword

<SubName>representstherequirednameofthesubroutinebeingcreated

<Argument/s>representstheoptionalargument/softhesubroutine

<statement>representstheexecutableCitectVBAscriptstatement/s

EndSubisthesubroutineterminatingstatement

ThenamegiventothesubroutineimmediatelyfollowstheSUBkeyword,andis
usedtoidentifythesubroutinetoCitectVBA.Thisnameisreferredtowhenthe
subroutineiscalledupon(called)tobeexecuted(performthestatementsit
contains)bysomeotherprocedureinCitectVBA.
SubroutinenamescancontainthelettersAtoZandatoz,theunderscore_
anddigits0to9.Thesubroutinenamemustbeginwithaletter,benolonger
than40characters,cannotcontainthespacecharacter,andcannotbeareserved
word.Subroutinenames(oncedeclared),becomeakeywordinCitectVBA.Like
mostkeywordsinCitectVBA,thesenamesarenotcasesensitive.

64
Thesubroutinenamealwaysendswithapairofparentheses()whichmayor
maynotcontainoneormoreargumentsrequiredby(necessaryforusein)the
subroutine.Multipleargumentsifused,areseparatedbycommas(,).Seethe
sectiontitledArgumentsinCitectVBAformoredetailsandargumentsyntax.
AllthelineslocatedbetweentheSUBandtheENDSUBstatements,containthe
statementsthatwillbeexecutedwhenthesubroutineiscalledinCitectVBA.
Thesestatementswillbeexecutedoneatatimeinlogicalorderfromtopto
bottomwithinthesubroutine.
See Also

Functions

SubroutinesandFunctions
Functions
Arguments
ACitectVBAfunctionstartswiththeFUNCTIONstatementandfinisheswith
theENDFUNCTIONstatement.Allotherstatementsthatliebetweenthe
FUNCTIONandENDFUNCTIONstatements,willbeexecutedbythefunction,
whencalledtodoso.
Note:Inthefollowingfunctionsyntaxexample:

Everyplaceholdershowninsidearrowbrackets(<placeholder>)shouldbe
replacedinanyactualcodewiththevalueoftheitemthatitdescribes.The
arrowbracketsandthewordtheycontainshouldnotbeincludedinthe
statement,andareshownhereonlyforyourinformation.

Statementsshownbetweensquarebrackets([])areoptional.Thesquare
bracketsshouldnotbeincludedinthestatement,andareshownhereonly
foryourinformation.

AtypicalCitectVBAfunctionisstructuredlikeinthefollowingexample:
Function <FunctionName> ( [ Byval ] [ <Argument/s> ] ) [ As
<ReturnDataType> ]
<statement>
<statement>
<statement>
[ <FunctionName> = <value> ]
End Function

where:

Functionistherequiredfunctionstatementbasickeyword

[Byval]istheoptionalparameterfortheargument;

<FunctionName>representstherequirednameofthefunctionbeingcreated

(<Argument/s>)representstheoptionalargument/softhefunction

<ReturnDataType>representstheoptionalreturndatatypeofthefunction

<statement>representstheexecutableCitectVBAscriptstatement/s

65

=<value>representstheoptionalassignmentofthereturnvalueforthe
function

EndFunctionisthefunctionterminatingstatement

Thenamegiventothefunction,immediatelyfollowstheFUNCTIONkeyword,
andisusedtoidentifythefunctiontoCitectVBA.Thisnameisreferredtowhen
thefunctioniscalledupon(called)tobeexecuted(performthestatementsit
contains)bysomeotherprocedureinCitectVBA.
FunctionnamescancontainthelettersAtoZandatoz,theunderscore_
anddigits0to9.Thefunctionnamemustbeginwithaletter,benolongerthan
40characters,cannotcontainthespacecharacter,andcannotbeareservedword.
Functionnames(oncedeclared),becomeakeywordinCitectVBA.Likemost
keywordsinCitectVBA,thesenamesarenotcasesensitive.
Thefunctionnamealwaysendswithapairofparentheses()whichmayormay
notcontainoneormoreargumentsrequiredby(necessaryforusein)the
function.Multipleargumentsifused,areseparatedbycommas(,).Seethe
sectiontitledArgumentsinCitectVBAformoredetailsandargumentsyntax.
AllthelineslocatedbetweentheFUNCTIONandtheENDFUNCTION
statements,containthestatementsthatwillbeexecutedwhenthefunctionis
calledinCitectVBA.Thesestatementswillbeexecutedoneatatimeinlogical
orderfromtoptobottomwithinthefunction.
Thereturnvalueofthefunctionisoptionallyassignedwithinthefunctionina
statementusingthefunctionname.Thisvalueisoftenusedwithinthecalling
proceduretodeterminethestatusofthefunction.Commonly,thisvaluemaybe
aBooleanTrueorFalsetoindicatethesuccessfulcompletionornotofthe
function.
See Also

Arguments

SubroutinesandFunctions
Arguments
Subroutines
AccessingFunctionsinDLLs
ArgumentsareusedinCitectVBAtopassvaluesintosubroutinesandfunctions
whentheyarebeingcalled.Argumentsarepositionedbetweenparentheses()
immediatelyafterthesubroutineorfunctionnameinthesubroutineorfunction
declaration.Ifnoargumentsarerequiredforthesubroutineorfunction,the
parenthesesmustbeincludedandleftemptyinthedeclaration.
Argumentsareoptionalinthesensethatsubroutinesandfunctionsdonot
requirethem.However,ifargumentsaretobeusedinasubroutineorfunction,
theargumentsmustfirstbedeclaredwiththesubroutineorfunction
declaration,beforetheycanbeused.Ifdeclared,theymustbeusedwhenever
thesubroutineorfunctioniscalled.

66
CitectVBAdoesNOTsupportnamedargumentssoallargumentsmustbeused
indeclarationorder.Ifomitted,stringsdefaulttoanemptystring(),and
numericvaluesdefaulttozero(0).BooleanvaluesinCitectVBAarerepresented
with1forTRUE,and0forFALSE.
Multipleargumentsmustbeseparatedbyacomma(,)placedbetweenthe
arguments.Thenumberofargumentsthatcanbeusedinanysinglesubroutine
orfunctionisnotstated,(butlikelylimitedtosomethinglike255).Ifyouare
declaringasubroutineorfunctionwiththatmanyarguments,youshould
probablysplityoursubroutineorfunctionintosmallerseparatelogicalroutines
withlessargumentsforeachroutine.Ifanargumentisomitted,itsplacemustbe
declaredbytheuseofacommainthecall.
IfyouwanttousethevalueinaVijeoCitecttagasanargumenttoafunctionor
subroutine,youmustassignthevalueofthetagtoaCitectVBAvariable,and
thenpassthevariableastheargument.YoucannotpassaVijeoCitecttagname
asanargumenttoafunctionorsubroutine.
Eachargumentdeclarationinasubroutineorfunctionmustbestructuredusing
theproperCitectVBAargumentsyntaxasdescribedbelow.
CitectVBAargumentstructuresyntaxinthedeclarationoffunctionsor
subroutinesisasfollows:
( [ Byval ] <Argument/s> [ As <DataType> ] )

where:

[Byval]istheoptionalparameterfortheargument.

<Argument/s>representstheargument/srequiredbythefunctionor
subroutine.

[As<DataType>]representstheoptionaldatatypedeclarationofthe
argument.

TheoptionalByvalparameterspecifiesthatthevariableispassedbyvalue
insteadofbyreference(seethesectiontitledPassingVariablesByrefandByval
withCitectVBA).
Note:VijeoCitecttagvaluesMUSTbedeclaredbyvaluewhenpassedas
argumentvaluestoaCitectVBAprocedurefromwithinaVijeoCitectcommand
orexpressionfield.Thisisbestdonebydeclaringavariable,assigningitthetag
value,thenpassingthevariablebyvalue.
Thefunctionorsubroutinenamealwaysendswithapairofparentheses()
whichmayormaynotcontainoneormoreargumentsrequiredby(necessary
forusein)thefunctionorsubroutine.Multipleargumentsifused,areseparated
bycommas(,).
TheoptionalAs<DataType>parameterisusedtospecifythedatatypeofthe
argumentvariable.Theargumentdatatypesmustbeindividuallydeclared,or

67
willbeofVariantdatatypebydefault.Validdatatypesforargumentsin
CitectVBAare:String,Integer,Double,Long,andVariant(seethesectiontitled
CitectVBA_Data_TypesfordescriptionsofdatatypesinCitectVBA).
Example

' Arguments are declared with the function or subroutine


' The function is called from the subroutine highlighted below
Function longArea(Byval longLength As Long, _
Byval longWidth As Long) As Long
' multiplies arguments and
' assigns result to return value
longArea = longLength * longWidth
End Function
Sub FindArea
' declare long variables X Y and Z
Dim longX As Long
Dim longY As Long
Dim longZ As Long
'
X
'
Y

assign numeric value 12 to variable X


= 12
assign numeric value 34 to variable Y
= 34

' call function named longArea,


' passing in values of X and Y variables
' as arguments
'store result in variable Z
Z = longArea(X, Y)
' copy result Z to tag
TestTag_1 = Z
End Sub

Granted,thatsnotlikelythewayyoudactuallycalculateanareagiventwo
fixedvaluesinasubroutinethatcallsafunction.Youcouldjustaseasilydothe
calculationwithinthesubroutine.However,thisexampledoesdemonstratethe
passingofvaluesfromasubroutinetoafunction,andtheretrievalofareturn
valuefromthefunctionbacktothecallingsubroutine.
Noteinthepreviousexample,thattheargumentnames(longLengthand
longWidth)areonlyusedwithinthefunctioninwhichtheyweredeclared.The
valuestheyrepresentedwerepassedinwiththecalltothefunctioninthe
statementline:
Z = longArea(X, Y)

ThevaluesofthevariablesXandYwerepassedintothefunctionlongArea
andwerehandledwithinthefunctionasitsargumentnameslongLengthand
longWidth.TheresultwasreturnedandstoredinthevariablenamedZ.
See Also

SubroutinesandFunctions

68
Subroutines
Functions

DLLs and APIs


DynamicLinkedLibraries(DLLs)arefilesthatcontainfunctionswhichcanbe
calledfromanyapplicationrunningunderMicrosoftWindows.Atruntime,a
functioninaDLLisdynamicallylinkedintoanapplicationthatcallsit.No
matterhowmanyapplicationscallafunctioninaDLL,thatfunctionexistsin
onlyasinglefileonthecomputer,andtheDLLisloadedonlyonceinmemory.
Anapplicationprogramminginterface(API)isasetoffunctionsyoucanuseto
workwithacomponent,application,ortheoperatingsystem.TypicallyanAPI
consistsofoneormoreDLLsthatprovidesomespecificfunctionality.
Forexample,theWindowsAPIincludestheDLLsthatmakeuptheWindows
OperatingSystem(OS).EveryWindowsapplicationinteractswiththeWindows
APIdirectlyorindirectly.TheWindowsAPIisprovidedtoensurethatall
applicationsrunningunderWindowswillbehaveinaconsistentmanner.
Note:VijeoCitectitselfprovidesanAPIforexternalaccesstoVijeoCitectI/O
variabletagsviaaDLLinterface.
APIsaretraditionallywrittenforCandC++programmerswhoarebuilding
Windowsapplications,however,thefunctionsinaDLLcanalsobecalledby
otherprogramminglanguages,includingCitectVBA.BecausemostDLLsare
writtenanddocumentedprimarilyforC/C++programmers,callingaDLL
functionmaydiffersomewhatfromcallingaCitectVBAfunction.Inorderto
workwithanAPI,youneedtounderstandhowtopassargumentsfrom
CitectVBAtoaDLLfunction.SeePassingArgumentstoDLLFunctionsfrom
CitectVBA.
See Also

PassingvariablesByrefandByval
CitectVBAFunctionReference

Accessing Functions in DLLs


TobeabletocallanduseanexternalDLLfunctionusingCitectVBA,youmust
havepreviouslyprovidedCitectVBAwithdetailsaboutthefunctionbeing
called.CitectVBArequiresinformationlikethenameofthefunction,wherethat
functionislocated,whatargumentsitexpects,andwhattypeofdataitreturns.
CitectVBAusestheDeclarestatementtodetailthatinformation.
TheDeclarestatementmustbepositionedintheCitectVBAfileinyourproject
aboveandbeforeanycodethatcallsthatdeclaredfunctionoftheDLL.

Declare statement
structure

TheDeclarestatementconsistsoftherequiredDeclarekeyword,followedbythe
requiredFunctionstatement,therequiredLibstatement,theoptionalAlias

69
statement,theoptionalArgumentstatement(s)containedwithinbraces,andthe
optionalreturndatatypestatement.
Note:TheuseoftheOPTIONALcomponentsoftheDeclarestatementsyntax
indicatesthattheymaynotberequiredinallDLLfunctions.Itisnotuptoyou
whetheryoucanoptionallyusethemornot.IfincludedinaDLLfunction,they
MUSTbeusedwhendeclaringthatfunctiontoCitectVBA.
TheDeclarestatementinCitectVBAdetailsthename,filelocation,arguments,
intrinsicconstants,andtypedefinitionsthattheDLLfunctionrequires.Heres
anexampleoftheDeclarestatementfortheWindowsAPIGetTempPathA
function,whichreturnsthepathtotheWindowssystemtemporaryfolder:
Declare Function GetTempPathA Lib "kernel32" _
(Byval nBufferLength As Long, _
Byval lpBuffer As String) As Long

TheDeclarekeywordindicatestoCitectVBAthatyouintendtocallafunction
belongingtoanexternalDLL.TheDeclarekeywordmustbeusedfirstinthe
declarationstatement.
Declare - Function Statement
TheFunctionstatementconsistsoftheFunctionkeyword,followedbythename
thatyouwillusewhencallingthisfunctionfromCitectVBA.
Declare - Lib Statement
TheLibstatementspecifieswhichDLLcontainsthefunctionyouwishtouse.
TheLibstatementconsistsoftheLibkeyword,followedbythenameoftheDLL
containedwithinstringdoublequotes.SomecommonlyusedDLLsinthe
WindowsAPIforexample,areKernel32.dllwhichperformslowlevelOS
functionslikememorymanagementandresourcehandling,theUser32.dll
whichperformsWindowsmessagehandling,timers,menusand
communicationfunctions,andtheGDI32.dllwhichperformsthegraphics
displayandfontmanagementfunctions.
Declare - Alias Statement
InthepreviousDeclarestatementexample,thenameofthedeclaredfunctionin
CitectVBAisthesameasthenameoftheactualfunctionwithintheDLL.This
doesnotnecessarilyhavetobethecase.Therearesomeinstanceswherethe
nameofthefunctionintheDLLisincompatiblewiththenamingstructureof
CitectVBA,andcannotbeusedasadeclaredfunctionnameinCitectVBA.An
examplewouldbethoseDLLfunctionnamesthatstartwithanunderscore.
Toovercomesuchincompatibilites,theCitectVBADeclarestatementsupports
theuseofanaliasnamefortheDLLfunction,throughtheuseoftheoptional
Aliasstatement.TheAliasstatementconsistsoftheAliaskeyword,followedby
theactualnameoftheDLLfunctioncontainedwithinstringdoublequotes.The

70
AliasstatementmustbepositionedwithintheDeclarestatementbetweenthe
LibstatementandtheArgumentstatement.
HeresanexampleoftheDeclarestatementfortheWindowsAPI
GetTempPathAfunctionasusedabove,however,thistimeusingtheoptional
Aliasstatement:
Declare Function GetWinTempPath Lib "kernel32" _
(Byval nBufferLength As Long, _Alias "GetTempPathA" _
Byval lpBuffer As String) As Long

Inthisexample,thenameoftheAPIfunctionintheDLLisGetTempPathA,and
thenamebywhichyouwouldcallthisfunctionfromCitectVBAis
GetWinTempPath.NotethattheactualnameoftheDLLfunctionappears
containedwithinstringdoublequotespositionedaftertheAliaskeyword.This
instructsCitectVBAtousethealiasfunctionnamewhencallingtheDLL.
BecauseanaliasallowsyoutonameadeclaredDLLfunctionanythingyouwant
inCitectVBA,youcanmakethefunctionnameconformtoyourownnaming
standards.
Note:DLLfunctionsarecasesensitive;CitectVBAfunctionnamesarenot.When
declaringDLLfunctionsinCitectVBA,becarefultoaccuratelyremaincase
sensistiveinthedeclaration.
See Also

Passing variables Byref


and Byval

Functions
PassingvariablesByrefandByval
PassingArgumentstoDLLFunctionsfromCitectVBA
DLLsandAPIs
Passinganargumentbyreference(usingtheByrefparameter)passesapointer
tothememorylocationofthatargument.Apointerisjustamemoryaddress
thatindicateswherethevalueisstored.Iftheproceduremodifiesthat
argumentsvalue,itmodifiesthesourceofthatargument,sowhenexecution
returnstothecallingprocedure,thesourcecontainsthemodifiedvalue.
Passinganargumenttoafunctionbyvalue(usingtheByvalparameter),onthe
otherhand,passesacopyofthevalueastheargument.Thispreventsthat
functionfrommodifyingthesourceoftheargument.Whenexecutionreturnsto
thecallingprocedure,thesourcecontainsthesamevalueitdidbeforethe
functionwascalled.
TheByrefparameteristhedefaultinCitectVBAanddoesnotneedtobeused
explicitlywithinCitectVBA.Byrefgivesothersubroutinesandfunctions
permissiontomakechangestothesourceofthevaluesthatarepassedinByref.
ThekeywordByvaldeniesthispermissionsotheargumentsourcecannotbe
altered.
TherearetwopossiblemethodsforindicatingtoCitectVBAthatyouwishto
passanargumentbyvalue:

71

Whendeclaringtheargumentinthesubroutineorfunctiondeclaration
statement,byusingtheByvalkeywordplacedimmediatelybeforethe
argumentname.Thisensuresthatthesubroutineorfunctionwillalwaysuse
acopyoftheargumentpassedinandnotmodifythesource.Forexample,
thefollowingfunctionTestPassArghasdeclareditsfirstargumentintValas
beingrequestedByval.
Function TestPassArg(Byval intVal As Integer, varVal, strVal as
String)

Whenpassinganargumenttoasubroutineorfunction,byenclosingthe
individualargumentwithinparentheses.Onlythevalueoftheargument,
andnotitsaddressinmemory,ispassedtothesubroutineorfunction,once
againensuringthatthesourceoftheargumentisnotmodified.Forexample,
onlythevariablevar3ispassedbyvaluetothesubroutineTestPassArg
(becauseonlythatargumentisenclosedwithinparenthesesinthe
subroutinecall).
TestPassArg var1, var2, (var3)

Inthenextexample,theparameteriVarispassedbyvaluetothefunction
TestFunction.Sinceargumentspassedtofunctionsmustbeenclosedin
parentheses,anextrapairisusedtoforcetheargumenttobepassedby
value.
TestFunction((iVar))

Note:VijeoCitectdoesnotsupportpassingbyreference,soVijeoCitecttag
valuesMUSTbedeclaredbyvaluewhenpassedasargumentstoa
CitectVBAprocedurefromwithinaVijeoCitectcommandorexpression
field.Thisisbestdonebydeclaringthevariable,assigningitthetagvalue,
thenpassingthevariablebyvalue.(SeetheExamplebelow.)
Example

SupposeyouhadavariabletagofintegertypenamediTag1andyouneedto
passittoafunction.FromwithinaCitectVBAscript,orVijeoCitectcommandor
expressionfield,youwouldusethefollowingcodeexampletopassthevariable
tagvaluetoafunctionnamedTagArgumentTest:
CiVBA
Dim iVar1 as Integer
iVar1 = iTag1
TagArgumentTest(iVar1)

Note:Cicodedoesnotsupportpassingbyreference,soCitectVBAvariables
passedtoCicodefunctionsusingtheCicodeCallOpenfunctionmustbe
enclosedinbracketstoforcethepassingofthosevariablesbyvalue.
See Also

PassingArgumentstoDLLFunctionsfromCitectVBA
DLLsandAPIs

72
Arguments

Passing Arguments to DLL Functions from CitectVBA


ManyargumentstoDLLfunctionsarepassedbyvalue.Bydefault,argumentsin
CitectVBAarepassedbyreference,soitsimperativethatyouincludetheByval
keywordinthefunctiondefinitionwhentheDLLfunctionrequiresthatan
argumentbepassedbyvalue.SeePassingvariablesByrefandByval.
Note:AlthoughtheByvalkeywordappearsinfrontofsomeargumentsoftype
String,stringsarealwayspassedtoWindowsAPIfunctionsbyreference,
thereforeanyDLLfunctioncanalwaysmodifyastringsourcedirectly.
DLLfunctionsdontreturnstringsinthesamewaythatCitectVBAfunctionsdo.
BecausestringsarealwayspassedtoDLLfunctionsbyreference,theDLL
functioncanmodifythevalueofthestringargument.Ratherthanreturninga
stringasthereturnvalueforthefunction,asyouwouldprobablydoin
CitectVBA,aDLLfunctionreturnsastringintoanargumentoftypeStringthat
waspassedtothefunction.Theactualreturnvalueforthefunctionisoftena
longintegerspecifyingthenumberofbytesthatwerewrittenintothestring
argument.
TocallaDLLfunctionthatwritestoaStringvariable,youneedtotake
additionalstepstoformatthestringproperly.Firstofall,theStringvariable
mustbeanullterminatedstring.Anullterminatedstringendsinaspecialnull
character.Secondly,aDLLfunctioncantchangethesizeofastringonceithas
beencreated.
Therefore,youneedtomakesurethatthestringthatyoupasstoafunctionis
largeenoughtoholdtheentirereturnvalue,andthatitterminateswithaNull
character.WhenyoupassastringtoaDLLfunction,youllusuallyneedto
specifythesizeofthestringthatyouvepassedinanotherargument.Windows
keepstrackofthelengthofthestringtoensurethatitdoesntoverwriteany
memorythatthestringisusing.
Note:Itsonlynecessarytopassinanullterminatedstringanditssizeifyoure
returningastringfromafunction.Ifthefunctiondoesnotreturnastringintoa
stringargument,butinsteadtakesastringthatprovidesinformationtothe
function,youcansimplypassinanormalCitectVBAStringvariable.
ANullstringisastringofvalue0[noCharactercode];notethatthisisnotthe
sameasanemptystring().
See Also

DLLsandAPIs
Arguments
PassingvariablesByrefandByval

73

OLE Services
OLE(ObjectLinkingandEmbedding)servicesisthetermusedtogenerally
describetheintegrateduseofseparatesoftwarecomponents(applications)
workingtogethertoprovidecustomsoftwaresolutionsbaseduponthe
MicrosoftComponentObjectModel(COM)architecture.
WhenconsideringtheuseofOLEservices,youshouldbeawarethatthereare
differentusesofOLEwhichhavedevelopedovertheyearsandwhichmaybe
confusedwithoneanother.ExamplesofdifferentOLEservicesinclude:object
linking,objectembedding,visualediting,draganddrop,ActiveXControls,
OLEAutomation,OLEDB,OLEMessaging,andOLENetworkingservices.See
OLEterminology.
VijeoCitectsupportslinkedandembeddedOLEobjectsinitsgraphicspages
withtheuseofActiveXControls.SeeAccessingActiveXObjectswith
CitectVBA.
VijeoCitectcanuseCitectVBAtoperformasanOLEAutomationcontroller.See
OLEautomationobjects.VijeoCitectcanalsoexchangedatawithother
applicationsusingotherdatatransfertechnologies.

OLE terminology

OLEsupercededtheDynamicDataExchangeprotocol.NetworkDDEwas
introducedtoaffordthesamedatatransferfacilitybetweenWindows
applicationsconnectedacrossthesamenetwork.VijeoCitectsupportsbothDDE
andNetworkDDEconnectivity.
OLE Linking and Embedding
Thedifferencesbetweenlinkedobjectsandembeddedobjectswhichmayaffect
you,concernwherethedataisstored,andhowitisupdatedafteryouplaceitin
thedestinationfile.WithlinkedOLEobjects,thesourceoftheOLEobjectdata
remainsintheoriginaldatafileoftheapplicationthatwasusedtocreateit,and
onlyacopyofthedataiseverdisplayedinthedestinationdocument.Thedatais
updatedonlywhenthesourcefileismodified.EmbeddedOLEobjectsduplicate
andstorealocalcopyofthesourcefiledatawithinthedestinationdocument
datafile,andarenotlinkedtothesourcefile.Thatis,thedatacopyinthe
destinationfiledoesnotchangewhenyoumodifythesourcefile.
WithbothlinkedandembeddedOLEobjects,whentheOLEobjectinthe
destinationdocumentisdoubleclicked,theoriginalapplication(thatwasused
tocreatethedata)oftheOLEobjectislaunchedtopermiteditingofthedata
usingthatsourceprogramseditor.LinkedOLEobjectsstoretheirdatabackin
theoriginalsourcedatafiles,whilstembeddedOLEobjectsstoretheirdatain
thedestinationprogramdatafiles.
OLE Automation
OLEAutomationwasdevelopedtopermitthe(remote)controlofother
applicationsonthesamecomputer.Applicationswhichexposetheir

74
functionalityusingOLEAutomationareknownasOLEAutomationservers,
andcouldbeautomatedbycoderunninginacompletelyseparateapplication,
knownasOLEAutomationclientsorcontrollers.
OLEAutomationserversexposedtheirfunctionalitythroughstructuredobject
models,whicharelistingsoftheinternalfunctions,methodsandpropertiesof
theapplicationobject.AllMicrosoftOfficeapplicationsareOLEAutomation
serverstosomeextent,andcanbesubsequentlycontrolledbyanyOLE
Automationcompliantcontroller,usingtheappropriatesyntaxtomanipulate
andcontroltherelevantapplicationobjectmodel.
NotallapplicationsthatsupportOLEservicessupportOLEAutomation.For
example,manyproductssupportdraganddrop,andobjectlinkingand
embedding,butdonotsupportOLEAutomation.Linkingandembeddingallow
theusertoaccesstheobject,whereasOLEAutomationallowsoneapplicationto
controlanotherapplication,possiblywithminimalornouserinteraction.
See Also

OLE automation objects

OLEServices
CitectVBAsupportsthereferencingandcontrolofOLEAutomationobjectsof
externalapplications,permittingyoutousetheproperties,methodsandevents
ofthoseobjectsfromwithinVijeoCitect.
ToaccessanOLEAutomationobjectusingCitectVBA,youmustfirstdeclarean
objectvariableinyourCitectVBAcode,thenassignanOLEAutomation
referencetothevariable.SeeDeclarationofOLEAutomationobjectsin
CitectVBA,andAssigningreferencestoOLEAutomationobjectsinCitectVBA.
ObjectsdeclaredinaCitectVBASuborFunctionprocedurearelocaltothat
procedure,andtheirlifetimeendsalongwiththeendoftheprocedure.An
objectdeclaredoutsideaprocedurehasmodularscopetoallprocedureswithin
thesameCitectVBAfilemoduleandlastsforthelifetimeofthevariablethat
retainsthereferencetotheobject.
Allobjectreferencesmustbedeletedwhentheyarenolongerrequired,to
releasethememorytheywereusing.
WhenconsideringtheuseofOLEAutomation,youshouldbeawarethatthere
aredifferentusesofOLEwhichhavedevelopedovertheyearsandwhichmay
beconfusedwithoneanother.

See Also

Declaration of OLE
automation objects

OLEServices
CitectVBAobjectscanonlybedeclaredandreferencedwithinCitectVBAfile
modules.CitectVBAmodularobjectshavemodularscopeandcannotbe
referenced(accessedandused)fromoutsidetheirCitectVBAmodule(file).
Note:CitectVBAobjectscannotbeuseddirectlyinVijeoCitectcommandor
expressionfields.

75
OncedeclaredwithinaCitectVBAmodule,CitectVBAobjectscanbereferenced
andusedinanyprocedurewithinthesamecodemodule.Anobjectdeclared
outsideofaprocedurehasmodularscopetoallprocedureswithinthatsame
CitectVBAmodule(file).ObjectsdeclaredwithinaSuborFunctionprocedure
havelocalscopeonlywithinthatprocedure.
Theobjectvariablemustbedeclaredbeforeitcanbeassignedanobject
reference.ObjectvariablesaredeclaredbytheDimStatementwiththeAsObject
CitectVBAdatatypeusingthefollowingsyntax:
Dim <VariableName> As Object

where:

DimistherequiredVariabledeclarationstatementBASICkeyword

<VariableName>representstherequirednameofthevariablebeing
declared(dimensioned)

AsObjectdeclaresthevariableasaCitectVBAobjectdatatype

Note:Theplaceholdershowninsidearrowbrackets(<placeholder>)shouldbe
replacedinanyactualcodewiththevalueoftheitemthatitdescribes.The
arrowbracketsandthewordtheycontainshouldnotbeincludedinthe
statement,andareshownhereonlyforyourinformation.
Forexample:
' create local variables to store object references
Dim objExcelApp As Object
Dim objWordApp As Object

Oncedeclared,youcanthenassignanOLEAutomationreferencetotheobject
variableinCitectVBA.
See Also

Assigning references to
OLE automation objects

DeletingOLEautomationobjects
UsingOLEautomationobjects
AnOLEAutomationobjectMUSTbedefinedbeforeitcanbeused.Once
defined(seeDeclarationofOLEAutomationobjectsinCitectVBA),youassign
anOLEAutomationreferencetotheobjectvariableinCitectVBAusingthe
CitectVBACreateObjectfunctionwithinaCitectVBASetstatementinthe
followingsyntax:
Set <objVarName> = CreateObject(<objClassName>)

where:

Setistherequiredreferenceassignmentstatementkeyword

<objVarName>representstherequirednameofthevariablereceivingthe
reference

76

CreateObject()functioncreatestheobjectoftheclasstypespecifiedinthe
argument

<objClassName>representstherequirednameoftheclassprovidingthe
object

TheobjectclassnamepassedastheargumenttotheCreatObjectfunction
usuallyconsistsofthefullyqualifiedclassnameoftheobjectbeingcreated,for
exampleWord.ApplicationorExcel.Application.
Example

' create variable to store object reference


Dim objExcelApp As Object
' create the app object and assign the reference
Set objExcelApp = CreateObject("Excel.Application")
' or
' create variable to store object reference
Dim objWordApp As Object
' create the app object and assign the reference
Set objWordApp = CreateObject("Word.Application")

Onceassigned,youcanthenusethatobjectvariableinyourCitectVBAcodeto
manipulatethereferencedobjectmodel.SeeUsingOLEautomationobjects.
Dependantobjects(whichcannotbecreatedindependantly)canbedrilled
downtoandsubsequentlyassignedfromexisting(externallycreatable)
independantobjects,byusingamethodofthehigherlevelobject.See
UnderstandingobjectmodelsinOLEAutomation.
Forexamplesofindependantobjects,MicrosoftExcelprovidesthe
Excel.Application,Excel.Sheet,andExcel.Chartexternallycreatableobjects
amongstothers,(twoofwhicharedemonstratedinOLEAutomationexample
usingtheMicrosoftExcelobject),andMicrosoftWordprovidesthe
Word.Application,Word.Document,andWord.Pictureexternallycreatable
objectsamongstothers(andisdemonstratedinOLEAutomationexampleusing
theMicrosoftWordobject).
See Also

Using OLE automation


objects

OLEautomationobjects
ThetrickwithsuccessfullyusingOLEAutomationisdeterminingwhatyoucan
andcantdowithit.Intheory,youcandoanythingtheOLEAutomationserver
applicationcando.However,inpractice,noteveryOLEAutomationserver
applicationexposesallofitsfunctionalitythroughitsOLEAutomation
interface.
YouhavetobeabletousethenativeprogramminglanguageoftheOLE
Automationserverapplicationinyourcode.Youalsoneedtoknowaboutthe
limitationsimposedbytheVijeoCitectoperatingenvironment,andits
implementationoftheCitectVBAprogramminglanguage.

77
CitectVBAdoesnotsupportearlybindingofOLEAutomationobjects,asthere
isnomechanismforprovidingareferencetotheobjecttypelibrary(likeyoucan
doinMicrosoftVisualStudio)untilruntime.So,CitectVBAcompileerrorscan
occurwithvalidVBAcodewhichmayworkwellinotherVBAsupporting
applications.MostportedVBAcodewillrequiresomemodificationtoovercome
suchlimitationsandperformasexpectedinCitectVBA.Forexample,CitectVBA
doesnotsupporttheuseofWithstatementsconcerningpropertiesormethods
ofanobject,yetdoessupporttheuseofForEachstatementswithobjectsina
collection.
CitectVBAdoesnotsupporttheuseofnamedargumentsusingthe:=named
argumentoperator(colonfollowedbyanequalsign).Nordoesitsupportthe
useofmissingargumentsusingplaceholdercommas,however,CitectVBAdoes
supporttheuseoftheemptykeywordinplaceofmissingarguments.
CitectVBAdoesnotsupportthepassingofSCADAvariabletagsbyreference,
however,thetagvaluecanbecopiedtoaCitectVBAvariable,anditcanbe
passedbyvalue.SeePassingVariablesByrefandByvalwithCitectVBA.
Tohelpovercometheseandotherdifficulties,youshouldknowhowtoaccess
theobjectmodeloftheOLEAutomationserverapplications.CitectVBAdoes
notsupporttheuseofapplicationdefinedobjecttypesnorintrinsicconstants
duetolatebindingoftheobjectmodel.CitectVBAsupportsonly10datatypes,
sobeawareofthepossibilityofdatabeinglostduetoroundingwhen
convertingbetweendifferentdatatypes.SeeRoundingNumbersinCitectVBA.
TomakefulluseoftheOLEAutomationobjectmodels,youshouldmake
yourselffamiliarwithObjectrelatedterms.SeeUnderstandingobjectmodelsin
OLEAutomation.
See Also

Accessing the object


model of OLE
automation server
applications

OLEautomationobjects
Duringthedevelopmentstageofyourproject,toaccesstheobjectmodelofany
OLEAutomationserverapplications,youmusthaveacopyoftheappropriate
applicationprograminstalledonthecomputeryouaredevelopingtheOLE
Automationcontrollerwith.
Equally,duringVijeoCitectruntime,theremustbeacopyoftheappropriate
applicationprograminstalledonthecomputeryouarerunningtheOLE
Automationcontrollerfrom.If,forexample,youwerecallingthecodewhich
createstheobjectfromsayabuttononagraphicspageonaVijeoCitectClient
machine,theappropriateapplicationprogrammustbeinstalledoneveryClient
machinewithaccesstothatgraphicspage,forthecodetowork(ifcalled)onthat
Clientmachine.
AlloftheMicrosoftOfficesuiteofproductssupporttheVBAlanguageinsome
manner,andexportanOLEAutomationobjecttypelibrarywhichyoucanview
anduse.SeeHowtoviewanOLEAutomationobjecttypelibraryfroma
MicrosoftOfficeproduct.

78
Also,theVBprogrammingIDEwithinVisualStudiocanbereferencedtoload
theappropriatetypelibraryasrequired.SeeHowtoviewanOLEAutomation
objecttypelibraryinVB.
Boththesesuitesprovideanobjectbrowserwhichyoucanusetoexplorethe
objectmodels.Youusethestructureoftheobjectmodeltoaccess,manipulate
andcontroltheOLEAutomationobjectusingCitectVBA.SeeUnderstanding
objectmodelsinOLEAutomation.
See Also

Understanding object
models in OLE
automation

OLEautomationobjects
ObjectsarethefundamentalbuildingblocksofOLEAutomation,andobject
modelsarearoadmaptotheobjectstructure.OLEAutomationusingCitectVBA
involvescreatingandmodifyingtheobjectsprovidedbyotherapplications
(externaltotheVijeoCitectapplication).Forinstance,everyelementof
MicrosoftWord(documents,tables,paragraphs,bookmarks,fieldsandsoon)
canberepresentedbyanobjectinCitectVBAusingOLEautomationwiththe
Wordobjectmodel.
What are objects and collections?
AnobjectrepresentsanelementoftheOLEAutomationapplication.A
collectionisanobjectthatcontainsseveralotherobjects,usuallyofthesame
type.Forexample,allthebookmarkobjectsinadocumentarecontainedina
singleBookmarkscollectionobjectoftheWordapplication.Usingappropriate
propertiesandmethods,OLEAutomationpermitsthemodificationofasingle
objectoranentirecollectionofobjects.
What is a property?
Apropertyisanattributeofanobjectoranaspectofitsbehavior.Forexample,
propertiesofaWorddocumentincludeitsname,itscontent,anditssavestatus,
aswellaswhetherchangetrackingisturnedon.Tochangethecharacteristicsof
anyreferencedobject,youchangethevaluesofitsproperties.
Tosetthevalueofaproperty,followthereferencetoanobjectwithaperiod,the
propertyname,anequalsign,andthenewpropertyvalue.Thefollowing
exampleturnsonchangetrackingintheWorddocumentnamedMyDoc.doc.
objWordApp.Documents("MyDoc.doc").TrackRevisions = True

Inthisexample,Documentsreferstothecollectionofopendocuments,andthe
nameMyDoc.docidentifiesasingledocumentinthecollection.The
TrackRevisionspropertyissetforthatsingledocument.
Youcanalsoreturninformationaboutanobjectbyreturningthevalueofoneof
itsproperties.ThefollowingexamplereturnsthenameoftheactiveWord
document.
docName = objWordApp.ActiveDocument.Name

79
Inthisexample,ActiveDocumentreferstothedocumentintheactivewindowin
Word.ThenameofthatdocumentisassignedtothevariabledocName.
Note:Somepropertiescannotbeset.TheHelptopicforeachpropertyindicates
whetheryoucansetthatproperty(readwrite),onlyreadtheproperty(read
only),oronlywritetheproperty(writeonly).AlsotheObjectBrowserinthe
VisualBasicEditordisplaysthereadwritestatusatthebottomofthebrowser
windowwhenthepropertyisselected.
What is a method?
Amethodisanactionthatanobjectcanperform.Forexample,justasaWord
documentcanbeprinted,theDocumentobjecthasaPrintOutmethod.Methods
oftenhaveargumentsthatqualifyhowtheactionisperformed.Thefollowing
exampleprintsthefirstthreepagesoftheactiveWorddocument.
objWordApp.ActiveDocument.PrintOut From:=1, To:=3

Inmostcases,methodsareactionsandpropertiesarequalities.Usingamethod
causessomethingtohappentoanobject,whileusingapropertyreturns
informationabouttheobjectoritcausesaqualityabouttheobjecttochange.
Returning an object
Mostobjectsreturnasingleobjectfromthecollection.Forexample,the
DocumentscollectioncontainsthecurrentlyopenWorddocuments.Youusethe
DocumentspropertyoftheApplicationobject(theobjectatthetopoftheWord
objecthierarchy)toreturntheDocumentscollection.
Afteryouveaccessedthecollection,youcanreturnasingleobjectbyusingan
indexvalueinparentheses(thisissimilartohowyouworkwithVBAarrays).
Theindexvaluecanbeeitheranumberoraname.
ThefollowingexampleusestheDocumentspropertytoaccesstheDocument
collection.Theindexnumberisusedtoreturnthefirstdocumentinthe
Documentscollection.TheClosemethodisthenappliedtotheDocumentobject
toclosethefirstdocumentintheDocumentscollection.
objWordApp.Documents(1).Close

Thefollowingexampleusesaname(specifiedasastring)toidentifya
DocumentobjectwithintheDocumentscollection.
objWordApp.Documents("Sales.doc").Close

Collectionobjectsoftenhavemethodsandpropertieswhichyoucanuseto
modifytheentirecollectionofobjects.TheDocumentsobjecthasaSavemethod
thatsavesallthedocumentsinthecollection.Thefollowingexamplesavesthe
opendocumentsbyapplyingtheSavemethod.
objWordApp.Documents.Save

TheDocumentobjectalsohasaSavemethodavailableforsavingasingle
document.ThefollowingexamplesavesthedocumentnamedReport.doc.

80
objWordApp.Documents("Report.doc").Save

ToreturnanobjectthatisfurtherdownintheWordobjecthierarchy,youmust
drilldowntoitbyusingpropertiesandmethodstoreturnobjects.
Toseehowthisisdone,inWord,opentheVisualBasicEditorandclickObject
BrowserontheViewmenu.ClickApplicationintheClasseslistontheleft.Then
clickActiveDocumentfromthelistofmembersontheright.Thetextatbottom
oftheObjectBrowserindicatesthatActiveDocumentisareadonlyproperty
thatreturnsaDocumentobject.ClickDocumentatthebottomoftheObject
Browser;theDocumentobjectisautomaticallyselectedintheClasseslist,and
theMemberslistdisplaysthemembersoftheDocumentobject.Scrollthrough
thelistofmembersuntilyoufindClose.ClicktheClosemethod.Thetextatthe
bottomoftheObjectBrowserwindowshowsthesyntaxforthemethod.For
moreinformationaboutthemethod,pressF1orclicktheHelpbuttontojumpto
theClosemethodHelptopic.
Giventhisinformation,youcanwritethefollowinginstructiontoclosethe
activedocument.
objWordApp.ActiveDocument.Close SaveChanges:=wdSaveChanges

Thefollowingexamplemaximizestheactivedocumentwindow.
objWordApp.ActiveDocument.ActiveWindow.WindowState =
wdWindowStateMaximize

TheActiveWindowpropertyreturnsaWindowobjectthatrepresentstheactive
window.TheWindowStatepropertyissettothemaximizeconstant
(wdWindowStateMaximize).
ThefollowingexamplecreatesanewdocumentanddisplaystheSaveAsdialog
boxsothatanamecanbeprovidedforthedocument.
objWordApp.Documents.Add.Save

TheDocumentspropertyreturnstheDocumentscollection.TheAddmethod
createsanewdocumentandreturnsaDocumentobject.TheSavemethodis
thenappliedtotheDocumentobject.
Asyoucansee,youusemethodsorpropertiestodrilldowntoanobject.Thatis,
youreturnanobjectbyapplyingamethodorpropertytoanobjectaboveitin
theobjecthierarchy.Afteryoureturntheobjectyouwant,youcanapplythe
methodsandcontrolthepropertiesofthatobject.
See Also

Using the Microsoft


Word object model

OLEServices
Youshouldusetheassociatedonlinehelpdocumentationthatcamewiththe
objectapplicationtoobtaindetailsoftheobjectmodel.
Thehelpisquiteeasytouse.Eachoftheclassesandcollectionscanbeclickedto
jumptoitspage.

81
InCitectVBA,youmustusethefullApplicationobjectqualifierwhen
referencingthepropertiesandmethodsoftheobject.Forexample,youmustuse
thefullsyntaxApplication.ActiveDocument.PrintOut,insteadof
ActiveDocument.PrintOut.
See Also

OLE automation
example using the
Microsoft Word object

OLEServices
AllcommandsinWordaredirectedtotheactivedocument,whichmaybe
changedincode.Itisrecommendedtousenamedarguments,astheargument
sequencesarerecordedincorrectlyinsomedocumentation,includingthetype
libraryandwhattherecorderwritestomacros.
Sub runWord()
' demonstrating the use of OLE Automation
' to manipulate Word
' create local variables
Dim objWordApp As Object
' create the app object and assign the reference
Set objWordApp = CreateObject("Word.Application")
' manipulate the app object
' insert appropriate VBA code here to manipulate Word object
' close Word
objWordApp.Quit
' delete the object
Set objWordApp= Nothing
End Sub

See Also

Using the Microsoft


Excel object model
See Also

Deleting OLE
automation objects

OLEautomationexampleusingtheMicrosoftWordobject
UsingOLEautomationobjects
Youshouldusetheassociatedonlinehelpdocumentationthatcamewiththe
objectapplicationtoobtaindetailsoftheobjectmodel.
UsingtheMicrosoftExcelobjectmodel
UsingOLEautomationobjects
Allobjectreferencesmustbedeletedwhentheyarenolongerrequired,to
releasethememorytheywereusing.
YoudeleteanOLEAutomationreferencetotheobjectvariableinCitectVBA
usingtheCitectVBANothingkeywordwithinaCitectVBASetstatementinthe
followingsyntax:
Set <objVarName> = Nothing

82
where:

Setistherequiredreferenceassignment/releasestatementkeyword.
<objVarName>representstherequirednameofthevariableholdingthe

reference.

Nothingisthekeywordusedtoreleasetheobjectreference.

Whenseveralobjectvariablesrefertothesameobject,theyalsorefertothe
memoryandsystemresourcesassociatedwiththeobject.Theseresourcesare
releasedonlyafterallofthemhavebeensettoNothing,eitherexplicitlyusing
Set,orimplicitlyafterthelastobjectvariablesettoNothinggoesoutofscope.
Example

See Also

' Word example


' create variable to store object reference
Dim objWord as Object
' create object and assign reference to variable
Set objWord = CreateObject( "Word.Document" )
' insert appropriate VBA code here to manipulate Word object
' release reference
Set objWord = Nothing
' Excel example
' create local variables
Dim objExcelApp As Object
Dim objExcelCht As Object
' create the app object and assign the reference
Set objExcelApp = CreateObject("Excel.Application")
' create a chart and assign the reference
Set objExcelCht = objExcelApp.Charts.Add()
' insert appropriate VBA code here to manipulate Excel objects
' delete the objects
Set objExcelApp = Nothing
Set objExcelCht = Nothing

UsingOLEautomationobjects

File Input/Output with CitectVBA


CitectVBAsupportsfullsequentialandbinaryfileInput/Output(I/O).
Filesstoredondisk,cancontaintext(ASCII)charactersorbinary(onesand
zeros)digits.AllCitectVBAfilesthatcontainCitectVBAcodearestoredastext
files.However,youcanuseCitectVBAtostoreandretrievefilesineitherformat,
usingCitectVBAfileI/Ofunctionsandstatements.
TheFileI/OfunctionspredefinedinCitectVBAare:
ChDir, ChDrive, Close, CurDir, Dir, EOF, FileCopy, FileLen,
FreeFile, Get #, GetAttr, Input #, Kill, Line Input #, Loc, LOF,
MkDir, RmDir, Name, Open, Print #, Put, Seek, SetAttr, Write #.

83
FordetailsofallpredefinedCitectVBAfunctions,seeCitectVBAFunction
Reference.

84

85

Chapter 5: Function and Statement


Categories
Array Functions
CitectVBAarrayfunctionsareprovidedtoallowyoutodeclare,resize,initialize,
populate,anderasearraysandtheirelements.
ThearrayfunctionspredefinedinCitectVBAare:
Dim
Erase
Lbound
Option Base
ReDim
Ubound

Allocates storage for, and declares the data type of, variables and arrays in a module.
Reinitializes the elements of a fixed array.
Returns the smallest available subscript for the dimension of the indicated array.
Declares the default lower bound for array subscripts.
Used to size or resize a dynamic array that has already been declared using the Dim
statement with empty parentheses.
Returns the value of the largest usable subscript for the specified dimension of an array.

Conditional Statements
Do Loop
End Function
Exit
For

Allows you to execute a block of statements an indefinite number of times.


Ends a block of statements such as a Sub procedure or function.
Exits a loop or procedure.
Repeats its block of statements a set number of times as determined by the values used
with the To clause.
Branches unconditionally and without return to the label specified in the GoTo statement.
Goto
Tests an initial condition and then either performs or omits to perform the statements it
If
contains, dependant upon the logical result of the test condition.
CitectVBAs error-handling routine and specifies the line label of the error-handling routine.
OnError
Select
Tests the same variable for many different conditions.
Ends execution of the program.
Stop
WhileWend Similar to the Do While loop statement.
With
Not supported in CitectVBA.

Conversion Functions
CitectVBAconversionfunctionsareprovidedtoassistwithdatamanipulation
andcalculationinyourformulas.Conversionfunctionscanbeusedin
CitectVBAstatements,andwill(likeallotherfunctions),returnavaluetothe
caller.

88

ASCII character code


conversion

VijeoCitectusesthefollowingcharactercodeconversionfunnctions:

Date conversion

VijeoCitectusesthefollowingdateconversionfunctions:

Asc
Chr

CDate
CDbl
CInt
CLng
CSng
CStr
CVar

Returns the numeric ASCII value of a string.


Returns the string ASCII value of a number.

Converts an expression to a variant of date data type.


Converts an expression to a double data type.
Converts an expression to a integer data type.
Converts an expression to a long data type.
Converts an expression to a single data type.
Converts an expression to a string data type.
Converts an expression to a variant data type.

Date and time


formatting/conversion

VijeoCitectusesthefollowingformatting/conversionfunctions:

Number and string


conversion

VijeoCitectusesthefollowingfunctionsforconvertingandformattingnumbers
andstrings:

DateSerial
TimeSerial

Format
Hex
Oct
Str
Val

Constructs a date value.


Constructs an time value.

Formats a string, number, or variant to the format expression (fmt ).


Converts a value to a string representing the hex value.
Converts a value to a string representing the octal value.
Converts a value to a string containing numeric characters.
Converts a string containing numeric characters to a numeric value.

Declarations
CitectVBAdeclarationsallowyoutomanipulateandcontrolvariablesand
constants.TheDeclarationfunctionsandstatementspredefinedinCitectVBA
are:
CreateObject function
Const statement
Declare statement
Dim statement
IsDate
IsEmpty
IsNull
IsNumeric
Nothing keyword

Creates an OLE Automation object reference


Assigns a symbolic name to a constant value.
Declare references to external procedures in a DLL.
Allocates storage for, and declares the data type of, variables and arrays.
Determines if a Variant parameter can be converted to a date.
Determines if a Variant parameter has been initialized.
Determines if a Variant contains NULL.
Determines if a Variant can be converted to a numeric data type.
Releases an OLE Automation object reference from a variable of object
type.

89
Option Base statement
Declares the default lower bound for array subscripts.
Option Compare statement Determines the default string comparison method. Forces explicit
declaration of all variables.
Used to size or resize a dynamic array.
ReDim statement
Assigns an OLE Automation object reference to a variable of object type.
Set statement
Allocates storage for, and declares the data type of, variables and arrays.
Static statement
Indicates the data type used within the Variant.
VarType

Date and Time Functions


CitectVBAdateandtimefunctionsletyoumakeuseofyourcomputerssystem
timeanddate.
ThedateandtimefunctionspredefinedinCitectVBAare:
Date function
Date statement
DateSerial function
DateValue function
Day function
Hour function
Minute function
Month function
Now function
Second function
Time function
Time (statement)
Timer event
TimeSerial function
TimeValue function
WeekDay function
Year function

Determines the current system date according to the setting of the


computer's system time.
Sets the current system date.
Constructs a date value.
Calculates a date.
Calculates the day.
Extracts the hours value from an expression (Time ).
Extracts the minutes value from an expression (Time ).
Calculates the month.
Determines the current date and time according to the setting of the
computer's system date and time.
Extracts the seconds value from an expression (Time ).
Determines the current time according to the setting of the computer's
system time.
Sets the current system time.
Used to track elapsed time.
Constructs an time value.
Calculates a time.
Calculates the weekday value of a date.
Calculates the year.

File I/O Functions


CitectVBAfileInput/Output(I/O)functionsareprovidedtoenablereadand
writediskfilefunctionality.

90
ThefileI/OfunctionspredefinedinCitectVBAare:
ChDir
ChDrive
Close
CurDir, CurDir$
Dir
EOF
FileCopy
FileLen
FreeFile
Get #
GetAttr
Input
Kill
Line Input #
Loc
LOF
MkDir
Name
Open
Print (function)
Print #
Put #
RmDir
Seek
Write #

Changes the system environment current directory on the specified drive.


Changes the system environment current drive to the specified drive.
Closes the file/s previously opened with the Open statement.
Returns the current system environment path for the specified drive (Drv ).
Returns a file or directory name that matches the given File and Attrib
arguments.
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.
Copies a file from Src to Dest.
Determines the byte length of a file.
Retrieves the next sequential system file number available for association
with a file.
Reads data from a disk file into a variable.
Returns an Integer representing the attribute settings of a file, directory, or
volume.
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.
Deletes files from disk.
Reads a single line from an open sequential file and assigns it to a String
variable.
Returns a number indicating the current position within a file opened using
the Open statement.
Returns a number indicating the byte length of a sequential file opened using
the Open statement.
Creates the directory specified in the Path parameter.
Renames the disk file specified in the OldFileName parameter, to the name
specified in the NewFileName parameter.
Enables input/output (I/O) to a disk file.
Displays a message in the Vijeo Citect Kernel and the Cicode Editor output
window.
Reads data from OutputList and writes that data to a sequential file.
Writes data from a variable to a disk file.
Deletes the directory specified in the Path parameter.
Sets the current position within a file opened using the Open statement,
ready for the next read or write action.
Writes data to a Sequential file opened in output or append mode and reads
that data from a list of variables.

Math/Trigonometry Functions
CitectVBAmathfunctionsareprovidedtoassistwithnumbermanipulationand
calculationinyourformulas.MathematicalfunctionscanbeusedinCitectVBA

91
statements,andwill(likeallotherfunctions),returnavaluetothecaller.

Numeric functions

VijeoCitectusesthefollowingpredefinednumericfunctions:
Abs
Exp
Fix
Int
Log
Rnd
Sgn
Sqrt

Trigonometric functions

returns the absolute value of a number (Num ).


returns base log (e) to the power of (Num ).
returns the Integer value of a number (Num ).
returns the Integer value of a number (Num ).
returns the natural log of a number (Num ).
returns a random value influenced by (Num ).
returns a value indicating the Sign of (Num ).
returns the square root value of a number (Num ).

VijeoCitectusesthefollowingtrigonometricfunctions:
Atn
Cos
Sin
Tan

returns the Arctangent value of a number (Num ).


returns the Cosine value of angle (Rad ).
returns the Sine value of angle (Rad ).
returns the Tangent value of angle (Rad ).

Trigonometryusesanglesandratios,axes,degrees,Pi,radiansandangular
conversions.CitectVBAsupportstheuseofDecimalnumbersbydefault,aswell
asHexadecimalandOctalnumbers.SeeNumbers.
WhenusingnumbersinCitectVBA,youmustconsiderthedatatypeofthe
variablesthatholdandstorethenumbers,aswellasthebehaviourofCitectVBA
whendealingwithnumbers.SeeNumericDataTypes.

Miscellaneous Functions
ThemiscellaneousfunctionspredefinedinCitectVBAare:
Beep statement
Randomize statement
Rem statement
SendKeys statement

Sounds a tone through the computer's speaker.


Initializes the random number generator.
Used to include explanatory remarks in a program.
Sends keystrokes to the active window as if entered at the keyboard.

92

Procedural Statements
CitectVBAproceduralfunctionstatementsareprovidedtoassistwith
conditionalcodeexecutionandprogramflow:
Call statement
Function statement
End Function statement
Sub statement
End Sub statement
CicodeCallOpen function
CicodeCallReturn function

Transfers control to a Sub procedure, function procedure, or dynamic-link


library (DLL) procedure.
Declares and defines a procedure that can receive arguments and return a
value of a specified data type.
Ends a program or a block of statements within a function.
Declares and defines a Sub procedures name, parameters and code.
Ends a program or a block of statements within a subroutine.
Calls a Cicode function from CitectVBA.
Obtains the return value of the most recently completed Cicode function
opened with the CitectVBA CicodeCallOpen function.

CicodefunctionsusedtohandleCitectVBAfunctionsandstatements:
VbCallOpen function
VbCallRun function
VbCallReturn function

Opens a CitectVBA function or subroutine from Cicode.


Runs the opened CitectVBA function or subroutine from Cicode.
Obtains the return value of the completed CitectVBA function previously
opened with the Cicode VbCallOpen function.

String Functions
CitectVBAstringsfunctionsareprovidedtocreate,editandimplementstrings
withinCitectVBAcode.ThestringsfunctionspredefinedinCitectVBAare:
Asc
Chr
InStr
LCase
Left, Left$
Len
Line Input #
LTrim
Mid
Option Compare
Right
RTrim
Space
StrComp
String
Trim
UCase

Returns a numeric value that is the ASCII code for the first character in a string.
Converts an ASCII number to a one character string.
Returns the character position of the first occurrence of string2 within string1.
Returns a copy of string in which all characters have been converted to lowercase.
Returns the left most characters of a string parameter.
Determines the number of characters in the string argument.
Reads a single line from an open sequential file and assigns it to a string variable.
Strips any leading spaces from a string variable.
Returns a substring within a string.
Determines the default string comparison method.
Returns the right most characters of a string parameter.
Strips any trailing spaces from a string variable.
Adds a specified number of spaces in a print statement.
Returns a variant that is the result of the comparison of two strings.
Create a string that consists of one character repeated a specific number of times.
Strips any leading and trailing spaces from Str variable.
Returns a copy of string in which all characters have been converted to uppercase.

93

Chapter 6: CitectVBA Function Reference


ThischapterdescribesthepredefinedCitectVBAfunctionsandstatements.

Abs
Description

Syntax

Calculatestheabsolute(positive)valueofanumber.Theabsolutevalueofa
numberisthenumberwithoutitssign.Absdoesnotroundthenumber,and
ignoresthefractionalvalueofthenumber.
Abs(Num)
Num ............ Number:TheargumentNummustcontainanintegeror
expressionrepresentingavalidnumericvalue.

ReturnValue

Returnstheabsolutevalueofthenumber(Num)providedintheargument.
Thedatatypeofthereturnvalueisthesameasthatofthenumberargument.
However,ifthenumberargumentisaVariantofVarType(String)andcanbe
convertedtoanumber,thereturnvaluewillbeaVariantofVarType(Double).If
thenumericexpressionresultsinanull,Absreturnsanull.

RelatedFunctions
Example

Sgn
Variable=Abs(-67); ! Sets Variable to 67.
Variable=Abs(67); ! Sets Variable to 67.

Asc
Description

Syntax

ConvertsatextstringcharactertoitsnumericASCIIcodevalue.TheAsc
functionexpectstheargument(Str)tobeavalidstringexpression.IfStrcontains
nocharacters,aruntimeerroroccurs.TheAscfunctionperformstheoppositeof
theChrfunction,whichconvertsanumberintoitsstringcharacterASCIIcode
value.
Asc(Str)
Str.............. String:TheargumentStrmustbeastringorexpressionthat
canrepresentavalidtextvalue.

96
ReturnValue

RelatedFunctions
Example

ReturnsthenumericASCIIcodevalueofthefirstcharacterin(Str)providedin
theargument.
Chr
Dim vntVar ' declare result holder variable
vntVar = Asc("A")' returns 65
vntVar = Asc("Z")' returns 90
vntVar = Asc("a")' returns 97
vntVar = Asc("z")' returns 122
vntVar = Asc("Apple")' returns 65
vntVar = Asc("Zoe")' returns 90

Atn
Description

CalculatesthetrigonometricArctangentvalueofaTangentnumber.
TheAtnfunctionexpectstheargument(Num)tobeavalidtangentvalue
betweentherangeofPi/2to+Pi/2(representingtheratioofthetwosidesofa
rightangletriangle),andcalculatesthecorrespondingangleinradians.
AtnistheinversetrigonometricfunctionofTan(whichtakesanangleasits
argument,andreturnstheratiooftwosidesofarightangletriangle).Donot
confuseAtnwiththeCotangent,whichistheinverseofaTangent(1/tangent).

Syntax

Atn(Num)
Num ............ Number:TheargumentNummustcontainanintegeror
expressionrepresentingavalidnumericvalue.

ReturnValue
RelatedFunctions
Example

ReturnstheArctangentvalueoftheangle(Num)providedintheargument.
Cos | Sin | Tan
Dim Msg, Pi' Declare variables.
Pi = 4 * Atn(1)' Calculate Pi

Beep
Description

Syntax

TheBeepstatementsoundsatonethroughthecomputersspeaker.The
frequencyanddurationofthebeepdependsonthecomputershardware.
Beep

97
RelatedFunctions
Example

SendKeys
If (TestTag_1 <1) OR (TestTag_1 > 100) Then
Beep
Else
Startup_AN38.Value = TestTag_1
End If

Call
Description

TheCallStatementtransferscontroltoaSubprocedure,Functionprocedure,or
dynamiclinklibrary(DLL)procedure.
TherequiredProcedureNameisthenameofthefunctionorsubroutinetocall.The
optionalParametersisthelistofargumentstopasstothecalledfunctionor
subroutine.
YouarenotrequiredtousetheCallstatementwhencallinganCitectVBA
subroutineoraDLLfunction.Parenthesesmustbeusedintheargumentlistif
theCallstatementisbeingused.

Syntax
RelatedFunctions
Example

CallProcedureName[Parameter(s)]
End Function | Sub | End Sub | Exit
Call Beep

CDate
Description

ConvertsanyvaliddateexpressiontoaDatedatatype.
TheCDatefunctionexpectstheargument(Date)tobeadateexpression(limited
tonumbersorstringsinanycombination)thatcanrepresentadatefrom
January1,100throughDecember31,9999.

Syntax

CDate(Date)
Date ............. Date:TheargumentDatemustbeastringorexpressionthat
canrepresentadatevalue.Thisincludesanycombinationof
dateliterals,numbersthatlooklikedates,stringsthatlook
likedates,anddatesfromfunctions.

ReturnValue

Returnsthevalueoftheexpression(Date)providedintheargumentasavariant
withavartypeof7(datedatatype).

98
RelatedFunctions
Example

CDbl | CInt | CLng | CSng | CStr | CVar


Dim MybDate, MDate, MTime, MSTime
' Define date.
MybDate = "May 29, 1959"
' Convert to Date data type.
MDate = CDate(MybDate)
' Define time.
MTime = "10:32:27 PM"
' Convert to Date data type.
MSTime = CDate(MTime)

CDbl
Description
Syntax

Convertsexpressionstoadoubledatatype.
CDbl(Exp)
Exp ............. Expression:TheargumentExpwilldependuponwhich
datatypeisexpectedinthefunction.Ifastringisexpected,
ExpmaybeavalidstringorVariantcontainingavalue
recognizableasastring.Ifanumberisexpected,Expmaybe
avalidnumberorVariantcontainingavaluerecognizableas
anumber.

ReturnValue

RelatedFunctions
Example

Returnsthevalueoftheexpression(Exp)providedintheargumentasadouble
datatype.
CDate | CInt | CLng | CSng | CStr | CVar
Dim x as integer
Dim z as double
z = CDbl(x)'Converts the integer value of x to a double value in z

ChDir
Description

ChDirstatementchangesthesystemenvironmentcurrentdirectoryonthe
specifieddrive.
TheparameterPathmustbeastringorexpressionthatcanrepresentavalid
DOSfilestructurepathvalue.TheparameterDirmustbeastringorexpression
thatcanrepresentavalidDOSfilestructuredirectoryname.ThePathandDir
parameterstogether,mustbelimitedtolessthan128characters.ThePathdrive

99
letterisoptional,unlessthedirectoryisonanotherdrive.TherequiredDir
parametermustbeavaliddirectoryname.
Note:Thefilesystemkeepstrackofthecurrentdrive,andthecurrentdirectory
ofeverydrive.UsetheCurDirstatementtodeterminethecurrentdirectory.The
currentdrivelettercanbeextractedfromtheLeftcharacterreturnedinthe
CurDirstatement.
TheChDirstatementchangesthecurrentdirectorybutnotthecurrentdrive.To
changethecurrentdrive,usetheChDrivestatement.
Syntax

ChDirPathDir
Path ............. Path:TheparameterPathmustbeastringorexpression
thatcanrepresentavalidDOSfilestructurepathvalue.This
includesadirectoryname,andmayincludearelativeor
staticdirectoryorfolderstructureanddriveletter,inthe
order:
[<driveletter>:][\<rootdirectoryname>][\<subdirectory> ...
\<subdirectory>\] directoryname

Notethatthepathcanberelativetothecurrentdirectory.A
singleperiodrepresentsthecurrentdirectory(.),andtwo
periodsrepresenttheparentdirectoryofthecurrent
directory(..).Forexample:

chdir..changestotheparentdirectoryofthecurrent
directory

chdir..\testchangestothetestsubdirectoryofthe
parentdirectory

Dir .............. Directory:TheparameterDirmustbeastringorexpression


thatcanrepresentavalidDOSfilestructuredirectoryname.
Dirisnotcasesensitive.DirisoftenusedwiththePath
parameter.
RelatedFunctions
Example

ChDrive | CurDir, CurDir$ | Dir | MkDir | RmDir


Dim strPath as String
strPath = CurDir()' store current path
ChDir "\"' change to root dir on current drive
<statements>' do stuff in root directory
ChDir strPath' change back to previous path

100

ChDrive
Description

Changesthesystemenvironmentcurrentdrivetothespecifieddrive.
TheparameterDrvmustbeastringorexpressionthatcanrepresentavalidDOS
filestructuredriveletter.TheDrvmaybelocaltothecomputer,ormappedfrom
anywhereonthenetworkconnectedtothecomputer.IfDrvcontainsmorethan
oneletter,onlythefirstcharacterisused.
Note:Thefilesystemkeepstrackofthecurrentdrive,andthecurrentdirectory
ofeverydrive.UsetheCurDirstatementtodeterminethecurrentdirectory.The
currentdrivelettercanbeextractedfromtheLeftcharacterreturnedinthe
CurDirstatement.
TheChDrivestatementchangesthecurrentdrivebutnotthecurrentdirectory
onanydrive.Tochangethecurrentdirectory,usetheChDirstatement.

Syntax

ChDriveDrv
Drv ............. Drive:TheparameterDrvmustbeastringorexpression
thatcanrepresentavalidDOSfilestructuredriveletter.Drv
iscaseinsensitiveandmustendwithacolon(:).TheDrv
maybelocaltothecomputer,ormappedfromanywhereon
thenetworkconnectedtothecomputer.Drvisoftenincluded
aspartofthePathparameter.

RelatedFunctions
Example

ChDir | CurDir, CurDir$ | Dir | RmDir | MkDir


Dim strCurPath as String
strCurPath = CurDir$()' store current path as string
ChDir "\"' change to root directory of current drive
<statements>' do stuff in root directory
ChDrive "C"' change to C drive (if not already there)
<statements>' do stuff in current directory on C drive
ChDrive strCurPath' change back to previous drive
ChDir strCurPath' change back to previous path

Chr
Description

ConvertsanumberintoitsstringcharacterASCIIcodevalue.
TheChrfunctionexpectstheargument(Num)tobeavalidnumericinteger
(wholepositivenumberwithintherange0to255inclusive).IfChrcontainsno
number,aruntimeerroroccurs.
Note:Values8,9,10,and13converttobackspace,tab,linefeed,andcarriage
returncharactersrespectively.

101
TheChrfunctionperformstheoppositeoftheAscfunction,whichconvertsa
textstringcharactertoitsnumericASCIIcodevalue.
Syntax

Chr(Num)
Num ............ Number:TheargumentNummustcontainanintegeror
expressionrepresentingavalidnumericvalue.

ReturnValue

RelatedFunctions
Example

ReturnsasinglecharacterstringrepresentingtheASCIIcharactercodevalueof
thenumber(Num)providedintheargument.
Asc
Dim vntVar ' declare result holder variable
vntVar = Chr(65)' returns "A"
vntVar = Chr(97)' returns "a"
vntVar = Chr(90)' returns "Z"
vntVar = Chr(122)' returns "z"

CicodeCallOpen
Description

TheCicodeCallOpenfunctionisusedtocallaCicodefunctionfromCitectVBA.
ItisusedtoinitiateandexecuteacalltotheCicodefunctionandreturnsan
integervaluerepresentingthesuccessorfailureofthisCitectVBAfunction
makingthecall.
Note:ThisCitectVBAfunctiondoesnotreturntheactualreturnvalueofthe
Cicodefunctionbeingcalled.Youcanobtainthatreturnvaluebyusingthe
associatedCicodeCallReturnfunction.
TheCicodeCallOpenfunctionshouldbeusedinitsownseparatelineof
CitectVBAcodeandmustnotbenestedwiththeCicodeCallReturnfunction.
Fordetails,seeCallingCicodefromCitectVBA.

Syntax

<ReturnValue>=CicodeCallOpen(<FunctName>,<ArgList>)
where:

<ReturnValue>representsthereturnvalueforthefunctionintherangeof0
to3.<FunctName>representsthenameoftheCicodefunctionbeingcalled.

<ArgList>representsavariablelengthcommaseparatedargumentlistof
alltheargumentstobepassedtotheCicodefunctionbeingopened
(dependantuponwhichCicodefunctionisbeingcalledandthearguments
thatCicodefunctionrequires).Theargumentlistshouldnotbeenclosed
withinbrackets,althoughwhenusingvariablenamesasarguments,those

102
variableargumentswithinthelistmustbeindividuallyenclosedwithin
bracketstoforcethepassingofthevariabletoCicodebyvalue.
ReturnValue

CicodeCallOpenreturnsaintegerdatatypecontainingavalueintherangeof0

to3:

RelatedFunctions
Example

0ifCicodeCallOpenfunctionwassuccessful

1forCicodeCallOpenfunctionfailure

2forspecifiedCicodefunctionnotfound

3forincorrectnumberofargumentsforspecifiedCicodefunctionpassedin
<ArgList>.

CicodeCallReturn
Inthefollowingexample,aCitectVBAvariableisenclosedinbracketstoforce
thepassingofthevariablebyvalue.SeePassingvariablesByrefandByval.
Dim vntRet as Variant
' declare modular variant variable to store function results
Function TestCicode() As Integer
' declare local variables
Dim intRet As Integer
Dim strReply as String
Dim intMaxScale as Integer
' copy current tag value to variable
' uses the project variable tag named MAX_SCALE
intMaxScale = MAX_SCALE
' call Cicode function
' for example: TrnSetScale( AN, Pen, Percent, Scale)
intRet = CicodeCallOpen( "TrnSetScale", 53, -1, 100, (IntMaxScale)
)
' Note the syntax used:
' - brackets around the CitectVBA function argument list.
' (This is only necessary when the CitectVBA function is preceded
by an equals (=) sign .)
' - double quotes around the Cicode function name
' - no brackets around the Cicode function argument list
' - brackets around individual variable arguments
' test results
If intRet = 0 Then
'
' insert code for successful completion here
'
vntRet = CicodeCallReturn()
strReply = "CicodeCallOpen Function successfully called"
Else
'

103
' insert code for unsuccessful completion here
'
Select Case intRet
Case = 1
' assign return comment for this case
strReply = "CicodeCallOpen Function call failed"
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

CicodeCallReturn
Description

TheCicodeCallReturnfunctionisusedtoobtainthereturnvalueofthemost
recentlycompletedCicodefunctionopenedandrunwiththeCitectVBA
CicodeCallOpenfunction.
NoargumentsarepassedtotheCicodeCallReturnfunction,asitwillalways
returntheresultofthemostrecentreturnvaluefortheCicodefunctioncalled
bytheCitectVBACicodeCallOpenfunction.
TheCicodeCallReturnfunctionshouldbeusedinitsownseparatelineof
CitectVBAcodeandmustnotbenestedwiththeCicodeCallOpenfunction.For
details,seeCallingCicodefromCitectVBA.

Syntax

<ReturnValue> = CicodeCallReturn()

where:

<ReturnValue>representsthereturnvalueoftheCicodefunctionspecified
inthemostrecentcalloftheCicodeCallOpenfunction.Notethatthereturn
datatypeofCicodeCallReturnwilldependuponthereturndatatypeofthe

104
completedCicodefunctionmostrecentlycalledbytheCicodeCallOpen
function.

Return Value:CicodeCallReturnreturnsthereturnvalueofthecompleted

CicodefunctionmostrecentlycalledbytheCicodeCallOpenfunction.
RelatedFunctions
Example

CicodeCallOpen
' declare modular variant variable to store function results
Dim vntRet as Variant
Function TestCicode() As Integer
' declare local variables
Dim intRet As Integer
Dim strReply as String
Dim intMaxScale as Integer
' copy current tag value to variable
' uses the project variable tag named MAX_SCALE
intMaxScale = MAX_SCALE
' call Cicode function
' for example: TrnSetScale( AN, Pen, Percent, Scale)
intRet = CicodeCallOpen( "TrnSetScale", 53, -1, 100, (IntMaxScale)
)
' Note the syntax used:
' - brackets around the CitectVBA function argument list
' - double quotes around the Cicode function name
' - no brackets around the Cicode function argument list
' - brackets around individual variable arguments
' test results
If intRet = 0 Then
'
' insert code for successful completion here
'
vntRet = CicodeCallReturn()
strReply = "CicodeCallOpen Function successfully called"
Else
'
' insert code for unsuccessful completion here
'
Select Case intRet
Case = 1
' assign return comment for this case
strReply = "CicodeCallOpen Function call failed"
Case = 2
' assign return comment for this case
strReply = "Cicode Function not found"
Case = 3

105
' 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

CInt
Description
Syntax

Convertsexpressionstoanintegerdatatype.
CInt(Exp)
Exp ............. Expression:TheargumentExpwilldependuponwhich
datatypeisexpectedinthefunction.Ifastringisexpected,
ExpmaybeavalidstringorVariantcontainingavalue
recognizableasastring.Ifanumberisexpected,Expmaybe
avalidnumberorVariantcontainingavaluerecognizableas
anumber.

ReturnValue

RelatedFunctions
Example

Returnsthevalueoftheexpression(Exp)providedintheargumentasaninteger
datatype.
CDate | CDbl | CLng | CSng | CStr | CVar
Dim x as integer
Dim y as long
x = CInt(y)'Converts the long value of y to an integer value in x

CLng
Description
Syntax

Convertsexpressionstoalongdatatype.
CLng(Exp)

106
Exp ............. Expression:TheargumentExpwilldependuponwhich
datatypeisexpectedinthefunction.Ifastringisexpected,
ExpmaybeavalidstringorVariantcontainingavalue
recognizableasastring.
Ifanumberisexpected,Expmaybeavalidnumberor
Variantcontainingavaluerecognizableasanumber.
ReturnValue

RelatedFunctions
Example

Returnsthevalueoftheexpression(Exp)providedintheargumentasalong
datatype.
CDate | CDbl | CInt | CSng | CStr | CVar
Dim x as integer
Dim y as long
y = CLng(x)'Converts the integer value of x to an long value in y

Close
Description

Closesthefile/spreviouslyopenedwiththeOpenstatement.
TheoptionalFileNumListparametercancontainoneormorevalidfileassociated
referencenumbersusingthefollowingsyntax:
[[#]FileNum] [, [#]FileNum] ...

whereFilenumisanyvalidnumberassociatedwithanopenfile.
IftheClosestatementisusedwithoutanyargumentsitclosesallopenfiles.
WhentheClosestatementisexecuted,theassociationofafilewithitsfile
numberends.
Syntax

CloseFileNumList
FileNumList ...... FileNumberList:TheargumentFileNumListmustcontain
oneormorevalidintegerornumericexpressionvalues
representingassociatedfilenumbersusingthefollowing
syntax:
[[#]filenumber][,[#]filenumber]...wherefilenumberisany
validnumberassociatedwithanopenfile.

RelatedFunctions
Example

FileCopy | FreeFile | Kill | Name | Open


Dim strFileContents As String
Dim strTemp As String
Open "c:\test.txt" For Input As #1' open file.
Do While Not EOF(1)' loop until end of file
strTemp = Input(10, #1)' read next ten characters

107
strFileContents = strFileContents & strTemp' join strings
Loop
Close #1

Const
Description

Assignsasymbolicnametoaconstantvalueusingthefollowingsyntax:
Const VarName [As DataType] = Expression

Aconstantmustbedefinedbeforeitisused.Unlikevariables,constantsare
assignedvalueswheninitializedandretainthatsamevalueduringthelifeofthe
constant.
Constantstatementscanonlybedeclaredandassignedusingsimple
expressions.ConstantscanNOTbeassignedvaluesfromvariables,userdefined
functions,intrinsicCitectVBAfunctions(suchasChr),orfromanyexpression
thatinvolvesanoperator.
ConstantsdeclaredinaSuborFunctionprocedurearelocaltothatprocedure.A
constantdeclaredoutsideaprocedurehasmodularscopetoallprocedures
withinthesameCitectVBAfilemodule.SeeScopeofCitectVBA.
ConstantscanbeusedanywhereinyourCitectVBAcodewhereyoucouldusea
CitectVBAexpression.
IfyouuseConstoutsideaprocedureitsscopebecomesglobal.
Atypedeclarationcharactermayalsobeused.Howeverifnoneisused,
CitectVBAwillautomaticallyassignoneofthefollowingdatatypestothe
constant:long(ifitisalongorinteger);Double(ifadecimalplaceispresent);or
String(ifitisastring).
Syntax

Const(VarName,Exp)
VarName......... VariableName:TheargumentVarNamemustbeastring
representingavalidvariablename.
Exp ............. Expression:TheargumentExpwilldependuponwhich
datatypeisexpectedinthefunction.Ifastringisexpected,
ExpmaybeavalidstringorVariantcontainingavalue
recognizableasastring.
Ifanumberisexpected,Expmaybeavalidnumberor
Variantcontainingavaluerecognizableasanumber.

RelatedFunctions

Dim | ReDim | Static

108
Example

' Correct declaration examples


' long assignment
Const Seven = 7
' double assignment
Const Pi = 3.14159
' string assignment
Const Lab = "Laboratory"
' Incorrect declaration examples
' NOTE that the following declarations demonstrate incorrect
assignments
' because each contains an operator
Const conPi = 4 * Atn(1)
' will cause a CitectVBA compile error
Const conDegToRad = (conPi / 180)
' will cause a CitectVBA compile error

Cos
Description

CalculatesthetrigonometricCosinevalueofanangle.
TheCosfunctionexpectstheargument(Rad)tobeavalidanglevalueinradians,
andcalculatestheratioofthetwosidesofarightangletriangleoneithersideof
theangle.Theratioisthelengthofthesideadjacenttotheangledividedbythe
lengthofthehypotenuse.
Note:Toconvertdegreestoradians,multiplydegreesbyPi/180.Toconvert
radianstodegrees,multiplyradiansby180/Pi.

Syntax

Cos(Rad)
Rad ............. Radians:TheargumentRadmustbeexpressedinradians,
andmustbeavalidnumericvalue.

ReturnValue

ReturnstheCosinevalueoftheangle(Rad)providedintheargument.
Theresultliesintherange1to+1.
Coswillreturnadouble.

RelatedFunctions
Example

Atn | Sin | Tan


Variable=Cos(0.7854);! Sets Variable to 0.7071...

109

CreateObject
Description
Syntax

CreatesanewOLEAutomationobjectandassignsareferencetotheobject.
Set <objVarName> = CreateObject(<objClassName>)

where:

Setistherequiredreferenceassignmentstatementkeyword.

<objVarName>representstherequirednameofthevariablereceivingthe
reference.

CreateObjectistherequiredobjectdeclarationfunctionkeyword.

()definestherequiredargumentsectionofthefunction.

<objClassName>representstherequiredclassnameoftheobjecttobe
created.

Theobjectvariable(<objVarName>)mustbedeclaredbeforeitcanbesetto
referenceanOLEAutomationobject.
RelatedFunctions
Example

Dim | Set
' create variable to store object reference
Dim objWord as Object
' create object and assign reference to variable
Set objWord = CreateObject( "Word.Document" )
' insert appropriate VBA code here to manipulate Word object
' release reference
Set objWord = Nothing.

CSng
Description
Syntax

Convertsexpressionstoasingledatatype.
CSng(Exp)
Exp ............. Expression:TheargumentExpwilldependuponwhich
datatypeisexpectedinthefunction.Ifastringisexpected,
ExpmaybeavalidstringorVariantcontainingavalue
recognizableasastring.
Ifanumberisexpected,Expmaybeavalidnumberor
Variantcontainingavaluerecognizableasanumber.

ReturnValue

Returnsthevalueoftheexpression(Exp)providedintheargumentasasingle
datatype.

110
RelatedFunctions
Example

CDate | CDbl | CInt | CLng | CStr | CVar


Dim x as integer
Dim s as single
s = CSng(x)'Converts the integer value of x to a single value in s

CStr
Description
Syntax

Convertsexpressionstoastringdatatype.
CStr(Exp)
Exp ............. Expression:TheargumentExpwilldependuponwhich
datatypeisexpectedinthefunction.Ifastringisexpected,
ExpmaybeavalidstringorVariantcontainingavalue
recognizableasastring.
Ifanumberisexpected,Expmaybeavalidnumberor
Variantcontainingavaluerecognizableasanumber.

ReturnValue

RelatedFunctions

Returnsthevalueoftheexpression(Exp)providedintheargumentasastring
datatype.
CDate | CDbl | CInt | CLng | CStr | CVar |
CSng

Example

Dim x as integer
Dim t as string
t = CStr(x)'Converts the integer value of x to a string value in t

Description

BothCurDirandCurDir$functionsreturnthecurrentsystemenvironmentpath
forthespecifieddrive(Drv).

CurDir, CurDir$

TheparameterDrvmustbeastringorexpressionthatcanrepresentavalidDOS
filestructuredriveletter.TheDrvmaybelocaltothecomputer,ormappedfrom
anywhereonthenetworkconnectedtothecomputer.IfDrvcontainsmorethan
oneletter,onlythefirstcharacterisused.
Note:Thefilesystemkeepstrackofthecurrentdrive,andthecurrentdirectory
ofeverydrive.UsetheCurDirstatementtodeterminethecurrentdirectory.The
currentdrivelettercanbeextractedfromtheLeftcharacterreturnedinthe
CurDirstatement.

111
IfnoDrvisspecifiedorifDrvisazerolengthstring(),CurDirfunctions
returnthesystemenvironmentpathforthecurrentdrive.
Syntax

CurDir(Drv)
Drv ............. Drive:TheparameterDrvmustbeastringorexpression
thatcanrepresentavalidDOSfilestructuredriveletter.Drv
iscaseinsensitiveandmustendwithacolon(:).TheDrv
maybelocaltothecomputer,ormappedfromanywhereon
thenetworkconnectedtothecomputer.Drvisoftenincluded
aspartofthePathparameter.

ReturnValue

CurDirreturnsaVariantcontainingastring;CurDir$returnsaString.

RelatedFunctions

ChDir | ChDrive | Dir | MkDir | RmDir

Example

Dim vntCurPath As Variant


Dim strCurPath As String
vntCurPath = CurDir()' store current path as variant
strCurPath = CurDir$()' store current path as string

CVar
Description
Syntax

Convertsexpressionstoavariantdatatype.
CVar(Exp)
Exp ............. Expression:TheargumentExpwilldependuponwhich
datatypeisexpectedinthefunction.Ifastringisexpected,
ExpmaybeavalidstringorVariantcontainingavalue
recognizableasastring.
Ifanumberisexpected,Expmaybeavalidnumberor
Variantcontainingavaluerecognizableasanumber.

ReturnValue

RelatedFunctions
Example

Returnsthevalueoftheexpression(Exp)providedintheargumentasavariant
datatype.
CDate | CDbl | CInt | CLng | CSng | CStr
Dim x as integer
Dim v as variant
v = CVar(x)'Converts the integer value of x to a variant value in
v

112

Date
Description

Syntax
ReturnValue

RelatedFunctions

Determinesthecurrentsystemdateaccordingtothesettingofthecomputers
systemdateandtime.Unlikeotherfunctions,Datedoesnotrequiretrailing
parentheses.
Date()
ReturnsaVariant(ofStringdatatype)containingthestringvalueofthecurrent
systemdate.
DateSerial | DateValue | Year | Month | WeekDay |
Day | TimeValue | Hour | Minute | Second

Example

varSysDate
varSysDate = Date
' retrieves system date

Description

Setsthecurrentsystemdate.

Date statement

TheDateValueliteralisdisplayedinshortdateformatusingthelocalesettings
ofyourdevelopmentsystem.Toviewthelocalesettingsforyoursystem,in
Windows,selectStart,Settings,ControlPanel,RegionalOptions,Date.For
example:inAustralia,theshortdateformatisrepresentedasd/MM/yyyy.
RelatedFunctions
Example

Time(statement)
Dim varCitectVBAReleaseDate
varCitectVBAReleaseDate = #01/07/2001#
Date = varCitectVBAReleaseDate
' sets system date to CitectVBA Release Date

DateSerial
Description

Syntax

ConstructsadatevaluefromthegivenYear,Month,andDayargumentspassed
tothefunction.TheDateSerialfunctionexpectsallthreeparameterstobevalid.
DatevaluesinCitectVBAareevaluatedusingtheGregorianCalendar.
DateSerial()

113
ReturnValue

RelatedFunctions
Example

ReturnsaVariant(ofdatedatatype)containingadatevaluecorrespondingto
theYear,MonthandDayvaluesthatwerepassedintothefunction.
TimeSerial
Dim varMyBDate
varMyBDate = DateSerial(1958, 7, 08)
' constructs and stores date value.

DateValue
Description

Syntax

Calculatesadatefromthegivendateargumentpassedtothefunction.Date
valuesinCitectVBAareevaluatedusingtheGregorianCalendar.TheDateValue
functionexpectstheargumentvalue(Date)tobeastringoranyexpressionthat
canrepresentadate.
DateValue(Date)
Date ............. Date:TheargumentDatemustbeastringorexpressionthat
canrepresentadatevalue.Thisincludesanycombinationof
dateliterals,numbersthatlooklikedates,stringsthatlook
likedates,anddatesfromfunctions.

ReturnValue

RelatedFunctions
Example

Returnsavariant(ofdatedatatype)correspondingtothestringdateexpression
thatwaspassedin.
TimeValue
Dim varMyBDate
varMyBDate = DateValue("1958/07/08")
' stores date value.

Day
Description

Syntax

Calculatesthedayfromthegivendateargumentpassedtothefunctionusing
theGregorianCalendar.
Day(Date)
Date ............. Date:TheargumentDatemustbeastringorexpressionthat
canrepresentadatevalue.Thisincludesanycombinationof
dateliterals,numbersthatlooklikedates,stringsthatlook
likedates,anddatesfromfunctions.

114
ReturnValue
RelatedFunctions
Example

Returnsavariantdatecorrespondingtothedateexpressionthatwaspassedin.
Date | Year | Month | WeekDay
Dim varMyBDate, varMyDay
varMyBDate = #July 8, 1958#
varMyDay = Day(varMyBDate)
' stores 8 for day value.

Declare
Description

Syntax

TheDeclarestatementisusedatmodule(file)leveltodeclarereferencesto
externalproceduresinadynamiclinklibrary(DLL).
DeclareFunction<FunctionName>Lib<LibName>[Alias<AliasName>]
[([<ArgList>])][As<ReturnType>]
where:

RelatedFunctions
Example

DeclareistherequiredDeclarationstatementkeyword

FunctionistherequiredFunctionstatementkeyword

<FunctionName>representstherequirednameofthefunctionbeing
declared

LibistherequiredLibrarystatementkeyword

<LibName>representstherequiredDLLfilenamecontainingthefunction
beingcalled

AliasistheoptionalAliasstatementkeyword

<AliasName>representstheoptionalfunctionnamewithintheDLLbeing
called

()definestherequiredargumentsectionofthefunction

<ArgList>representstheoptionalargument/softhefunction

AsistheoptionalAsstatementkeyworddeclaringthereturndatatype

<ReturnType>representstheoptionalreturndatatype

Dim
Declare Function GetWinTempPath Lib "kernel32" _
Alias "GetTempPathA" _
(ByVal nBufferLength As Long, _
ByVal lpBuffer As String) As Long

115

Dim
Description

Syntax

TheDimstatementallocatesstoragefor,anddeclaresthedatatypeof,variables
andarraysinamodule.
DimVariableName[(Subscripts)][AsDataType]
where:

RelatedFunctions
Example

DimistherequiredvariabledeclarationstatementBASICkeyword

<VariableName>representstherequirednameofthevariablebeing
declared(dimensioned)

()aretheoptionalparenthesestoholdanarraysubscriptrange
(dimensions)

<Subscripts>representstheoptionalsubscriptrangeforanarray

AsistheoptionalAsstatementkeyworddeclaringthevariabledatatype

<DataType>representstheoptionalCitectVBAdatatypedeclarationforthe
variableSyntaxDimVarName

VarNameVariableName:TheargumentVarNamemustbeastring
representingavalidvariablename.

Const | ReDim | Static


Dim
Dim
Dim
Dim
Dim
Dim
Dim
Dim
Dim
Dim

bytVar
binVar
strVar
intVar
lngVar
sngVar
dblVar
vntVar
objVar
dtmVar

As
As
As
As
As
As
As
As
As
As

Byte
Boolean
String
Integer
Long
Single
Double
Variant
Object
Date

Dir
Description

DirfunctionreturnsafileordirectorynamethatmatchesthegivenFileand
Attribarguments.

TheFileargumentisoptional,andrepresentsastringexpressionthat
specifiesavalidfilename,andmayincludeaDOSpathstructureincluding

116
directoryorfoldernames,andadriveletter.YoumustspecifyFilethefirst
timeyoucalltheDirfunction,oranerroroccurs.

TheAttribargumentisoptional,andcanbeaconstantornumeric
expressionwhosesumspecifiesfileattributevalues.Ifyouspecifyfile
attributesinthefunctioncall,Filemustbeincluded.IftheVolumeattribute
value(8)isspecified,allotherattributevaluesareignored.

Dirsupportstheuseofmultiplecharacter(*)andsinglecharacter(?)wildcards
tospecifymultiplefiles.
DirreturnsthefirstfilenamethatmatchesbothFileandAttrib.Togetany
additionalfilenamesthatmatch,callDiragainwithnoarguments.Whenno
morefilenamesmatch,Dirreturnsazerolengthstring().Onceazerolength
stringisreturned,youmustspecifyargument/sinthenextcall(toresetthe
function),oranerroroccurs.
CallingDirwithanyargumentwillresetthefunction,anditwilltreatthecallas
anewcall.PreviousargumentspassedtotheDirfunctionareoverwrittenand
forgotten(reset).Youcanresetthefunction(bysupplyingargumentsinthe
functioncall)atanytime,evenifithasnotyetreturnedeverypossibleargument
matchresult.
CallingDirwiththeDirectoryattribute(16)doesnotcontinuallyreturn
Directorynames.Youwillneedtochecktheattributevalueofeveryreturnresult
todetermineifthereturnisavaliddirectoryname.Todoso,usetheGetAttr
function.Becausefilenamesareretrievedinnoparticularorder,youmaywant
tostorereturnedfilenamesinanarrayandthensortthearray.
Note:Thefilesystemkeepstrackofthecurrentdrive,andthecurrentdirectory
ofeverydrive.UsetheCurDirstatementtodeterminethecurrentdirectory.The
currentdrivelettercanbeextractedfromtheLeftcharacterreturnedinthe
CurDirstatement.
Syntax

Dir(File,Attrib)
File.............. FileName:TheargumentFilemustbeastringor
expressionthatcanrepresentavalidfilename,andmay
includeaDOSpathstructureincludingdirectoryorfolder
names,andadriveletter.
Attrib............ FileAttributes:TheargumentAttribmustbeanumberor
expressionthatcanrepresentasumoftheattributevaluesof
afile.Thiscanbeaconstantoranumericexpressionwhich
includesanycombinationofattributenumericvalues,whose
sumspecifiesallrelevantattributesofafile.
where:

0=Normal

117

1=ReadOnly

2=Hidden

4=System

8=Volume

16=DirectoryorFolder

32=Archive

Possiblecombinationsofvaluescansumto0,1,2,3,infacteverynumberfrom0
to64,eachrepresentingauniquecombinationofattributevalues.Forexample,a
fileattributevalueof6representsthatthefilehasbothSystem(4)andHidden
(2)attributesset.
ReturnValue

ReturnsaStringrepresentingthenameofafile,directory,orfolderthatmatches
aspecifiedpatternorfileattribute,orthevolumelabelofadrive.IfFileisnot
found,azerolengthstring()isreturned.IfAttribisomitted,allfilesare
returnedthatmatchFile.

RelatedFunctions

ChDir | ChDrive | CurDir, CurDir$ | MkDir | RmDir

Example
Dim strCurPath As String' declare string to store current path
Dim strFileName As String' declare string to store retrieved file name
Dim intFileCount As Integer' declare integer to keep count of retrieved files
Dim arrFileList() As String ' declare string array to store file names
strCurPath = CurDir$()' store current path for later restoration
ChDir "\"
' change to root directory of current drive
strFileName = Dir(*.dat)' retrieve file name with .dat extension
Do
' initialize loop
If strFileName = "" Then ' check to see if valid filename returned
exit do
' exit from loop
Else
intFileCount = intFileCount + 1' increment file counter variable
arrFileList(intFileCount) = strFileName' store file name in arrayRedim
arrFileList(intFileCount)' increase array size to count value
strFileName = Dir()' retrieve next file name to match original Dir call
EndIf
Loop Until strFileName = ""' loop again
ChDir strCurPath'restore previous current directory

118

Do Loop
Description

TheDo...Loopconditionalstatementallowsyoutoexecuteablockofstatements
anindefinitenumberoftimes.ThevariationsoftheDo...LoopareDoWhile,Do
Until,DoLoopWhile,andDoLoopUntil.
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>

DoWhileandDoUntilchecktheconditionbeforeenteringtheloop,thusthe
blockofstatementsinsidetheloopareonlyexecutedwhenthoseconditionsare
met.DoLoopWhileandDoLoopUntilchecktheconditionafterhaving
executedtheblockofstatementstherebyguaranteeingthattheblockof
statementsisexecutedatleastonce.
AnyDostatementcanbeexitedusingtheExitDostatement.

End Function
Description

Syntax
RelatedFunctions
Example

TheEndFunctionstatementendsaprogramorablockofstatementswithina
function.ACitectVBAfunctionstartswiththeFUNCTIONstatementand
finisheswiththeENDFUNCTIONstatement.Allotherstatementsthatlie
betweentheFUNCTIONandENDFUNCTIONstatementswillbeexecutedby
thefunctionwhencalledtodoso.
EndFunction
Call | Sub | End Sub | Exit
Function GetColor2( c% ) As Long
GetColor2 = c% * 25
If c% > 2 Then
GetColor2 = 255' 0x0000FF - Red
End If

119
If c% > 5 Then
GetColor2 = 65280' 0x00FF00 - Green
End If
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

End Sub
Description

Syntax
RelatedFunctions
Example

TheEndSubstatementendsaprogramorablockofstatementswithina
subroutine.ACitectVBAsubroutinestartswiththeSUBstatementandfinishes
withtheENDSUBstatement.AllotherstatementsthatliebetweentheSUBand
ENDSUBstatements,willbeexecutedbythesubroutine,whencalledtodoso.
EndSub
Call | End Function | Sub | Exit
Function GetColor2( c% ) As Long
GetColor2 = c% * 25
If c% > 2 Then
GetColor2 = 255' 0x0000FF - Red
End If
If c% > 5 Then
GetColor2 = 65280' 0x00FF00 - Green
End If
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

120

EOF
Description

EOFfunctionreturnsaBooleanTrueorFalsevalueduringfileaccessthat
indicateswhetherthecurrentpositionofanopenfilehasreachedtheendofthe
file.TherequiredFileNumargumentmustcontainanIntegerrepresentingany
validsystemfilenumberassociatedwithanopenfile.
Note:Thefilesystemkeepstrackofallopenfilesandthecurrentpositionof
accesswithineveryfile.Everystatementorfunctionthataccessesthedata
withinafile,altersthecurrentpositionwithinthatfile.TheLocfunctioncanbe
usedtodeterminethecurrentpositionwithinanopenfile.
UsetheLOFandLocfunctionsinsteadofEOFwhenreadingbinaryfileswith
theInputfunction,oruseGetwhenusingtheEOFfunction.
Note:AnerroroccurswithfilesopenedforBinaryaccess,whenthefileisread
usingtheInputfunctionuntilEOFreturnsTrue.

Syntax

EOF(FileNum)
FileNum ......... FileNumber:TheargumentFileNummustcontainan
Integerornumericexpressionrepresentinganyvalid
numberintherange1to511inclusive,whichisreferenced
bythefilesystemtobeassociatedwithanopenfile.

ReturnValue

RelatedFunctions
Example

ReturnsanIntegercontainingtheBooleanvalueFalseuntiltheendofthefile
hasbeenreached.ReturnsTruewhentheendofafileopenedforRandomor
sequentialInputhasbeenreached.
FileLen | Loc | LOF | Seek
Dim strFileContents as String, strTemp as String
Open "c:\test.txt" For Input As #1' open file
Do While Not EOF(1)' loop until end of file
strTemp = Input(10, #1)' read next ten characters
strFileContents = strFileContents & strTemp' join strings
Loop
Close #1

Erase
Description
Syntax

ReinitialisestheelementsofafixedarrayspecifiedintheArrayListparameter.
Erase(Arraylist)

121
Arraylist......... ArrayList:TheparameterArrayListmustbeacomma
delimitedlistofvalidvariablearraynames.
RelatedFunctions
Example

Dim | ReDim
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.

Exit
Description
Syntax
Example

Exitsalooporprocedure.
Exit{Do|For|Function|Sub}
' 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

Exp
Description

Calculatestheexponentialofanumber.Theexponentialisthebaseofthe
naturallogarithmeraisedtoapower(e^Num).TheExpfunctioncomplements
theLogfunctionandissometimesreferredtoastheantilogarithm.
Note:Thevalueoftheconstanteisapproximately2.71828.

122
Syntax

Exp(Num)
Num ............ Number:TheargumentNummustcontainanIntegeror
expressionrepresentingavalidnumericvalue.

ReturnValue

RelatedFunctions
Example

Returnsthevalueequivalenttothebaseofthenaturallogarithm(e)raisedtothe
powerofthenumber(Num)providedintheargument.
Log
Variable=Exp(1);! Sets Variable to 2.7182...

FileCopy
Description

CopiesafilefromSrctoDest.
Therequiredsourcefile(Src)anddestinationfile(Dest)argumentsmustbe
validstringexpressionsrepresentingvalidfilenames.Srcisthefilenameofthe
filetocopyfrom.Destisthefilenametobecopiedto.BothSrcandDest
argumentsmaycontainaDOSpathstructureincludingdirectoryorfolder
names,andadriveletter.
IftheDestfiledoesnotexist,itwillbecreatedbytheFileCopystatement.Ifthe
Destfilealreadyexists,itwillbeoverwritten.
TheFileCopystatementdoesnotworkonacurrentlyopenfile.BoththeSrcand
DestfilesmustbeclosedbeforeusingtheFileCopystatement.Tocloseanopen
file,usetheClosestatement.
Note:Thefilesystemkeepstrackofthecurrentdrive,andthecurrentdirectory
ofeverydrive.UsetheCurDirstatementtodeterminethecurrentdirectory.The
currentdrivelettercanbeextractedfromtheLeftcharacterreturnedinthe
CurDirstatement.

Syntax

FileCopySrc,Dest
Src .............. SourceFile:TheargumentSrcmustbeastringor
expressionthatcanrepresentavalidDOSfilestructure
FileName.Srciscaseinsensitive.Thismayincludearelative
orstaticPathincludingdirectoryorfolderstructureand
driveletter.Tospecifymultiplefiles,theFileNamemay
consistofmultiplecharacter(*)andsinglecharacter(?)
wildcardsinthefilename.
Dest ............. DestinationFile:TheargumentDestmustbeastringor
expressionthatcanrepresentavalidDOSfilestructure
FileName.Destiscaseinsensitive.Thismayincludearelative

123
orstaticPathincludingdirectoryorfolderstructureand
driveletter.Tospecifymultiplefiles,theFileNamemay
consistofmultiplecharacter(*)andsinglecharacter(?)
wildcardsinthefilename.
RelatedFunctions
Example

Close | FreeFile | Kill | Name | Open


Dim SourceFile as String, DestinationFile as String
SourceFile = "SRCFILE.Dat"' Define source file name.
DestinationFile = "DESTFILE.Dat"' Define target file name.
FileCopy SourceFile, DestinationFile' Copy source to target.

FileLen
Description

FileLenfunctiondeterminesthebytelengthofafile.TherequiredFileargument
mustbevalidstringexpressionrepresentingavalidfilename.Filemaycontaina
DOSpathstructureincludingdirectoryorfoldernames,andadriveletter.
TheFileLenfunctionreturnsthesizeofafileimmediatelybeforeitwasmost
recentlyopened.Toobtainthelengthofafilethatisalreadyopen,usetheLOF
function.

Syntax

FileLen(File)
File.............. FileName:TheargumentFilemustbeastringor
expressionthatcanrepresentavalidfilename,andmay
includeaDOSpathstructureincludingdirectoryorfolder
names,andadriveletter.

ReturnValue
RelatedFunctions
Example

ReturnsaLongvaluerepresentingthelengthofthefilemeasuredinbytes.
EOF | Loc | LOF | Seek
Dim lonFileSize As Long
lonFileSize = FileLen("C:\TESTFILE.txt")' returns length of file
in bytes

Fix
Description

Calculatestheintegerportionofanumber.Fixdoesnotroundthenumber,and
ignoresthefractionalvalueofthenumber.
Fixexpectstheargument(Num)tobeavalidnumericvalue.Iftheargument
valueispositive,roundstheNumdownbydroppinganyfractionalvalue.Ifthe

124
argumentvalueisnegative,roundstheNumuptothenextintegernumber
greaterthanorequaltoNum.
DonotconfuseFixwithInt,whichroundsanegativeargumentvalue(Num)
downtothenextintegernumberlessthanorequaltoNum.
Syntax

Fix(Num)
Num ............ Number:TheargumentNummustcontainanIntegeror
expressionrepresentingavalidnumericvalue.

ReturnValue
RelatedFunctions
Example

ReturnstheIntegervalueofthenumber(Num)providedintheargument.
Abs | Int | Sgn | Sqrt
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

For
Description

Example

Repeatsitsblockofstatementsasetnumberoftimesasdeterminedbythe
valuesusedwiththeToclause.
For <CounterName> = <BeginValue> To <EndValue> [Step <StepValue>]
<statement/s>
Next

Format
Description

Formatsastring,number,orvarianttotheformatexpression(fmt).TheFormat
functionexpectstheargument(Exp)tobeavalidexpressiontobeformatted.
TheFormatfunctionexpectstheargument(fmt)tobeastringofcharactersthat
specifyhowtheexpressionistodisplayed,orthenameofacommonlyused
formatthathasbeenpredefinedinCitectVBA.Donotmixdifferenttypeformat
expressionsinasinglefmtparameter.
Ifthefmtparameterisomittedoriszerolengthandtheexpressionparameteris
anumeric,Format[$]providesthesamefunctionalityastheStr[$]functionby
convertingthenumericvaluetotheappropriatereturndatatype.Positive
numbersconverttostringsusingFormat[$]lacktheleadingspacereservedfor

125
displayingthesignofthevalue,whereasthoseconvertedusingStr[$]retainthe
leadingspace.
Toformatnumbers,youcanusethecommonlyusedformatsthathavebeen
predefinedinCitectVBA,oryoucancreateuserdefinedformatswithstandard
charactersthathavespecialmeaningwhenusedinaformatexpression.
Syntax

Format(Exp[,fmt])
Exp ............. Expression:TheargumentExpwilldependuponwhich
datatypeisexpectedinthefunction.Ifastringisexpected,
ExpmaybeavalidstringorVariantcontainingavalue
recognizableasastring.
Ifanumberisexpected,Expmaybeavalidnumberor
Variantcontainingavaluerecognizableasanumber.

ReturnValue

Returnsaformattedstring.
Predefinednumericformatnames:

GeneralDisplaythenumberasis,withnothousandSeparators

FixedDisplayatleastonedigittotheleftandtwodigitstotherightofthe
decimalseparator.

StandardDisplaynumberwiththousandseparator,ifappropriate;display
twodigitstotherightofthedecimalseparator.

PercentDisplaynumbermultipliedby100withapercentsign(%)
appendedtotherightdisplaytwodigitstotherightofthedecimal
separator.

ScientificUsestandardscientificnotation.

True/FalseDisplayFalseifnumberis0,otherwisedisplayTrue.

Userdefinednumberformats.

NullstringDisplaythenumberwithnoformatting.

0Digitplaceholder.

Displayadigitorazero
Ifthenumberbeingformattedhasfewerdigitsthantherearezeros(oneither
sideofthedecimal)intheformatexpression,leadingortrailingzerosare
displayed.Ifthenumberhasmoredigitstotherightofthedecimalseparator
thantherearezerostotherightofthedecimalseparatorintheformat
expression,thenumberisroundedtoasmanydecimalplacesastherearezeros.
Ifthenumberhasmoredigitstoleftofthedecimalseparatorthantherearezeros
totheleftofthedecimalseparatorintheformatexpression,theextradigitsare
displayedwithoutmodification.

126

Digitplaceholder(#).Displaysadigitornothing.Ifthereisadigitinthe
expressionbeingformattedinthepositionwherethe#appearsintheformat
string,displaysit;otherwise,nothingisdisplayed.

Decimalplaceholder(.).Thedecimalplaceholderdetermineshowmany
digitsaredisplayedtotheleftandrightofthedecimalseparator.

Percentageplaceholder.(%)Thepercentcharacter(%)isinsertedinthe
positionwhereitappearsintheformatstring.Theexpressionismultiplied
by100.

Thousandseparator(,).Thethousandseparatorseparatesthousandsfrom
hundredswithinanumberthathasfourormoreplacestotheleftofthe
decimalseparator.Useofthisseparatorasspecifiedintheformatstatement
containsacommasurroundedbydigitplaceholders(0or#).Twoadjacent
commasoracommaimmediatelytotheleftofthedecimalseparator
(whetherornotadecimalisspecified)meansscalethenumberbydividing
itby1000,roundingasneeded.

Scientificformat(EE+ee+).Iftheformatexpressioncontainsatleastone
digitplaceholder(0or#)totherightofE,E+,eore+,thenumberis
displayedinscientificformattedEoreinsertedbetweenthenumberandits
exponent.Thenumberofdigitplaceholderstotherightdeterminesthe
numberofdigitsintheexponent.UseEoretoplaceaminussignnextto
negativeexponents.UseE+ore+toplaceaplussignnexttopositive
exponents.

Timeseparator(:).Theactualcharacterusedasthetimeseparatordepends
ontheTimeFormatspecifiedintheInternationalsectionoftheControl
Panel.

Dateseparator(/).Theactualcharacterusedasthedateseparatorinthe
formattedoutdependsonDateFormatspecifiedintheInternationalsection
oftheControlPanel.

Displayaliteralcharacter(+$()).Todisplayacharacterotherthanoneof
thoselisted,precedeitwithabackslash(\).

Displaythenextcharacterintheformatstring(\).Thebackslashitselfisnt
displayed.Todisplayabackslash,usetwobackslashes(\\).
Note:Examplesofcharactersthatcantbedisplayedasliteralcharactersare
thedateandtimeformattingcharacters(a,c,d,h,m,n,p,q,s,t,w,y,and/:),the
numericformattingcharacters(#,0,%,E,e,comma,andperiod),andthe
stringformattingcharacters(@,&,<,>,and!).

Displaythestringinsidethedoublequotationmarks(String).Toincludea
stringinfmtfromwithinCitectVBA,youmustusetheANSIcodefora
doublequotationmarkChr(34)toenclosethetext.

127

Displaythenextcharacterasthefillcharacter(*).Anyemptyspaceinafield
isfilledwiththecharacterfollowingtheasterisk.

Unlessthefmtargumentcontainsoneofthepredefinedformats,aformat
expressionfornumberscanhavefromonetofoursectionsseparatedby
semicolons.
If you use

The result is

One section
Two
Three

The format expression applies to all values.


The first section applies to positive values, the second to negative sections values.
The first section applies to positive values, the second to negative sections values, and the
third to zeros.
The first section applies to positive values, the second to negative section values, the third
to zeros, and the fourth to Null values.

Four

Thefollowingexamplehastwosections:thefirstdefinestheformatforpositive
valuesandzeros;thesecondsectiondefinestheformatfornegativevalues.
$#,##0;($#,##0)
Ifyouincludesemicolonswithnothingbetweenthem.themissingsectionis
printedusingtheformatofthepositivevalue.Forexample,thefollowingformat
displayspositiveandnegativevaluesusingtheformatinthefirstsectionand
displaysZeroifthevalueiszero.
"$#,##0;;\Z\e\r\o"

Somesampleformatexpressionsfornumbersareshownbelow.(Theseexamples
allassumetheCountryissettoUnitedStatesintheInternationalsectionofthe
ControlPanel.)Thefirstcolumncontainstheformatstrings.Theothercolumns
containtheoutputtheresultsiftheformatteddatahasthevaluegiveninthe
columnheadings.
Format (fmt)

Positive 3

Negative 3

Decimal .3

Null string
0
0.00
#,##0
#,##0.00;;;Nil
$#,##0;($#,##0)
$#,##0.00;($#,##0.00)
0%
0.00%
0.00E+00
0.00E-00

3
3
3.00
3
3.00
$3
$3.00
300%
300.00%
3.00E+00
3.00E00

-3
-3
-3.00
-3
-3.00
($3)
($3.00)
-300%
-300.00%
-3.00E+00
-3.00E00

0.3
1
0.30
1
0.30
$1
$0.30
30%
30.00%
3.00E-01
3.00E-01

Null

Nil

128
Numberscanalsobeusedtorepresentdateandtimeinformation.Youcan
formatdateandtimeserialnumbersusingdateandtimeformatsornumber
formatsbecausedate/timeserialnumbersarestoredasfloatingpointvalues.
Toformatdatesandtimes,youcanuseeitherthecommonlyusedformatthat
havebeenpredefinedorcreateuserdefinedtimeformatsusingstandard
meaningofeach:
General

Long Date
Medium
Short Date
Long Time
Medium
Short Time
c
d
dd
ddd
ddddd
w
ww
m
mm
mmm
mmmm
q
y
yy
yyyy
h
hh
n
nn
s
ss

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).
Display a Long Date, as defined in the International section of the Control Panel.
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.
Display a Short Date, as defined in the International section of the Control Panel.
Display a Long Time, as defined in the International section of the Control panel. Long
Time includes hours, minutes, seconds.
Display time in 12-hour format using hours and minuets and the Time AM/PM designator.
Display a time using the 24-hour format (e.g. 17:45)
Display the date as dddd and display the time as ttttt. in the order.
Display the day as a number without a leading zero (1-31).
Display the day as a number with a leading zero (01-31).
Display the day as an abbreviation (Sun-Sat).
Display a date serial number as a complete date (including day , month, and year).
Display the day of the week as a number (1- 7 ).
Display the week of the year as a number (1-53).
Display the month as a number without a leading zero (1-12). If m immediately follows h or
hh, the minute rather than the month is displayed.
Display the month as a number with a leading zero (01-12). If mm immediately follows h or
hh, the minute rather than the month is displayed.
Display the month as an abbreviation (Jan-Dec).
Display the month as a full month name (January-December).
display the quarter of the year as a number (1-4).
Display the day of the year as a number (1-366).
Display the day of the year as a two-digit number (00-99)
Display the day of the year as a four-digit number (100-9999).
Display the hour as a number without leading zeros (0-23).
Display the hour as a number with leading zeros (00-23).
Display the minute as a number without leading zeros (0-59).
Display the minute as a number with leading zeros (00-59).
Display the second as a number without leading zeros (0-59).
Display the second as a number with leading zeros (00-59).

129
ttttt

AM/PM
am/pm
A/P
a/p
AMPM

m/d/yy
d-mmmm-yy
d-mmmm
mmmm-yy
hh:nn
h:nn:ss a/p
h:nn:ss
m/d/yy/h:nn

Display a time serial number as a complete time (including hour, minute, 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.
Use the 12-hour clock and display an uppercase AM/PM
Use the 12-hour clock display a lowercase am/pm
Use the 12-hour clock display a uppercase A/P
Use the 12-hour clock display a lowercase a/p
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 contents 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.
2/26/65
26-February-65
26 February
February 65
AM/PM 06:45 PM
6:45:15 p
18:45:15
2/26/65 18:45

StringscanalsobeformattedwithFormat[$].Aformatexpressionforstrings
canhaveonesectionortwosectionsseparatedbyasemicolon.
If you use

The result is

One section only


Two sections

The format applies to all string data.


The first section applies to string data, the second to Null values and zero-length
strings.

Thefollowingcharacterscanbeusedtocreateaformatexpressionforstrings:
@
&
<
>
!

RelatedFunctions
Example

Character placeholder. Displays a character or a space. Placeholders are filled from right to left
unless there is an !character in the format string.
Character placeholder. Display a character or nothing.
Force lowercase.
Force uppercase.
Force placeholders to fill from left to right instead of right to left.

Hex | Oct | Str | Val


' Format Function Example
' This example shows various uses of the Format function to format
values
' using both named and user-defined formats. For the date
separator (/),

130
' 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".

131

FreeFile
Description

Syntax
ReturnValue

Retrievesthenextsequentialsystemfilenumberavailableforassociationwitha
file.UsetheFreeFilefunctiontoretrieveanunassociatedfilenumberfromthe
filesystem.ThisnumbercanbeusedbytheOpenstatementtobeassociated
withafile.
FreeFile
ReturnsanIntegerreferencenumberreadyforbeingassociatedwithafile.

RelatedFunctions

Close | FileCopy | Kill | Name | Open

Example

Dim intFileNum as Integer


intFileNum = FreeFile'retrieve next free file number
Open "c:\TEST.txt" For Output As #intFileNum
Write #intFileNum, "This is a sample line of text."
Close #intFileNum

Function
Description

TheFunctionstatementdeclaresanddefinesafunctionprocedure,itsname,
parameters,andcodetobeenacteduponwhenthesubroutineiscalled.
Functionsdifferfromsubroutinesinthatfunctionsreturnavalue,whereas
subroutinesdonot.
TherequiredFunctionNameisthenameofthefunctionbeingdeclared.The
optionalArgLististhelistofargumentsusedwithinthefunction.
ACitectVBAfunctionstartswiththeFUNCTIONstatementandfinisheswith
theENDFUNCTIONstatement.Allotherstatementsthatliebetweenthe
FUNCTIONandENDFUNCTIONstatementswillbeexecutedbythefunction
whencalledtodoso.

Syntax
RelatedFunctions
Example

FunctionFname[(Arguments)][Astype]
Call | End Function | Sub | End Sub | Exit
Function GetColor2( c% ) As Long
GetColor2 = c% * 25
If c% > 2 Then
GetColor2 = 255' 0x0000FF - Red
End If
If c% > 5 Then
GetColor2 = 65280' 0x00FF00 - Green

132
End If
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

Get #
Description

Getstatementreadsdatafromadiskfileintoavariable.
TherequiredFileNumargumentisasystemreferencenumberassociatedwithan
openfile.TheoptionalRecNumargumentisthebytepositionwheretheread
startsforfilesopenedinBinarymode.IfyouomitRecNum,thenextrecordor
bytefollowingthelastGetorPutstatement(orpointedtobythelastSeek
function)isread.Youmustincludedelimitingcommas.
TherequiredVarNameisthenameofthevariablewherethefiledataisread
(copied)to.
Randommode
ForfilesopenedinRandommode,thefollowingrulesapply:

IfthelengthofthedatabeingreadislessthanthelengthspecifiedintheLen
clauseoftheOpenstatement,Getreadssubsequentrecordsonrecord
lengthboundaries.Thespacebetweentheendofonerecordandthe
beginningofthenextrecordispaddedwiththeexistingcontentsofthefile
buffer.Becausetheamountofpaddingdatacantbedeterminedwithany
certainty,itisgenerallyagoodideatohavetherecordlengthmatchthe
lengthofthedatabeingread.

Ifthevariablebeingreadintoisavariablelengthstring,Getreadsa2byte
descriptorcontainingthestringlengthandthenreadsthedatathatgoesinto
thevariable.Therefore,therecordlengthspecifiedbytheLenclauseinthe
Openstatementmustbeatleast2bytesgreaterthantheactuallengthofthe
string.

IfthevariablebeingreadintoisaVariantofnumerictype,Getreads2bytes
identifyingtheVarTypeoftheVariantandthenthedatathatgoesintothe
variable.Forexample,whenreadingaVariantofVarType3,Getreads6
bytes:2bytesidentifyingtheVariantasVarType3(Long)and4bytes

133
containingtheLongdata.TherecordlengthspecifiedbytheLenclausein
theOpenstatementmustbeatleast2bytesgreaterthantheactualnumber
ofbytesrequiredtostorethevariable.
Note:YoucanusetheGetstatementtoreadaVariantarrayfromdisk,but
youcantuseGettoreadascalarVariantcontaininganarray.Youalsocant
useGettoreadobjectsfromdisk.

IfthevariablebeingreadintoisaVariantofVarType8(String),Getreads2
bytesidentifyingtheVarType,2bytesindicatingthelengthofthestring,and
thenreadsthestringdata.TherecordlengthspecifiedbytheLenclausein
theOpenstatementmustbeatleast4bytesgreaterthantheactuallengthof
thestring.

Ifthevariablebeingreadintoisadynamicarray,Getreadsadescriptor
whoselengthequals2plus8timesthenumberofdimensions,thatis,2+8*
NumberOfDimensions.TherecordlengthspecifiedbytheLenclauseinthe
Openstatementmustbegreaterthanorequaltothesumofallthebytes
requiredtoreadthearraydataandthearraydescriptor.Forexample,the
followingarraydeclarationrequires118byteswhenthearrayiswrittento
disk.

Ifthevariablebeingreadintoisafixedsizearray,Getreadsonlythedata.
Nodescriptorisread.

Ifthevariablebeingreadintoisanyothertypeofvariable(notavariable
lengthstringoraVariant),Getreadsonlythevariabledata.Therecord
lengthspecifiedbytheLenclauseintheOpenstatementmustbegreater
thanorequaltothelengthofthedatabeingread.

Getreadselementsofuserdefinedtypesasifeachwerebeingreadindividually,
exceptthatthereisnopaddingbetweenelements.Ondisk,adynamicarrayina
userdefinedtype(writtenwithPut)isprefixedbyadescriptorwhoselength
equals2plus8timesthenumberofdimensions,thatis,2+8*
NumberOfDimensions.TherecordlengthspecifiedbytheLenclauseinthe
Openstatementmustbegreaterthanorequaltothesumofallthebytes
requiredtoreadtheindividualelements,includinganyarraysandtheir
descriptors.
Binarymode
ForfilesopenedinBinarymode,alloftheRandomrulesapply,except:

TheLenclauseintheOpenstatementhasnoeffect.Getreadsallvariables
fromdiskcontiguously;thatis,withnopaddingbetweenrecords.

Foranyarrayotherthananarrayinauserdefinedtype,Getreadsonlythe
data.Nodescriptorisread.

134
Getreadsvariablelengthstringsthatarentelementsofuserdefinedtypes
withoutexpectingthe2bytelengthdescriptor.Thenumberofbytesreadequals
thenumberofcharactersalreadyinthestring.
Syntax

Get#(FileNum,RecNum,VarName)
FileNum ......... FileNumber:TheargumentFileNummustcontainan
Integerornumericexpressionrepresentinganyvalid
numberintherange1to511inclusive,whichisreferenced
bythefilesystemtobeassociatedwithanopenfile.
RecNum ......... RecordNumber:TheargumentRecNum.
VarName......... VariableName:TheargumentVarNamemustbeastring
representingavalidvariablename.

RelatedFunctions

Example

GetAttr | Input | Line Input # | Print # | Put # |


Write #
Type Record ' Define user-defined type.
ID As Integer
Name As String * 20
End Type
Dim recRecord As Record
Dim intPosition As Integer
Dim intFileNum as Integer
intFileNum = FreeFile'retrieve next free file number
' Open sample file for random access.
Open "TESTFILE.txt" For Random As #intFileNum
' Read the sample file using the Get statement.
intPosition = 3' Define third record number.
Get #intFileNum, intPosition, recRecord' Read third record.
Close #intFileNum' Close file.

GetAttr
Description

GetAttrfunctionreturnsanIntegerrepresentingtheattributesettingsofafile,
directory,orvolume.
TherequiredFileargumentmustbevalidstringexpressionrepresentingavalid
filename.FilemaycontainaDOSpathstructureincludingdirectoryorfolder
names,andadriveletter.
Todeterminewhichattributesareset,usetheANDoperatortoperforma
bitwisecomparisonofthevaluereturnedbytheGetAttrfunctionandthevalue
oftheindividualfileattributeyouwant.Iftheresultisnotzero,thatattributeis

135
setforthenamedfile.Forexample,thereturnvalueofthefollowingAND
expressioniszeroiftheArchiveattributeisnotset:
Const AttrArchive = 32
Result = GetAttr(FileName) And AttrArchive' A nonzero value is
returned if the Archive attribute is set.

Syntax

GetAttr(File)
File.............. FileName:TheargumentFilemustbeastringor
expressionthatcanrepresentavalidfilename,andmay
includeaDOSpathstructureincludingdirectoryorfolder
names,andadriveletter.

ReturnValue

RelatedFunctions
Example

ReturnsanIntegernumberindicatingthesumAttributevalueofafile,directory,
orfolderfortheFileargument,where:

0=Normal

1=ReadOnly

2=Hidden

4=System

8=Volume

16=DirectoryorFolder

32=Archive

Get # | Line Input # | Print # | Put #


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.

Goto
Description

TheGoToconditionalstatementbranchesunconditionallyandwithoutreturnto
thelabelspecifiedintheGoTostatement.Thelabelmustbelocatedinthesame
subroutineorfunctionastheGotostatement.

136
Example

<statement/s>
If <condition> then
GoTo Label1
Else
GoTo Label2
End If
Label1:
<statement/s>
GoTo Label3
Label2:
<statement/s>
GoTo Label3
Label3:
<statement/s>

Inthisexample,CitectVBAteststheIfcondition,andjumpstothepartofthe
scriptthatbeginswiththelabel
Label1:iftheconditionwastrue,orjumpstothepartofthescriptthatbegins
withthelabelLabel2:iftheconditionwasfalse.Thiscouldbeanywhereinthe
samesubroutineorfunction.

Hex
Description

Convertsanumericvaluetoatextstringrepresentingthehexadecimalvalueof
thenumber.
TheHexfunctionexpectstheargument(Num)tobeavalidnumericvalue.Itis
roundedtonearestwholenumberbeforeevaluation.

Syntax

Hex(Num)
Num ............ Number:TheargumentNummustcontainanIntegeror
expressionrepresentingavalidnumericvalue.

ReturnValue

RelatedFunctions
Example

Returnsatextstringcontainingthehexadecimalvalueofthenumeric(Num)
valueprovidedintheargument.
Format | Oct | Str | Val
Dim MyHex as String
MyHex = Hex(5)'returns "5"
MyHex = Hex(10)'returns "A"
MyHex = Hex(459)'returns "1CB"

137

Hour
Description
Syntax

Calculatesthehourvaluefromthegiventimeargumentpassedtothefunction.
Hour(Time)
Time............. Time:TheargumentTimemustbeastringorexpression
thatcanrepresentatimevalue.Thisincludesand
combinationoftimeliterals,numbersthatlookliketimes,
stringsthatlookliketimes,andtimesfromfunctions.

ReturnValue
RelatedFunctions
Example

Returnsanintegerbetween0and23thatisthehouroftheparameter(Time).
Minute | Second
Dim varMyHour, varMyTime
varMyTime = "08:04:23 PM"
varMyHour = Hour(varMyTime)
' stores hours value.

If
Description

Testsaninitialconditionandtheneitherperformsoromitstoperformthe
statementsitcontains,dependantuponthelogicalresultofthetestcondition.
Theconditioncanbeacomparisonoranexpression,andmustlogicallyevaluate
toeitherTrueorFalse.TheIfstatementhasbothsinglelineandmultipleline
syntaxstructure.
ThesinglelinesyntaxusestheIf<TestCondition>Then
<StatementToPerformIfTrue>structure,however,canonlyperformasingle
statementifandonlyifthetestconditionresultisTrue.NoEndIfstatementis
required:

Example

If<Condition>Then<Statement>
IftheresultoftheIftestconditionwasTrue,theprogramflowcontinuesinto
andperformsthestatementfollowingtheThenstatement,untilitreachesthe
endoftheline.
ToperformasinglestatementconditionallyuponaFalseresult,usetheNOT
logicaloperator:
If NOT <Condition> Then <Statement>

Toperformmultiplestatements,usethemultiplelinesyntaxstructurewhich
endswiththeEndIfstatement:

138
If <Condition> Then
' Then statement block
' perform only if true
<Statement/s>
End If

IftheresultoftheIftestconditionwasTrue,theprogramflowcontinuesintothe
Thenstatementblock,andperformsthestatementsfollowingtheThen
statement,untilitreachestheEndIfstatement.
IftheresultoftheIftestconditionwasFalse,theprogramflowjumps
completelyovertheThenstatementblock,whichinthiscaseexitstheIf
structure(withoutperforminganystatementsotherthantheinitialtest
condition).
ThemutiplelineIfstructurecanperformdifferentblocksofstatements
dependantuponEITHERaTrueORaFalseresulttothetestcondition,through
theuseoftheElsestatementblock:
If <Condition> Then
' Then statement block
' perform only if true
<Statement/s>
Else
' Else statement block
' perform only if false
<Statement/s>
End If

IftheresultoftheIftestconditionwasTrue,theprogramflowperformsthe
Thenblockstatements,untilitreachestheElsestatement.Itthenjumps
completelyovertheElsestatementblockandexitstheIfstructure(without
performinganyoftheElsestatementblockstatements).
FurthertestconditionscanbeplacedintoanIfstructurethroughtheuseofthe
optionalElseIf<Condition>statementblock.ElseIfstatementblockscanonlybe
positionedwithinanIfstructurebeforetheElsestatementblock.Iftheresultof
theIftestconditionwasFalse,theprogramflowjumpscompletelyoverthe
Thenstatementblock(withoutperforminganyofthosestatements)totheElse
statementtoperformthestatementsintheElsestatementblockuntilitreaches
theEndIfstatement.
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

139
' Else statement block
' perform only if false
<Statement/s>
End If

TheElseIftestconditionisonlyevaluatedaftertheinitialIfstructuretest
conditionresultsinFalse.
IftheresultoftheElseIftestconditionwasTrue,thestatementswithintheElseIf
statementblockareperformed.Theprogramflowthenjumpscompletelyover
theElsestatementblockandexitstheIfstructure(withoutperforminganyofthe
Elsestatementblockstatements).
IftheresultoftheElseIftestconditionwasFalse,theprogramflowjumps
completelyovertheElseIfstatementblock(withoutperforminganyofthose
statements)totheElsestatementtoperformthestatementsintheElsestatement
blockuntilitreachestheEndIfstatement.
ThereisnoapparentlimittothenumberofElseIfstatementblocksthatanyone
Ifstructurecanhold,however,theSelectCaseStatementstructurehandles
multipleconditionresultalternativesmuchmoreefficiently.

Input

Input#statementreadsdatafromaSequentialfileandassignsthatdatato
variables.InputfunctionreturnscharactersfromafileopenedinInputorBinary
mode.
TheInput#statementhastwoparametersFileNumandVarList.Therequired
FileNumargumentistheassociatedfilenumberusedintheOpenstatement
whenthefilewasopened.TherequiredVarListargumentisacommadelimited
listofvariablesthatareassignedvaluesreadfromthefile.
TheInputfunctionhastwoparameters:NumandFileNum.TherequiredNum
argumentisanumberorvalidnumericexpressionspecifyingthenumberof
characters(bytes)tobereadfromthefile.FileNumistheassociatedfilenumber
usedintheOpenstatementwhenthefilewasopened.
Thefilesystemtracksallopenfilesandthecurrentpositionofaccesswithin
everyfile.Everystatementorfunctionthataccessesthedatawithinafile,alters
thecurrentpositionwithinthatfile.TheLocfunctioncanbeusedtodetermine
thecurrentpositionwithinanopenfile.
UsetheLOFandLocfunctionsinsteadofEOFwhenreadingbinaryfileswith
theInputfunction,oruseGetwhenusingtheEOFfunction.
AnerroroccurswithfilesopenedforBinaryaccess,whenthefileisreadusing
theInputfunctionuntilEOFreturnsTrue.

140
DatareadwiththeInput#statementhasusuallybeenwrittentoafilewiththe
Write#statement.DatareadwiththeInputfunctionhasusuallybeenwrittento
afilewiththePrint#orPutstatements.
WhensavingdatatoafileforfuturereadingwiththeInput#statement,usethe
Write#statementinsteadofthePrint#statementtowritethedatatothefile.
UsingWrite#ensurestheintegrityofeachseparatedatafieldbyproperly
delimitingit,soitcanbereadbackinusingInput#.UsingWrite#alsoensuresit
canbecorrectlyreadinanylocale.
Syntax

Input#(FileNum,VarList)
FileNum ......... FileNumber:TheargumentFileNummustcontainan
Integerornumericexpressionrepresentinganyvalid
numberintherange1to511inclusive,whichisreferenced
bythefilesystemtobeassociatedwithanopenfile.
VarList ........... VariableList:TheargumentVarListmustbeapredefined
validCitectVBAvariablenameorcommadelimitedlistof
validvariablenames.

ReturnValue

Input#statementreturnsdatarecordbyrecordfromafileopenedinInputor
Binarymode.Dataitemsinafilemustappearinthesameorderasthevariables
inVarListandmatchvariablesofthesamedatatype.Ifavariableisnumericand
thedataisnotnumeric,avalueofzeroisassignedtothevariable.
InputfunctionreturnsaStringcontainingcharactersfromafileopenedinInput
orBinarymode.TheInputfunctionreturnsallofthecharactersitreads,
includingcommas,carriagereturns,linefeeds,quotationmarks,andleading
spaces.

RelatedFunctions

Example

Get # | GetAttr | Line Input # | Print # | Put # |


Write #
Dim strFileContents As String
Dim strTemp As String
Dim strString As String
Dim intFileNum as Integer
Dim intNumber as Integer
intFileNum = FreeFile'retrieve next free file number
Open "c:\test.txt" For Input As #intFileNum' open file.
Do While Not EOF(intFileNum)' loop until end of file
strTemp = Input(10, #intFileNum)' read next ten characters
strFileContents = strFileContents & strTemp' join strings
Loop
Input #intFileNum, strString, intNumber' Read data into two
variables.
Close #intFileNum

141

InStr
Description

ReturnsthecharacterpositionofthefirstoccurrenceofString2withinString1.
TheoptionalNumargumentisanumericexpressionthatsetsthestarting
positionforthesearch.Ifomitted,searchbeginsatthefirstcharacterposition.If
NumcontainsNull,anerroroccurs.
TherequiredString1argumentisthestringexpressionbeingsearched.
TherequiredString2argumentisthestringexpressionbeingsearchedfor.

Syntax

InStr(Num,String1,String2)
Num ............ Number:TheargumentNummustcontainanIntegeror
expressionrepresentingavalidnumericvalue.
String1 .......... String:TheargumentStrmustbeastringorexpressionthat
canrepresentavalidtextvalue.
String2 .......... String:TheargumentStrmustbeastringorexpressionthat
canrepresentavalidtextvalue.

ReturnValue

ReturnsavariantcontainingaLongdatatypeindicatingtheresultofthestring
search.Returns0if:

StringToSearchisofzerolength.

StringToMatchisnotfound.

StartPosislongerthanStringToMatch.

Returnsavaluerepresentingthecountpositionwherecharactermatchwasfirst
found.
ReturnsNullifStringToSearchorStringToMatchcontainsnull.
RelatedFunctions

IsNull | Left,Left$ | Mid | Right | StrComp

Example

Dim strToSearch as String


Dim strToFind as String
Dim lngPosition as Long
strToSearch = "Good Bye"
' note this has an uppercase "B"
strToFind = "bye"
' note this has a lowercase "b"
lngPosition = InStr(1, strToSearch, strToFind, 0)
' returns 0 (Did not find match)
lngPosition = InStr(1, strToSearch, strToFind, 1)
' returns 6 (Position of first character in match)

142

Int
Description

Calculatestheintegerportionofanumber.Intdoesnotroundthenumber,and
ignoresthefractionalvalueofthenumber.
Intexpectstheargument(Num)tobeavalidnumericvalue.Iftheargument
valueispositive,roundstheNumdownbydroppinganyfractionalvalue.Ifthe
argumentvalueisnegative,roundstheNumdowntothenextintegernumber
lessthanorequaltoNum.
DonotconfuseIntwithFix,whichroundsanegativeargumentvalue(Num)up
tothenextintegernumbergreaterthanorequaltoNum.

Syntax

Int(Num)
Num ............ Number:TheargumentNummustcontainanIntegeror
expressionrepresentingavalidnumericvalue.

ReturnValue

RelatedFunctions
Example

Returnstheintegervalueofthenumber(Num)providedintheargument.If
NumcontainsaNull,IntreturnsaNull.
Abs | Fix | Rnd | Sgn | Sqrt
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

IsDate
Description

Determinesifanexpressioncanbeconvertedtoadate.
TherequiredexpressionargumentisaVariantcontainingadateexpressionor
stringexpressionrecognizableasadateortimevalue.

Syntax

IsDate(Date)
Date ............. Date:TheargumentDatemustbeastringorexpressionthat
canrepresentadatevalue.Thisincludesanycombinationof
dateliterals,numbersthatlooklikedates,stringsthatlook
likedates,anddatesfromfunctions.

ReturnValue
RelatedFunctions

ReturnsaBooleanTrueorFalse.
IsEmpty | IsNull | IsNumeric | VarType

143
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
Description

Determinesifavariantparameterhasbeeninitialised.
TherequiredExpargumentisavariantcontaininganumericorstring
expression.However,becauseIsEmptyisusedtodetermineifindividual
variablesareinitialised,theExpargumentismostoftenasinglevariablename.
IsEmptyreturnsTrueifthevariableisuninitialised,orisexplicitlysetto
Empty;otherwise,itreturnsFalse.FalseisalwaysreturnedifExpcontainsmore
thanonevariable.

Note:IsEmptyonlyreturnsmeaningfulinformationforvariants.
Syntax

IsEmpty(Exp)
Exp ............. Expression:TheargumentExpwilldependuponwhich
datatypeisexpectedinthefunction.Ifastringisexpected,
ExpmaybeavalidstringorVariantcontainingavalue
recognizableasastring.Ifanumberisexpected,Expmaybe
avalidnumberorVariantcontainingavaluerecognizableas
anumber.

RelatedFunctions

ReturnsaBooleanTrueorFalse.

RelatedFunctions

IsDate | IsNull | IsNumeric | VarType

Example

Dim x' Empty


x = 5' Not Empty - Long
x = Empty' Empty
y = x' Both Empty
MsgBox "x" & " IsEmpty: " & IsEmpty(x)

144

IsNull
Description

DeterminesifaVariantcontainsNull.
IsNullreturnsTrueifexpressionisNull;otherwise,IsNullreturnsFalse.IfExp
consistsofmorethanonevariable,NullinanyconstituentvariablecausesTrue
tobereturnedfortheentireexpression.
TheNullvalueindicatesthattheVariantcontainsnovaliddata.Nullisnotthe
sameasEmpty,whichindicatesthatavariablehasnotyetbeeninitialised.Itis
alsonotthesameasazerolengthstring(),whichissometimesreferredtoasa
nullstring.
Note:UsetheIsNullfunctiontodeterminewhetherVarNamecontainsaNull
value.ExpressionsthatyoumightexpecttoevaluatetoTrueundersome
circumstances,suchasIfVar=NullandIfVar<>Null,arealwaysFalse.Thisis
becauseanyexpressioncontainingaNullisitselfNulland,therefore,False.

Syntax

IsNull(Exp)
Exp ............. Expression:TheargumentExpwilldependuponwhich
datatypeisexpectedinthefunction.Ifastringisexpected,
ExpmaybeavalidstringorVariantcontainingavalue
recognizableasastring.Ifanumberisexpected,Expmaybe
avalidnumberorVariantcontainingavaluerecognizableas
anumber.

ReturnValue
RelatedFunctions
Example

ReturnsaBooleanTrueorFalse.
IsDate | IsEmpty | IsNumeric | VarType
Dim MyVar, MyCheck
MyCheck = IsNull(MyVar)

' Returns False.

MyVar = ""
MyCheck = IsNull(MyVar)

' Returns False.

MyVar = Null
MyCheck = IsNull(MyVar)

' Returns True.

IsNumeric
Description

Determinesifavariantcanbeevaluatedasanumber.
TherequiredExpargumentisavariantcontaininganumericexpressionor
stringexpressionthatcanbeevaluatedasanumber.

145
IsNumericreturnsFalseifExpisadateexpression.
Syntax

IsNumeric(Exp)
Exp ............. Expression:TheargumentExpwilldependuponwhich
datatypeisexpectedinthefunction.Ifastringisexpected,
ExpmaybeavalidstringorVariantcontainingavalue
recognizableasastring.Ifanumberisexpected,Expmaybe
avalidnumberorVariantcontainingavaluerecognizableas
anumber.

ReturnValue
RelatedFunctions
Example

ReturnsaBooleanTrueorFalse.
IsDate | IsEmpty | IsNull | VarType
Dim TestVar' Declare variable.
TestVar = InputBox("Please enter a number, letter, or symbol.")
If IsNumeric(TestVar) Then' Evaluate variable.
MsgBox "Entered data is numeric."' Message if number.
Else
MsgBox "Entered data is not numeric."' Message if not.
End If

Kill
Description

Killstatementdeletesfilesfromdisk.
TherequiredFileargumentmustbevalidstringexpressionrepresentingavalid
filename.FilemaycontainaDOSpathstructureincludingdirectoryorfolder
names,andadriveletter.
Killsupportstheuseofmultiplecharacter(*)andsinglecharacter(?)wildcards
tospecifymultiplefiles.TheKillstatementdoesnotworkonacurrentlyopen
file.ToremoveadirectoryusetheRmDirstatement.
Thefilesystemtracksthecurrentdriveandthecurrentdirectoryofeverydrive.
UsetheCurDirstatementtodeterminethecurrentdirectory.Thecurrentdrive
lettercanbeextractedfromtheLeftcharacterreturnedintheCurDirstatement.

Syntax

KillFile
File.............. FileName:TheargumentFilemustbeastringor
expressionthatcanrepresentavalidfilename,andmay
includeaDOSpathstructureincludingdirectoryorfolder
names,andadriveletter.

146
RelatedFunctions
Example

Close | FileCopy | FreeFile | Name | Open


' Assume TESTFILE is a file containing some data.
Kill "TestFile"
' Delete all Dat files in current directory.
Kill "*.Dat"

Lbound
Description

Determinesthevalueofthelowestsubscriptforthe(ArrayDimension)ofthe
(ArrayName)providedintheargument.
Lboundexpectstherequiredargument(ArrayName)tobeavalidvariablearray
name.Theoptionalargument(ArrayDimension)mustbeawholelongnumber
indicatingwhichdimensionslowerboundistobereturned.Use1forthefirst
dimension,2forthesecond,andsoon.IfArrayDimensionisomitted,1is
assumed.

Syntax

Lbound(ArrayName,ArrayDimension)
ArrayName ....... ArrayName:TheargumentArrayNamemustbeastringor
expressionthatcanrepresentavalidvariablearrayname.
ArrayDimension ... ArrayDimension:TheargumentArrayDimensionmustbea
numericvalueorexpressionthatcanrepresentavalidlong
datatypevalue.

ReturnValue
RelatedFunctions
Example

ReturnsanumberofLongdatatype.
Ubound
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.

LCase
Description

ConvertsalluppercaselettersinStrtolowercaseletters.Alllowercaseletters
andnonlettercharactersremainunchanged.

147
Syntax

LCase(Str)
Str.............. String:TheargumentStrmustbeastringorexpressionthat
canrepresentavalidtextvalue.

ReturnValue
RelatedFunctions
Example

Returnsastring.
UCase
Dim strMixedCase as String
Dim strLowerCase as String
Dim strUpperCase as String
strMixedCase = "AbCdE"
strLowerCase = LCase(strMixedCase)' returns "abcde"
strUpperCase = UCase(strMixedCase)' returns "ABCDE"

Left, Left$
Description

ReturnstheleftmostNumcharactersofStr.
TherequiredStrargumentisaStringexpressionfromwhichtheleftmost
charactersarereturned.IfStrcontainsNull,Nullisreturned.
TherequiredNumargumentisaVariant(Long)numericexpressionindicating
howmanycharacterstoreturn.If0,azerolengthstring()isreturned.If
greaterthanorequaltothenumberofcharactersinstring,theentirestringis
returned.

Syntax

Left(Str,Num)
Str.............. String:TheargumentStrmustbeastringorexpressionthat
canrepresentavalidtextvalue.
Num ............ Number:TheargumentNummustcontainanIntegeror
expressionrepresentingavalidnumericvalue.

ReturnValue

RelatedFunctions
Example

TheLeftfunctionreturnsavariantcontainingaStringdatatype.TheLeft$
functionreturnsaString.
InStr | Mid | Right
Dim strGreeting as String
Dim strTest
strGreeting = "Hello World"
strTest = Left(strGreeting, 1)' Returns "H".
strTest = Left(strGreeting, 7)' Returns "Hello W".
strTest = Left(strGreeting, 20)' Returns "Hello World".

148

Len
Description

Syntax

TheLenfunctiondeterminesthenumberofcharactersintheStrargument.The
LenBfunctiondeterminesthenumberofbytesintheVarNameargument.

TheStrargumentcanbeanyvalidstringexpression.IfStrcontainsNull,
Nullisreturned.

TheVarNameargumentcanbeanyvalidvariablename.IfVarNamecontains
Null,Nullisreturned.IfVarNameisaVariant,LenBtreatsitthesameasa
Stringandalwaysreturnsthenumberofcharactersitcontains.

Len(Str)
Str.............. String:TheargumentStrmustbeastringorexpressionthat
canrepresentavalidtextvalue.

ReturnValue
RelatedFunctions
Example

ReturnsaLong.
InStr | Left,Left$ | Mid | Right
Dim strTest as String
Dim lngStringLength as Long
strTest = "CitectVBA"
lngStringLength = Len(strTest)' returns 9

Line Input #
Description

LineInput#statementreadsasinglelinefromanopensequentialfileand
assignsittoaStringvariable.
TherequiredFileNumargumentisasystemreferencenumberassociatedwithan
openfile.TherequiredVarNameisthenameofthevariablewherethefiledatais
read(copied)to.
Note:Thenumbersign(#)precedingFileNumisnotoptional.
TheLineInput#statementreadsfromafileonecharacteratatimeuntilit
encountersacarriagereturn(Chr(13))orcarriagereturnlinefeed(Chr(13)+
Chr(10))sequence.Carriagereturnlinefeedsequencesareskippedratherthan
appendedtothecharacterstring.
Note:Thefilesystemkeepstrackofallopenfilesandthecurrentpositionof
accesswithineveryfile.Everystatementorfunctionthataccessesthedata
withinafile,altersthecurrentpositionwithinthatfile.TheLocfunctioncanbe
usedtodeterminethecurrentpositionwithinanopenfile.

149
DatareadwiththeLineInput#statementhasusuallybeenwrittentoafilewith
thePrint#statement.
Syntax

LineInput#FileNum,VarName
FileNum ......... FileNumber:TheargumentFileNummustcontainan
Integerornumericexpressionrepresentinganyvalid
numberintherange1to511inclusive,whichisreferenced
bythefilesystemtobeassociatedwithanopenfile.
VarName......... VariableName:TheargumentVarNamemustbeastring
representingavalidvariablename.

RelatedFunctions

Example

Get # | GetAttr | Input | Print # | Put # | Write


#
Dim strTextLine As String
Dim intFileNum As Integer
Open "c:\TEST.txt" For Input As #intFileNumintFileNum = FreeFile
'retrieve next free file number
Do While Not EOF(intFileNum)' Loop until end of file.
Line Input #intFileNum, strTextLine' Read line into variable.
Print TextLine' Print line.
Loop
Close #intFileNum

Loc
Description

Locfunctionreturnsanumberindicatingthecurrentpositionwithinafile
openedusingtheOpenstatement.
TherequiredFileNumargumentmustcontainanIntegerrepresentinganyvalid
numberassociatedwithanopenfile.

Syntax

Loc(FileNum)
FileNum ......... FileNumber:TheargumentFileNummustcontainan
Integerornumericexpressionrepresentinganyvalid
numberintherange1to511inclusive,whichisreferenced
bythefilesystemtobeassociatedwithanopenfile.

ReturnValue

ReturnsaLongrepresentingthecurrentpositionwithinafile,thevalue
dependantuponwhichfileaccessmodethefilewasopenedwith:

IfthefilewasopenedinRandommode,theLocfunctionwillreturna
numberrepresentingthelastrecordreadfromorwrittentothefile.

150

RelatedFunctions
Example

IfthefilewasopenedinSequentialmode,theLocfunctionwillreturna
numberrepresentingthecurrentbytepositioninthefiledividedby128.
(However,informationreturnedbyLocforSequentialfilesisneitherused
norrequired.)

IfthefilewasopenedinBinarymode,theLocfunctionwillreturnanumber
representingthepositionofthelastbytereadfromorwrittentothefile.

EOF | FileLen | LOF | Seek


Dim lonLoc As Long
Dim strLine As String
Open "TESTFILE.txt" For Binary As #1' Open file
Do While lonLoc < LOF(1)' Loop until end of file
strLine = strLine & Input(1, #1)' Read character into variable
lonLoc = Loc(1)' Get current position within file
Loop
<statements>' Do stuff with retrieved data
Close #1
' Close file

LOF
Description

LOFfunctionreturnsanumberindicatingthebytelengthofasequentialfile
openedusingtheOpenstatement.
TherequiredFileNumargumentmustcontainanIntegerrepresentinganyvalid
numberassociatedwithanopenfile.
Note:Thefilesystemkeepstrackofallopenfilesandthecurrentpositionof
accesswithineveryfile.Everystatementorfunctionthataccessesthedata
withinafile,altersthecurrentpositionwithinthatfile.TheLocfunctioncanbe
usedtodeterminethecurrentpositionwithinanopenfile.
TheLOFfunctionreturnsthesizeofafilethatisalreadyopen.
Toobtainthelengthofafilethatisnotopen,usetheFileLenfunction.
UsetheLOFandLocfunctionsinsteadofEOFwhenreadingbinaryfileswith
theInputfunction.

Syntax

LOF(FileNum)
FileNum ......... FileNumber:TheargumentFileNummustcontainan
Integerornumericexpressionrepresentinganyvalid
numberintherange1to511inclusive,whichisreferenced
bythefilesystemtobeassociatedwithanopenfile.

ReturnValue

ReturnsaLongrepresentingthesizeofafileinbytes.

151
RelatedFunctions
Example

EOF | FileLen | Loc | Seek


Dim lonFileSize As Long
lonFileSize = LOF "C:\TESTFILE.txt"' returns length of file in
bytes

Log
Description

Calculatesthenaturallogarithmofanumber
Logexpectstheargument(Num)tobeavalidnumericvalue.Theargument
valuemustbegreaterthanzero.
Thenaturallogarithmisthelogarithmtothebasee.Youcancalculatethebasen
logarithmsforanynumberXbydividingthenaturallogarithmofXbythe
naturallogarithmofnasfollows:
Logn (X ) = Log(X ) / Log(n )

Note:Thevalueoftheconstanteisapproximately2.71828.
Syntax

Log(Num)
Num ............ Number:TheargumentNummustcontainanIntegeror
expressionrepresentingavalidnumericvalue.

ReturnValue
RelatedFunctions
Example

Returnsthenaturallogofthenumber(Num)providedintheargument.
Exp
Variable=Log(100);! Sets Variable to 2 (i.e. 100=10 to the power
of 2).

LTrim
Description
Syntax

StripsanyleadingspacesfromStrvariable.
LTrim(Str)
Str.............. String:TheargumentStrmustbeastringorexpressionthat
canrepresentavalidtextvalue.

ReturnValue
RelatedFunctions

Returnsastring.
RTrim | Trim

152
Example

Dim strTest as String


Dim strResult as String
Dim lngStartLength as Long
Dim lngFinishLength as Long
strTest = "
CitectVBA"
lngStartLength = Len(strTest)' returns 14
strResult = LTrim(strTest)' returns "CitectVBA"
lngStringLength = Len(strResult)' returns 9

Mid
Description

TheMidFunctionextractsaportionofastringfromStr.
Note:Todeterminethenumberofcharactersinastring,usetheLenfunction.
TheStrargumentcanbeanyvalidstringexpression.IfStrcontainsNull,Nullis
returned.
TherequiredNumargumentisaLongnumericexpressionthatsetsthestarting
positionfortheextraction.IfNumisgreaterthanthenumberofcharactersin
string,Midreturnsazerolengthstring().
TheoptionalLenargumentisaVariantcontainingaLongdatatype
representingthenumberofcharacterstoreturn.Ifomittedoriftherearefewer
thanLencharactersinStr(includingthecharacteratpositionNum),all
charactersfromtheNumpositiontotheendofthestringarereturned.

Syntax

Mid(Str,Num,Len)
Str.............. String:TheargumentStrmustbeastringorexpressionthat
canrepresentavalidtextvalue.IfStrcontainsNull,Nullis
returned.
Num ............ Number:TherequiredNumargumentisaLongnumeric
expressionthatsetsthestartingpositionfortheextraction.If
Numisgreaterthanthenumberofcharactersinstring,Mid
returnsazerolengthstring().
Len.............. Number:TheoptionalLenargumentisaVariantcontaininga
Longdatatyperepresentingthenumberofcharactersto
return.IfomittedoriftherearefewerthanLencharactersin
Str(includingthecharacteratpositionNum),allcharacters
fromtheNumpositiontotheendofthestringarereturned.

ReturnValue
RelatedFunctions

TheMidfunctionreturnsaVariant(containingaStringdatatype).
InStr | Left, Left$ | Right

153
Example

Dim strSource as String


Dim strFirstWord as String
Dim strSecondWord as String
Dim strThirdWord as String
Dim lngPosition as Long
Dim lngNextPosition as Long
Dim lngWordLength as Long
strSource = "Mid Function Demo"' Create test string.
lngPosition = 1' Start at character position 1
lngNextPosition = Instr(lngPosition, strSource," ")' Locate first
space character
lngWordLength = lngNextPosition - lngPosition' calculate word
length
strFirstWord = Mid(strSource, lngPosition, lngWordLength)'
Returns first word "Mid"
lngPosition = lngNextPosition + 1' Move to next word position
lngNextPosition = Instr(lngPosition, strSource," ")' Locate next
space character
lngWordLength = lngNextPosition - lngPosition' calculate word
length
strSecondWord = Mid(strSource, lngPosition, lngWordLength)'
Returns second word "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"

Minute
Description

Syntax

Calculatestheminutevaluefromthegiventimeargumentpassedtothe
function.
Minute(Time)
Time............. Time:TheargumentTimemustbeastringorexpression
thatcanrepresentatimevalue.Thisincludesand
combinationoftimeliterals,numbersthatlookliketimes,
stringsthatlookliketimes,andtimesfromfunctions.

ReturnValue

RelatedFunctions

Returnsanintegerbetween0and59representingtheminuteoftheparameter
(Time).
Hour | Second

154
Example

Dim varMyMin, varMyTime


varMyTime = "08:04:23 PM"
varMyMin = Minute(varMyTime)
' stores minutes value.

MkDir
Description

TheMkDirstatementcreatesthedirectoryspecifiedinthePathparameter.
TherequiredparameterPathmustbeastringorexpressionthatcanrepresenta
validDOSfilestructurepathvalue,mustcontainadirectoryname,maycontain
arelativepathstructure,andmaycontainadriveletter.ThePathparameter
mustbelimitedtolessthan128characters.
TheMkDirstatementisrelativetothecurrentdirectory.Ifnopathstructureis
provided,thedirectoryiscreatedinthecurrentdirectory.Ifnodriveisspecified,
theMkDirstatementcreatesthedirectoryonthecurrentdrive.
Note:Thefilesystemkeepstrackofthecurrentdrive,andthecurrentdirectory
ofeverydrive.UsetheCurDirstatementtodeterminethecurrentdirectory.The
currentdrivelettercanbeextractedfromtheLeftcharacterreturnedinthe
CurDirstatement.

Syntax

MkDirPath
Path ............. Path:TheparameterPathmustbeastringorexpression
thatcanrepresentavalidDOSfilestructurepathvalue.This
includesadirectoryname,andmayincludearelativeor
staticdirectoryorfolderstructureanddriveletter,inthe
order:
[<driveletter>:][\<rootdirectoryname>][\<subdirectory> ...
\<subdirectory>\] directoryname

Thepathcanberelativetothecurrentdirectory.Asingleperiodrepresentsthe
currentdirectory(.).Twoperiodsrepresenttheparentdirectoryofthecurrent
directory(..).Forexample:
chdir ..' changes to the parent directory of the current directory
chdir ..\test' changes to the test subdirectory of the parent
directory

RelatedFunctions
Example

ChDir | ChDrive | CurDir, CurDir$ | Dir | RmDir


Dim strPath As String
Dim strDir As String
strPath = CurDir()' store current path
strDir = "Temp"

155
ChDir "\"' change to root dir on current drive
MkDir strDir' create new directory
ChDir strPath' change back to previous path

Month
Description

Syntax

Calculatesthemonthfromthegivendateargumentpassedtothefunctionusing
theGregorianCalendar.
Month(Date)
Date ............. Date:TheargumentDatemustbeastringorexpressionthat
canrepresentadatevalue.Thisincludesanycombinationof
dateliterals,numbersthatlooklikedates,stringsthatlook
likedates,anddatesfromfunctions.

ReturnValue

RelatedFunctions
Example

Returnsanintegerbetween1and12inclusive,thatrepresentsthemonthofthe
year.
Date | Year | WeekDay | Day
Dim varMyBDate, varMyMonth
varMyBDate = "08 July 1958"
varMyMonth = Month(varMyBDate)
' returns 7 for July

Name
Description

TheNamestatementrenamesthediskfilespecifiedintheOldFileName
parameter,tothenamespecifiedintheNewFileNameparameter.
TherequiredparameterOldFileNamemustbevalidexistingfilename,may
containapathstructure,andmaycontainadriveletter.
TheNewFileNameparametermustbeastringorexpressionthatcanrepresenta
validDOSfilenamevalue,maycontainarelativepathstructure,andmay
containadriveletter.TheNewFileNameparametermustbelimitedtolessthan
128characters.
TheNamestatementusesthefilesystemrelativetothecurrentdirectory.Ifno
pathstructureisprovided,theNewFileNamefileisexpectedtobeinthecurrent
directory.Ifnodriveisspecified,theNamestatementexpectsthefiletobeon
thecurrentdrive.

156
UsingName,youcanmoveafilefromonedirectoryorfoldertoanother.Ifthe
pathinNewFileNameexistsandisdifferentfromthepathinOldFileName,the
Namestatementmovesthefiletothenewdirectoryorfolderandrenamesthe
file,ifnecessary.IfNewFileNameandOldFileNamehavedifferentpathsandthe
samefilename,Namemovesthefiletothenewlocationandleavesthefilename
unchanged.
Namedoesnotsupporttheuseofmultiplecharacter(*)andsinglecharacter(?)
wildcardstospecifymultiplefiles.
TheNamestatementdoesnotworkonacurrentlyopenfile.Youmustclosean
openfilebeforerenamingit.
Note:Thefilesystemkeepstrackofthecurrentdrive,andthecurrentdirectory
ofeverydrive.UsetheCurDirstatementtodeterminethecurrentdirectory.The
currentdrivelettercanbeextractedfromtheLeftcharacterreturnedinthe
CurDirstatement.
Syntax

NameOldFileNameNewFileName
OldFileName ...... FileName:TheargumentFilemustbeastringor
expressionthatcanrepresentavalidfilename,andmay
includeaDOSpathstructureincludingdirectoryorfolder
names,andadriveletter.
NewFileName..... FileName:TheargumentFilemustbeastringor
expressionthatcanrepresentavalidfilename,andmay
includeaDOSpathstructureincludingdirectoryorfolder
names,andadriveletter.

RelatedFunctions
Example

Close | FileCopy | FreeFile | Kill | Open


Dim strNewFileName As String
Dim strOldFileName As String
strOldFileName = "c:\temp\oldfile.txt"
strNewFileName = "newfile.txt"
ChDir "\"' change to root dir on current drive
Name strOldFileName strNewFileName' moves file to root dir and
renames it
ChDir strPath' change back to previous path

Nothing
Description

ReleasesanOLEAutomationobjectreferencefromavariableofobjecttype.The
NothingkeywordisusedinaSetstatement.

157
Inthefollowingdeclarationsyntaxexample,eachplaceholdershowninside
arrowbrackets(<placeholder>)shouldbereplacedinanyactualcodewiththe
valueoftheitemthatitdescribes.Thearrowbracketsandthewordtheycontain
shouldnotbeincludedinthestatement,andareshownhereonlyforyour
information.
Syntax

Set<objVarName>=Nothing
where:

RelatedFunctions
Example

Setistherequiredreferenceassignment/releasestatementkeyword

<objVarName>representstherequirednameofthevariablereceivingthe
reference

Nothingisthekeywordusedtoreleasetheobjectreference

Thenothingkeywordshouldbeusedwhenyouarefinishedwithanobject,
toclearanyvariablesthatreferencetheobject,sotheobjectcanbereleased
frommemory.

CreateObject | Function | Set


' create variable to store object reference
Dim objWord as Object
' create object and assign reference to variable
Set objWord = CreateObject( "Word.Document" )
' insert appropriate VBA code here to manipulate Word object
' release reference
Set objWord = Nothing

Now
Description

Syntax
ReturnValue

Determinesthecurrentdateandtimeaccordingtothesettingofthecomputers
systemdateandtimeusingtheGregorianCalendar.Unlikeotherfunctions,
Nowdoesnotrequiretrailingparentheses.
Now()
TheNowfunctionreturnsaVariantdatatypecontainingadateandtimevalue
thatisstoredinternallyasadoubledatatype.
ThenumberrepresentsadateandtimefromJanuary1,100throughDecember
31,9999.Numberstotheleftofthedecimalpointrepresentthedateand
numberstotherightrepresentthetime.

RelatedFunctions

Date | Time | Timer

158
Example

Dim vntToday
vntToday = Now
' stores current system date and time.

Oct
Description

Convertsanumericvaluetoatextstringrepresentingtheoctalvalueofthe
number.
TheOctfunctionexpectstheargument(Num)tobeavalidnumericvalue.Itis
roundedtonearestwholenumberbeforeevaluation.

Syntax

Oct(Num)
Num ............ Number:TheargumentNummustcontainanIntegeror
expressionrepresentingavalidnumericvalue.

ReturnValue

RelatedFunctions
Example

Returnsatextstringcontainingtheoctalvalueofthenumeric(Num)value
providedintheargument.
Format | Hex | Str | Val
Dim MyOct as String
MyOct = Oct(4)'returns "4"
MyOct = Oct(8)'returns "10"
MyOct = Oct(459)'returns "713"

OnError
Description

Syntax
Example

CitectVBAserrorhandlingroutineandspecifiesthelinelabeloftheerror
handlingroutine.Thelineparameterreferstoalabel.Thatlabelmustbepresent
inthecodeoranerrorisgenerated.
OnError{GoToline|ResumeNext|GoTo0}
On Error GoTo errHandler
Dim x as object
x.draw ' Object not set
jpe ' Undefined function call
print 1/0 ' Division by zero
Err.Raise 6' Generate an "Overflow" error
Exit Sub

159

errHandler:
Print Err.Number, Err.Description
Resume Next

Open
Description

Openstatementenablesinput/output(I/O)toadiskfile.
TherequiredFileargumentmustbeavalidstringexpressionrepresentinga
validfilename.FilemaycontainaDOSpathstructureincludingdirectoryor
foldernames,andadriveletter.
TherequiredModeargumentmustbeavalidkeywordspecifyingthefileI/O
mode:Append,Binary,Input,Output,orRandom.Ifunspecified,thefileis
openedforRandomaccess.
TheoptionalAccessargumentmustbeavalidkeywordspecifyingtheoperations
permittedontheopenfile:Read,Write,orReadWrite.
TheoptionalLockargumentmustbeavalidkeywordspecifyingtheoperations
permittedontheopenfilebyotherprocesses:Shared,LockRead,LockWrite,
andLockReadWrite.
TherequiredFileNumargumentmustcontainanIntegerrepresentingthe
numberthatwillbeassociatedwiththefile.Thisisthefilesystemreference
numbersuppliedbytheFreeFilestatementthatcanbeusedinfunctionssuchas
Get#,Input#,LineInput#,Print#,andWrite#.InBinary,Input,andRandom
modes,youcanopenafileusingadifferentfilenumberwithoutfirstclosingthe
file.InAppendandOutputmodes,youmustcloseafilebeforeopeningitwitha
differentfilenumber.
Note:Thefilesystemtracksallopenfilesandthecurrentpositionofaccess
withineveryfile.Everystatementorfunctionthataccessesthedatawithinafile,
altersthecurrentpositionwithinthatfile.TheLocfunctioncanbeusedto
determinethecurrentpositionwithinanopenfile.
TheoptionalRecLenargumentmustbeanumberlessthanorequalto32,767
(bytes).ForfilesopenedforRandomaccess,thisvalueistherecordlength.For
sequentialfiles,thisvalueisthenumberofcharactersbuffered.TheLenclauseis
ignoredifmodeisBinary.
YoumustopenafilebeforeanyI/Ooperationcanbeperformedonit.Open
allocatesabufferforI/Otothefileanddeterminesthemodeofaccesstouse
withthebuffer.Ifthefileisalreadyopenedbyanotherprocessandthespecified
typeofaccessisnotallowed,theOpenoperationfailsandanerroroccurs.

160
Ifthefilespecifiedbypathnamedoesntexist,itiscreatedwhenafileisopened
forAppend,Binary,Output,orRandommodes.
Syntax

Open(FileForModeAccessAccessLockAs#FileNumLen=RecLen)
File.............. FileName:TheargumentFilemustbeastringor
expressionthatcanrepresentavalidfilename,andmay
includeaDOSpathstructureincludingdirectoryorfolder
names,andadriveletter.
Mode............ FileMode:TheargumentModemustbeaCitectVBA
keywordspecifyingthefileI/Omode:Append,Binary,
Input,Output,orRandom.
Lock ............. FileLock:TheargumentLockmustbeaCitectVBA
keywordspecifyingtheoperationspermittedontheopenfile
byotherprocesses:Shared,LockRead,LockWrite,andLock
ReadWrite.AccessFileAccess:TheargumentAccessmust
beaCitectVBAkeywordspecifyingtheoperationspermitted
ontheopenfile:Read,Write,orReadWrite.
FileNum ......... FileNumber:TheargumentFileNummustcontainan
Integerornumericexpressionrepresentinganyvalid
numberintherange1to511inclusive,whichisreferenced
bythefilesystemtobeassociatedwithanopenfile.
RecLen ........... RecordLength:TheargumentRecLenmustcontainan
Integerornumericexpressionrepresentingthebytelengthof
afilerecordasanumberlessthanorequalto32,767.

RelatedFunctions
Example

Close | FileCopy | FreeFile | Kill | Name


' The following code opens the file TESTFILE in sequential-input
mode.
Open "TESTFILE" For Input As #1
' Close before reopening in another mode.
Close #1
' 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

161
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

Option Base
Description

Declaresthedefaultlowerboundforarraysubscripts.
TheOptionBasestatementisoptional.Ifused,itcanappearonlyonceina
CitectVBAfile,andmustbeusedbeforeyoudeclarethedimensionsofany
arrays.
Thevalueofthenumberparametermustbeeither0or1.Thedefaultis0.
TheToclauseinthearraysubscriptrangeofaDimstatementprovidesamore
flexiblewaytocontrolthelowerboundofanarray.Ifyoudontexplicitlysetthe
lowerboundwithaToclause,theOptionBasesetting(ifused)comesintoaffect,
ordefaultstozero(ifnotused).
TheexamplebelowusestheOptionBasestatementtooverridethedefaultbase
arraysubscriptvalueof0.

Syntax

OptionBaseNum
Num ............ Number:TheargumentNummustcontainanIntegeror
expressionrepresentingavalidnumericvalue.

RelatedFunctions
Example

Dim | ReDim
' Module level statement
Option Base 1
' Create the array
Dim Arr(20)

162
' Declare message variables
Dim Msg As String
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

Option Compare
Description

RelatedFunctions

DetermineshowstringsarecomparedwithinaCitectVBAmodule.Theoptional
OptionComparestatementifused,mustbeplacedatthetopoftheCitectVBA
filealongwithanyotherOptiondeclarations.
InStr | StrComp

Example

Option Compare Binary


Dim vntResult as Variant
vntResult = StrComp("CitectVBA rules!", "Citectvba Rules!")
' returns 1 (strings unequal)

Example

Option Compare Text


Dim vntResult as Variant
vntResult = StrComp("CitectVBA rules!", "Citectvba Rules!")
' returns 0 (strings equal)

Option Explicit
Description

Forcesexplicitdeclarationofallvariables.
TheoptionalOptionExplicitstatementifused,mustbeplacedatthetopofthe
CitectVBAfile.Thiscausesacheckofvariabledeclarationsatcompiletime.
Settingthisoptionisagoodwaytocatchmisspellingofvariablesinyourcode.

Syntax

Option Explicit

RelatedFunctions

Const | Dim

163
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

Print (function)
Description

DisplaysamessageintheruntimeCitectKernel,andtheCicodeEditoroutput
windowifyouareindebugmode.
Note:DonotconfusethisfunctionwiththePrint#statement,whichprints
datatodisk.

RelatedFunctions

TraceMsg(Cicodefunction)

Print #
Description

Print#statementreadsdatafromOutputListandwritesthatdatatoasequential
file.
ThePrint#statementhastwoparametersFileNumandOutputList.Therequired
FileNumargumentistheassociatedfilenumberusedintheOpenstatement
whenthefilewasopened.TherequiredOutputListargumentisadelimitedlist
ofexpressionswhosevaluesarewrittentothefile.
Note:Thenumbersignhashcharacter(#)precedingFileNumisnotoptional.
Thischaracterindicatesdiskfileaccesswiththefilereferencedbythesystemfile
numberthatfollowsit.DonotconfusePrint#whichprintstodisk,withPrint
whichdisplaysdataonthescreen.
DatawrittenwithPrint#isusuallyreadfromafilewithLineInput#orInput.
Note:IfyouwanttoreadthedatafromafileusingtheInput#statement,usethe
Write#statementinsteadofthePrint#statementtowritethedatatothefile.
UsingWrite#ensurestheintegrityofeachseparatedatafieldbyproperly
delimitingit,soitcanbereadbackinusingInput#.UsingWrite#alsoensuresit
canbecorrectlyreadinanylocale.
Ifyouomitexpressionlist,thePrint#statementprintsablanklineinthefile,but
youmustincludethecomma.BecausePrint#writesanimageofthedatatothe
file,youmustdelimitthedatasoitisprintedcorrectly.Ifyouusecommasas
delimiters,Print#alsowritestheblanksbetweenprintfieldstothefile.
ThePrint#statementusuallywritesVariantdatatoafilethesamewayitwrites
anyotherdatatype.However,therearesomeexceptions:

164
IfthedatabeingwrittenisaVariantofVarType0(Empty),Print#writesnothing
tothefileforthatdataitem.
IfthedatabeingwrittenisaVariantofVarType1(Null),Print#writestheliteral
#NULL#tothefile.
IfthedatabeingwrittenisaVariantofVarType7(Date),Print#writesthedate
tothefileusingtheShortDateformatdefinedintheWIN.INIfile.Wheneither
thedateorthetimecomponentismissingorzero,Print#writesonlythepart
providedtothefile.
Syntax

Print#FileNum,OutputList
FileNum ......... FileNumber:TheargumentFileNummustcontainan
Integerornumericexpressionrepresentinganyvalid
numberintherange1to511inclusive,whichisreferenced
bythefilesystemtobeassociatedwithanopenfile.
OutputList ....... FileOutputList:TheargumentOutputListmaycontainone
ormoreformattednumericand/orstringexpressionstobe
writtentothefileusingthefollowingsyntax:
[ {Spc( s ) | Tab [( n ) ] } ] [expression] [charpos]

where:

[]squarebracketsareusedforillustrativepurposestoindicateinthecode
thattheargumentstheyencloseareoptionallyusedintheOutputList.Do
notusethesquarebracketsthemselvesinyourcode.

{}curlybracesarerequiredtoencompassanddelineatetheargumentsthey
enclose,andtoseparatetheircontentsfromtheotherargumentsinthe
OutputList.

(|)verticallineareusedforillustrativepurposestoindicateinthecodethat
eithersideofthelineisanalternativeargument.Youcanusetheargument
providedononeofthelineortheother,butnotbothargumentsatthesame
timewithinthesamesetofcurlybraces.Donotincludetheverticallinein
yourcode.

{Spc(s)}argumentisoptionallyusedtoinsertsnumberofspacecharacters
intheoutputfileatthepositionoftheargumentintheOutputList.TheSpc
argumentmustbeenclosedbycurlybracestodelineateitfromanexpression.
TheSpcargumentcanberepeatedanynumberoftimestoinsertspacesin
thefilebetweenexpressions.TheSpcargumentismutuallyexclusivewiththe
Tabargumentwhenusedwithinthesamesetofcurlybraces.

{Tab(n)}argumentisoptionallyusedtopositiontheinsertionpointtoan
absolutecolumnnumberintheoutputfileatthepositionoftheargumentin
theOutputList,wherenisthecolumnnumber.UseTabwithnoargumentto
positiontheinsertionpointatthebeginningofthenextprintzone.TheTab

165
argumentmustbeenclosedbycurlybracestodelineateitfromanexpression.
TheTabargumentcanberepeatedanynumberoftimestoinserttabsinthe
filebetweenexpressions.TheTabargumentismutuallyexclusivewiththeSpc
argumentwhenusedwithinthesamesetofcurlybraces.

ReturnValue

RelatedFunctions

Example

expressionargumentrepresentsavalidnumericorstringexpressionto
outputtothefile.Theexpressionargumentcanberepeatedanynumberof
times.

charposisthecharacterthatdeterminesthepositionofthenextcharacterin
theoutput.Asemicolonmeansthenextcharacterisprintedimmediately
afterthelastcharacter;acommameansthenextcharacterisprintedatthe
startofthenextprintzone.Printzonesbeginevery14columns.Ifneither
characterisspecified,thenextcharacterisprintedonthenextline.

Input#statementreturnsdatarecordbyrecordfromafileopenedinInputor
Binarymode.Dataitemsinafilemustappearinthesameorderasthevariables
inVarListandmatchvariablesofthesamedatatype.Ifavariableisnumericand
thedataisnotnumeric,avalueofzeroisassignedtothevariable.
Get # | GetAttr | Input | Line Input # | Put # |
Write #
Thefollowingexamplewritesdatatoatestfile.
Dim I, FNum, FName' Declare variables.
For I = 1 To 3
FNum = FreeFile' Determine next file number.
FName = "TEST" & FNum
Open FName For Output As FNum' Open file.
Print #1, "This is test #" & I' Write string to file.
Print #1, "Here is another "; "line"; I
Next I
Close' Close all files.
The following example writes data to a test file and reads it
back.
Dim FileData, Msg, NL' Declare variables.
NL = Chr(10)' Define newline.
Open "TESTFILE" For Output As #1' Open to write file.
Print #1, "This is a test of the Print # statement."
Print #1,' Print blank line to file.
Print #1, "Zone 1", "Zone 2"' Print in two print zones.
Print #1, "With no space between" ; "." ' Print two strings
together.
Close #1
Open "TESTFILE" for Input As #2' Open to read file.
Do While Not EOF(2)
Line Input #2, FileData' Read a line of data.

166
Msg = Msg & FileData & NL' Construct message.
MsgBox Msg
Loop
Close #2' Close all open files.
Kill "TESTFILE"' Remove file from disk.

Put #
Description

Put#statementwritesdatafromavariabletoadiskfile.
TherequiredFileNumargumentisasystemreferencenumberassociatedwithan
openfile.
Note:Thenumbersign(#)precedingFileNumisnotoptional.
TheoptionalRecNumargumentisthebytepositionwherethereadstartsforfiles
openedinBinarymode.Thefirstrecordorbyteinafileisatposition1,the
secondrecordorbyteisatposition2,andsoon.IfyouomitRecNum,thenext
recordorbytefollowingthelastGetorPutstatement(orpointedtobythelast
Seekfunction)isread.Youmustincludedelimitingcommas.
Note:Thefilesystemkeepstrackofallopenfilesandthecurrentpositionof
accesswithineveryfile.Everystatementorfunctionthataccessesthedata
withinafile,altersthecurrentpositionwithinthatfile.TheLocfunctioncanbe
usedtodeterminethecurrentpositionwithinanopenfile.
TherequiredVarNameisthenameofthevariablewherethefiledataisread
(copied)from.
DatawrittenwiththePut#statementisusuallyreadfromafilewiththeGet#
statement.
Randommode
ForfilesopenedinRandommode,thefollowingrulesapply:

Ifthelengthofthedatabeingwrittenislessthanthelengthspecifiedinthe
LenclauseoftheOpenstatement,Putwritessubsequentrecordsonrecord
lengthboundaries.Thespacebetweentheendofonerecordandthe
beginningofthenextrecordispaddedwiththeexistingcontentsofthefile
buffer.Becausetheamountofpaddingdatacantbedeterminedwithany
certainty,itisgenerallyagoodideatohavetherecordlengthmatchthe
lengthofthedatabeingwritten.Ifthelengthofthedatabeingwrittenis
greaterthanthelengthspecifiedintheLenclauseoftheOpenstatement,an
erroroccurs.

Ifthevariablebeingwrittenisavariablelengthstring,Putwritesa2byte
descriptorcontainingthestringlengthandthenthevariable.Therecord

167
lengthspecifiedbytheLenclauseintheOpenstatementmustbeatleast2
bytesgreaterthantheactuallengthofthestring.

IfthevariablebeingwrittenisaVariantofanumerictype,Putwrites2bytes
identifyingtheVarTypeoftheVariantandthenwritesthevariable.For
example,whenwritingaVariantofVarType3,Putwrites6bytes:2bytes
identifyingtheVariantasVarType3(Long)and4bytescontainingtheLong
data.TherecordlengthspecifiedbytheLenclauseintheOpenstatement
mustbeatleast2bytesgreaterthantheactualnumberofbytesrequiredto
storethevariable.
Note:YoucanusethePutstatementtowriteaVariantarraytodisk,butyou
cantusePuttowriteascalarVariantcontaininganarraytodisk.Youalso
cantusePuttowriteobjectstodisk.

IfthevariablebeingwrittenisaVariantofVarType8(String),Putwrites2
bytesidentifyingtheVarType,2bytesindicatingthelengthofthestring,and
thenwritesthestringdata.TherecordlengthspecifiedbytheLenclausein
theOpenstatementmustbeatleast4bytesgreaterthantheactuallengthof
thestring.

Ifthevariablebeingwrittenisadynamicarray,Putwritesadescriptor
whoselengthequals2plus8timesthenumberofdimensions,thatis,2+8*
NumberOfDimensions.TherecordlengthspecifiedbytheLenclauseinthe
Openstatementmustbegreaterthanorequaltothesumofallthebytes
requiredtowritethearraydataandthearraydescriptor.Forexample,the
followingarraydeclarationrequires118byteswhenthearrayiswrittento
disk.
Dim MyArray(1 To 5,1 To 10) As Integer

The118bytesaredistributedasfollows:18bytesforthedescriptor(2+8*2),
and100bytesforthedata(5*10*2).

Ifthevariablebeingwrittenisafixedsizearray,Putwritesonlythedata.No
descriptoriswrittentodisk.

Ifthevariablebeingwrittenisanyothertypeofvariable(notavariable
lengthstringoraVariant),Putwritesonlythevariabledata.Therecord
lengthspecifiedbytheLenclauseintheOpenstatementmustbegreater
thanorequaltothelengthofthedatabeingwritten.

Putwriteselementsofuserdefinedtypesasifeachwerewrittenindividually,
exceptthereisnopaddingbetweenelements.Ondisk,adynamicarrayina
userdefinedtypewrittenwithPutisprefixedbyadescriptorwhoselength
equals2plus8timesthenumberofdimensions,thatis,2+8*
NumberOfDimensions.TherecordlengthspecifiedbytheLenclauseinthe
Openstatementmustbegreaterthanorequaltothesumofallthebytes
requiredtowritetheindividualelements,includinganyarraysandtheir
descriptors.

168
Binarymode
ForfilesopenedinBinarymode,alloftheRandomrulesapply,except:

TheLenclauseintheOpenstatementhasnoeffect.Putwritesallvariables
todiskcontiguously;thatis,withnopaddingbetweenrecords.

Foranyarrayotherthananarrayinauserdefinedtype,Putwritesonlythe
data.Nodescriptoriswritten.

Putwritesvariablelengthstringsthatarentelementsofuserdefinedtypes
withoutthe2bytelengthdescriptor.Thenumberofbyteswrittenequalsthe
numberofcharactersinthestring.Forexample,thefollowingstatements
write10bytestofilenumber1:
VarString$=String$(10,)

Putwritesvariablelengthstringsthatarenotelementsofuserdefinedtypes
withoutthe2bytelengthdescriptor.
Put #1,,VarString$
Syntax

Put#FileNum,RecNum,VarName
FileNum ......... FileNumber:TheargumentFileNummustcontainan
Integerornumericexpressionrepresentinganyvalid
numberintherange1to511inclusive,whichisreferenced
bythefilesystemtobeassociatedwithanopenfile.
RecNum ......... RecordNumber:TheargumentRecNum.
VarName......... VariableName:TheargumentVarNamemustbeastring
representingavalidvariablename.

RelatedFunctions

Get # | GetAttr | Input | Line Input # | Put # |


Write #

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
Dim MyRecord As Record, RecordNumber' Declare variables.
' Open file for random access.
Open "TESTFILE" For Random As #1 Len = Len(MyRecord)
For RecordNumber = 1 To 5' Loop 5 times.
MyRecord.ID = RecordNumber' Define ID.
MyRecord.Name = "My Name" & RecordNumber ' Create a string.

169
Put #1, RecordNumber, MyRecord' Write record to file.
Next RecordNumber
Close #1' Close file.

Randomize
Description

TheRandomizestatementinitialisestherandomnumbergenerator.
Ithasoneoptionalparameternumber.Thisparametercanbeanyvalidnumber
andisusedtoinitialisetherandomnumbergenerator.Ifyouomittheparameter
thenthevaluereturnedbytheTimereventisusedasthedefaultparameterto
seedtherandomnumbergenerator.

Syntax
RelatedFunctions
Example

Randomize[number]
Timer
Dim MValue
' Initialise random-number generator
Randomize
MValue = Int((6 * Rnd) + 1)
Print MValue

ReDim
Description

Usedtosizeorresizeadynamicarraythathasalreadybeendeclaredusingthe
Dimstatementwithemptyparentheses.
UsetheReDimstatementtochangethenumberofelementsinandarray,butnot
tochangethenumberofdimensionsinanarrayorthetypeoftheelementsin
thearray.

Syntax

ReDimArrayName(Subscripts)[AsType][,varname(Subscripts)]
ArrayName ....... ArrayName:TheargumentArrayNamemustbeastringor
expressionthatcanrepresentavalidvariablearrayname.
Subscripts........ Subscripts:TheargumentSubscriptsmustcontainan
IntegerorexpressionrepresentingavalidTonumericvalue
rangewhendeclaringthedimensionsofanvariablearray.
Upto60multipledimensionsmaybedeclared.
Thesubscriptsargumentusesthefollowingsyntax:
[lower To] upper [,[lower To] upper] . . .

170
Whennotexplicitlystatedinlower,thelowerboundofanarrayiscontrolledby
theOptionBasestatement.ThelowerboundiszeroifnoOptionBasestatement
ispresentintheCitectVBAfile.
RelatedFunctions
Example

Dim | Const | Static


Dim TestArray() As Integer
Dim I
ReDim TestArray(10)
For I = 1 To 10
TestArray(I) = I + 10
Print TestArray(I)
Next I

Rem
Description
Syntax

Usedtoincludeexplanatorycommentsinaprogram.
Rem<Comment>
where<Comment>isthetextofanycommentyouwanttoincludeinthecode.

Example

' This is another way to comment


Rem This is a remark

Right
Description

ReturnstherightmostNumcharactersofStr.TherequiredStrargumentisa
Stringexpressionfromwhichtherightmostcharactersarereturned.IfStr
containsNull,Nullisreturned.
TherequiredNumargumentisaVariant(Long)numericexpressionindicating
howmanycharacterstoreturn.If0,azerolengthstring()isreturned.If
greaterthanorequaltothenumberofcharactersinstring,theentirestringis
returned.
Note:Todeterminethenumberofcharactersinastring,usetheLenfunction.

Syntax

Right(Str,Num)
Str.............. String:TheargumentStrmustbeastringorexpressionthat
canrepresentavalidtextvalue.
Num ............ Number:TheargumentNummustcontainanIntegeror
expressionrepresentingavalidnumericvalue.

171
ReturnValue

RelatedFunctions
Example

TheRightfunctionreturnsavariantcontainingastringdatatype.
TheRight$functionreturnsastring.
InStr | Left, Left$ | Mid
Dim strGreeting as String
Dim strTest
strGreeting = "Hello World"
strTest = Right(strGreeting, 1)' Returns "d"
strTest = Right(strGreeting, 5)' Returns "World"
strTest = Right(strGreeting, 20)' Returns "Hello World"

RmDir
Description

TheRmDirstatementdeletesthedirectoryspecifiedinthePathparameter.
TherequiredparameterPathmustbeastringorexpressionthatcanrepresenta
validDOSfilestructurepathvalue,mustcontainadirectoryname,maycontain
arelativepathstructure,andmaycontainadriveletter.ThePathparameter
mustbelimitedtolessthan128characters.
TheRmDirstatementisrelativetothecurrentdirectory.Ifnopathstructureis
provided,thedirectoryisexpectedtobeasubdirectoryofthecurrentdirectory.
Ifnodriveisspecified,theRmDirstatementdeletesthedirectoryonthecurrent
drive.
Thecurrentdirectorycannotbedeleted.Tochangethecurrentdirectoryto
anotherdirectory,usetheChDirstatement.Thedirectorytobedeletedmustbe
emptyandcontainnofilesorsubdirectories.Todeletefilesinadirectory,use
theKillstatement.
Note:Thefilesystemkeepstrackofthecurrentdrive,andthecurrentdirectory
ofeverydrive.UsetheCurDirstatementtodeterminethecurrentdirectory.The
currentdrivelettercanbeextractedfromtheLeftcharacterreturnedinthe
CurDirstatement.

Syntax

RmDirPath
Path ............. Path:TheparameterPathmustbeastringorexpression
thatcanrepresentavalidDOSfilestructurepathvalue.This
includesadirectoryname,andmayincludearelativeor
staticdirectoryorfolderstructureanddriveletter,inthe
order:
[<driveletter>:][\<rootdirectoryname>][\<subdirectory> ...
\<subdirectory>\] directoryname

172
Note:Thepathcanberelativetothecurrentdirectory.Asingleperiod
representsthecurrentdirectory(.).Twoperiodsrepresenttheparentdirectory
ofthecurrentdirectory(..).Forexample,chdir..changestotheparentdirectory
ofthecurrentdirectory.chdir..\testchangestothetestsubdirectoryofthe
parentdirectory
RelatedFunctions
Example

ChDir | ChDrive | CurDir, CurDir$ | Dir | MkDir


Dim strDir As String
strDir = CurDir' retrieve current directory name
Kill "*.*"' delete all files from current directory
ChDir "\"' change to root dir on current drive
RmDir strDir' delete directory

Rnd
Description

Generatesadecimalfractionnumberusingtheoptionalargumentvalue(Num)
todeterminethesequenceofthe(random)numbergeneration.
Rndexpectstheargument(Num)ifsupplied,tobeavalidnumericvalue.
IfNumislessthanzero,Rndgeneratesthesamenumbereverytime,usingNum
astheseed.IfNumisequalthanzero,Rndrepeatsthemostrecentlygenerated
number.IfNumisgreaterthanzero,Rndgeneratesthenextrandomnumberin
thesequence.IfNumisnotsupplied,Rndgeneratesthenextrandomnumberin
thesequence.
BeforecallingRnd,usetheRandomizestatementwithoutanargumentto
initialisetherandomnumbergeneratorwithaseedbasedonthesystemtimer.
Note:Thesquarebrackets[]inthesyntaxindicatethattheargumentisoptional.
DoNOTincludethesquarebracketsinyourcode.

Syntax

Rnd[(Num)]
Num ............ Number:TheargumentNummustcontainanIntegeror
expressionrepresentingavalidnumericvalue.

ReturnValue

RelatedFunctions
Example

Returnsa(random)decimalfractionnumberinfluencedbythe(Num)provided
intheargument.Thereturnvalueliesintherangeoflessthan1butgreaterthan
orequalto0.
Randomize
Dim vntRndValue
Randomize' Initialize random-number generator.
vntRndValue = Int((6 * Rnd) + 1) ' returns a value between 1 and 6

173

RTrim
Description
Syntax

StripsanytrailingspacesfromStrvariable.
RTrim(Str)
Str.............. String:TheargumentStrmustbeastringorexpressionthat
canrepresentavalidtextvalue.

ReturnValue
RelatedFunctions
Example

ReturnsaString.
LTrim | Trim
Dim strTest as String
Dim strResult as String
Dim lngStartLength as Long
Dim lngFinishLength as Long
strTest = "CitectVBA
"
lngStartLength = Len(strTest)' returns 14
strResult = RTrim(strTest)' returns "CitectVBA"
lngStringLength = Len(strResult)' returns 9

Second
Description

Syntax

Calculatesthesecondvaluefromthegiventimeargumentpassedtothe
function.
Second(Time)
Time............. Time:TheargumentTimemustbeastringorexpression
thatcanrepresentatimevalue.Thisincludesand
combinationoftimeliterals,numbersthatlookliketimes,
stringsthatlookliketimes,andtimesfromfunctions.

ReturnValue
RelatedFunctions
Example

Returnsanintegerthatisthesecondportionoftheparameter(Time).
Hour | Minute
Dim varMySec, varMyTime
varMyTime = "08:04:23 PM"
varMySec = Second(varMyTime)
' stores seconds value.

174

Seek
Description

SetsthecurrentpositionwithinafileopenedusingtheOpenstatement,ready
forthenextreadorwriteaction.
TherequiredFileNumargumentmustcontainanIntegerrepresentinganyvalid
systemfilenumberassociatedwithanopenfile.
TherequiredPositionargumentmustcontainanIntegerorexpression
representingavalidnumber.
Note:Thefilesystemkeepstrackofallopenfilesandthecurrentpositionof
accesswithineveryfile.Everystatementorfunctionthataccessesthedata
withinafile,altersthecurrentpositionwithinthatfile.TheLocfunctioncanbe
usedtodeterminethecurrentpositionwithinanopenfile.

Syntax

SeekFileNum,Position
FileNum ......... FileNumber:TheargumentFileNummustcontainan
Integerornumericexpressionrepresentinganyvalid
numberintherange1to511inclusive,whichisreferenced
bythefilesystemtobeassociatedwithanopenfile.
Position .......... Number:TheargumentNummustcontainanIntegeror
expressionrepresentingavalidnumericvalue.

RelatedFunctions
Example

EOF | FileLen | Loc | LOF


Open "TESTFILE" For Input As #1' Open file for reading.
For i = 1 To 24 Step 3' Loop until end of file.
Seek #1, i' Seek to byte position
MyChar = Input(1, #1)' Read next character of data.
Print MyChar'Print character of data
Next i
Close #1' Close file.

Select
Description

TheSelectCasestatementteststhesamevariableformanydifferentconditions.
ThetestvalueprovidedwiththeinitialSelectCasestatementislogicallytested
againsttheCasetestcondition.
TheSelectCasestructurecanperformdifferentblocksofstatementsdependant
uponwhicheverCasestatementtestcondition(ifmorethanone)firstresultsas
True,throughtheuseoftheCasestatementblock:

175
Select Case <TestValue>
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

IftheresultoftheCasetestconditionwasTrue,theprogramflowperformsthe
statementscontainedwithinthatCasestatementblock,andwillthenexitthe
SelectCasestructure(withoutperforminganyoftheElsestatementblock
statements).
IftheresultoftheCasetestconditionwasFalse,theprogramflowjumps
completelyovertheCasestatementblock(withoutperforminganyofthose
statements)totheCaseElsestatementtoperformthestatementsintheElse
statementblockuntilitreachestheEndSelectstatement.
FurthertestconditionscanbeplacedintoaSelectCasestructurethroughthe
optionaluseoffurtherCasestatementblocks.Casestatementblockscanonlybe
positionedwithinaSelectCasestructurebeforetheCaseElsestatementblock.
Select Case <TestValue>
Case <Condition>
' Case statement block
' perform only if case true
<Statement/s>
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

EachCasestatementblockisevaluatedinorderuntilthetestconditionofone
resultsasTrue.Theprogramflowperformsthestatementscontainedwithinthat
Casestatementblock,andwillthenexittheSelectCasestructure(without
performinganyotherstatements).
ThestatementsofONLYoneCasestatementblockareeverperformed,unlessall
resultinFalseandthereisnoCaseElseblockdeclared,inwhichcasenoCase
statementblocksareperformedatall.
Thefollowingexamplemayhelpclarifythelogictestingbeingperformedina
SelectCasestructure.Letssaythatwehaveavariablenamed(intDayOfWeek)

176
containinganinteger(rangingfrom1to7)representingthedayoftheweek,and
wewishedtodisplaythatvalueasastring(namedstrDayOfWeek)containing
thenameofthedayoftheweek,assuminginthisexample,thatSundayisthe
firstdayoftheweek(1).TheSelectCasestructurewouldlooklikethis:
Dim strDayOfWeek As String
Select Case intDayOfWeek
Case = 1
StrDayOfWeek = "Sunday"
Case = 2
StrDayOfWeek = "Monday"
Case = 3
StrDayOfWeek = "Tuesday"
Case = 4
StrDayOfWeek = "Wednesday"
Case = 5
StrDayOfWeek = "Thursday"
Case = 6
StrDayOfWeek = "Friday"
Case = 7
StrDayOfWeek = "Saturday"
Case Else
StrDayOfWeek = "Invalid"
End Select

TheSelectCasestructuretendstobeeasiertoread,understand,andfollowand
shouldbeusedinplaceofacomplicatedmultinestedIf...ElseIfstructure.

SendKeys
Description

Sendsoneormorekeystrokestotheactivewindowoftheactiveapplicationasif
theyhadbeenenteredatthekeyboard.
ThevalueoftheWaitargumentdetermineswhentheSendKeysfunction
completesandreturnscontroltoCitectVBA.Ifomitted,WaitistreatedasFALSE
bydefault.
Note:YoucantuseSendKeystosendkeystrokestoanapplicationthatisnot
designedtoruninMicrosoftWindows.SendkeysalsocantsendthePRINT
SCREENkey{PRTSC}toanyapplication..

Syntax

SendKeys(keys,wait)

keysrepresentsthestringthatissenttotheactivewindow.

waitrepresentsenterTRUEorFALSE.

177
Ifwaitistruethekeystrokesmustbeprocessedbeforecontrolisreturnedtothe
callingprocedure.Thisargumentisoptional.Ifyouomitit,itisassumedtobe
false.
ReturnValue
Example

None
Dim intCounter As Integer' Declare variables.
Dim dblProgID As Double, ' Launch Windows Calculator program.
dblProgID = Shell("Calc.exe", 1)' Set up counting loop.
For intCounter = 1 To 5' Send keystrokes to Calculator
SendKeys intCounter & "{+}", True' to add the value of intCounter
each time
Next intCounter ' Return focus to Calculator.
AppActivate "Calculator"' Send keystrokes toClose Calculator.
SendKeys "%{F4}", True

Set
Description
Syntax

AssignsanOLEAutomationobjectreferencetoavariableofobjecttype.
Syntax

. . . . Set <objVarName> = CreateObject(<objClassName>)|


Nothing

where:

Setistherequiredreferenceassignmentstatementkeyword

<objVarName>representstherequirednameofthevariablereceivingthe
referenceandeither:

CreateObjectistherequiredobjectdeclarationfunctionkeyword

( )definestherequiredargumentsectionoftheCreateObjectfunction

<objClassName>representstherequiredclassnameoftheobjecttobe
created,or:

Nothingisthekeywordusedtoreleasetheobjectreference

Theobjectvariable(<objVarName>)mustbedeclaredbeforeitcanbesetto
referenceanOLEAutomationobject.
RelatedFunctions
Example

CreateObject | Nothing
' create variable to store object reference
Dim objWord as Object
' create object and assign reference to variable
Set objWord = CreateObject( "Word.Document" )

178
' insert appropriate VBA code here to manipulate Word object
' release reference
Set objWord = Nothing

Sgn
Description

Indicatesthesignofanumber.Sgndoesnotroundthenumber,andignoresthe
fractionalvalueofthenumber.
Sgnexpectstheargument(Num)tobeavalidnumericvalue.IfNumisgreater
thanzero,Sgnreturnsthevalueof1.IfNumisequaltozero,Sgnreturnsthe
valueof0.IfNumislessthanzero,Sgnreturnsthevalueof1.

Syntax

Sgn(Num)
Num ............ Number:TheargumentNummustcontainanIntegeror
expressionrepresentingavalidnumericvalue.

ReturnValue

RelatedFunctions
Example

ReturnsavalueindicatingtheSign(+or)valueofthe(Num)providedinthe
argument.
Abs | Fix | Int | Sqrt
Dim vntVal
vntVal = Sgn(99.8)' returns 1
vntVal = Sgn(-99.8)' returns -1
vntVal = Sgn(0)' returns 0

Sin
Description

CalculatesthetrigonometricSinevalueofanangle.TheSinfunctionexpectsthe
argument(Rad)tobeavalidanglevalueinradians,andcalculatestheratioof
twosidesofarightangletriangle.Theratioisthelengthofthesideoppositeto
theangledividedbythelengthofthehypotenuse.
Toconvertdegreestoradians,multiplydegreesbyPi/180.Toconvertradiansto
degrees,multiplyradiansby180/Pi.Formoreinformation,seeCircleMaths.

Syntax

Sin(Rad)
Rad ............. Radians:TheargumentRadmustbeexpressedinradians,
andmustbeavalidnumericvalue.

179
ReturnValue

RelatedFunctions
Example

ReturnstheSinevalueoftheangle(Rad)providedintheargument.Theresult
liesintherange1to+1.
Atn | Cos | Tan
Variable=Sin(0.7854);! Sets Variable to 0.7071

Space
Description

Syntax

CreatesaStringconsistingofthespecifiednumberNumofspaces.TheSpace
functionisusefulforformattingoutputandclearingdatainfixedlengthstrings.
Space(Num)
Num ............ Number:TheargumentNummustcontainanIntegeror
expressionrepresentingavalidnumericvalue.

ReturnValue
RelatedFunctions
Example

ReturnsaVariantcontainingaStringdatatype.
String
Dim strTest as String
' Returns a string with 10 spaces.
strTest = Space(10)
' Insert 10 spaces between two strings.
strTest = "Hello" & Space(10) & "World"

Sqrt
Description

Syntax

Calculatesthesquarerootofanumber.Sqrtexpectstheargument(Num)tobea
validnumericvaluegreaterthanorequalto0.
Sqrt(Num)
Num ............ Number:TheargumentNummustcontainanIntegeror
expressionrepresentingavalidnumericvalue.

ReturnValue
RelatedFunctions

Returnsthesquarerootvalueofthe(Num)providedintheargument.
Abs | Fix | Int | Sgn

180
Example

Variable=Sqrt(4);
! Sets Variable to 2.

Static
Description

Syntax

TheStaticstatementallocatesstorageforanddeclaresthedatatypeof
variablesandarraysthatwillretaintheirvaluesbetweensubsequentreferences.
Staticvariablesaremorecommonlyusedwithinprocedures(subroutinesand
functions),andhavelocalscope.
Static<VariableName>[(<Subscripts>)][As<DataType>]
where:

RelatedFunctions
Example

StaticistherequiredvariabledeclarationstatementBASICkeyword

<VariableName>representstherequirednameofthevariablebeing
declared(dimensioned)

( )aretheoptionalparenthesestoholdanarraysubscriptrange
(dimensions)

<Subscripts>representstheoptionalsubscriptrangeforanarray

AsistheoptionalAsstatementkeyworddeclaringthevariabledatatype

<DataType>representstheoptionalCitectVBAdatatypedeclarationforthe
variable

Const | Dim | ReDim


Static
Static
Static
Static
Static
Static
Static
Static
Static
Static
Static

bytVar
binVar
strVar
intVar
lngVar
sngVar
dblVar
vntVar
objVar
dtmVar
udtVar

As
As
As
As
As
As
As
As
As
As
As

Byte
Boolean
String
Integer
Long
Single
Double
Variant
Object
Date
<UserDefinedTypeName>

181

Stop
Description

Example

Endsexecutionoftheprogram.TheStopstatementcanbeplacedanywherein
yourcode.
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

Str
Description

Convertsanumericvaluetoatextstringcontainingnumericcharacters.TheStr
functionexpectstheargument(Num)tobeavalidnumericvalue.
TheStrfunctionisoftenusedtoprepareanumericalvaluefordisplayasastring
inacaption,label,stringfield,orstringexpression.
TheStrfunctionperformstheoppositeoftheValfunction,whichconvertsatext
stringcontainingnumericcharacterstoanumericvalue.
Note:Becarefulofdatatypecoercionissueswithvariantdatatypes.See
Variants.
Num ............ Number:TheargumentNummustcontainanIntegeror
expressionrepresentingavalidnumericvalue.Syntax
Str(Num)

ReturnValue

Returnsastringcontainingthenumericcharacterrepresentationofthenumeric
(Num)valueprovidedintheargument.
TheStrfunctionalwaysreservesthefirstreturnstringcharacterforthesignof
Num.IfNumispositive,aleadingspaceisusedandtheplussignisimplied.

RelatedFunctions
Example

Format | Hex | Oct | Val


Dim vntVar ' declare result holder variable
vntVar = Str()' returns " "

182
vntVar = Str(65)' returns " 65"
vntVar = Str(97.578)' returns " 97.578"
vntVar = Str(-97.578)' returns "-97.578"

StrComp
Description

Returnsanintegerthatistheresultofthecomparisonoftwostrings.
TherequiredString1argumentisanyvalidstringexpression.Therequired
String2argumentisanyvalidstringexpression.
TheoptionalCompareargumentisanumericexpressionthatspecifiesthetypeof
stringcomparison.Itcanbeomitted,0,or1.Specify0(default)toperforma
binarycomparison.Specify1toperformatextualcomparison.Ifcompareis
Null,anerroroccurs.

Syntax

StrComp(String1,String2)
String1 .......... String:TheargumentStrmustbeastringorexpressionthat
canrepresentavalidtextvalue.
String2 .......... String:TheargumentStrmustbeastringorexpressionthat
canrepresentavalidtextvalue.

ReturnValue

Example

Returnsavariantcontaininganintegerdatatypeindicatingtheresultofthe
stringcompare:

Returns1whereString1islessthanString2.

Returns0whereString1isequaltoString2.

Returns1whereString1isgreaterthanString2.

ReturnsNullwhereString1orString2isNull.

Dim strTest1 as String


Dim strTest2 as String
Dim strTest3 as String
Dim vntComp
strTest1 = "ABCD"
strTest2 = "abcd"
strTest3 = NULL
vntComp = StrComp(strTest1, strTest2)
' Returns -1 (less than)
vntComp = StrComp(strTest1, strTest1)
' Returns 0 (equal to)
vntComp = StrComp(strTest2, strTest1)

183
' Returns 1 (greater than)
vntComp = StrComp(strTest1, strTest3)
' Returns NULL (strTest3 is NULL)

String
Description

Createsastringthatconsistsofonecharacterrepeatedaspecificnumberof
times.
TherequiredNumargumentisLongnumericexpressionindicatinghowmany
characterstoreturn.IfNumcontainsNull,Nullisreturned.
TherequiredCharacterargumentisaStringexpressionfromwhichthefirst
characterisrepeatedandreturned,orisaVariant(Long)representingavalid
charactercode.IfcharactercontainsNull,Nullisreturned.

Syntax

String(Num)
Num ............ Number:TheargumentNummustcontainanIntegeror
expressionrepresentingavalidnumericvalue.

RelatedFunctions
Example

Space
Dim strTest as String
strTest = String(5, "*")
' Returns "*****"
strTest = String(5, 42)
' Returns "44444"
strTest = String(10, "Today")
' Returns "TTTTTTTTTT"

Sub
Description

Declaresanddefinesasubroutineprocedure,itsname,parameters,andcodeto
beenacteduponwhenthesubroutineiscalled.Subroutinesdifferfrom
functionsinthatfunctionsreturnavalue,whereassubroutinesdonot.
TherequiredSubroutineNameisthenameofthesubroutinebeingdeclared.
TheoptionalArgLististhelistofargumentsusedwithinthesubroutine.
ACitectVBAsubroutinestartswiththeSUBstatementandfinisheswiththe
ENDSUBstatement.AllotherstatementsthatliebetweentheSUBandEND
SUBstatements,willbeexecutedbythesubroutine,whencalledtodoso.

184
Syntax
RelatedFunctions
Example

Sub
Call | End Function | End Sub | Exit
Function GetColor2( c% ) As Long
GetColor2 = c% * 25
If c% > 2 Then
GetColor2 = 255' 0x0000FF - Red
End If
If c% > 5 Then
GetColor2 = 65280' 0x00FF00 - Green
End If
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

Tan
Description

CalculatesthetrigonometricTangentvalueofanangle.TheTanfunctionexpects
theargument(Rad)tobeavalidanglevalueinradians,andcalculatestheratio
oftwosidesofarightangletriangle.Theratioisthelengthofthesideopposite
totheangledividedbythelengthofthesideadjacenttotheangle.
Note:Toconvertdegreestoradians,multiplydegreesbyPi/180.Toconvert
radianstodegrees,multiplyradiansby180/Pi.

Syntax

Tan(Rad)
Rad ............. Radians:TheargumentRadmustbeexpressedinradians,
andmustbeavalidnumericvalue.

ReturnValue

Example

ReturnstheTangentvalueoftheangle(Rad)providedintheargument.Tanwill
returnasadouble.
Variable=Tan(1);! Sets Variable to 1.5574...

185

Time
Description

Determinesthecurrentsystemtimeaccordingtothesettingofthecomputers
clock.Unlikeotherfunctions,Timedoesnotrequiretrailingparentheses.
Therequiredtimevalueargumentisanynumericexpression,stringexpression,
oranycombination,thatcanrepresentatimevalue.
TheTime()function(bracketsincluded)determinesthecurrentsystemtime
accordingtothesettingofthecomputersclock.

Syntax
ReturnValue
RelatedFunctions
Example

Time[()]
TheTime()functionreturnsavariant(Date)indicatingthecurrentsystemtime.
Date | Timer | Now
' Time function example
Dim varMyTime
varMyTime = Time
' stores current system time.

Time (statement)
Description
RelatedFunctions
Example

Setsthesystemtime.
Datestatement
' Time statement example
Dim varMyTime
' Assign a time.
varMyTime = #4:35:17 PM#
' Set system time to variant varMyTime.
Time = varMyTime

Timer
Description

Syntax
ReturnValue

TheTimereventisusedtotrackelapsedtimeorcanbedisplayedasastopwatch
inadialog.
Timer()
Thenumberofsecondssincemidnight.

186
RelatedFunctions
Example

Date | Time | Now


Dim TS As Single
Dim TE As Single
Dim TEL As Single
TS = Timer
MsgBox "Starting Timer"
TE = Timer
TT = TE - TS
Print TT

TimeSerial
Description

Syntax
ReturnValue

RelatedFunctions
Example

ConstructsatimevalueseriallyfromthegivenHrs,Mins,andSecsarguments
passedtothefunction.TheTimeSerialFunctionexpectsallthreeargumentsto
bevalid.
TimeSerial()
ReturnsaVariant(ofdatedatatype)containingatimevaluecorrespondingto
theHrs,Mins,andSecsvaluesthatwerepassedintothefunction.
DateSerial
Dim varMyTime
varMyTime = TimeSerial(14, 35, 17)
' stores time as 2:35:17 PM

TimeValue
Description

Syntax

Calculatesatime.TheTimeValuefunctionexpectstheargumentvalue(Time)to
beastringoranyexpressionthatcanrepresentatimevalue.
TimeValue(Time)
Time............. Time:TheargumentTimemustbeastringorexpression
thatcanrepresentatimevalue.Thisincludesand
combinationoftimeliterals,numbersthatlookliketimes,
stringsthatlookliketimes,andtimesfromfunctions.

ReturnValue

Returnsavariant(ofdatedatatype)correspondingtotheparameter(Time).

187
RelatedFunctions
Example

DateValue
Dim varMyTime
varMyTime = TimeValue("2:35:17 PM")
' stores time as 14:35:17

Trim
Description
Syntax

StripsanyleadingandtrailingspacesfromStrvariable.
Trim(Str)
Str.............. String:TheargumentStrmustbeastringorexpressionthat
canrepresentavalidtextvalue.

ReturnValue
RelatedFunctions
Example

ReturnsaString.
LTrim | RTrim
Dim strTest as String
Dim strResult as String
Dim lngStartLength as Long
Dim lngFinishLength as Long
strTest = "
CitectVBA
"
lngStartLength = Len(strTest)
' returns 19
strResult = Trim(strTest)
' returns "CitectVBA"
lngStringLength = Len(strResult)
' returns 9

Ubound
Description

Determinesthevalueofthelargestsubscriptforthe(ArrayDimension)ofthe
(ArrayName)providedintheargument.Uboundexpectstherequiredargument
(ArrayName)tobeavalidvariablearrayname.
Theoptionalargument(ArrayDimension)mustbeawholelongnumber
indicatingwhichdimensionslowerboundistobereturned.Use1forthefirst
dimension,2forthesecond,andsoon.IfArrayDimensionisomitted,1is
assumed.

Syntax

Ubound(ArrayName,ArrayDimension)

188
ArrayName ....... ArrayName:TheargumentArrayNamemustbeastringor
expressionthatcanrepresentavalidvariablearrayname.
ArrayDimension ... ArrayDimension:TheargumentArrayDimensionmustbea
numericvalueorexpressionthatcanrepresentavalidlong
datatypevalue.
ReturnValue
RelatedFunctions
Example

ReturnsanumberofLongdatatype.
Lbound
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.

UCase
Description

Syntax

ConvertsalllowercaselettersinStrtouppercaseletters.Alluppercaseletters
andnonlettercharactersremainunchanged.
UCase(Str)
Str.............. String:TheargumentStrmustbeastringorexpressionthat
canrepresentavalidtextvalue.

ReturnValue
RelatedFunctions
Example

Returnsastring.
UCase
Dim strMixedCase as String
Dim strLowerCase as String
Dim strUpperCase as String
strMixedCase = "AbCdE"
strLowerCase = LCase(strMixedCase)' returns "abcde"
strUpperCase = UCase(strMixedCase)' returns "ABCDE"

Val
Description

Convertsatextstringcontainingnumericcharacterstoanumericvalue.TheVal
functionexpectstheargument(Str)tobeavalidstringexpression.TheVal
functionstopsreadingthestringwhenitreachesanonnumericcharacter.

189
Symbolssuchasdollarsignsandcommasarenotrecognised;however,radix
prefixesforoctal(&0)andhexadecimal(&H)are.Blanks,tabsandlinefeedsare
strippedoutfromthereturn.
TheValfunctionperformstheoppositeoftheStrfunction,whichconvertsa
numericvaluetoatextstringcontainingnumericcharacters.
Syntax

Val(Str)
Str.............. String:TheargumentStrmustbeastringorexpressionthat
canrepresentavalidtextvalue.

ReturnValue

RelatedFunctions
Example

Returnsthenumericvalueofastringofcharactersextractedfromthe(Str)
providedintheargument.
Format | Hex | Oct | Str
Dim vntVar ' declare result holder variable
vntVar = Val("65")' returns 65
vntVar = Val("90 Main St.")' returns 90
vntVar = Val("12+34+56")' returns 12
vntVar = Val(" 12 34 56 ")' returns 123456
vntVar = Val("&0FF")' returns
vntVar = Val("Zoe")' returns 0

VarType
Description

DeterminesthedatatypeofaVariantvariable.
TherequiredVarNameargumentisaVariantcontaininganyvariable(except
userdefinedtype).

Syntax

VarType(VarName)
VarName......... VariableName:TheargumentVarNamemustbeastring
representingavalidvariablename.

ReturnValue

Thesearethereturnvalues:
Return Value

Data Type

0
1
2
3
4

Empty
Null
Integer
Long
Single

190

RelatedFunctions
Example

Return Value

Data Type

5
6
7
8

Double
Not Applicable
Date/Time
String

IsDate | IsEmpty | IsNull | IsNumeric


Dim IntVar, StrVar, DateVar, MyCheck
' Initialize variables.
IntVar = 459
StrVar = "Hello World"
DateVar = #2/12/69#
MyCheck = VarType(IntVar)' Returns 2.
MyCheck = VarType(DateVar)' Returns 7.
MyCheck = VarType(StrVar)' Returns 8.

VbCallOpen function
Description

TheVbCallOpenfunctionisaCicodefunctionusedtocallaCitectVBAfunction
orsubroutinefromCicode.ItisusedtoinitiateacalltotheCitectVBAfunction
orsubroutineandreturnsahandle(ofOBJECTdatatype)tothatopened
functioncall.
VbCallOpenisusedinconjunctionwithVbCallRunandVbCallReturn
functions,whichcanallbenestedtoimplementtheentirefunctionsetwitha
singlelineofCicode.Forfurtherinformation,seethesectionCallingCitectVBA
fromCicode.

Syntax

<ReturnValue>=VbCallOpen(<FunctName>,<ArgList>)
where:

ReturnValue

<ReturnValue>representsthehandletotheopenedCitectVBAfunction.

<FunctName>representsthenameoftheCitectVBAfunctionorsubroutine
beingcalled.

<ArgList>representsacommaseparatedlistofargumentstopasstothe
functionorsubroutinebeingcalled.

VbCallOpenreturnsanObjectdatatypecontainingahandletotheCitectVBA

functionbeingcalled.Ifthefunctionfailsthereturnvalueiszero.
RelatedFunctions

VbCallRunfunction | VbCallReturnfunction

191
Example

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

Function CiVBATest(Value As Integer) As Integer


CiVBATest = Value * 2
End Function

VbCallRun function
Description

UsedtoexecutetheCitectVBAfunctionorsubroutine(previouslyopenedwith
theCicodeVbCallOpenfunction),andrequiresthehandlereturnedfromthe
VbCallOpenfunctioncall.
TheVbCallRunfunctionprovidesanopportunityfortheopenedCitectVBA
functiontocompleteandreturnavalueinthemultithreadedCitect/SCADA
environment.Itpassesitsargumentvalue(ofOBJECTdatatype)throughasits
returnvalueuponcompletion.
VbCallRunisusedinconjunctionwithVbCallOpenandVbCallReturn
functions,whichcanallbenestedtoimplementtheentirefunctionsetwitha
singlelineofCicode.Fordetails,seeCallingCitectVBAfromCicode.

Syntax

<ReturnValue>=VbCallRun(<CallHandle>)
where:

ReturnValue

RelatedFunctions

<ReturnValue>representsthehandletotheopenedCitectVBAfunction
passedinas<CallHandle>.

<CallHandle>representsthehandletothepreviouslyopenedCitectVBA
functionasreturnedbytheVbCallOpenfunction.

VbCallRun(passesthroughand)returnsaObjectdatatypecontainingahandle
totheCitectVBAfunctionbeingcalled.

VbCallOpen function | VbCallReturn function

192
Example

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

Function CiVBATest(Value As Integer) As Integer


CiVBATest = Value * 2
End Function

VbCallReturn function
Description

UsedtoobtainthereturnvalueofthecompletedCitectVBAfunction(previously
openedwiththeCicodeVbCallOpenfunction),andrequiresthehandle
returnedfromtheVbCallRunfunctioncall.
VbCallReturnisusedinconjunctionwithVbCallOpenandVbCallRun
functions,whichcanallbenestedtoimplementtheentirefunctionsetwitha
singlelineofCicode.Forfurtherinformation,seethesectionCallingCitectVBA
fromCicode.

Syntax

<ReturnValue>=VbCallReturn(<CallHandle>)
where:

ReturnValue
RelatedFunctions
Example

<ReturnValue>representsthevaluereturnedbythecompletedCitectVBA
function(whichwaspreviouslyopenedbytheCicodeVbCallOpen
function).Thedatatypeofthereturnvalueisdependentuponthedatatype
ofthereturnvaluefortheCitectVBAfunctionopened.

<CallHandle>representsthehandletothepreviouslyopenedCitectVBA
functionasreturnedbytheCicodeVbCallRunfunction.

VbCallReturnreturnsthecompletedreturnvaluefortheCitectVBAfunction.

VbCallOpen function | VbCallRun function


FUNCTION
TestCitectVBA()
INT iRet;
STRING sMsg = "Hello";
INT iVal = 123;

193

iRet = VbCallReturn(VbCallRun(VbCallOpen("CiVBATest",
iVal)));
Message("TestCitectVBA Function", "CiVBATest = " +
IntToStr(iRet), 0);
END

Example

Function CiVBATest(Value As Integer) As Integer


CiVBATest = Value * 2
End Function

WeekDay
Description

Syntax

Calculatestheweekdayvalueofthegivendateargumentpassedtothefunction.
DatevaluesinCitectVBAareevaluatedusingtheGregorianCalendar.
WeekDay(Date)
Date ............. Date:TheargumentDatemustbeastringorexpressionthat
canrepresentadatevalue.Thisincludesanycombinationof
dateliterals,numbersthatlooklikedates,stringsthatlook
likedates,anddatesfromfunctions.

ReturnValue

RelatedFunctions
Example

Returnsanintegerbetweentherangeof17inclusiverepresentingthewhole
numberfortheweekday:
Return Value

Description

1
2
3
4
5
6
7

Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

Date | Year | Month | Day


Dim varMyBDate, varMyWeekDay
varMyBDate = #8/07/1958#
varMyWeekDay = WeekDay(varMyBDate)
' returns 3 (Tuesday)

194

WhileWend
Description

Example

With

TheWhile...WendloopconditionalstatementissimilartotheDo Whileloop
statement.Theconditionischeckedbeforeexecutingtheblockofstatements
comprisingtheloop.
While <condition>
<statement/s>
Wend

Important:TheWithstatementisnotsupportedinCitectVBA.
Whenperformingaseriesofcommandsonanobject,youmustexplicitlyreferto
thenameoftheobjectwitheachcommand.

Write #
Description

Write#statementwritesdatatoaSequentialfileopenedinoutputorappend
modeandreadsthatdatafromalistofvariables.
TheWrite#statementhastwoparametersFileNumandVarList.Therequired
FileNumargumentistheassociatedfilenumberusedintheOpenstatement
whenthefilewasopened.TherequiredVarListargumentisacommadelimited
listofvariablesthatareassignedvaluesreadfromthefile.
Note:Thefilesystemkeepstrackofallopenfilesandthecurrentpositionof
accesswithineveryfile.Everystatementorfunctionthataccessesthedata
withinafile,altersthecurrentpositionwithinthatfile.TheLocfunctioncanbe
usedtodeterminethecurrentpositionwithinanopenfile.
DatawrittentoafilewiththeWrite#statementisusuallyreadwiththeInput#
statement.
Note:WhensavingdatatoafileforfuturereadingwiththeInput#statement,
usetheWrite#statementinsteadofthePrint#statementtowritethedatatothe
file.UsingWrite#ensurestheintegrityofeachseparatedatafieldbyproperly
delimitingit,soitcanbereadbackinusingInput#.UsingWrite#alsoensuresit
canbecorrectlyreadinanylocale.

Syntax

Write#FileNum,VarList
FileNum ......... FileNumber:TheargumentFileNummustcontainan
Integerornumericexpressionrepresentinganyvalid
numberintherange1to511inclusive,whichisreferenced
bythefilesystemtobeassociatedwithanopenfile.

195
VarList ........... VariableList:TheargumentVarListmustbeapredefined
validCitectVBAvariablenameorcommadelimitedlistof
validvariablenames.
RelatedFunctions

Get# | GetAttr | Input | LineInput# | Print# | Put#

Example

Dim strFileContents As String


Dim strTemp As String
Dim strString As String
Dim intFileNum as Integer
Dim intNumber as Integer
intFileNum = FreeFile'retrieve next free file number
Open "c:\test.txt" For Output As #intFileNum' open file.
Write #intFileNum, "This is a test of the Write # statement."
Close #intFileNum

Year
Description

Syntax

Calculatestheyearfromthegivendateargumentpassedtothefunction.Date
valuesinCitectVBAareevaluatedusingtheGregorianCalendar.
Year(Date)
Date ............. Date:TheargumentDatemustbeastringorexpressionthat
canrepresentadatevalue.Thisincludesanycombinationof
dateliterals,numbersthatlooklikedates,stringsthatlook
likedates,anddatesfromfunctions.

ReturnValue
RelatedFunctions
Example

Returnsanintegerrepresentingayear19302029inclusive.
Date | Month | WeekDay | Day
Dim varMyBDate, varMyYear
varMyDate = "08/07/58"
varMyYear = Year(varMyBDate)
' returns 1958

196

Appendix A: ASCII/ANSI Character Code


Listings
ThetablebelowshowstheLatin1ANSIcharacterset.
Codes031arecontrolcodes.ThestandardASCIIcodesarefrom32127
(decimal)andarecommonregardlessoftheANSIsetbeingused.Theremaining
codesfrom160255(decimal)varybetweenlanguagesdependentuponthe
ANSIsetbeingused.
Symbol

Decimal

Hex

{NUL}
{SOH}
{STX}
{ETX}
{EOT}
{ENQ}
{ACK}
{BEL}
{BS}
{HT}
{LF}
{VT}
{FF}
{CR}
{SO}
{SI}
{DLE}
{DC1}
{DC2}
{DC3}
{DC4}
{NAK}
{SYN}
{ETB}
{CAN}
{EM}
{SUB}
{ESC}

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

00
01
02
03
04
05
06
07
08
09
0A
0B
0C
0D
0E
0F
10
11
12
13
14
15
16
17
18
19
1A
1B

19
Symbol

Decimal

Hex

{FS}
{GS}
{RS}
{US}
{SPC}
!
"
#
$
%
&
'
(
)
*
+
,
.
/
0
1
2
3
4
5
6
7
8
9
:
;
<
=
>
?
@
A
B
C

28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67

1C
1D
1E
1F
20
21
22
23
24
25
26
27
28
29
2A
2B
2C
2D
2E
2F
30
31
32
33
34
35
36
37
38
39
3A
3B
3C
3D
3E
3F
40
41
42
43

19
Symbol

Decimal

Hex

D
E
F
G
H
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z
[
\
]
^
_
`
a
b
c
d
e
f
g
h
i
j
k

68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107

44
45
46
47
48
49
4A
4B
4C
4D
4E
4F
50
51
52
53
54
55
56
57
58
59
5A
5B
5C
5D
5E
5F
60
61
62
63
64
65
66
67
68
69
6A
6B

20
Symbol

Decimal

Hex

l
m
n
o
p
q
r
s
t
u
v
w
x
y
z
{
|
}
~
{Delete}

108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147

6C
6D
6E
6F
70
71
72
73
74
75
76
77
78
79
7A
7B
7C
7D
7E
7F
80
81
82
83
84
85
86
87
88
89
8A
8B
8C
8D
8E
8F
90
91
92
93

"

20
Symbol

Decimal

Hex

"

148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187

94
95
96
97
98
99
9A
9B
9C
9D
9E
9F
A0
A1
A2
A3
A4
A5
A6
A7
A8
A9
AA
AB
AC
AD
AE
AF
B0
B1
B2
B3
B4
B5
B6
B7
B8
B9
BA
BB

{NBSP}

20
Symbol

Decimal

Hex

188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227

BC
BD
BE
BF
C0
C1
C2
C3
C4
C5
C6
C7
C8
C9
CA
CB
CC
CD
CE
CF
D0
D1
D2
D3
D4
D5
D6
D7
D8
D9
DA
DB
DC
DD
DE
DF
E0
E1
E2
E3

20
Symbol

Decimal

Hex

228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255

E4
E5
E6
E7
E8
E9
EA
EB
EC
ED
EE
EF
F0
F1
F2
F3
F4
F5
F6
F7
F8
F9
FA
FB
FC
FD
FE
FF

20

Index
A
Abs function,95
access, file,82
Application Programming Interface (API),68
arguments,65,70,72
arithmetical operators,51
array subscripts,34
arrays,32
declaration,33
dimensions,34
dynamic size,37
fixed size,35
multi-dimensional,36
subscripts,34
Asc function,95
assigning references,75
assignment operators,50
Atn function,96
B
Beep statement,96
bounds,34
ByRef,70
ByVal,70
C
calendars, in databases,49
Call,97
Call statement,97
CDate function,97
CDbl function,98
character
line continuation,23
underscore,23
ChDir statement,98
ChDrive statement,100
Chr function,100
CInt function,105

CLng function,105
Close statement,106
coercion and variant data types,37
comments,22
file header,22
comparing strings,53
concatenation,54
Const,107
Const statement,107
constant declaration,28
constant naming,24
constants,24,27
date,44
declaring,28
scope,20
constants, intrinsic,30
constraints, date and time,47
control structures,54
DO statement,56
WHILE statement,56
Cos function,108
CSng function,109
CStr function,110
CurDir function,110
CVar function,111
D
data types,27
arrays,32
coercion,37
default,37
numeric,39
variant as default,37
databases and calendars,49
date,47
data type structure,47
date and time data constraints,47
date constants,44
date data type structure,47
date formatting,45

206

Date function,112
date functions,89
date handling,43
date values,48
DateSerial function,112
DateValue function,113
Day function,113
decimal numbers,39
decision making
DO Statement,56
WHILE statement,56
declaration, object,74
deletion, object,81
Dim statement,115
dimension,30
array declaration,33
array subscript declaration,34
variable declaration,30
Dir function,115,118
DO Statement,56
DO statement,56
double precison numbers,39
Dynamic Linked Libraries (DLLs),68
dynamic size arrays,37
E
End Function statement,118
END statement,60
End Sub statement,119
EOF function,120
Erase statement,120
EXIT statement,61
Exp function,121
exponential notation,40
F
file access,82
file I/O functions,89
FileCopy function,122
FileLen function,123
files,19

Fix function,123
fixed size arrays,35
floating point calculation rules,41
floating point numbers,39
FOR statement,56
Format function,124
formatting, date,45
FreeFile function,131
function
Abs,95
Asc,95
Atn,96
Beep,96
CDate,97
CDbl,98
Chr,100
CInt,105
CLng,105
Const statement,107
Cos,108
CSng,109
CStr,110
CurDir,110
CVar,111
Date,112
DateSerial,112
DateValue,113
Day,113
Dim statement,115
Dir,115
EOF,120
Erase statement,120
Exp,121
FileCopy,122
FileLen,123
Fix,123
Format,124
FreeFile,131
GetAttr,134

207

Hex,136
Hour,137
Input #,139
InStr function,141
Int,142
IsDate function,142
IsEmpty,143
IsNull,144
IsNumeric,144
Lbound,146
LCase,146
Left,147
Left$,147
Len,148
Loc,149
LOF,150
Log,151
LTrim,151
Mid,152
Minute,153
Month,155
Now,157
Oct,158
Option Base statement,161
Option Explicit,162
Print #,163
Put #,166
ReDim,169
Rem,170
Right,170
Rnd,172
RTrim,173
Second,173
Seek,174
SendKeys,176
Sgn,178
Sin,178
Space,179
Sqr,179

Str,181
StrComp,182
String,183
Tan,184
Time,185
Timer event,185
TimeSerial,186
TimeValue,186
Trim,187
Ubound,187
UCase,188
Val,188
VarType,189
WeekDay,193
Write #,194
Year,195
Function statement,131
functions,24,62,64,91
G
Get statement,132
GetAttr function,134
global scope,20
GOTO statement,55
H
handling, date,43
headers, file,22
Hex function,136
hexadecimal numbers,39
Hour function,137
I
IF statement,57
initializing variables,32
Input # function,139
InStr function,141
Int function,142
intrinsic constants,30
IsDate function,142
IsEmpty function,143
IsNull function,144

208

IsNumeric function,144
K
keywords,24
Kill statement,145
L
labels,23,24
Lbound function,146
LCase function,146
Left function,147
Left$ function,147
Len function,148
LenB function,148
lifetime, scope,20
line continuation character,23
Line Input # statement,148
Loc function,149
local scope,20
LOF function,150
Log function,151
logical operators,52
loops
DO Statement,56
WHILE statement,56
lower bound,34
LTrim function,151
M
math functions,90
mathematical operators,51
Microsoft Excel OLE,81
Microsoft Word OLE,80
Mid function,152
Minute function,153
MkDir statement,154
models, object,77
modular scope,20
Month function,155
multi-dimensional arrays,36
N
Name statement,155

naming,24
labels,23
notation, exponential,40
Now function,157
numbers,39
data types,39
numbers, rounding rules for,41
numeric data types,39
numeric precision,39
O
object declaration,74
object deletion,81
object models,77
Oct function,158
octal numbers,39
OLE automation objects,74,76
OLE services,73
OnError statement,61
Open statement,159
operator precedence,52
operators,49
arithmetic,51
operators, assignment,50
operators, logical,52
operators, relational,51
Option Base statement,161
option base statement,26
option compare statement,25
option explicit,25
Option Explicit statement,162
option explicit statement,25
option statements,25
P
precedence, operator,52
precision, numeric,39
Print # function,163
private scope,20
procedure functions,92,97
Call,97

209

End Function statement,118


End Sub statement,119
Function,131
Sub,183
public scope,20
Put # function,166
R
ReDim statement,169
relational operators,51
Rem statement,170
Right function,170
RmDir statement,171
Rnd function,172
RTrim function,173
rules, floating point,41
rules, rounding,41
S
scope,20
Second function,173
Seek function,174
SELECT CASE statement,59
SendKeys function,176
services, OLE,73
Sgn function,178
Sin function,178
single precision numbers,39
Space function,179
Sqr function,179
statement
Beep,96
ChDir,98
ChDrive,100
Close,106
Const,107
Dim,115
Erase,120
Get,132
Kill,145
Line Input #,148

MkDir,154
Name,155
Open,159
Option Base,161
Option Explicit,162
ReDim,169
Rem,170
RmDir,171
Time,185
statements,21
END,60
EXIT,61
FOR,56
GOTO,55
IF,57
OnError,61
option,25
option explicit,25
SELECT CASE,59
STOP,61
WITH,62
static variable scope,20
STOP statement,61
Str function,181
StrCompare function,182
string comparison,53
string concatenation,54
String function,183
string functions,92
strings,52
structures, control,54
Sub statement,183
subroutines,24,62,63
subscripts,34
T
Tan function,184
Time function,185
time functions,89
Time statement,185

time values,48
Timer event,185
TimeSerial function,186
TimeValue function,186
to clause within array subscripts,34
trigonometry functions,90
Trim function,187
U
Ubound function,187
UCase function,188
underscore character,23
upper bound,34
V
Val function,188
values, date,48
values, time,48

variable declaration,30
variable initialization,32
variable naming,24
variables,24,30
lifetime,20
scope,20
variant data type,37
variant variables,37
VarType function,189
W
WeekDay function,193
WHILE statement,56
WITH statement,62
Write # function,194
Y
Year function,195

You might also like