CitectVBA Reference Guide
CitectVBA Reference Guide
3 Fitzsimons Lane
PO Box 174
Pymble NSW 2073
Australia
COPYRIGHT
© Copyright 2004 Citect Corporation. All rights reserved.
TRADEMARKS
Citect Pty. Limited has made every effort to supply trademark information about company names, products and services mentioned in this manual.
Trademarks shown below were derived from various sources.
IBM, IBM PC and IBM PC AT are registered trademarks of International Business Machines Corporation.
MS-DOS, Windows, Windows 95, Windows NT, Windows 98, Windows 2000, Windows for Workgroups, LAN Manager, Microsoft Windows XP, Excel
and MSMAIL are trademarks of Microsoft Corporation.
Novell, Netware and Netware Lite are registered trademarks of Novell Inc.
GENERAL NOTICE
Some product names used in this manual are used for identification purposes only and may be trademarks of their respective companies.
Printed in Australia.
Contents
Exponential Notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Floating Point Calculation Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Rounding Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Rounding down . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
Rounding up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
Arithmetic rounding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
Banker's rounding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
Random rounding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Alternate rounding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Date Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Date Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Formatting Date Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Day . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Month. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
Year . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
Period/Era . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
Time. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
Date and Time Data Constraints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
Date Data Type Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Date-values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Time-values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Dates in Databases Using Different Calendars . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
Assignment Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
Arithmetical (Math) Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
Relational Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
Logical Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
Operator Precedence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
String Comparisons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
String Concatenation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
Control Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
GoTo statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
Do statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
While statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
For statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
If statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Select case statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
End statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Exit statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
OnError statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
Stop statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
With statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
Subroutines and Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
Contents v
Subroutines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
DLLs and APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
Accessing Functions in DLLs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
Declare statement structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
Declare - Function Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
Declare - Lib Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
Declare - Alias Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
Passing variables Byref and Byval . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
Passing Arguments to DLL Functions from CitectVBA . . . . . . . . . . . . . . . . . . . . . . . 58
OLE Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
OLE terminology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
OLE Linking and Embedding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
OLE Automation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
OLE automation objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
Declaration of OLE automation objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
Assigning references to OLE automation objects . . . . . . . . . . . . . . . . . . . . . 61
Using OLE automation objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
Accessing the object model of OLE automation server applications. . . . . . . 63
Understanding object models in OLE automation . . . . . . . . . . . . . . . . . . . . . 64
What are objects and collections? . . . . . . . . . . . . . . . . . . . . . . . . . . 64
What is a property? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
What is a method? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
Returning an object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
Using the Microsoft Word object model. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
OLE automation example using the Microsoft Word object. . . . . . . . . . . . . . 67
Using the Microsoft Excel object model. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
Deleting OLE automation objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
File Input/Output with CitectVBA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
CSng . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
CStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
CurDir, CurDir$ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
CVar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
Date . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
Date statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
DateSerial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
DateValue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
Day . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
Declare . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
Dim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
Dir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
Do Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
End Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
End Sub . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
EOF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
Erase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
Exit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
Exp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
FileCopy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
FileLen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
Fix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
For . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
FreeFile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
Get # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
GetAttr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
Goto . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
Hex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
Hour . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
If . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
InStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
Int . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
IsDate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
IsEmpty . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
IsNull . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
IsNumeric . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
Kill . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
Lbound . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
LCase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
Left, Left$ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
Len . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
Line Input # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
viii Contents
Loc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
LOF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
Log . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
LTrim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
Mid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
Minute . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
MkDir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
Month . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
Name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
Nothing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
Now . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
Oct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
OnError . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
Open . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
Option Base . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
Option Compare . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
Option Explicit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
Print (function) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
Print # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
Put # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
Randomize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
ReDim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
Rem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
Right . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
RmDir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
Rnd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
RTrim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
Second . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
Seek . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
Select . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
SendKeys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
Sgn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
Sin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
Space . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
Sqrt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
Static . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
Stop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
Str . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
StrComp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
Sub . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
Tan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
Time (statement) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
Contents ix
Timer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
TimeSerial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
TimeValue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
Trim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
Ubound . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
UCase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
Val . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
VarType . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
VbCallOpen function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
VbCallRun function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
VbCallReturn function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
WeekDay . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
While…Wend . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
With . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
Write # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
Year . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
Index 213
x Contents
Chapter 1: Introducing CitectVBA
CitectVBA Files
CitectVBA code scripts can be saved to file, can include comments, statements,
various representations of numbers, can handle many different data types, and
can have multiple and nested control structures. However, CitectVBA is
primarily provided with CitectSCADA to interact with ActiveX objects.
CitectVBA files are ASCII text files stored in ANSI format with a BAS extension
(filename.BAS), and are known as file modules.
CitectVBA file modules can be viewed and edited in any text editor program.
They can be used in CitectSCADA, but must be saved as 'text with linebreaks'
with a '.BAS' file extension.
Cicode Editor
The Cicode Editor is CitectVBA aware and designed to help you create, edit, test,
and debug CitectVBA file modules in your CitectSCADA project.
The Cicode Editor has features suitable for use with CitectVBA file modules
including:
Ability to create, open, edit, and save CitectVBA file modules
Customizable coloration of CitectVBA code syntax structure
Recognition of predefined keywords with tooltip prompting and auto-
completion functionality
Fully integrated debugging of CitectVBA file modules
Separate VB Watch window for viewing runtime CitectVBA variable values
A sample CitectVBA file module named Sample.Bas is included in the
User\Example subfolder on the drive on which you installed CitectSCADA.
This module explains most of the CitectVBA functionality. The separate file
CitectVBATest.bas is installed to the CitectSCADA bin folder and contains the
example CitectVBA Test Project code for use with the example project tutorial
guide.
4 Chapter 2: Understanding CitectVBA Language Basics
Scope of CitectVBA
The scope of an object determines which portions of your code scripts can use
that object.
Note: The use of Global, Public, and Private keywords has no effect on scope in
CitectVBA.
Procedural (local) level Variables and constants declared (using the Dim, Static, or Const statements)
scope within a CitectVBA procedure (subroutine or function) have local scope to only
that within the procedure. This means that procedural level variables and
constants cannot be referenced (accessed and used) from anywhere outside of
that procedure.
The Global, Public, and Private keywords are not supported by CitectVBA at the
procedural level and should not be used within a procedure.
Procedural level variables declared using the Dim statement do not retain their
assigned values when dereferenced. Procedural level variables declared using
the Static statement, however, do retain their assigned values between
references, even after that procedure moves out of scope.
Modular level scope Constants declared (using the Const statement) and variables declared (using
the Static statement) at the modular level (outside any procedure) in a
CitectVBA file have modular scope to all procedures within that same
CitectVBA module (file). This means that modular constants and static variables
can only be referenced from a procedure located within the same file module,
and cannot be referenced from outside of that file module. This has no effect in
CitectVBA, even if declared using the Global keyword.
Modular level constants and static variables retain their assigned values for the
entire runtime of the project.
Chapter 2: Understanding CitectVBA Language Basics 5
Global level scope Variables declared (using the Dim, Global, or Public statements) at the modular
level (outside any procedure) in a CitectVBA module (file), have global scope
within the CitectSCADA project. This means that modular CitectVBA variables
(except statics) can be referenced from both inside and outside of their file
module.
Global level variables can be used directly within CitectSCADA command or
expression fields.
Procedures (subroutines or functions) declared within a CitectVBA file module,
like global variables, have global scope within a CitectSCADA project. They can
be referenced or called from any CitectVBA module, as well as from any
CitectSCADA command or expression field.
Equally important, all CitectSCADA variable tags, alarm tags, and ActiveX
objects are accessible to all CitectVBA file modules (and their procedures) within
that project, in the same manner as they have always been accessible to project
Cicode files. For information about referencing CitectSCADA project tags using
CitectVBA, see Integrating CitectVBA with CitectSCADA.
Global level variables will also retain their assigned values between subsequent
references, behaving somewhat similarly to the values stored in CitectSCADA
tags. In this regard, Global and Public statements are redundant at the
modular (global) level in CitectVBA, as they perform the exact same duty as the
Dim statement.
See Also Multithread Considerations with CitectVBA
CitectVBA Files
CitectVBA Statements
A statement in CitectVBA is an unbroken sequence of syntactically correct code
script containing at least one CitectVBA keyword instruction. A single statement
in CitectVBA is one complete segment of code script that instructs CitectSCADA
to do something.
In CitectVBA there is no statement terminator. As in other BASIC programming
languages, the end of the line containing the statement is treated as the
statement terminator by default.
Most often, a statement consists of a single line of CitectVBA script. However,
more than one statement can be placed on one line of CitectVBA script, provided
each statement is separated by a colon character (:); for example:
Pump234.AddPoint( 25, 100) : Pump234.AddPoint( 0, 75)
is equivalent in CitectVBA to:
Pump234.AddPoint( 25, 100)
Pump234.AddPoint( 0, 75)
6 Chapter 2: Understanding CitectVBA Language Basics
Comments
Comments are non-executed sections of code that are ignored by the CitectVBA
compiler. Comments allow programmers to describe the purpose of a section of
code to facilitate code maintenance.
As in other BASIC programming languages, both the apostrophe character ( ' ),
and the keyword REM are recognized as the start of a comment in CitectVBA. All
characters following an apostrophe or the keyword REM are ignored by the
CitectVBA compiler until it reaches the end of the line. Line continuation
characters do not work inside comments.
REM, like all other keywords and most names in CitectVBA, is not case
sensitive.
' This whole line is a comment
rem This whole line is a comment
Rem This whole line is a comment
REM This whole line is a comment
Both types of comments can be used on their own separate line, or the
apostrophe character can be used to start a comment at the end of a statement on
the same line as a statement.
Pump234.AddPoint( 25, 100) ' Add point to pump 234
Everything placed on the same line after an apostrophe is treated by CitectVBA
as a comment. If you want to place a comment on the same line as a statement,
the comment must be placed last after all statements on that line. Comments
cannot be placed between multiple statements on the same line.
Not every line of code requires a comment. In fact, CitectVBA should contain
understandable naming structures and be laid out in such a manner as to make
comments unnecessary. However, where a complex function, equation, or logic
structure is not readily understandable by viewing the code, it is good practice
to include a pertinent comment to make the code more understandable when
viewed in isolation.
See Also Comments
Header information You should include header information with every file you create or edit. Data
such as the file name, author name, creation date, update date, editing history,
and the like should be included to form the header information. Each function or
subroutine should include a brief comment describing the purpose or function
of the procedure.
Chapter 2: Understanding CitectVBA Language Basics 7
Labels
Labels can be used to divide a large CitectVBA function or subroutine into
logical sub-sections of code script. Labels are often used in association with the
GoTo statement. All of the CitectVBA script following the label and extending
through to another label, or to the end of the function or subroutine containing
the label, is regarded as belonging to that label. Or more appropriately, the label
is said to identify, or be attached to, that particular section of CitectVBA script.
Labels must begin with a letter, be no longer than 40 characters, and cannot be a
reserved word. Labels must terminate with the colon character (:). Label names
can only contain the letters 'A' to 'Z' and 'a' to 'z', the underscore '_' character,
and the digits '0' to '9'. Label names cannot contain the space character.
Label names (once declared), become a keyword in CitectVBA. Like most
keywords in CitectVBA, label names are not case sensitive. For example, all of
the following label examples are treated identically in CitectVBA:
label1:
Label1:
LABEL1:
Note: Labels as used in CitectVBA are not the same as labels used in
CitectSCADA.
See Also CitectVBA Files
Naming
Function, subroutine, variable, constant, and label naming in CitectVBA must
begin with a letter, be no longer than 40 characters, and cannot be a reserved
word. Names can only contain the letters 'A' to 'Z' and 'a' to 'z', the underscore '_'
character, and the digits '0' to '9'. Names cannot contain the space character. You
cannot use the name of a CitectVBA predefined function as a name. For a list of
predefined functions, see CitectVBA Function Reference.
Function, subroutine, variable, constant, and label object names (once declared),
become a keyword in CitectVBA. Like most keywords in CitectVBA, these
names are not case sensitive. For example, all of the following examples are
treated identically in CitectVBA:
pump234.addpoint(25, 100)
Pump234.AddPoint(25, 100)
PUMP234.ADDPOINT(25, 100)
When naming in CitectVBA, make the name an appropriately descriptive term
that is easily recognizable. For example:
X.addpoint(25, 100)
doesn't make as much sense as:
Pump234.AddPoint(25, 100)
Combining upper- and lowercase letters between words in the name is an
acceptable common programming practice, and aids in readability.
Identically named objects cannot be declared more than once per CitectSCADA
project, even though they may exist in different CitectVBA code file modules.
However, if an object declared locally within a procedure has the same name as
an object declared in a module, CitectVBA will reference the local procedure
scope object instead of the modular scope object.
See Also Scope of CitectVBA
CitectVBA Files
Accessing Cicode Tags with CitectVBA
Chapter 2: Understanding CitectVBA Language Basics 9
Option Statements
CitectVBA supports the use of file scope Option statements which determine the
default behaviour of some CitectVBA functions. For instance, the Option
Explicit statement causes the CitectVBA compiler to produce compile errors
whenever it encounters the use of previously undeclared variables. The Option
Compare statement sets the default comparison method for string comparisons.
The Option Base statement sets the default base number for CitectVBA variable
arrays to either zero or one.
You must declare all option statements in CitectVBA at the beginning of your
CitectVBA code files.
See Also Option Explicit statement
Option Compare statement
Option Base statement
CitectVBA Function Reference
Option Explicit As in other BASIC programming languages, CitectVBA supports the declaration
statement of variables both implicitly and explicitly. An unfortunate consequence of
implicit variable declaration is the possible misspelling of the variable name in
subsequent code writing, with unreliable program behaviour and unpredictable
consequences.
To prevent implicit declaration, and to foster good (consistent and reliable)
programming standards, you should use the option explicit statement at the
beginning of all your CitectVBA files:
Option Explicit
This causes the CitectVBA compiler to produce a compile error whenever it
encounters an undeclared variable. This can be useful in locating and identifying
variable name typing errors in your CitectVBA code at compile time, thus
trapping and preventing runtime errors caused by such mistakes.
See Also Option Explicit statement
Variable declaration
Option Statements
Option Compare The Option Compare statement determines how strings are compared within a
statement CitectVBA file, and like other Option statements in CitectVBA, should be
declared at the beginning of your CitectVBA code files.
When strings are compared using CitectVBA functions such as StrComp() or
InStr(), CitectVBA determines whether they contain equivalent characters and
how they differ if they do not match.
Note: When comparing strings, CitectVBA compares the ANSI values of each
character in the strings. For example, the character capital 'A' has the ANSI value
10 Chapter 2: Understanding CitectVBA Language Basics
of 65, and the character lowercase 'a' has the ANSI value of 97. For a listing of
ANSI character values, see ASCII/ANSI Character Code Listings.
You can use the Option Compare statement to specify the default case-
sensitivity behavior for CitectVBA functions when making string comparisons.
The Option Compare statement in CitectVBA has two settings:
Option Compare Binary: String comparisons are case-sensitive, and this is
the default string-comparison setting.
Option Compare Text: String comparisons are case-insensitive.
See Also Strings
Option Statements
Option Base statement The Option Base statement determines the default base number for the indexing
of variable arrays created within a CitectVBA file, and like other Option
statements in CitectVBA, should be declared at the beginning of your CitectVBA
code files.
There are two settings for the Option Base statement in CitectVBA:
Option Base 0: Variable arrays are indexed from number zero, and this is
the default setting.
Option Base 1: Variable arrays are indexed from number one.
For an example of using the Option Base statement, see Fixed Size Arrays
See Also Arrays of Variables
Option Statements
Chapter 2: Understanding CitectVBA Language Basics 11
Constants
A constant in CitectVBA refers to a value that does not change (remains
constant), such as the numeric value Pi (3.14159). You can create a constant in
CitectVBA named Pi, assign it the numeric value once in your code, then refer to
it by using the constant name, as shown here:
'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
12 Chapter 2: Understanding CitectVBA Language Basics
Declaration of CitectVBA constants can only be declared and referenced within CitectVBA file
constants modules. CitectVBA modular constants have modular scope and cannot be
referenced (accessed and used) from outside their CitectVBA module (file).
Note: CitectVBA constants cannot be used directly in CitectSCADA command
or expression fields.
Once declared within a CitectVBA module, CitectVBA constants can be
referenced and used in any procedure within the same code module. A constant
declared outside a procedure has modular scope to all procedures within that
same CitectVBA module (file). See Scope of CitectVBA. Constants declared in a
Sub or Function procedure have local scope only within that procedure.
CitectVBA constants are declared with the Const statement in the following
format.
Const <ConstantName> [ As <DataType> ] = <expression>
Chapter 2: Understanding CitectVBA Language Basics 13
where:
Const is the required constant declaration statement BASIC keyword
Intrinsic constants CitectVBA has no predefined intrinsic (built-in and declared) constants,
however, does provide limited support for intrinsic constants provided in object
libraries of ActiveX objects when the object they refer to is loaded using the
predefined CitectVBA CreateObject() function.
See Also Declaration of constants
Constants
Variables
Variables are used in CitectVBA to temporarily store data values. Variables let
you assign a descriptive name to the data you are working with. You can create a
variable once only in your code, and reference (refer to) it thereafter as many
times as you like, by using its name in your code in place of the data value.
Unlike constants, the value that a variable holds can be changed during the
runtime of the project.
All variables declared within a CitectVBA procedure (subroutine or function)
have local scope to that procedure only. Procedural level variables declared
using the Dim statement do not retain their assigned values when dereferenced.
Procedural level variables declared using the Static statement, however, retain
their assigned values between references, even after that procedure moves out of
scope.
CitectVBA code used within a CitectSCADA command or expression field is
treated as if the command or expression is a separate CitectVBA procedure.
Variables declared within such a command procedure have procedural scope
and lifetime, as described above.
Variables declared using the static statement at the modular level (outside any
procedure) in a CitectVBA file, have modular scope to all procedures within that
same CitectVBA module (file). Modular level static variables retain their
assigned values for the entire runtime of the project.
Variables declared (using the dim, global, or public statements) at the modular
level (outside any procedure) in a CitectVBA file do, however, have global scope
within the CitectSCADA project.
Note: Global and public statements are redundant at the modular (global)
level in CitectVBA, as they perform the exact same duty as the dim statement.
Chapter 2: Understanding CitectVBA Language Basics 15
Variable declaration In CitectVBA, variables are declared (dimensioned) with the dim statement in
the following format.
Dim <VariableName> [ As <DataType> ]
where:
Dim is the required Variable declaration statement BASIC keyword
Variable initialization CitectVBA variables are initialized when first declared. Numeric variables are
values initialized to 0 (zero). Variable-length strings are initialized to zero-length
strings (""). Fixed length strings are filled with zeros. Variant variables are
initialized to Empty.
To be sure of the contents of a variable, a valid value should be assigned to it
before it is used as a operand in a CitectVBA statement. For details, see
Assignment Operator.
Note: Only implicitly declared variables can be assigned an initial value in the
declaration. However, as explicit declaration is preferred practice in CitectVBA,
explicit variables must be declared before they can be assigned a value.
Every call to a procedure will reinitialize the value of all objects (except static
variables) declared within that procedure.
Note: In CitectVBA, use a static variable, a modular variable, or a CitectSCADA
tag to store variable values between procedures. For details, see Scope of
CitectVBA.
Objects (including variables) declared in CitectVBA are only initialized when
referenced by a running piece of code, and are removed from memory when all
references are closed.
In the CitectSCADA multithreaded environment, CitectVBA remains active in
memory only so long as a procedure is being processed. At the completion of a
CitectVBA procedure, all objects no longer referenced by that procedure are
removed from memory. For details, see Multithread Considerations with
CitectVBA.
See Also CitectVBA Data Types
Variable initialization values
Constants
Variant Declaration
Arrays of Variables
Arrays of Variables
Arrays of variables allow you to group like variables together, somewhat similar
to the grouping of like items in fields of a database. An array is an ordered group
of variables of the same name, containing values of the same data type.
Individual member elements of the array are indentified by a separate index
number. Arrays in CitectVBA start their indexing sequence by default at zero.
This default base value can be changed in a CitectVBA file module by using the
option base statement.
Chapter 2: Understanding CitectVBA Language Basics 17
<DataType> represents the optional CitectVBA data type declaration for the
array.
18 Chapter 2: Understanding CitectVBA Language Basics
Array Subscripts
Arrays can be declared with default or defined boundaries known as bounds.
Unless specifically defined in the array declaration statement, default lower
bound settings are used. The default lower bound is zero, unless set by the
module option base statement setting.
CitectVBA does not have an arbitrary upper bound on array dimensions. The
upper bound of the array dimension must be defined before the array can be
used. All bound values must be whole integers.
Subscripts are contained within one set of parentheses positioned immediately
after the array name in the array declaration statement.
Subscripts are used to specify the bounds of each dimension of an array when
the array is declared. If a single value is used, for instance (5), this represents the
upper bound for that dimension of the array. If a range is specified, for instance
(1 to 9), this specifies both the lower and upper bounds for that dimension of the
array. If more than one subscript is used, for instance ( 5, 1 To 9), each subscript
must be separated by a comma, and each subscript represents a separate
dimension of the array.
The syntax of an array subscript range consists of a numeric value range
separated by the to clause:
(<LowerBound> To <UpperBound>)
where:
( ) are the required parentheses to hold an array subscript range
(dimensions).
Chapter 2: Understanding CitectVBA Language Basics 19
<LowerBound> represents the lower bound of the subscript range for the
array dimension.
To is the clause linking the lower and upper bounds of the subscript range.
<UpperBound> represents the upper bound of the subscript range for the
array dimension.
See Also Fixed Size Arrays
Multi-Dimensional Arrays
Dynamic Size Arrays
Arrays of Variables
Dim
Multi-Dimensional Arrays
CitectVBA supports multi-dimensional arrays, declared using multiple
subscripts. Each subscript must be separated by a comma, and each subscript
represents a separate dimension of the array.
The following example declares a two-dimensional array.
Dim dblMat(20, 20) As Double
Unless specifically defined in the array declaration statement, default lower
bound settings are used. The default lower bound is zero, unless set by the
module option base statement setting. For more information on bounds, see
“Array Subscripts in CitectVBA.”
Reusing the previous example, either or both dimensions can be declared with
explicit lower bounds.
Dim dblMat(1 To 10, 1 To 10) As Double
Arrays can be more than two dimensional. This declaration creates an array that
has three dimensions with sizes 6 elements by 4 elements by 3 elements, using
base 0:
Dim ArrTest(5, 3, 2)
You can efficiently process a multi-dimensional array with the use of for loops.
In the following statements the elements in a multi-dimensional array are set to
a value.
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
Arrays declared (using the dim statement within procedures,) do not retain their
values between procedure calls in CitectVBA.
See Also Multi-Dimensional Arrays
Dynamic Size Arrays
Arrays of Variables
Array Subscripts
Option Base statement
Chapter 2: Understanding CitectVBA Language Basics 21
Variant Declaration
As is the case with Visual Basic, when a variable is introduced in CitectVBA, it is
not necessary to declare it first (see Option Explicit statement for an exception to
this rule). When a variable is used but not declared, it is implicitly created as a
22 Chapter 2: Understanding CitectVBA Language Basics
variant data type. Variants can also be declared explicitly using As Variant. Both
of the following example declarations as treated identically in CitectVBA:
Dim vntVar' implicit variant declaration
Dim vntVar As Variant ' explicit variant declaration
The IsEmpty( ) function can be used to find out if a variant variable has been
previously assigned a value.
Numbers in Variants
When storing numbers in variant variables, the data type used is always the
most compact type possible. For example, if you first assign a whole number to
the variant it will be stored as an integer or long. If you assign a number with a
fractional component, it is stored as a single or double.
Chapter 2: Understanding CitectVBA Language Basics 23
Numbers
CitectVBA supports three representations of numbers: decimal, octal, and
hexadecimal.
To indicate the use of octal (base 8) or hexadecimal (base 16) numbers, prefix the
number with &O or &H respectively. If no prefix is included with a number, it is
treated as decimal (base 10). For example:
Dim vntVar as Variant
vntVar = 12345' assign decimal value
vntVar = &o12345' assign octal value
vntVar = &h12345' assign hexadecimal value
Most numbers used in CitectVBA formulas are decimal numbers. Decimal
numbers consist of integral values (known as integers) positioned to the left of
the decimal point, and fractional values (known as fractions) positioned to the
right of the decimal point. If the decimal point is omitted, the number is treated
as an integer (whole number with no fraction).
When using numbers in CitectVBA, consideration must be given to the data type
of the variables that hold and store the numbers, as well as to the behaviour of
CitectVBA when dealing with numbers. For details, see “Numeric Data Types in
CitectVBA,” “Floating Point Calculation Rules in CitectVBA,” and “Rounding
Numbers in CitectVBA.”
See Also Date Handling
Variant Declaration
Strings
Variables
Constants
CitectVBA Data Types
CitectVBA Function Reference
24 Chapter 2: Understanding CitectVBA Language Basics
Exponential Notation
CitectVBA can handle very large numbers, up to a value of 1.7976931486232
raised to the power of 308, (1.7 308). To represent very large numbers such as
these, exponential notation is used.
Commonly, exponential notation uses the letter 'E' in the number, followed by
the sign of the number (+ or -), and then the exponential value (power) of the
number. CitectVBA uses the letter 'E' for Single data type exponential values,
Chapter 2: Understanding CitectVBA Language Basics 25
and the letter 'D' for Double data type exponential values. The maximum size
number for a double precision data type, as quoted above, would be represented
using exponential notation as 1.7976931486232D+308, or abbreviated to
1.79D+308.
You can use exponential notation in your CitectVBA calculations, so long as the
data types of all the variables in the calculation are capable of storing floating
point values; i.e.: Single, Double or Variant.
For details about precision, accuracy, and rounding issues with using floating
point variables in CitectVBA, see “Numeric Data Types in CitectVBA,” “Floating
Point Calculation Rules in CitectVBA,” and “Rounding Numbers in CitectVBA.”
See Also Numbers
Rounding Numbers
Rounding occurs when you convert a number of greater precision into a number
of lesser precision. For instance, when converting a floating-point number
26 Chapter 2: Understanding CitectVBA Language Basics
(single precision, double precision, or variant data types) into an integer or long
data type number. The possible ways of numeric rounding are discussed below.
Rounding down The simplest form of rounding is truncation. Any digits after the desired
precision are ignored and dropped. The CitectVBA Fix() function is an
example of truncation. For example, Fix(3.5) is 3, and Fix(-3.5) is -3.
The Int() function rounds down to the highest integer less than the value. Both
Int() and Fix() act the same way with positive numbers (truncating), but give
different results for negative numbers: Int(-3.5) gives -4.
The Fix() function is an example of symmetric rounding because it affects the
magnitude (absolute value) of positive and negative numbers in the same way.
The Int() function is an example of asymmetric rounding because it affects the
magnitude of positive and negative numbers differently.
Rounding up CitectVBA does not have a specific round-up function. However, for negative
numbers, both Fix() and Int() can be used to round upward, in different
ways:
Fix() rounds towards 0 (up in the absolute sense, but down in terms of
absolute magnitude). For example: Fix(-3.5) is -3.5.
Int() rounds away from 0 (up in terms of absolute magnitude, but down in
the absolute sense). For example: Int(-3.5) is -4.
Arithmetic rounding When continually rounding in one direction (down or up), the resulting number
is not necessarily the closest to the original number. For example, if you round
1.9 down to 1, the difference is a lot larger than if you round it up to 2. It is easy
to see that numbers from 1.6 to 2.4 should be rounded to 2. However, what about
1.5, which is equidistant between 1 and 2? By mathematical convention, the half-
way number is rounded up.
To implement rounding half-way numbers in a symmetric fashion, -.5 is
rounded down to -1, or in an asymmetric fashion, where -.5 is rounded up to 0.
CitectVBA does not have a function for arithmetic rounding.
Banker's rounding When you add rounded values together, always rounding .5 in the same
direction results in a bias that grows with the more numbers you add together.
One way to minimize the bias is with banker's rounding.
Banker's rounding rounds .5 up sometimes and down sometimes. The
convention is to round to the nearest even number, so that both 1.5 and 2.5
round to 2, and 3.5 and 4.5 both round to 4. Banker's rounding is symmetric.
In CitectVBA, the CByte(), CInt(), CLng(), CCur(), and Round() numeric
functions perform banker's rounding.
Chapter 2: Understanding CitectVBA Language Basics 27
Random rounding Even banker's rounding can bias totals. You can take an extra step to remove bias
by rounding .5 up or down in a truly random fashion. This way, even if the data
is deliberately biased, bias might be minimized. However, using random
rounding with randomly distributed data might result in a larger bias than
banker's rounding. Random rounding could result in two different totals on the
same data.
CitectVBA does not have a function for random rounding.
Alternate rounding Alternate rounding is rounding between .5 up and .5 down on successive calls.
CitectVBA does not have a function for alternate rounding.
See Also Numbers
Date Handling
CitectVBA has several pre-defined date and time functions that return date/time
values. There are three functions enabling you to determine the current date and
time set in Windows. The Now function, Date function, and Time function check
your system clock and return all or part of the current setting.
To retrieve the date portion of a date/time value, use the pre-defined DateValue
function. This function takes in either a string or a date value and returns only
the date portion.
Using DateValue, you can compare the date portion of a date variable to a
specific date value, like this:
If DateValue(dtmSomeDate) = #5/14/70# Then
' You know the date portion of dtmSomeDate is 5/14/70
End If
If you need just the time portion of a date variable, use the TimeValue function.
Using this function, you could write code that checks the time portion of a date
variable against a particular time, like this:
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
You can perform arithmetic or mathematics (math) on date/time values because
CitectVBA stores dates internally as serial values. Adding or subtracting
integers adds or subtracts days, whilst adding or subtracting fractions adds or
subtracts time. Therefore, adding 20 to a date value in CitectVBA adds 20 days,
while subtracting 1/24 subtracts one hour. For example, to get tomorrow's date,
you could just add 1 to today's date, like this:
dtmTomorrow = Date() + 1
28 Chapter 2: Understanding CitectVBA Language Basics
Date is a built-in CitectVBA function that returns the date portion (the integer
part) of the current date and time retrieved from the Windows operating system.
Adding 1 to that value returns a date that represents the next day.
The same mechanism works for subtracting two dates. Although CitectVBA
supplies the DateDiff function for finding the interval spanned by two date/
time values, if you just need to know the number of days between the two dates,
you can simply subtract one from the other.
See Also Date and Time Functions
Date Constants
Formatting Date Values
CitectVBA Function Reference
Date Constants
You can use date/time literals in CitectVBA code by enclosing them with the
hash sign (#), in the same way you enclose string literals with double quotation
marks (""). This is commonly known as declaring date constants.
For example, #2/6/10# represents the Australian date value of 2nd June, 2010 if
the short date setting for the locale was set to d/MM/yyyy. The same date
constant would represent the American date value of February 6, 2010 if the
short date setting for the locale was set to MM/d/yyyy. See “Formatting Date
Values in CitectVBA”.
Note: The system locale settings are determined using Regional Settings in
Windows Control Panel.
Similarly, you can compare a date/time value with a complete date/time literal:
If SomeDate > #3/6/99 1:20pm# Then
If you don’t include a time in a date/time literal, CitectVBA sets the time part of
the value to midnight (the start of the day). If you don’t include a date in a date/
time literal, CitectVBA sets the date part of the value to December 30, 1899.
CitectVBA accepts a wide variety of date and time formats in literals. These are
all valid date/time values:
SomeDate = #3-6-93 13:20#
SomeDate = #March 27, 1993 1:20am#
SomeDate = #Apr-2-93#
SomeDate = #4 April 1993#
In the same way that you can use the IsNumeric function to determine if a
Variant variable contains a value that can be considered a valid numeric value,
you can use the IsDate function to determine if a variant contains a value that
can be considered a valid date/time value. You can then use the CDate function
to convert the value into a date/time value.
Chapter 2: Understanding CitectVBA Language Basics 29
For example, the following code tests the Text property of a text box with IsDate.
If the property contains text that can be considered a valid date, CitectVBA
converts the text into a date and computes the days left until the end of the year:
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 Date and Time Functions
Formatting Date Values
CitectVBA Function Reference
Date Handling
Text All strings should be surrounded by single quotes, and any single quotes should
be entered as four single quotes in a row:
Value Example
it''''s it's
'Today is 'M/dd/yy' and it''''s 'h:mm Today is 01/22/99 and it's 8:18
Day The day can be displayed in one of four formats using a lowercase "d.
Value Meaning Example
d Day of the month as digits without 5
leading zeros for single digit days.
30 Chapter 2: Understanding CitectVBA Language Basics
Month The month can be displayed in one of four formats using capital "M". The letter
"M" must be uppercase to distinguish months from minutes.
Value Meaning Example
M Month as digits without leading zeros for 1
single digit months.
MM Month as digits with leading zeros for 01
single digit months.
MMM Month as a three letter abbreviation. Jan
MMMM Month as its full name. January
Year The year can be displayed in one of three formats using lowercase "y"..
Value Meaning Example
y 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.
yy Year represented only by the last two 09
digits.
yyyy Year represented by the full 4 digits. 1909
Period/Era The period/era string can be displayed in a single format using the letter "g". The
letter "g" must be lowercase. If you include the gg in a date string that does not
have any associated Era string, the gg is ignored.
Value Meaning
(Null) Gregorian dates are used. Does nothing if Gregorian is value of
iCalendarType
gg Period/era string. This is used by Windows to calculate the year when an
optional calendar is selected. See iCalendarType for optional Calendars.
Time The time can be displayed in one of many formats using the letter "h" or "H" to
denote hours, the letter "m" to denote minutes, the letter "s" to denote seconds
and the letter "t" to denote the time marker. The lowercase "h" denotes the 12
hour clock and uppercase "H" denotes the 24 hour clock. The "m" must be
Chapter 2: Understanding CitectVBA Language Basics 31
lowercase to denote minutes as opposed to Months. The "s" for seconds and "t"
for the time marker string must also be lowercase.
Value Meaning Example
h Hours without leading zeros for single digit hours (12 hour clock). 1
hh Hours with leading zeros for single digit hours (12 hour clock). 01
H Hours without leading zeros for single digit hours (24 hour clock). 1
HH Hours with leading zeros for single digit hours (24 hour clock). 01
m Minutes without leading zeros for single digit minutes. 9
mm Minutes with leading zeros for single digit minutes. 09
s Seconds without leading zeros for single digit seconds. 5
ss Seconds with leading zeros for single digit seconds. 05
t One character time marker string. This will be the first letter of the values in A
the AM symbol or PM symbol boxes in Regional Options
tt Multi-character time marker string. This will be values in the AM symbol or AM
PM symbol boxes in Regional Options
See Also Date Handling
Date Constants
Date and Time Data Constraints
Date-values
A date-value in CitectVBA is a count of the number of days from December 30,
1899. December 31, 1899 has the date-value of 1, and the 1st January 1900 is 2.
December 30, 1899 has the date value of zero. Negative date-values represent
dates prior to December 30, 1899.
A date-value in CitectVBA can actually range from January 1, 0100, to December
31, 9999 inclusive, which is a integer value ranging from -657434 up to +2958465
respectively. Using values outside this range will cause errors in CitectVBA.
The pre-defined CitectVBA Year, Month, and Day functions calculate and return
the appropriate year, month or day value (as an integer) from a date-value.
Chapter 2: Understanding CitectVBA Language Basics 33
Time-values
A time-value in CitectVBA represents the fractional time of day since the
previous midnight. Unlike a date-value which is simply a count of the number
of days, the time-value is a decimal fraction of a day.
As every day invariably consists of 24 hours, or 1440 minutes, or 86,400 seconds,
the time of day can be readily determined from a time-value using simple math.
An hour has the time-value of one twenty-fourth of one day (0.0416'), one
minute has the time-value of 0.000694', and a second has the time-value of
0.000011574'0'7'. Midday has the time-value of 0.50. 1AM has the time-value of
0.0416'. 1PM has the time value of 0.5416'.
The pre-defined CitectVBA Hour function, Minute function, and Second
function calculates and returns the appropriate hour, minute or second value (as
an integer) from a time-value.
See Also Date Handling
Date Constants
Formatting Date Values
Dates in Databases Using Different Calendars
Date and Time Data Constraints
Operators
Variables can be manipulated in CitectVBA using assignment, arithmetic,
relational, and logical operators.
The assignment operator is used to assign a value to a variable or constant
(that equals this).
Arithmetic operators are used to mathematically manipulate numeric
variables and numbers (addition, subtraction, multiplication, division, etc.).
Relational Operators are used to compare the relationship between variables
(less than, greater than, not equal to, etc.).
Logical operators are used to perform digital logic operations on variables (
AND, OR, NOT, etc.).
When using multiple operators in a CitectVBA statement, an order of
precedence is required to ensure the operations occur in a consistent and
predictable manner.
The string concatenation operator is used to join strings together.
See Also Constants
Variables
Numbers
Strings
Date Handling
CitectVBA Function Reference
Assignment Operator
The CitectVBA assignment operator uses the equals character ( = ) in a
CitectVBA statement. The variable named to the left side of the assignment
operator is assigned the operand value from the right side of the assignment
operator, as shown here:
' 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
Only one variable can be assigned at any one time with the assignment operator.
There must be a space on either side of the assignment operator, or the equals
character may be confused with either the variable name or the value being
assigned, and a compile error may occur.
Chapter 2: Understanding CitectVBA Language Basics 35
Unless the variable is a variant data type, the value being assigned must be the
same data type as the variable receiving the assigned value. For instance, if you
assign a text string into a long data type variable, you'll cause an error to occur.
The variable must be previously declared before being assigned a value. The
value of a variable can be changed any number of times in a later statements, as
in the following CitectVBA example:
' 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>
' <statement>
' reassign X to store the numeric value 789
X = 789
See Also Operators
Relational Operators
CitectVBA Relational Operators are used in CitectVBA statements to compare
the relationship between operands (values positioned immediately on either
side of the Relational Operator). The boolean result is either True or False. .
Operator Function Usage
< Less than X<Y
<= Less than or equal to X <= Y
= Equals X=Y
>= Greater than or equal to X >= Y
> Greater than X>Y
<> Not equal to X <> Y
See Also Operators
Logical Operators
Logical (boolean) operators are used to perform digital logic operations on
variables. All logical operations result in either a boolean True or False. .
Operator Function Usage
Not logical negation if not X
And logical And If (X> Y) And (X < Z)
Or logical Or If (X = Y) Or (X = Z)
See Also Operators
Operator Precedence
The operator precedence in CitectVBA runs like this:.
Operator Description Order
() Parenthesis Highest
^ Exponentiation
- Unary minus
/, * division/multplication
Mod Modulo
+, -, & addition, subtraction, concatenation
=, <>, <, >,<=,>= Relational
Not Logical negation
And Logical conjunction
Or logical disjunction
Chapter 2: Understanding CitectVBA Language Basics 37
Strings
Strings can be stored in CitectVBA variables of string and variant. When using
variant strings, be aware of type coercion in CitectVBA. Strings can be compared
with each other in CitectVBA to determine whether they contain the same
characters or not. Strings can be joined together to create longer strings in
CitectVBA using the concatenation operator.
Strings can be searched in CitectVBA using the:
InStr() function, which returns the character position of the first
occurrence of a string within another;
Left() function or Right() function which return a copy of the left or right
most characters of a string respectively; and
Mid() function, which returns the copy of a substring from within another
string.
To determine the length of a string, use the CitectVBA Len() function which
returns a Long variable containing the number of characters in the string.
String characters can be converted to ASCII values using the CitectVBA Asc()
function, and ASCII values can be converted to their string characters using the
Chr() Function.
String characters can be converted to all lowercase or all uppercase using the
CitectVBA Lcase() Function or the Ucase() Function respectively.
Leading or trailing spaces can be stripped off strings in CitectVBA using the
Ltrim() function or the Rtrim() function respectively.
Strings can be created consisting of a specified number of spaces or characters
using the Space() function or the String() function respectively.
For syntax details of using string functions in CitectVBA, see String Functions.
See Also Operators
Numbers
Control Structures
38 Chapter 2: Understanding CitectVBA Language Basics
String Comparisons
CitectVBA compares ANSI values of characters when comparing strings. For
example, the character capital 'A' has the ANSI value of 65, and the character
lowercase 'a' has the ANSI value of 97. For a listing of ANSI characters values,
see ASCII/ANSI Character Code Listings.
You can use CitectVBA relational operators (less than, greater than, equal to, not
equal to, and so on) to compare string variables. All relational operators return
either true or false.
With comparisons made using relational operators, the result depends on the
option compare string-comparison option setting of the CitectVBA file.
Consider the following example:
"Citectvba" > "CitectVBA"
If the file Option string-comparison setting is Option Compare Binary (or not set
at all), the comparison returns true. CitectVBA compares the binary (ANSI)
values for each corresponding position in the string until it finds two that differ.
In this example, the lowercase letter "v" corresponds to the ANSI value 118,
while the uppercase letter "V" corresponds to the ANSI value 86. Because 118 is
greater than 86, the comparison returns true.
If the file Option string-comparison setting is Option Compare Text, "Citectvba"
> "CitectVBA" returns false, because the strings are equivalent apart from case.
The built-in CitectVBA StrComp() Function returns a variant containing a value
representing the result of the comparison of two strings. It has an optional third
argument Comp which can override the file Option string-comparison setting.
See Also Option Compare statement
Strings
String Concatenation
To concatenate strings in CitectVBA, use the ampersand ( & ) concatenation
operator between the strings. Multiple concatenations can occur in the same
CitectVBA statement.
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"
Chapter 2: Understanding CitectVBA Language Basics 39
Control Structures
CitectVBA provides conditional control functionality, which can be used to
conditionally perform CitectVBA statements or blocks of statements dependant
upon the result of the condition tested. This is known as logical decision making.
The logical decision making control structures available in CitectVBA consist of
three conditional looping or repetitive statements (Do Statement, While
Statement, and For Statement), and two conditional flow control sequence
statements (Select Case Statement, and variations of the If Statement). In
addition, CitectVBA provides one unconditional branching GoTo Statement.
Note: In the control structure syntax examples, every placeholder shown inside
arrow brackets ( <placeholder> ) should be replaced in any actual code with the
value of the item that it describes. The arrow brackets and the word they contain
should not be included in the statement, and are shown here only for your
information. Also, statements shown between square brackets ( [ ] ) are
optional. The square brackets should not be included in the statement, and are
shown here only for your information.
See Also Operators
GoTo statement
Do statement
While statement
For statement
If statement
Select case statement
End statement
Exit statement
OnError statement
Stop statement
With statement
CitectVBA Function Reference
40 Chapter 2: Understanding CitectVBA Language Basics
GoTo statement The GoTo conditional statement branches unconditionally and without return to
the label specified in the GoTo statement. The label must be located in the same
subroutine or function as the Goto statement.
<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>
In this example, CitectVBA tests the If condition, and jumps to the part of the
script that begins with the label "Label1:" if the condition was true, or jumps to
the part of the script that begins with the label "Label2:" if the condition was
false. This could be anywhere in the same subroutine or function.
See Also Control Structures
Do statement The Do...Loop conditional statement allows you to execute a block of statements
an indefinite number of times. The variations of the Do...Loop are Do While, Do
Until, Do Loop While, and Do Loop Until.
Do While|Until <condition>
<statement/s>
Loop
Do Until <condition>
<statement/s>
Loop
Do
<statement/s>
Chapter 2: Understanding CitectVBA Language Basics 41
Do
<statement/s>
Loop Until <condition>
Do While and Do Until check the condition before entering the loop, thus the
block of statements inside the loop are only executed when those conditions are
met. Do Loop While and Do Loop Until check the condition after having
executed the block of statements thereby guaranteeing that the block of
statements is executed at least once.
Any Do statement can be exited using the Exit Do statement.
See Also Control Structures
While statement The While...Wend loop conditional statement is similar to the Do While loop
statement. The condition is checked before executing the block of statements
comprising the loop.
While <condition>
<statement/s>
Wend
For statement The For...Next loop conditional statement repeats its block of statements a set
number of times as determined by the values used with the To clause.
For <CounterName> = <BeginValue> To <EndValue> [Step <StepValue>]
<statement/s>
Next
The counter variable is increased or decreased (by the value stated in the
optional Step parameter), with each reiteration of the loop. The counter default
is to increment by one if the Step parameter is omitted.
See Also Control Structures
If statement The If statement in CitectVBA tests an initial condition and then either performs
or omits to perform the statements it contains, dependant upon the logical result
of the test condition. The condition can be a comparison or an expression, and
must logically evaluate to either True or False. The If statement has both single
line and multiple line syntax structure.
The single line syntax uses the If <TestCondition> Then
<StatementToPerformIfTrue> structure, however, can only perform a single
42 Chapter 2: Understanding CitectVBA Language Basics
statement if and only if the test condition result is True. No 'End If' statement is
required:
If <Condition> Then <Statement>
If the result of the If test condition was True, the program flow continues into
and performs the statement following the Then statement, until it reaches the
end of the line.
To perform a single statement conditionally upon a False result, use the NOT
logical operator:
If NOT <Condition> Then <Statement>
To perform multiple statements, use the multiple line syntax structure which
ends with the 'End If' statement:
If <Condition> Then
' Then statement block
' perform only if true
<Statement/s>
End If
If the result of the If test condition was True, the program flow continues into the
Then statement block, and performs the statements following the Then
statement, until it reaches the End If statement.
If the result of the If test condition was False, the program flow jumps
completely over the Then statement block, which in this case exits the If
structure (without performing any statements other than the initial test
condition).
The mutiple line If structure can perform different blocks of statements
dependant upon EITHER a True OR a False result to the test condition, through
the use of the Else statement block:
If <Condition> Then
' Then statement block
' perform only if true
<Statement/s>
Else
' Else statement block
' perform only if false
<Statement/s>
End If
If the result of the If test condition was True, the program flow performs the
Then block statements, until it reaches the Else statement. It then jumps
Chapter 2: Understanding CitectVBA Language Basics 43
completely over the Else statement block and exits the If structure (without
performing any of the Else statement block statements).
If the result of the If test condition was False, the program flow jumps
completely over the Then statement block (without performing any of those
statements) to the Else statement to perform the statements in the Else statement
block until it reaches the End If statement.
Further test conditions can be placed into an If structure through the use of the
optional Else If <Condition> statement block. ElseIf statement blocks can only be
positioned within an If structure before the Else statement block.
If <Condition> Then
' Then statement block
' perform only if true
<Statement/s>
ElseIf <Condition>
' Else If statement block
' perform only if true
<Statement/s>
Else
' Else statement block
' perform only if false
<Statement/s>
End If
The ElseIf test condition is only evaluated after the initial If structure test
condition results in False.
If the result of the ElseIf test condition was True, the statements within the ElseIf
statement block are performed. The program flow then jumps completely over
the Else statement block and exits the If structure (without performing any of the
Else statement block statements).
If the result of the ElseIf test condition was False, the program flow jumps
completely over the ElseIf statement block (without performing any of those
statements) to the Else statement to perform the statements in the Else statement
block until it reaches the End If statement.
There is no apparent limit to the number of Else If statement blocks that any one
If structure can hold, however, the Select Case Statement structure handles
multiple condition result alternatives much more efficiently.
See Also Control Structures
44 Chapter 2: Understanding CitectVBA Language Basics
Select case statement The Select Case statement tests the same variable for many different conditions.
The test value provided with the initial Select Case statement is logically tested
against the Case test condition.
The Select Case structure can perform different blocks of statements dependant
upon whichever Case statement test condition (if more than one) first results as
True, through the use of the Case statement block:
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
If the result of the Case test condition was True, the program flow performs the
statements contained within that Case statement block, and will then exit the
Select Case structure (without performing any of the Else statement block
statements).
If the result of the Case test condition was False, the program flow jumps
completely over the Case statement block (without performing any of those
statements) to the Case Else statement to perform the statements in the Else
statement block until it reaches the End Select statement.
Further test conditions can be placed into a Select Case structure through the
optional use of further Case statement blocks. Case statement blocks can only be
positioned within a Select Case structure before the Case Else statement block.
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>
Chapter 2: Understanding CitectVBA Language Basics 45
Case Else
' Else statement block
' perform only if all cases false
<Statement/s>
End Select
Each Case statement block is evaluated in order until the test condition of one
results as True. The program flow performs the statements contained within that
Case statement block, and will then exit the Select Case structure (without
performing any other statements).
The statements of ONLY one Case statement block are ever performed, unless all
result in False and there is no Case Else block declared, in which case no Case
statement blocks are performed at all.
The following example may help clarify the logic testing being performed in a
Select Case structure. Lets say that we have a variable named (intDayOfWeek)
containing an integer (ranging from 1 to 7) representing the day of the week, and
we wished to display that value as a string (named strDayOfWeek) containing
the name of the day of the week, assuming in this example, that Sunday is the
first day of the week (1). The Select Case structure would look like this:
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"
46 Chapter 2: Understanding CitectVBA Language Basics
End Select
The Select Case structure tends to be easier to read, understand, and follow and
should be used in place of a complicated multi-nested If...ElseIf structure.
See Also Control Structures
End statement The End statement Ends a block of statements such as a Sub procedure or
Function.
End[{Function | If | Sub}]
Example ' 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
See Also Control Structures
Chapter 2: Understanding CitectVBA Language Basics 47
OnError statement CitectVBAs error-handling routine and specifies the line label of the error-
handling routine. The line parameter refers to a label. That label must be present
in the code or an error is generated.
On Error { GoTo line | Resume Next | GoTo 0 }
Example
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
See Also Control Structures
Stop statement Ends execution of the program. The Stop statement can be placed anywhere in
your code.
With statement The With Statement is not supported in CitectVBA. When performing a series of
commands on an object, you must explicitly refer to the name of the object with
each command.
See Also Control Structures
48 Chapter 2: Understanding CitectVBA Language Basics
Subroutines A CitectVBA subroutine starts with the SUB statement and finishes with the
END SUB statement. All other statements that lie between the SUB and END
SUB statements, will be executed by the subroutine, when called to do so.
Note: In the following subroutine syntax example:
Every placeholder shown inside arrow brackets ( <placeholder> ) should be
replaced in any actual code with the value of the item that it describes. The
arrow brackets and the word they contain should not be included in the
statement, and are shown here only for your information.
Chapter 2: Understanding CitectVBA Language Basics 49
Where:
[ Byval ] is the optional parameter for the argument;
Sub is the required subroutine statement basic keyword
<SubName>'represents the required name of the subroutine being created
<Argument/s> represents the optional argument/s of the subroutine
<statement> represents the executable CitectVBA script statement/s
End Sub is the subroutine terminating statement
The name given to the subroutine immediately follows the SUB keyword, and is
used to identify the subroutine to CitectVBA. This name is referred to when the
subroutine is called upon (called) to be executed (perform the statements it
contains) by some other procedure in CitectVBA.
Subroutine names can contain the letters 'A' to 'Z' and 'a' to 'z', the underscore '_'
and digits '0' to '9'. The subroutine name must begin with a letter, be no longer
than 40 characters, cannot contain the space character, and cannot be a reserved
word. Subroutine names (once declared), become a keyword in CitectVBA. Like
most keywords in CitectVBA, these names are not case sensitive.
The subroutine name always ends with a pair of parentheses ( ) which may or
may not contain one or more arguments required by (necessary for use in) the
subroutine . Multiple arguments if used, are separated by commas ( , ). See the
section titled 'Arguments in CitectVBA' for more details and argument syntax.
All the lines located between the SUB and the END SUB statements, contain the
statements that will be executed when the subroutine is called in CitectVBA.
These statements will be executed one at a time in logical order from top to
bottom within the subroutine.
See Also Subroutines and Functions
Functions
Arguments
50 Chapter 2: Understanding CitectVBA Language Basics
Functions A CitectVBA function starts with the FUNCTION statement and finishes with
the END FUNCTION statement. All other statements that lie between the
FUNCTION and END FUNCTION statements, will be executed by the function,
when called to do so.
Note: In the following function syntax example:
Every placeholder shown inside arrow brackets ( <placeholder> ) should be
replaced in any actual code with the value of the item that it describes. The
arrow brackets and the word they contain should not be included in the
statement, and are shown here only for your information.
Statements shown between square brackets ( [ ] ) are optional. The square
brackets should not be included in the statement, and are shown here only
for your information.
A typical CitectVBA function is structured like in the following example:
Function <FunctionName> ( [ Byval ] [ <Argument/s> ] ) [ As
<ReturnDataType> ]
<statement>
<statement>
<statement>
[ <FunctionName> = <value> ]
End Function
where:
Function' is the required function statement basic keyword
[ Byval ] is the optional parameter for the argument;
<FunctionName> represents the required name of the function being created
( <Argument/s> ) represents the optional argument/s of the function
<ReturnDataType> represents the optional return data type of the function
<statement> represents the executable CitectVBA script statement/s
= <value> represents the optional assignment of the return value for the
function
'End Function' is the function terminating statement
The name given to the function, immediately follows the FUNCTION keyword,
and is used to identify the function to CitectVBA. This name is referred to when
the function is called upon (called) to be executed (perform the statements it
contains) by some other procedure in CitectVBA.
Function names can contain the letters 'A' to 'Z' and 'a' to 'z', the underscore '_'
and digits '0' to '9'. The function name must begin with a letter, be no longer than
Chapter 2: Understanding CitectVBA Language Basics 51
40 characters, cannot contain the space character, and cannot be a reserved word.
Function names (once declared), become a keyword in CitectVBA. Like most
keywords in CitectVBA, these names are not case sensitive.
The function name always ends with a pair of parentheses ( ) which may or may
not contain one or more arguments required by (necessary for use in) the
function. Multiple arguments if used, are separated by commas ( , ). See the
section titled 'Arguments in CitectVBA' for more details and argument syntax.
All the lines located between the FUNCTION and the END FUNCTION
statements, contain the statements that will be executed when the function is
called in CitectVBA. These statements will be executed one at a time in logical
order from top to bottom within the function.
The return value of the function is optionally assigned within the function in a
statement using the function name. This value is often used within the calling
procedure to determine the status of the function. Commonly, this value may be
a Boolean True or False to indicate the successful completion or not of the
function.
See Also Subroutines and Functions
Arguments
Subroutines
Accessing Functions in DLLs
Arguments Arguments are used in CitectVBA to pass values into subroutines and functions
when they are being called. Arguments are positioned between parentheses '( )'
immediately after the subroutine or function name in the subroutine or function
declaration. If no arguments are required for the subroutine or function, the
parentheses must be included and left empty in the declaration.
Arguments are optional in the sense that subroutines and functions do not
require them. However, if arguments are to be used in a subroutine or function,
the arguments must first be declared with the subroutine or function
declaration, before they can be used. If declared, they must be used whenever
the subroutine or function is called.
CitectVBA does NOT support named arguments so all arguments must be used
in declaration order. If omitted, strings default to an empty string (""), and
numeric values default to zero (0). Boolean values in CitectVBA are represented
with -1 for TRUE, and 0 for FALSE.
Multiple arguments must be separated by a comma ( , ) placed between the
arguments. The number of arguments that can be used in any single subroutine
or function is not stated, (but likely limited to something like 255). If you are
declaring a subroutine or function with that many arguments, you should
probably split your subroutine or function into smaller separate logical routines
with less arguments for each routine. If an argument is omitted, its place must be
declared by the use of a comma in the call.
52 Chapter 2: Understanding CitectVBA Language Basics
Functions
Declare statement The Declare statement consists of the required Declare keyword, followed by the
structure required Function statement, the required Lib statement, the optional Alias
Chapter 2: Understanding CitectVBA Language Basics 55
statement, the optional Argument statement(s) contained within braces, and the
optional return data type statement.
Note: The use of the OPTIONAL components of the Declare statement syntax
indicates that they may not be required in all DLL functions. It is not up to you
whether you can optionally use them or not. If included in a DLL function, they
MUST be used when declaring that function to CitectVBA.
The Declare statement in CitectVBA details the name, file location, arguments,
intrinsic constants, and type definitions that the DLL function requires. Here's
an example of the Declare statement for the Windows API GetTempPathA
function, which returns the path to the Windows system temporary folder:
Declare Function GetTempPathA Lib "kernel32" _
(Byval nBufferLength As Long, _
Byval lpBuffer As String) As Long
The Declare keyword indicates to CitectVBA that you intend to call a function
belonging to an external DLL. The Declare keyword must be used first in the
declaration statement.
Alias statement must be positioned within the Declare statement between the
Lib statement and the Argument statement.
Here's an example of the Declare statement for the Windows API
GetTempPathA function as used above, however, this time using the optional
Alias statement:
Declare Function GetWinTempPath Lib "kernel32" _
(Byval nBufferLength As Long, _Alias "GetTempPathA" _
Byval lpBuffer As String) As Long
In this example, the name of the API function in the DLL is GetTempPathA, and
the name by which you would call this function from CitectVBA is
GetWinTempPath. Note that the actual name of the DLL function appears
contained within string double quotes positioned after the Alias keyword. This
instructs CitectVBA to use the alias function name when calling the DLL.
Because an alias allows you to name a declared DLL function anything you want
in CitectVBA, you can make the function name conform to your own naming
standards.
Note: DLL functions are case sensitive; CitectVBA function names are not. When
declaring DLL functions in CitectVBA, be careful to accurately remain case
sensistive in the declaration.
See Also Functions
Passing variables Byref and Byval
Passing Arguments to DLL Functions from CitectVBA
DLLs and APIs
Passing variables Byref Passing an argument by reference (using the Byref parameter) passes a pointer
and Byval to the memory location of that argument. A pointer is just a memory address
that indicates where the value is stored. If the procedure modifies that
argument's value, it modifies the source of that argument, so when execution
returns to the calling procedure, the source contains the modified value.
Passing an argument to a function by value (using the Byval parameter), on the
other hand, passes a copy of the value as the argument. This prevents that
function from modifying the source of the argument. When execution returns to
the calling procedure, the source contains the same value it did before the
function was called.
The Byref parameter is the default in CitectVBA and does not need to be used
explicitly within CitectVBA. Byref gives other subroutines and functions
permission to make changes to the source of the values that are passed in Byref.
The keyword Byval denies this permission so the argument source cannot be
altered.
Chapter 2: Understanding CitectVBA Language Basics 57
There are two possible methods for indicating to CitectVBA that you wish to
pass an argument by value :
When declaring the argument in the subroutine or function declaration
statement, by using the Byval keyword placed immediately before the
argument name. This ensures that the subroutine or function will always use
a copy of the argument passed in and not modify the source. For example,
the following function TestPassArg has declared its first argument intVal as
being requested Byval.
Function TestPassArg(Byval intVal As Integer, varVal, strVal as
String)
When passing an argument to a subroutine or function, by enclosing the
individual argument within parentheses. Only the value of the argument,
and not its address in memory, is passed to the subroutine or function, once
again ensuring that the source of the argument is not modified. For example,
only the variable var3 is passed by value to the subroutine TestPassArg
(because only that argument is enclosed within parentheses in the
subroutine call).
TestPassArg var1, var2, (var3)
In the next example, the parameter iVar is passed by value to the function
TestFunction. Since arguments passed to functions must be enclosed in
parentheses, an extra pair is used to force the argument to be passed by
value.
TestFunction((iVar))
Note: CitectSCADA does not support passing by reference, so CitectSCADA
tag values MUST be declared by value when passed as arguments to a
CitectVBA procedure from within a CitectSCADA command or expression
field. This is best done by declaring the variable, assigning it the tag value,
then passing the variable by value. (See the Example below.)
ExampleExample Suppose you had a variable tag of integer type named "iTag1" and you need to
pass it to a function. From within a CitectVBA script, or CitectSCADA command
or expression field, you would use the following code example to pass the
variable tag value to a function named TagArgumentTest:
CiVBA
Dim iVar1 as Integer
iVar1 = iTag1
TagArgumentTest(iVar1)
Note: Cicode does not support passing by reference, so CitectVBA variables
passed to Cicode functions using the CicodeCallOpen function must be
enclosed in brackets to force the passing of those variables by value.
58 Chapter 2: Understanding CitectVBA Language Basics
OLE Services
OLE (Object Linking and Embedding) services is the term used to generally
describe the integrated use of separate software components (applications)
working together to provide custom software solutions based upon the
Microsoft Component Object Model (COM) architecture.
When considering the use of OLE services, you should be aware that there are
different uses of OLE which have developed over the years and which may be
confused with one another. Examples of different OLE services include: object
linking, object embedding, visual editing, drag-and-drop, ActiveX Controls,
OLE Automation, OLE DB, OLE Messaging, and OLE Networking services. See
OLE terminology.
CitectSCADA supports linked and embedded OLE objects in its graphics pages
with the use of ActiveX Controls. See Accessing ActiveX Objects with
CitectVBA.
CitectSCADA can use CitectVBA to perform as an OLE Automation controller.
See OLE automation objects. CitectSCADA can also exchange data with other
applications using other data transfer technologies.
OLE terminology OLE superceded the Dynamic Data Exchange protocol. Network DDE was
introduced to afford the same data transfer facility between Windows
applications connected across the same network. CitectSCADA supports both
DDE and Network DDE connectivity.
OLE Automation
'OLE Automation' was developed to permit the (remote) control of other
applications on the same computer. Applications which expose their
60 Chapter 2: Understanding CitectVBA Language Basics
OLE automation objects CitectVBA supports the referencing and control of OLE Automation objects of
external applications, permitting you to use the properties, methods and events
of those objects from within CitectSCADA.
To access an OLE Automation object using CitectVBA, you must first declare an
object variable in your CitectVBA code, then assign an OLE Automation
reference to the variable. See Declaration of OLE Automation objects in
CitectVBA, and Assigning references to OLE Automation objects in CitectVBA.
Objects declared in a CitectVBA Sub or Function procedure are local to that
procedure, and their lifetime ends along with the end of the procedure. An
object declared outside a procedure has modular scope to all procedures within
the same CitectVBA file module and lasts for the lifetime of the variable that
retains the reference to the object.
All object references must be deleted when they are no longer required, to
release the memory they were using.
When considering the use of OLE Automation, you should be aware that there
are different uses of OLE which have developed over the years and which may
be confused with one another.
See Also OLE Services
Declaration of OLE CitectVBA objects can only be declared and referenced within CitectVBA file
automation objects modules. CitectVBA modular objects have modular scope and cannot be
referenced (accessed and used) from outside their CitectVBA module (file).
Note: CitectVBA objects cannot be used directly in CitectSCADA command or
expression fields.
Chapter 2: Understanding CitectVBA Language Basics 61
Assigning references to An OLE Automation object MUST be defined before it can be used. Once
OLE automation objects defined (see Declaration of OLE Automation objects in CitectVBA), you assign
an OLE Automation reference to the object variable in CitectVBA using the
CitectVBA CreateObject function within a CitectVBA Set statement in the
following syntax:
Set <objVarName> = CreateObject(<objClassName>)
where:
Set is the required reference assignment statement keyword
<objVarName> represents the required name of the variable receiving the
reference
62 Chapter 2: Understanding CitectVBA Language Basics
CreateObject() function creates the object of the class type specified in the
argument
<objClassName> represents the required name of the class providing the
object
The object class name passed as the argument to the CreatObject function
usually consists of the fully qualified class name of the object being created, for
example "Word.Application" or "Excel.Application".
Using OLE automation The trick with successfully using OLE Automation is determining what you can
objects and can't do with it. In theory, you can do anything the OLE Automation server
application can do. However, in practice, not every OLE Automation server
application exposes all of its functionality through its OLE Automation
interface.
You have to be able to use the native programming language of the OLE
Automation server application in your code. You also need to know about the
Chapter 2: Understanding CitectVBA Language Basics 63
Accessing the object During the development stage of your project, to access the object model of any
model of OLE OLE Automation server applications, you must have a copy of the appropriate
application program installed on the computer you are developing the OLE
automation server
Automation controller with.
applications
Equally, during CitectSCADA runtime, there must be a copy of the appropriate
application program installed on the computer you are running the OLE
Automation controller from. If, for example, you were calling the code which
creates the object from say a button on a graphics page on a CitectSCADA Client
machine, the appropriate application program must be installed on every Client
machine with access to that graphics page, for the code to work (if called) on that
Client machine.
64 Chapter 2: Understanding CitectVBA Language Basics
All of the Microsoft Office suite of products support the VBA language in some
manner, and export an OLE Automation object type library which you can view
and use. See How to view an OLE Automation object type library from a
Microsoft Office product.
Also, the VB programming IDE within Visual Studio can be referenced to load
the appropriate type library as required. See How to view an OLE Automation
object type library in VB.
Both these suites provide an object browser which you can use to explore the
object models. You use the structure of the object model to access, manipulate
and control the OLE Automation object using CitectVBA. See Understanding
object models in OLE Automation.
See Also OLE automation objects
Understanding object Objects are the fundamental building blocks of OLE Automation, and object
models in OLE models are a roadmap to the object structure. OLE Automation using CitectVBA
involves creating and modifying the objects provided by other applications
automation
(external to the CitectSCADA application). For instance, every element of
Microsoft Word ( documents, tables, paragraphs, bookmarks, fields and so on)
can be represented by an object in CitectVBA using OLE automation with the
Word object model.
What is a property?
A property is an attribute of an object or an aspect of its behavior. For example,
properties of a Word document include its name, its content, and its save status,
as well as whether change tracking is turned on. To change the characteristics of
any referenced object, you change the values of its properties.
To set the value of a property, follow the reference to an object with a period, the
property name, an equal sign, and the new property value. The following
example turns on change tracking in the Word document named "MyDoc.doc."
objWordApp.Documents("MyDoc.doc").TrackRevisions = True
In this example, Documents refers to the collection of open documents, and the
name "MyDoc.doc" identifies a single document in the collection. The
TrackRevisions property is set for that single document.
Chapter 2: Understanding CitectVBA Language Basics 65
You can also return information about an object by returning the value of one of
its properties. The following example returns the name of the active Word
document.
docName = objWordApp.ActiveDocument.Name
In this example, ActiveDocument refers to the document in the active window in
Word. The name of that document is assigned to the variable "docName".
Note: Some properties cannot be set. The Help topic for each property indicates
whether you can set that property (read-write), only read the property (read-
only), or only write the property (write-only). Also the Object Browser in the
Visual Basic Editor displays the read-write status at the bottom of the browser
window when the property is selected.
What is a method?
A method is an action that an object can perform. For example, just as a Word
document can be printed, the Document object has a PrintOut method. Methods
often have arguments that qualify how the action is performed. The following
example prints the first three pages of the active Word document.
objWordApp.ActiveDocument.PrintOut From:=1, To:=3
In most cases, methods are actions and properties are qualities. Using a method
causes something to happen to an object, while using a property returns
information about the object or it causes a quality about the object to change.
Returning an object
Most objects return a single object from the collection. For example, the
Documents collection contains the currently open Word documents. You use the
Documents property of the Application object (the object at the top of the Word
object hierarchy) to return the Documents collection.
After you've accessed the collection, you can return a single object by using an
index value in parentheses (this is similar to how you work with VBA arrays).
The index value can be either a number or a name.
The following example uses the Documents property to access the Document
collection. The index number is used to return the first document in the
Documents collection. The Close method is then applied to the Document object
to close the first document in the Documents collection.
objWordApp.Documents(1).Close
The following example uses a name (specified as a string) to identify a
Document object within the Documents collection.
objWordApp.Documents("Sales.doc").Close
Collection objects often have methods and properties which you can use to
modify the entire collection of objects. The Documents object has a Save method
66 Chapter 2: Understanding CitectVBA Language Basics
that saves all the documents in the collection. The following example saves the
open documents by applying the Save method.
objWordApp.Documents.Save
The Document object also has a Save method available for saving a single
document. The following example saves the document named Report.doc.
objWordApp.Documents("Report.doc").Save
To return an object that is further down in the Word object hierarchy, you must
"drill down" to it by using properties and methods to return objects.
To see how this is done, in Word, open the Visual Basic Editor and click Object
Browser on the View menu. Click Application in the Classes list on the left. Then
click ActiveDocument from the list of members on the right. The text at bottom
of the Object Browser indicates that ActiveDocument is a read-only property
that returns a Document object. Click Document at the bottom of the Object
Browser; the Document object is automatically selected in the Classes list, and
the Members list displays the members of the Document object. Scroll through
the list of members until you find Close. Click the Close method. The text at the
bottom of the Object Browser window shows the syntax for the method. For
more information about the method, press F1 or click the Help button to jump to
the Close method Help topic.
Given this information, you can write the following instruction to close the
active document.
objWordApp.ActiveDocument.Close SaveChanges:=wdSaveChanges
The following example maximizes the active document window.
objWordApp.ActiveDocument.ActiveWindow.WindowState =
wdWindowStateMaximize
The ActiveWindow property returns a Window object that represents the active
window. The WindowState property is set to the maximize constant
(wdWindowStateMaximize).
The following example creates a new document and displays the Save As dialog
box so that a name can be provided for the document.
objWordApp.Documents.Add.Save
The Documents property returns the Documents collection. The Add method
creates a new document and returns a Document object. The Save method is
then applied to the Document object.
As you can see, you use methods or properties to drill down to an object. That is,
you return an object by applying a method or property to an object above it in
the object hierarchy. After you return the object you want, you can apply the
methods and control the properties of that object.
See Also OLE Services
Chapter 2: Understanding CitectVBA Language Basics 67
Using the Microsoft You should use the associated online help documentation that came with the
Word object model object application to obtain details of the object model.
The help is quite easy to use. Each of the classes and collections can be clicked to
jump to its page.
In CitectVBA, you must use the full Application object qualifier when
referencing the properties and methods of the object. For example, you must use
the full syntax "Application.ActiveDocument.PrintOut", instead of
"ActiveDocument.PrintOut".
See Also OLE Services
OLE automation All commands in Word are directed to the active document, which may be
example using the changed in code. It is recommended to use named arguments, as the argument
sequences are recorded incorrectly in some documentation, including the type
Microsoft Word object
library and what the recorder writes to macros.
Sub runWord()
' demonstrating the use of OLE Automation
' to manipulate Word
End Sub
See Also OLE automation example using the Microsoft Word object
Using OLE automation objects
68 Chapter 2: Understanding CitectVBA Language Basics
Using the Microsoft You should use the associated online help documentation that came with the
Excel object model object application to obtain details of the object model.
Deleting OLE All object references must be deleted when they are no longer required, to
automation objects release the memory they were using.
You delete an OLE Automation reference to the object variable in CitectVBA
using the CitectVBA Nothing keyword within a CitectVBA Set statement in the
following syntax:
Set <objVarName> = Nothing
where:
Set is the required reference assignment/release statement keyword.
You can integrate CitectVBA into your CitectSCADA project in two ways:
Use CitectVBA code script directly in your Command or Expression fields
within CitectSCADA.
Store user-defined CitectVBA script in a separate CitectVBA file.
In either case, all procedures within a CitectVBA script can access (read and
write) any CitectSCADA variable tag in the same way as Cicode can access
CitectSCADA tags.
See Also Accessing Cicode Tags with CitectVBA
In this example, the reference name for the Temperature meter object on the
ActiveX page in the Example project, would be referred to in CitectVBA as
ActiveX_AN125.
All object properties can be accessed and manipulated using CitectVBA in the
same way that object properties can be manipulated using Cicode.
See Also Accessing Cicode Tags with CitectVBA
Using CitectVBA in CitectSCADA Command or Expression fields
you can call the VbCallReturn function to get the return value of the CitectVBA
function called.
The Cicode VbCallOpen() function is used to initiate a call to the CitectVBA
function or subroutine, and returns a handle to the open function.
<ReturnValue> = VbCallOpen(<FunctName>, <ArgList>)
where
<ReturnValue> represents the handle to the opened function.
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
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"
Chapter 3: Integrating CitectVBA with CitectSCADA 79
End Select
End If
' display return comment for your information
MsgBox strReply
' assign return value for this function
TestCicode = intRet
End Function
See Also Calling CitectVBA from Cicode
Chapter 4: Using the CitectVBA Test Project
You can use the CitectVBA test project to help you learn the basics programming
with CitectVBA. Before you can use the project, you must:
Create the test project
Open the test project
Set up test project communications
Set up the test project computer
Add a variable tag to the project
Set up a graphics page to the project
Note: CitectSCADA stores the most recently opened project name in the
Citect.ini file, so that the next time CitectSCADA is started, that project
opens automatically ready for further editing.
See Also Setting up Test Project Communications
Chapter 4: Using the CitectVBA Test Project 83
7 From the Project Name list, select CitectVBA Test and click Next.
8 Click Next and then Finish to complete the CitectVBA project
communications setup.
See Also Adding a Variable Tag
Array Functions
CitectVBA array functions are provided to allow you to declare, resize, initialize,
populate, and erase arrays and their elements.
The array functions predefined in CitectVBA are:
Dim Allocates storage for, and declares the data type of, variables and arrays in a module.
Erase Reinitializes the elements of a fixed array.
Lbound Returns the smallest available subscript for the dimension of the indicated array.
Option Base Declares the default lower bound for array subscripts.
ReDim Used to size or resize a dynamic array that has already been declared using the Dim
statement with empty parentheses.
Ubound Returns the value of the largest usable subscript for the specified dimension of an array.
Conditional Statements
Do Loop Allows you to execute a block of statements an indefinite number of times.
End Function Ends a block of statements such as a Sub procedure or function.
Exit Exits a loop or procedure.
For Repeats its block of statements a set number of times as determined by the values used
with the To clause.
Goto Branches unconditionally and without return to the label specified in the GoTo statement.
If Tests an initial condition and then either performs or omits to perform the statements it
contains, dependant upon the logical result of the test condition.
OnError CitectVBAs error-handling routine and specifies the line label of the error-handling routine.
Select Tests the same variable for many different conditions.
Stop Ends execution of the program.
While…Wend Similar to the Do While loop statement.
With Not supported in CitectVBA.
Conversion Functions
CitectVBA conversion functions are provided to assist with data manipulation
and calculation in your formulas. Conversion functions can be used in
CitectVBA statements, and will (like all other functions), return a value to the
caller.
88 Chapter 5: Function and Statement Categories
ASCII character code Citect uses the following character code conversion funnctions:
conversion Asc Returns the numeric ASCII value of a string.
Chr Returns the string ASCII value of a number.
Number and string Citect uses the following functions for converting and formatting numbers and
conversion strings:
Format Formats a string, number, or variant to the format expression (fmt ).
Hex Converts a value to a string representing the hex value.
Oct Converts a value to a string representing the octal value.
Str Converts a value to a string containing numeric characters.
Val Converts a string containing numeric characters to a numeric value.
Declarations
CitectVBA declarations allow you to manipulate and control variables and
constants. The Declaration functions and statements predefined in CitectVBA
are:
CreateObject function Creates an OLE Automation object reference
Const statement Assigns a symbolic name to a constant value.
Declare statement Declare references to external procedures in a DLL.
Dim statement Allocates storage for, and declares the data type of, variables and arrays.
IsDate Determines if a Variant parameter can be converted to a date.
IsEmpty Determines if a Variant parameter has been initialized.
IsNull Determines if a Variant contains NULL.
IsNumeric Determines if a Variant can be converted to a numeric data type.
Nothing keyword Releases an OLE Automation object reference from a variable of object
type.
Chapter 5: Function and Statement Categories 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.
ReDim statement Used to size or resize a dynamic array.
Set statement Assigns an OLE Automation object reference to a variable of object type.
Static statement Allocates storage for, and declares the data type of, variables and arrays.
VarType Indicates the data type used within the Variant.
Math/Trigonometry Functions
CitectVBA math functions are provided to assist with number manipulation and
calculation in your formulas. Mathematical functions can be used in CitectVBA
Chapter 5: Function and Statement Categories 91
statements, and will (like all other functions), return a value to the caller.
Trigonometry uses angles and ratios, axes, degrees, Pi, radians and angular
conversions. CitectVBA supports the use of Decimal numbers by default, as well
as Hexadecimal and Octal numbers. See Numbers.
When using numbers in CitectVBA, you must consider the data type of the
variables that hold and store the numbers, as well as the behaviour of CitectVBA
when dealing with numbers. See Numeric Data Types.
Miscellaneous Functions
The miscellaneous functions predefined in CitectVBA are:
Beep statement Sounds a tone through the computer's speaker.
Randomize statement Initializes the random number generator.
Rem statement Used to include explanatory remarks in a program.
SendKeys statement Sends keystrokes to the active window as if entered at the keyboard.
92 Chapter 5: Function and Statement Categories
Procedural Statements
CitectVBA procedural function statements are provided to assist with
conditional code execution and program flow:
Call statement Transfers control to a Sub procedure, function procedure, or dynamic-link
library (DLL) procedure.
Function statement Declares and defines a procedure that can receive arguments and return a
value of a specified data type.
End Function statement Ends a program or a block of statements within a function.
Sub statement Declares and defines a Sub procedures name, parameters and code.
End Sub statement Ends a program or a block of statements within a subroutine.
CicodeCallOpen function Calls a Cicode function from CitectVBA.
CicodeCallReturn function Obtains the return value of the most recently completed Cicode function
opened with the CitectVBA CicodeCallOpen function.
String Functions
CitectVBA strings functions are provided to create, edit and implement strings
within CitectVBA code. The strings functions predefined in CitectVBA are:
Asc Returns a numeric value that is the ASCII code for the first character in a
string.
Chr Converts an ASCII number to a one character string.
InStr Returns the character position of the first occurrence of string2 within
string1.
LCase Returns a copy of string in which all characters have been converted to
lowercase.
Left, Left$ Returns the left most characters of a string parameter.
Len Returns the number of characters in a string.
LTrim Strips any leading spaces from a string variable.
Mid Returns a substring within a string.
Option Compare Determines the default string comparison method.
Right Returns the right most characters of a string parameter.
RTrim Strips any trailing spaces from a string variable.
Space Adds a specified number of spaces in a print statement.
StrComp Returns a variant that is the result of the comparison of two strings.
String Create a string that consists of one character repeated a specific number of
times.
Chapter 5: Function and Statement Categories 93
Trim Strips any leading and trailing spaces from Str variable.
UCase Returns a copy of string in which all characters have been converted to
uppercase.
Chapter 6: CitectVBA Function Reference
Abs
Description Calculates the absolute (positive) value of a number. The absolute value of a
number is the number without its sign. Abs does not round the number, and
ignores the fractional value of the number.
Syntax Abs(Num)
Num . . . . . . Number: The argument 'Num ' must contain an Integer or
expression representing a valid numeric value.
Return Value Returns the Absolute value of the number (Num) provided in the argument.
The data type of the return value is the same as that of the number argument.
However, if the number argument is a Variant of VarType (String) and can be
converted to a number, the return value will be a Variant of VarType (Double).
If the numeric expression results in a Null, Abs returns a Null.
Asc
Description Converts a text string character to its numeric ASCII code value. The Asc
function expects the argument (Str ) to be a valid string expression. If Str
contains no characters, a run-time error occurs. The Asc function performs the
opposite of the Chr function, which converts a number into its string character
ASCII code value.
Syntax Asc(Str)
Str . . .String: The argument 'Str ' must be a string or expression that can
represent a valid text value.
96 Chapter 6: CitectVBA Function Reference
Return Value Returns the numeric ASCII code value of the first character in (Str ) provided in
the argument.
Atn
Syntax Atn(Num)
Num . . . . . . Number: The argument 'Num ' must contain an Integer or
expression representing a valid numeric value.
Return Value Returns the Arctangent value of the angle (Num) provided in the argument.
Beep
Description The Beep statement sounds a tone through the computer's speaker. The
frequency and duration of the beep depends on hardware, which may vary
among computers.
Syntax Beep
Call
Description The Call Statement transfers control to a Sub procedure, Function procedure, or
dynamic-link library (DLL) procedure.
The required ProcedureName is the name of the function or subroutine to call.The
optional Parameters is the list of arguments to pass to the called function or
subroutine.
You are never required to use the Call statement when calling an CitectVBA
subroutine or a DLL function. Parentheses must be used in the argument list if
the Call statement is being used.
CDate
Syntax CDate(Date)
Date . . . . . . . Date: The argument 'Date ' must be a string or expression that can
represent a date value. This includes any combination of date
literals, numbers that look like dates, strings that look like dates,
and dates from functions.
Return Value Returns the value of the expression (Date ) provided in the argument as a variant
with a vartype of 7 (date data type).
CDbl
Syntax CDbl(Exp)
Exp . . . . . . . Expression: The argument 'Exp ' will depend upon which data type
is expected in the function. If a string is expected, Exp may be a
valid string or Variant containing a value recognizable as a string. If
a number is expected, Exp may be a valid number or Variant
containing a value recognizable as a number.
Return Value Returns the value of the expression (Exp) provided in the argument as a double
data type.
ChDir
Description ChDir statement changes the system environment current directory on the
specified drive.
The parameter Path must be a string or expression that can represent a valid
DOS file structure path value. The parameter Dir must be a string or expression
that can represent a valid DOS file structure directory name. The Path and Dir
parameters together, must be limited to less than 128 characters. The Path drive
letter is optional, unless the directory is on another drive. The required Dir
parameter must be a valid directory name.
Note: The file system keeps track of the current drive, and the current directory
of every drive. Use the CurDir statement to determine the current directory. The
current drive letter can be extracted from the Left character returned in the
CurDir statement.
The ChDir statement changes the current directory but not the current drive. To
change the current drive, use the ChDrive statement.
ChDrive
Description Changes the system environment current drive to the specified drive.
The parameter Drv must be a string or expression that can represent a valid DOS
file structure drive letter. The Drv may be local to the computer, or mapped from
anywhere on the network connected to the computer. If Drv contains more than
one letter, only the first character is used.
Note: The file system keeps track of the current drive, and the current directory
of every drive. Use the CurDir statement to determine the current directory. The
current drive letter can be extracted from the Left character returned in the
CurDir statement.
The ChDrive statement changes the current drive but not the current directory
on any drive. To change the current directory, use the ChDir statement.
Chr
Description Converts a number into its string character ASCII code value.
The Chr function expects the argument (Num ) to be a valid numeric integer
(whole positive number within the range 0 to 255 inclusive). If Chr contains no
number, a run-time error occurs.
Note: Values 8, 9, 10, and 13 convert to backspace, tab, linefeed, and carriage
return characters respectively.
The Chr function performs the opposite of the Asc function, which converts a
text string character to it's numeric ASCII code value.
Syntax Chr(Num)
Num . . . . . . Number: The argument 'Num ' must contain an Integer or
expression representing a valid numeric value.
Return Value Returns a single character string representing the ASCII character code value of
the number (Num) provided in the argument.
CicodeCallOpen
Description The Cicode CallOpen function is used to call a Cicode function from CitectVBA.
It is used to initiate and execute a call to the Cicode function and returns an
integer value representing the success or failure of this CitectVBA function
making the call.
Note: This CitectVBA function does not return the actual return-value of the
Cicode function being called. You can obtain that return value by using the
associated CicodeCallReturn function.
The CicodeCallOpen function should be used in its own separate line of
CitectVBA code and must not be nested with the CicodeCallReturn function.
For details, see Calling Cicode from CitectVBA.
102 Chapter 6: CitectVBA Function Reference
Return Value CicodeCallOpen returns a integer data type containing a value in the range of 0
to 3:
0 if CicodeCallOpen function was successful
1 for CicodeCallOpen function failure
2 for specified Cicode function not found
3 for incorrect number of arguments for specified Cicode function passed in
<ArgList>.
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"
104 Chapter 6: CitectVBA Function Reference
End Select
End If
' display return comment for your information
MsgBox strReply
' assign return value for this function
TestCicode = intRet
End Function
CicodeCallReturn
Description The CicodeCallReturn function is used to obtain the return value of the most
recently completed Cicode function opened and run with the CitectVBA
CicodeCallOpen function.
No arguments are passed to the CicodeCallReturn function, as it will always
return the result of the most recent return-value for the Cicode function called
by the CitectVBA CicodeCallOpen function.
The CicodeCallReturn function should be used in its own separate line of
CitectVBA code and must not be nested with the CicodeCallOpen function. For
details, see Calling Cicode from CitectVBA.
'
' 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"
106 Chapter 6: CitectVBA Function Reference
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
End Function
CInt
Syntax CInt(Exp)
Exp . . . . . . . Expression: The argument 'Exp ' will depend upon which data type
is expected in the function. If a string is expected, Exp may be a
valid string or Variant containing a value recognizable as a string. If
a number is expected, Exp may be a valid number or Variant
containing a value recognizable as a number.
Return Value Returns the value of the expression (Exp) provided in the argument as an integer
data type.
CLng
Syntax CLng(Exp)
Exp . . . . . . . Expression: The argument 'Exp ' will depend upon which data type
is expected in the function. If a string is expected, Exp may be a
valid string or Variant containing a value recognizable as a string.
If a number is expected, Exp may be a valid number or Variant
containing a value recognizable as a number.
Return Value Returns the value of the expression (Exp) provided in the argument as a long
data type.
Close
Description Closes the file/s previously opened with the Open statement.
The optional FileNumList parameter can contain one or more valid file associated
reference numbers using the following syntax:
[[#]FileNum] [, [#]FileNum] ...
where Filenum is any valid number associated with an open file.
If the Close statement is used without any arguments it closes all open files.
When the Close statement is executed, the association of a file with its file
number ends.
Const
Description Assigns a symbolic name to a constant value using the following syntax:
Const VarName [As DataType] = Expression
A constant must be defined before it is used. Unlike variables, constants are
assigned values when initialized and retain that same value during the life of the
constant.
Constant statements can only be declared and assigned using simple
expressions. Constants can NOT be assigned values from variables, user-defined
functions, intrinsic CitectVBA functions (such as Chr), or from any expression
that involves an operator.
Constants declared in a Sub or Function procedure are local to that procedure. A
constant declared outside a procedure has modular scope to all procedures
within the same CitectVBA file module. See Scope of CitectVBA.
Constants can be used anywhere in your CitectVBA code where you could use a
CitectVBA expression.
If you use Const outside a procedure its scope becomes global.
A type declaration character may also be used. However if none is used,
CitectVBA will automatically assign one of the following data types to the
constant: long (if it is a long or integer); Double (if a decimal place is present); or
String ( if it is a string).
Cos
Syntax Cos(Rad)
Rad . . . . . . . Radians: The argument 'Rad ' must be expressed in radians, and
must be a valid numeric value.
110 Chapter 6: CitectVBA Function Reference
Return Value Returns the Cosine value of the angle (Rad) provided in the argument.
The result lies in the range - 1 to +1.
Cos will return a double.
CreateObject
Description Creates a new OLE Automation object and assigns a reference to the object.
CSng
Syntax CSng(Exp)
Exp . . . . . . . Expression: The argument 'Exp ' will depend upon which data type
is expected in the function. If a string is expected, Exp may be a
valid string or Variant containing a value recognizable as a string.
If a number is expected, Exp may be a valid number or Variant
containing a value recognizable as a number.
Return Value Returns the value of the expression (Exp) provided in the argument as a single
data type.
CStr
Syntax CStr(Exp)
Exp . . . . . . . Expression: The argument 'Exp ' will depend upon which data type
is expected in the function. If a string is expected, Exp may be a
valid string or Variant containing a value recognizable as a string.
If a number is expected, Exp may be a valid number or Variant
containing a value recognizable as a number.
Return Value Returns the value of the expression (Exp) provided in the argument as a string
data type.
CurDir, CurDir$
Description Both CurDir and CurDir$ functions return the current system environment path
for the specified drive (Drv ).
The parameter Drv must be a string or expression that can represent a valid DOS
file structure drive letter. The Drv may be local to the computer, or mapped from
anywhere on the network connected to the computer. If Drv contains more than
one letter, only the first character is used.
Note: The file system keeps track of the current drive, and the current directory
of every drive. Use the CurDir statement to determine the current directory. The
current drive letter can be extracted from the Left character returned in the
CurDir statement.
If no Drv is specified or if Drv is a zero-length string (" "), CurDir functions
return the system environment path for the current drive.
Syntax CurDir(Drv)
Drv . . . . . . . Drive: The parameter 'Drv ' must be a string or expression that can
represent a valid DOS file structure drive letter. Drv is case
insensitive and must end with a colon ( : ). The Drv may be local to
the computer, or mapped from anywhere on the network
connected to the computer. Drv is often included as part of the Path
parameter.
Return Value CurDir returns a Variant containing a string; CurDir$ returns a String.
CVar
Syntax CVar(Exp)
Exp . . . . . . . Expression: The argument 'Exp ' will depend upon which data type
is expected in the function. If a string is expected, Exp may be a
valid string or Variant containing a value recognizable as a string.
Chapter 6: CitectVBA Function Reference 113
Return Value Returns the value of the expression (Exp) provided in the argument as a variant
data type.
Date
Description Determines the current system date according to the setting of the computer's
system date and time. Unlike other functions, Date does not require trailing
parentheses.
Syntax Date()
Return Value Returns a Variant (of String data type) containing the string value of the current
system date.
Related Functions DateSerial DateValue Year Month WeekDay Day TimeValue Hour
Minute Second
Example varSysDate
varSysDate = Date
' retrieves system date
Date statement
DateSerial
Description Constructs a date value from the given Year, Month, and Day arguments passed
to the function. The DateSerial function expects all three parameters to be valid.
Date values in CitectVBA are evaluated using the Gregorian Calendar.
Syntax DateSerial()
Return Value Returns a Variant (of date data type) containing a date value corresponding to
the Year, Month and Day values that were passed in to the function.
DateValue
Description Calculates a date from the given date argument passed to the function. Date
values in CitectVBA are evaluated using the Gregorian Calendar. The DateValue
function expects the argument value (Date ) to be a string or any expression that
can represent a date.
Syntax DateValue(Date)
Date . . . . . . . DateThe argument 'Date ' must be a string or expression that can
represent a date value. This includes any combination of date
literals, numbers that look like dates, strings that look like dates,
and dates from functions.
Return Value Returns a variant (of date data type) corresponding to the string date expression
that was passed in.
Day
Description Calculates the day from the given date argument passed to the function using
the Gregorian Calendar.
Syntax Day(Date)
Date . . . . . . . Date: The argument 'Date ' must be a string or expression that can
represent a date value. This includes any combination of date
literals, numbers that look like dates, strings that look like dates,
and dates from functions.
Return Value Returns a variant date corresponding to the date expression that was passed in.
Declare
Description The Declare statement is used at module (file) level to declare references to
external procedures in a dynamic-link library (DLL).
<AliasName> represents the optional function name within the DLL being
called
( ) defines the required argument section of the function
Dim
Description The Dim statement allocates storage for, and declares the data type of, variables
and arrays in a module.
Dir
Description Dir function returns a file or directory name that matches the given File and
Attrib arguments.
The File argument is optional, and represents a string expression that
specifies a valid file name, and may include a DOS path structure including
directory or folder names, and a drive letter. You must specify File the first
time you call the Dir function, or an error occurs.
The Attrib argument is optional, and can be a constant or numeric
expression whose sum specifies file attribute values. If you specify file
attributes in the function call, File must be included. If the Volume attribute
value (8) is specified, all other attribute values are ignored.
Dir supports the use of multiple-character ( * ) and single-character ( ? )
wildcards to specify multiple files.
Dir returns the first file name that matches both File and Attrib. To get any
additional file names that match, call Dir again with no arguments. When no
more file names match, Dir returns a zero-length string (" "). Once a zero-length
string is returned, you must specify argument/s in the next call (to reset the
function), or an error occurs.
Calling Dir with any argument will reset the function, and it will treat the call as
a new call. Previous arguments passed to the Dir function are overwritten and
forgotten (reset). You can reset the function (by supplying arguments in the
function call) at any time, even if it has not yet returned every possible argument
match result.
118 Chapter 6: CitectVBA Function Reference
Calling Dir with the Directory attribute (16) does not continually return
Directory names. You will need to check the attribute value of every return result
to determine if the return is a valid directory name. To do so, use the GetAttr
function. Because file names are retrieved in no particular order, you may want
to store returned file names in an array and then sort the array.
Note: The file system keeps track of the current drive, and the current directory
of every drive. Use the CurDir statement to determine the current directory. The
current drive letter can be extracted from the Left character returned in the
CurDir statement.
Return Value Returns a String representing the name of a file, directory, or folder that matches
a specified pattern or file attribute, or the volume label of a drive. If File is not
found, a zero-length string (" ") is returned. If Attrib is omitted, all files are
returned that match File.
Do Loop
Description The Do...Loop conditional statement allows you to execute a block of statements
an indefinite number of times. The variations of the Do...Loop are Do While, Do
Until, Do Loop While, and Do Loop Until.
Do While|Until <condition>
<statement/s>
Loop
Do Until <condition>
<statement/s>
120 Chapter 6: CitectVBA Function Reference
Loop
Do
<statement/s>
Loop While <condition>
Do
<statement/s>
Loop Until <condition>
Do While and Do Until check the condition before entering the loop, thus the
block of statements inside the loop are only executed when those conditions are
met. Do Loop While and Do Loop Until check the condition after having
executed the block of statements thereby guaranteeing that the block of
statements is executed at least once.
Any Do statement can be exited using the Exit Do statement.
End Function
Description The End Function statement ends a program or a block of statements within a
function. A CitectVBA function starts with the FUNCTION statement and
finishes with the END FUNCTION statement. All other statements that lie
between the FUNCTION and END FUNCTION statements will be executed by
the function when called to do so.
Sub TestColor2
Dim I as integer
For I = 1 to 10
Print GetColor2(I)
Next I
End Sub
End Sub
Description The End Sub statement ends a program or a block of statements within a
subroutine. A CitectVBA subroutine starts with the SUB statement and finishes
with the END SUB statement. All other statements that lie between the SUB and
END SUB statements, will be executed by the subroutine, when called to do so.
Sub TestColor2
122 Chapter 6: CitectVBA Function Reference
Dim I as integer
For I = 1 to 10
Print GetColor2(I)
Next I
End Sub
EOF
Description EOF function returns a Boolean True or False value during file access that
indicates whether the current position of an open file has reached the end of the
file. The required FileNum argument must contain an Integer representing any
valid system file number associated with an open file.
Note: The file system keeps track of all open files and the current position of
access within every file. Every statement or function that accesses the data
within a file, alters the current position within that file. The Loc function can be
used to determine the current position within an open file.
Use the LOF and Loc functions instead of EOF when reading binary files with
the Input function, or use Get when using the EOF function.
Note: An error occurs with files opened for Binary access, when the file is read
using the Input function until EOF returns True.
Syntax EOF(FileNum)
FileNum . . . File Number: The argument 'FileNum ' must contain an Integer or
numeric expression representing any valid number in the range 1 to
511 inclusive, which is referenced by the file system to be associated
with an open file.
Return Value Returns an Integer containing the Boolean value False until the end of the file
has been reached. Returns True when the end of a file opened for Random or
sequential Input has been reached.
Close #1
Erase
Description Reinitialises the elements of a fixed array specified in the ArrayList parameter.
Syntax Erase(Arraylist)
Arraylist . . . Array List: The parameter 'ArrayList ' must be a comma delimited
list of valid variable array names.
Exit
Example ' This sample shows Do ... Loop with Exit Do to get out.
Dim Value, Msg' Declare variables
Do
Value = InputBox("Enter a value from 5 to 10.")
124 Chapter 6: CitectVBA Function Reference
Exp
Description Calculates the exponential of a number. The exponential is the base of the
natural logarithm e raised to a power (e^Num). The Exp function complements
the Log function and is sometimes referred to as the antilogarithm.
Note: The value of the constant e is approximately 2.71828.
Syntax Exp(Num)
Num . . . . . . Number: The argument 'Num ' must contain an Integer or
expression representing a valid numeric value.
Return Value Returns the value equivalent to the base of the natural logarithm (e) raised to the
power of the number (Num) provided in the argument.
FileCopy
Note: The file system keeps track of the current drive, and the current directory
of every drive. Use the CurDir statement to determine the current directory. The
current drive letter can be extracted from the Left character returned in the
CurDir statement.
FileLen
Description FileLen function determines the byte length of a file. The required File argument
must be valid string expression representing a valid file name. File may contain a
DOS path structure including directory or folder names, and a drive letter.
The FileLen function returns the size of a file immediately before it was most
recently opened. To obtain the length of a file that is already open, use the LOF
function.
Syntax FileLen(File)
File. . . . . . . . File Name: The argument 'File ' must be a string or expression that
can represent a valid file name, and may include a DOS path
structure including directory or folder names, and a drive letter.
Return Value Returns a Long value representing the length of the file measured in bytes.
126 Chapter 6: CitectVBA Function Reference
Fix
Description Calculates the integer portion of a number. Fix does not round the number, and
ignores the fractional value of the number.
Fix expects the argument (Num) to be a valid numeric value. If the argument
value is positive, rounds the Num down by dropping any fractional value. If the
argument value is negative, rounds the Num up to the next integer number
greater than or equal to Num.
Do not confuse Fix with Int , which rounds a negative argument value (Num)
down to the next integer number less than or equal to Num.
Syntax Fix(Num)
Num . . . . . . Number: The argument 'Num ' must contain an Integer or
expression representing a valid numeric value.
Return Value Returns the Integer value of the number (Num) provided in the argument.
For
Description Repeats its block of statements a set number of times as determined by the
values used with the To clause.
Next
Format
Description Formats a string, number, or variant to the format expression (fmt ). The Format
function expects the argument (Exp ) to be a valid expression to be formatted.
The Format function expects the argument (fmt ) to be a string of characters that
specify how the expression is to displayed, or the name of a commonly used
format that has been predefined in CitectVBA. Do not mix different type format
expressions in a single fmt parameter.
If the fmt parameter is omitted or is zero-length and the expression parameter is
a numeric, Format[$] provides the same functionality as the Str[$] function by
converting the numeric value to the appropriate return data type. Positive
numbers convert to strings using Format[$] lack the leading space reserved for
displaying the sign of the value, whereas those converted using Str[$] retain the
leading space.
To format numbers, you can use the commonly used formats that have been
predefined in CitectVBA, or you can create user-defined formats with standard
characters that have special meaning when used in a format expression.
Date separator (/). The actual character used as the date separator in the
formatted out depends on Date Format specified in the International section
of the Control Panel.
Display a literal character (- + $ ( )). To display a character other than one of
those listed, precede it with a backslash (\).
Display the next character in the format string (\). The backslash itself isn't
displayed. To display a backslash, use two backslashes (\\).
Note: Examples of characters that can't be displayed as literal characters are
the date- and time- formatting characters (a,c,d,h,m,n,p,q,s,t,w,y, and /:), the
numeric formatting characters(#,0,%,E,e,comma, and period), and the
string- formatting characters (@,&,<,>, and !).
"String"Display the string inside the double quotation marks (“String”). To
include a string in fmt from within CitectVBA, you must use the ANSI code
for a double quotation mark Chr(34) to enclose the text.
Display the next character as the fill character (*). Any empty space in a field
is filled with the character following the asterisk.
Unless the fmt argument contains one of the predefined formats, a format
expression for numbers can have from one to four sections separated by
semicolons.
If you use The result is
One section The format expression applies to all values.
Two The first section applies to positive values, the second to negative sections values.
Three The first section applies to positive values, the second to negative sections values, and the
third to zeros.
Four The first section applies to positive values, the second to negative section values, the third
to zeros, and the fourth to Null values.
The following example has two sections: the first defines the format for positive
values and zeros; the second section defines the format for negative values.
"$#,##0; ($#,##0)"
If you include semicolons with nothing between them. the missing section is
printed using the format of the positive value. For example, the following format
displays positive and negative values using the format in the first section and
displays "Zero" if the value is zero.
"$#,##0;;\Z\e\r\o"
Some sample format expressions for numbers are shown below. (These examples
all assume the Country is set to United States in the International section of the
Control Panel.) The first column contains the format strings. The other columns
130 Chapter 6: CitectVBA Function Reference
contain the output the results if the formatted data has the value given in the
column headings.
Format (fmt) Positive 3 Negative 3 Decimal .3 Null
Null string 3 -3 0.3
0 3 -3 1
0.00 3.00 -3.00 0.30
#,##0 3 -3 1
#,##0.00;;;Nil 3.00 -3.00 0.30 Nil
$#,##0;($#,##0) $3 ($3) $1
$#,##0.00;($#,##0.00) $3.00 ($3.00) $0.30
0% 300% -300% 30%
0.00% 300.00% -300.00% 30.00%
0.00E+00 3.00E+00 -3.00E+00 3.00E-01
0.00E-00 3.00E00 -3.00E00 3.00E-01
Numbers can also be used to represent date and time information. You can
format date and time serial numbers using date and time formats or number
formats because date/time serial numbers are stored as floating-point values.
To format dates and times, you can use either the commonly used format that
have been predefined or create user-defined time formats using standard
meaning of each:
General Display a date and/or time. for real numbers, display a date and time.(e.g. 4/3/93 03:34
PM); If there is no fractional part, display only a date (e.g. 4/3/93); if there is no integer
part, display time only (e.g. 03:34 PM).
Long Date Display a Long Date, as defined in the International section of the Control Panel.
Medium Display a date in the same form as the Short Date, as defined in the international section of
the Control Panel, except spell out the month abbreviation.
Short Date Display a Short Date, as defined in the International section of the Control Panel.
Long Time Display a Long Time, as defined in the International section of the Control panel. Long
Time includes hours, minutes, seconds.
Medium Display time in 12-hour format using hours and minuets and the Time AM/PM designator.
Short Time Display a time using the 24-hour format (e.g. 17:45)
c Display the date as dddd and display the time as ttttt. in the order.
d Display the day as a number without a leading zero (1-31).
dd Display the day as a number with a leading zero (01-31).
ddd Display the day as an abbreviation (Sun-Sat).
ddddd Display a date serial number as a complete date (including day , month, and year).
w Display the day of the week as a number (1- 7 ).
ww Display the week of the year as a number (1-53).
m 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.
Chapter 6: CitectVBA Function Reference 131
mm 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.
mmm Display the month as an abbreviation (Jan-Dec).
mmmm Display the month as a full month name (January-December).
q display the quarter of the year as a number (1-4).
y Display the day of the year as a number (1-366).
yy Display the day of the year as a two-digit number (00-99)
yyyy Display the day of the year as a four-digit number (100-9999).
h Display the hour as a number without leading zeros (0-23).
hh Display the hour as a number with leading zeros (00-23).
n Display the minute as a number without leading zeros (0-59).
nn Display the minute as a number with leading zeros (00-59).
s Display the second as a number without leading zeros (0-59).
ss Display the second as a number with leading zeros (00-59).
ttttt 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.
AM/PM Use the 12-hour clock and display an uppercase AM/PM
am/pm Use the 12-hour clock display a lowercase am/pm
A/P Use the 12-hour clock display a uppercase A/P
a/p Use the 12-hour clock display a lowercase a/p
AMPM Use the 12-hour clock and display the contents of the 11:59 string(s1159) in the WIN.INI
file with any hour before noon; display the 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.
m/d/yy 2/26/65
d-mmmm-yy 26-February-65
d-mmmm 26 February
mmmm-yy February 65
hh:nn AM/PM 06:45 PM
h:nn:ss a/p 6:45:15 p
h:nn:ss 18:45:15
m/d/yy/h:nn 2/26/65 18:45
Strings can also be formatted with Format[$]. A format expression for strings
can have one section or two sections separated by a semicolon.
If you use The result is
One section only The format applies to all string data.
Two sections The first section applies to string data, the second to Null values and zero-length
strings.
132 Chapter 6: CitectVBA Function Reference
The following characters can be used to create a format expression for strings:
@ 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.
FreeFile
Description Retrieves the next sequential system file number available for association with a
file. Use the FreeFile function to retrieve an unassociated file number from the
file system. This number can be used by the Open statement to be associated
with a file.
Syntax FreeFile
Return Value Returns an Integer reference number ready for being associated with a file.
Function
Description The Function statement declares and defines a function procedure, its name,
parameters, and code to be enacted upon when the subroutine is called.
Functions differ from subroutines in that functions return a value, whereas
subroutines do not.
The required FunctionName is the name of the function being declared. The
optional ArgList is the list of arguments used within the function.
A CitectVBA function starts with the FUNCTION statement and finishes with
the END FUNCTION statement. All other statements that lie between the
FUNCTION and END FUNCTION statements will be executed by the function
when called to do so.
Sub TestColor2
Chapter 6: CitectVBA Function Reference 135
Dim I as integer
For I = 1 to 10
Print GetColor2(I)
Next I
End Sub
Get #
Description Get statement reads data from a disk file into a variable.
The required FileNum argument is a system reference number associated with an
open file. The optional RecNum argument is the byte position where the read
starts for files opened in Binary mode. If you omit RecNum, the next record or
byte following the last Get or Put statement (or pointed to by the last Seek
function) is read. You must include delimiting commas.
The required VarName is the name of the variable where the file data is read
(copied) to.
Random mode
For files opened in Random mode, the following rules apply:
If the length of the data being read is less than the length specified in the Len
clause of the Open statement, Get reads subsequent records on record-
length boundaries. The space between the end of one record and the
beginning of the next record is padded with the existing contents of the file
buffer. Because the amount of padding data can't be determined with any
certainty, it is generally a good idea to have the record length match the
length of the data being read.
If the variable being read into is a variable-length string, Get reads a 2-byte
descriptor containing the string length and then reads the data that goes into
the variable. Therefore, the record length specified by the Len clause in the
Open statement must be at least 2 bytes greater than the actual length of the
string.
If the variable being read into is a Variant of numeric type, Get reads 2 bytes
identifying the VarType of the Variant and then the data that goes into the
variable. For example, when reading a Variant of VarType 3, Get reads 6
bytes: 2 bytes identifying the Variant as VarType 3 (Long) and 4 bytes
containing the Long data. The record length specified by the Len clause in
the Open statement must be at least 2 bytes greater than the actual number
of bytes required to store the variable.
136 Chapter 6: CitectVBA Function Reference
Note: You can use the Get statement to read a Variant array from disk, but
you can't use Get to read a scalar Variant containing an array. You also can't
use Get to read objects from disk.
If the variable being read into is a Variant of VarType 8 (String), Get reads 2
bytes identifying the VarType, 2 bytes indicating the length of the string, and
then reads the string data. The record length specified by the Len clause in
the Open statement must be at least 4 bytes greater than the actual length of
the string.
If the variable being read into is a dynamic array, Get reads a descriptor
whose length equals 2 plus 8 times the number of dimensions, that is, 2 + 8 *
NumberOfDimensions. The record length specified by the Len clause in the
Open statement must be greater than or equal to the sum of all the bytes
required to read the array data and the array descriptor. For example, the
following array declaration requires 118 bytes when the array is written to
disk.
If the variable being read into is a fixed-size array, Get reads only the data.
No descriptor is read.
If the variable being read into is any other type of variable (not a variable-
length string or a Variant), Get reads only the variable data. The record
length specified by the Len clause in the Open statement must be greater
than or equal to the length of the data being read.
Get reads elements of user-defined types as if each were being read individually,
except that there is no padding between elements. On disk, a dynamic array in a
user-defined type (written with Put) is prefixed by a descriptor whose length
equals 2 plus 8 times the number of dimensions, that is, 2 + 8 *
NumberOfDimensions. The record length specified by the Len clause in the
Open statement must be greater than or equal to the sum of all the bytes
required to read the individual elements, including any arrays and their
descriptors.
Binary mode
For files opened in Binary mode, all of the Random rules apply, except:
The Len clause in the Open statement has no effect. Get reads all variables
from disk contiguously; that is, with no padding between records.
For any array other than an array in a user-defined type, Get reads only the
data. No descriptor is read.
Get reads variable-length strings that aren't elements of user-defined types
without expecting the 2-byte length descriptor. The number of bytes read equals
the number of characters already in the string.
FileNum . . . File Number: The argument 'FileNum ' must contain an Integer or
numeric expression representing any valid number in the range 1 to
511 inclusive, which is referenced by the file system to be associated
with an open file.
RecNum . . . Record Number: The argument 'RecNum ' .
VarName . . . Variable Name: The argument 'VarName ' must be a string
representing a valid variable name.
GetAttr
Description GetAttr function returns an Integer representing the attribute settings of a file,
directory, or volume.
The required File argument must be valid string expression representing a valid
file name. File may contain a DOS path structure including directory or folder
names, and a drive letter.
To determine which attributes are set, use the AND operator to perform a
bitwise comparison of the value returned by the GetAttr function and the value
of the individual file attribute you want. If the result is not zero, that attribute is
138 Chapter 6: CitectVBA Function Reference
set for the named file. For example, the return value of the following AND
expression is zero if the Archive attribute is not set:
Const AttrArchive = 32
Result = GetAttr(FileName) And AttrArchive' A nonzero value
is returned if the Archive attribute is set.
Syntax GetAttr(File)
File. . . . . . . . File Name: The argument 'File ' must be a string or expression that
can represent a valid file name, and may include a DOS path
structure including directory or folder names, and a drive letter.
Return Value Returns an Integer number indicating the sum Attribute value of a file, directory,
or folder for the File argument, where:
0 = Normal
1 = Read Only
2 = Hidden
4 = System
8 = Volume
16 = Directory or Folder
32 = Archive
Goto
Description The GoTo conditional statement branches unconditionally and without return to
the label specified in the GoTo statement. The label must be located in the same
subroutine or function as the Goto statement.
Example <statement/s>
If <condition> then
Chapter 6: CitectVBA Function Reference 139
GoTo Label1
Else
GoTo Label2
End If
Label1:
<statement/s>
GoTo Label3
Label2:
<statement/s>
GoTo Label3
Label3:
<statement/s>
In this example, CitectVBA tests the If condition, and jumps to the part of the
script that begins with the label "
Label1:" if the condition was true, or jumps to the part of the script that begins
with the label "Label2:" if the condition was false. This could be anywhere in the
same subroutine or function.
Hex
Description Converts a numeric value to a text string representing the hexadecimal value of
the number.
The Hex function expects the argument (Num ) to be a valid numeric value. It is
rounded to nearest whole number before evaluation.
Syntax Hex(Num)
Num . . . . . . Number: The argument 'Num ' must contain an Integer or
expression representing a valid numeric value.
Return Value Returns a text string containing the hexadecimal value of the numeric (Num)
value provided in the argument.
Hour
Description Calculates the hour value from the given time argument passed to the function.
Syntax Hour(Time)
Time. . . . . . . Time: The argument 'Time ' must be a string or expression that can
represent a time value. This includes and combination of time
literals, numbers that look like times, strings that look like times,
and times from functions.
Return Value Returns an integer between 0 and 23 that is the hour of the parameter (Time ).
If
Description Tests an initial condition and then either performs or omits to perform the
statements it contains, dependant upon the logical result of the test condition.
The condition can be a comparison or an expression, and must logically evaluate
to either True or False. The If statement has both single line and multiple line
syntax structure.
The single line syntax uses the If <TestCondition> Then
<StatementToPerformIfTrue> structure, however, can only perform a single
statement if and only if the test condition result is True. No 'End If' statement is
required:
If the result of the If test condition was True, the program flow continues into
and performs the statement following the Then statement, until it reaches the
end of the line.
To perform a single statement conditionally upon a False result, use the NOT
logical operator:
If NOT <Condition> Then <Statement>
To perform multiple statements, use the multiple line syntax structure which
ends with the 'End If' statement:
If <Condition> Then
' Then statement block
' perform only if true
<Statement/s>
End If
If the result of the If test condition was True, the program flow continues into the
Then statement block, and performs the statements following the Then
statement, until it reaches the End If statement.
If the result of the If test condition was False, the program flow jumps
completely over the Then statement block, which in this case exits the If
structure (without performing any statements other than the initial test
condition).
The mutiple line If structure can perform different blocks of statements
dependant upon EITHER a True OR a False result to the test condition, through
the use of the Else statement block:
If <Condition> Then
' Then statement block
' perform only if true
<Statement/s>
Else
' Else statement block
' perform only if false
<Statement/s>
End If
If the result of the If test condition was True, the program flow performs the
Then block statements, until it reaches the Else statement. It then jumps
completely over the Else statement block and exits the If structure (without
performing any of the Else statement block statements).
142 Chapter 6: CitectVBA Function Reference
Further test conditions can be placed into an If structure through the use of the
optional Else If <Condition> statement block. ElseIf statement blocks can only be
positioned within an If structure before the Else statement block. If the result of
the If test condition was False, the program flow jumps completely over the
Then statement block (without performing any of those statements) to the Else
statement to perform the statements in the Else statement block until it reaches
the End If statement.
If <Condition> Then
' Then statement block
' perform only if true
<Statement/s>
ElseIf <Condition>
' Else If statement block
' perform only if true
<Statement/s>
Else
' Else statement block
' perform only if false
<Statement/s>
End If
The ElseIf test condition is only evaluated after the initial If structure test
condition results in False.
If the result of the ElseIf test condition was True, the statements within the ElseIf
statement block are performed. The program flow then jumps completely over
the Else statement block and exits the If structure (without performing any of the
Else statement block statements).
If the result of the ElseIf test condition was False, the program flow jumps
completely over the ElseIf statement block (without performing any of those
statements) to the Else statement to perform the statements in the Else statement
block until it reaches the End If statement.
There is no apparent limit to the number of Else If statement blocks that any one
If structure can hold, however, the Select Case Statement structure handles
multiple condition result alternatives much more efficiently.
Input Input # statement reads data from a Sequential file and assigns that data to
variables. Input function returns characters from a file opened in Input or Binary
mode.
Chapter 6: CitectVBA Function Reference 143
The Input # statement has two parameters FileNum and VarList. The required
FileNum argument is the associated file number used in the Open statement
when the file was opened. The required VarList argument is a comma delimited
list of variables that are assigned values read from the file.
The Input function has two parameters: Num and FileNum. The required Num
argument is a number or valid numeric expression specifying the number of
characters (bytes) to be read from the file. FileNum is the associated file number
used in the Open statement when the file was opened.
Note: The file system keeps track of all open files and the current position of
access within every file. Every statement or function that accesses the data
within a file, alters the current position within that file. The Loc function can be
used to determine the current position within an open file.
Use the LOF and Loc functions instead of EOF when reading binary files with
the Input function, or use Get when using the EOF function.
Note: An error occurs with files opened for Binary access, when the file is read
using the Input function until EOF returns True.
Data read with the Input # statement has usually been written to a file with the
Write # statement. Data read with the Input function has usually been written to
a file with the Print # or Put statements.
Note: When saving data to a file for future reading with the Input # statement,
use the Write # statement instead of the Print # statement to write the data to the
file. Using Write # ensures the integrity of each separate data field by properly
delimiting it, so it can be read back in using Input #. Using Write # also ensures it
can be correctly read in any locale.
Return Value Input # statement returns data record by record from a file opened in Input or
Binary mode. Data items in a file must appear in the same order as the variables
in VarList and match variables of the same data type. If a variable is numeric and
the data is not numeric, a value of zero is assigned to the variable.
Input function returns a String containing characters from a file opened in Input
or Binary mode. The Input function returns all of the characters it reads,
144 Chapter 6: CitectVBA Function Reference
InStr
Description Returns the character position of the first occurrence of String2 within String1.
The optional Num argument is a numeric expression that sets the starting
position for the search. If omitted, search begins at the first character position. If
Num contains Null, an error occurs.
The required String1 argument is the string expression being searched.
The required String2 argument is the string expression being searched for.
Return Value Returns a variant containing a Long data type indicating the result of the string
search. Returns 0 if:
StringToSearch is of zero length.
Int
Description Calculates the integer portion of a number. Int does not round the number, and
ignores the fractional value of the number.
Int expects the argument (Num) to be a valid numeric value. If the argument
value is positive, rounds the Num down by dropping any fractional value. If the
argument value is negative, rounds the Num down to the next integer number
less than or equal to Num.
Do not confuse Int with Fix, which rounds a negative argument value (Num) up
to the next integer number greater than or equal to Num.
Syntax Int(Num)
146 Chapter 6: CitectVBA Function Reference
Return Value Returns the integer value of the number (Num) provided in the argument. If
Num contains a Null, Int returns a Null.
IsDate
Syntax IsDate(Date)
Date . . . . . . . Date: The argument 'Date ' must be a string or expression that can
represent a date value. This includes any combination of date
literals, numbers that look like dates, strings that look like dates,
and dates from functions.
Print MArray1 & " is a date " & Chr(10) & MCheck
Print x & " is a date" & Chr(10) & MChekk
IsEmpty
Syntax IsEmpty(Exp)
Exp . . . . . . . Expression: The argument 'Exp ' will depend upon which data type
is expected in the function. If a string is expected, Exp may be a
valid string or Variant containing a value recognizable as a string. If
a number is expected, Exp may be a valid number or Variant
containing a value recognizable as a number.
IsNull
The Null value indicates that the Variant contains no valid data. Null is not the
same as Empty, which indicates that a variable has not yet been initialised. It is
also not the same as a zero-length string (" "), which is sometimes referred to as a
null string.
Note: Use the IsNull function to determine whether VarName contains a Null
value. Expressions that you might expect to evaluate to True under some
circumstances, such as If Var = Null and If Var <> Null, are always False. This is
because any expression containing a Null is itself Null and, therefore, False.
Syntax IsNull(Exp)
Exp . . . . . . . Expression: The argument 'Exp ' will depend upon which data type
is expected in the function. If a string is expected, Exp may be a
valid string or Variant containing a value recognizable as a string. If
a number is expected, Exp may be a valid number or Variant
containing a value recognizable as a number.
MyVar = ""
MyCheck = IsNull(MyVar) ' Returns False.
MyVar = Null
MyCheck = IsNull(MyVar) ' Returns True.
IsNumeric
Syntax IsNumeric(Exp)
Exp . . . . . . . Expression: The argument 'Exp ' will depend upon which data type
is expected in the function. If a string is expected, Exp may be a
Chapter 6: CitectVBA Function Reference 149
Kill
Lbound
Description Determines the value of the lowest subscript for the (ArrayDimension) of the
(ArrayName) provided in the argument.
Lbound expects the required argument (ArrayName) to be a valid variable array
name. The optional argument (ArrayDimension) must be a whole long number
indicating which dimension's lower bound is to be returned. Use 1 for the first
dimension, 2 for the second, and so on. If ArrayDimension is omitted, 1 is
assumed.
LCase
Description Converts all uppercase letters in Str to lowercase letters. All lowercase letters
and non-letter characters remain unchanged.
Syntax LCase(Str)
Chapter 6: CitectVBA Function Reference 151
Str . . . . . . . . String: The argument 'Str ' must be a string or expression that can
represent a valid text value.
Left, Left$
Return Value The Left function returns a variant containing a String data type. The Left$
function returns a String.
Len
Description The Len function determines the number of characters in the Str argument. The
LenB function determines the number of bytes in the VarName argument.
The Str argument can be any valid string expression. If Str contains Null,
Null is returned.
The VarName argument can be any valid variable name. If VarName contains
Null, Null is returned. If VarName is a Variant, LenB treats it the same as a
String and always returns the number of characters it contains.
Syntax Len(Str)
Str . . . . . . . . String: The argument 'Str ' must be a string or expression that can
represent a valid text value.
Line Input #
Description Line Input # statement reads a single line from an open sequential file and
assigns it to a String variable .
The required FileNum argument is a system reference number associated with an
open file. The required VarName is the name of the variable where the file data is
read (copied) to.
Note: The number sign ( # ) preceding FileNum is not optional.
The Line Input # statement reads from a file one character at a time until it
encounters a carriage return (Chr(13)) or carriage return–linefeed (Chr(13) +
Chapter 6: CitectVBA Function Reference 153
Chr(10)) sequence. Carriage return - linefeed sequences are skipped rather than
appended to the character string.
Note: The file system keeps track of all open files and the current position of
access within every file. Every statement or function that accesses the data
within a file, alters the current position within that file. The Loc function can be
used to determine the current position within an open file.
Data read with the Line Input # statement has usually been written to a file with
the Print # statement.
Loc
Description Loc function returns a number indicating the current position within a file
opened using the Open statement.
The required FileNum argument must contain an Integer representing any valid
number associated with an open file.
Syntax Loc(FileNum)
154 Chapter 6: CitectVBA Function Reference
FileNum . . . File Number: The argument 'FileNum ' must contain an Integer or
numeric expression representing any valid number in the range 1 to
511 inclusive, which is referenced by the file system to be associated
with an open file.
Return Value Returns a Long representing the current position within a file, the value
dependant upon which file access mode the file was opened with:
If the file was opened in Random mode, the Loc function will return a number
representing the last record read from or written to the file.
If the file was opened in Sequential mode, the Loc function will return a number
representing the current byte position in the file divided by 128. (However,
information returned by Loc for Sequential files is neither used nor required.)
If the file was opened in Binary mode, the Loc function will return a number
representing the position of the last byte read from or written to the file.
LOF
Description LOF function returns a number indicating the byte length of a sequential file
opened using the Open statement.
The required FileNum argument must contain an Integer representing any valid
number associated with an open file.
Note: The file system keeps track of all open files and the current position of
access within every file. Every statement or function that accesses the data
within a file, alters the current position within that file. The Loc function can be
used to determine the current position within an open file.
Chapter 6: CitectVBA Function Reference 155
The LOF function returns the size of a file that is already open.
To obtain the length of a file that is not open, use the FileLen function.
Use the LOF and Loc functions instead of EOF when reading binary files with
the Input function.
Syntax LOF(FileNum)
FileNum . . . File Number: The argument 'FileNum ' must contain an Integer or
numeric expression representing any valid number in the range 1 to
511 inclusive, which is referenced by the file system to be associated
with an open file.
Log
Syntax Log(Num)
Num . . . . . . Number: The argument 'Num ' must contain an Integer or
expression representing a valid numeric value.
Return Value Returns the natural log of the number (Num) provided in the argument.
LTrim
Syntax LTrim(Str)
Str . . . . . . . . String: The argument 'Str ' must be a string or expression that can
represent a valid text value.
Mid
Return Value The Mid function returns a Variant (containing a String data type).
Minute
Description Calculates the minute value from the given time argument passed to the
function.
Syntax Minute(Time)
Time. . . . . . . Time: The argument 'Time ' must be a string or expression that can
represent a time value. This includes and combination of time
literals, numbers that look like times, strings that look like times,
and times from functions.
Return Value Returns an integer between 0 and 59 representing the minute of the parameter
(Time ).
MkDir
Description The MkDir statement creates the directory specified in the Path parameter.
The required parameter Path must be a string or expression that can represent a
valid DOS file structure path value, must contain a directory name, may contain
a relative path structure, and may contain a drive letter. The Path parameter
must be limited to less than 128 characters.
The MkDir statement is relative to the current directory. If no path structure is
provided, the directory is created in the current directory. If no drive is specified,
the MkDir statement creates the directory on the current drive.
Note: The file system keeps track of the current drive, and the current directory
of every drive. Use the CurDir statement to determine the current directory. The
Chapter 6: CitectVBA Function Reference 159
current drive letter can be extracted from the Left character returned in the
CurDir statement.
Month
Description Calculates the month from the given date argument passed to the function using
the Gregorian Calendar.
Syntax Month(Date)
Date . . . . . . . Date: The argument 'Date ' must be a string or expression that can
represent a date value. This includes any combination of date
literals, numbers that look like dates, strings that look like dates,
and dates from functions.
Return Value Returns an integer between 1 and 12 inclusive, that represents the month of the
year.
160 Chapter 6: CitectVBA Function Reference
Name
Description The Name statement renames the disk file specified in the OldFileName
parameter, to the name specified in the NewFileName parameter.
The required parameter OldFileName must be valid existing file name, may
contain a path structure, and may contain a drive letter.
The NewFileName parameter must be a string or expression that can represent a
valid DOS file name value, may contain a relative path structure, and may
contain a drive letter. The NewFileName parameter must be limited to less than
128 characters.
The Name statement uses the file system relative to the current directory. If no
path structure is provided, the NewFileName file is expected to be in the current
directory. If no drive is specified, the Name statement expects the file to be on
the current drive.
Using Name, you can move a file from one directory or folder to another. If the
path in NewFileName exists and is different from the path in OldFileName, the
Name statement moves the file to the new directory or folder and renames the
file, if necessary. If NewFileName and OldFileName have different paths and the
same file name, Name moves the file to the new location and leaves the file name
unchanged.
Name does not support the use of multiple-character ( * ) and single-character (?)
wildcards to specify multiple files.
The Name statement does not work on a currently open file. You must close an
open file before renaming it.
Note: The file system keeps track of the current drive, and the current directory
of every drive. Use the CurDir statement to determine the current directory. The
current drive letter can be extracted from the Left character returned in the
CurDir statement.
Nothing
Description Releases an OLE Automation object reference from a variable of object type. The
Nothing keyword is used in a Set statement.
In the following declaration syntax example, each placeholder shown inside
arrow brackets ( <placeholder> ) should be replaced in any actual code with the
value of the item that it describes. The arrow brackets and the word they contain
should not be included in the statement, and are shown here only for your
information.
The nothing keyword should be used when you are finished with an object,
to clear any variables that reference the object, so the object can be released
from memory.
Now
Description Determines the current date and time according to the setting of the computer's
system date and time using the Gregorian Calendar. Unlike other functions,
Now does not require trailing parentheses.
Syntax Now()
Return Value The Now function returns a Variant data type containing a date and time value
that is stored internally as a double data type.
The number represents a date and time from January 1, 100 through December
31, 9999. Numbers to the left of the decimal point represent the date and
numbers to the right represent the time.
Oct
Description Converts a numeric value to a text string representing the octal value of the
number.
Chapter 6: CitectVBA Function Reference 163
The Oct function expects the argument (Num ) to be a valid numeric value. It is
rounded to nearest whole number before evaluation.
Syntax Oct(Num)
Num . . . . . . Number: The argument 'Num ' must contain an Integer or
expression representing a valid numeric value.
Return Value Returns a text string containing the octal value of the numeric (Num) value
provided in the argument.
OnError
Description CitectVBAs error-handling routine and specifies the line label of the error-
handling routine. The line parameter refers to a label. That label must be present
in the code or an error is generated.
Exit Sub
errHandler:
Print Err.Number, Err.Description
Resume Next
164 Chapter 6: CitectVBA Function Reference
Open
File. . . . . . . . File Name: The argument 'File ' must be a string or expression that
can represent a valid file name, and may include a DOS path
structure including directory or folder names, and a drive letter.
Mode . . . . . . File Mode: The argument 'Mode ' must be a CitectVBA keyword
specifying the file I/O mode: Append, Binary, Input, Output, or
Random.
Lock . . . . . . . File Lock: The argument 'Lock ' must be a CitectVBA keyword
specifying the operations permitted on the open file by other
processes: Shared, Lock Read, Lock Write, and Lock Read Write.
AccessFile Access: The argument 'Access ' must be a CitectVBA
keyword specifying the operations permitted on the open file:
Read, Write, or Read Write.
FileNum . . . File Number: The argument 'FileNum ' must contain an Integer or
numeric expression representing any valid number in the range 1 to
511 inclusive, which is referenced by the file system to be associated
with an open file.
RecLen. . . . . Record Length: The argument 'RecLen ' must contain an Integer or
numeric expression representing the byte length of a file record as a
number less than or equal to 32,767.
Example ' 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
166 Chapter 6: CitectVBA Function Reference
End Type
Dim recRecord As Record' Declare variable.
Open "TESTFILE" For Random As #1 Len = Len(recRecord)
' 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
Option Compare
Description Determines how strings are compared within a CitectVBA module. The optional
Option Compare statement if used, must be placed at the top of the CitectVBA
file along with any other Option declarations.
Option Explicit
Print (function)
Description Displays a message in the runtime Citect Kernel, and the Cicode Editor output
window if you are in debug mode.
Note: Do not confuse this function with the Print # statement, which prints data
to disk.
Print #
Description Print # statement reads data from OutputList and writes that data to a sequential
file.
The Print # statement has two parameters FileNum and OutputList.
The required FileNum argument is the associated file number used in the Open
statement when the file was opened.
The required OutputList argument is a delimited list of expressions whose values
are written to the file.
Note: The number sign hash character ( # ) preceding FileNum is not optional.
This character indicates disk file access with the file referenced by the system file
Chapter 6: CitectVBA Function Reference 169
number that follows it. Do not confuse Print # which prints to disk, with Print
which displays data on the screen.
Data written with Print # is usually read from a file with Line Input # or Input.
Note: If you want to read the data from a file using the Input # statement, use the
Write # statement instead of the Print # statement to write the data to the file.
Using Write # ensures the integrity of each separate data field by properly
delimiting it, so it can be read back in using Input #. Using Write # also ensures it
can be correctly read in any locale.
If you omit expressionlist, the Print # statement prints a blank line in the file, but
you must include the comma. Because Print # writes an image of the data to the
file, you must delimit the data so it is printed correctly. If you use commas as
delimiters, Print # also writes the blanks between print fields to the file.
The Print # statement usually writes Variant data to a file the same way it writes
any other data type. However, there are some exceptions:
If the data being written is a Variant of VarType 0 (Empty), Print # writes nothing
to the file for that data item.
If the data being written is a Variant of VarType 1 (Null), Print # writes the literal
#NULL# to the file.
If the data being written is a Variant of VarType 7 (Date), Print # writes the date
to the file using the Short Date format defined in the WIN.INI file. When either
the date or the time component is missing or zero, Print # writes only the part
provided to the file.
( | ) vertical line are used for illustrative purposes to indicate in the code that
either side of the line is an alternative argument. You can use the argument
provided on one of the line or the other, but not both arguments at the same
time within the same set of curly braces. Do not include the vertical line in
your code.
{Spc( s) } argument is optionally used to insert 's' number of space characters
in the output file at the position of the argument in the OutputList. The Spc
argument must be enclosed by curly braces to delineate it from an expression.
The Spc argument can be repeated any number of times to insert spaces in
the file between expressions. The Spc argument is mutually exclusive with the
Tab argument when used within the same set of curly braces.
{Tab(n) } argument is optionally used to position the insertion point to an
absolute column number in the output file at the position of the argument in
the OutputList, where 'n' is the column number. Use Tab with no argument to
position the insertion point at the beginning of the next print zone. The Tab
argument must be enclosed by curly braces to delineate it from an expression.
The Tab argument can be repeated any number of times to insert tabs in the
file between expressions. The Tab argument is mutually exclusive with the Spc
argument when used within the same set of curly braces.
expression argument represents a valid numeric or string expression to
output to the file. The expression argument can be repeated any number of
times.
charpos is the character that determines the position of the next character in
the output. A semicolon means the next character is printed immediately
after the last character; a comma means the next character is printed at the
start of the next print zone. Print zones begin every 14 columns. If neither
character is specified, the next character is printed on the next line.
Return Value Input # statement returns data record by record from a file opened in Input or
Binary mode. Data items in a file must appear in the same order as the variables
in VarList and match variables of the same data type. If a variable is numeric and
the data is not numeric, a value of zero is assigned to the variable.
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
Put #
Note: The file system keeps track of all open files and the current position of
access within every file. Every statement or function that accesses the data
within a file, alters the current position within that file. The Loc function can be
used to determine the current position within an open file.
The required VarName is the name of the variable where the file data is read
(copied) from.
Data written with the Put # statement is usually read from a file with the Get #
statement.
Random modeFor files opened in Random mode, the following rules apply:
If the length of the data being written is less than the length specified in the Len
clause of the Open statement, Put writes subsequent records on record-length
boundaries. The space between the end of one record and the beginning of the
next record is padded with the existing contents of the file buffer. Because the
amount of padding data can't be determined with any certainty, it is generally a
good idea to have the record length match the length of the data being written. If
the length of the data being written is greater than the length specified in the Len
clause of the Open statement, an error occurs.
If the variable being written is a variable-length string, Put writes a 2-byte
descriptor containing the string length and then the variable. The record length
specified by the Len clause in the Open statement must be at least 2 bytes greater
than the actual length of the string.
If the variable being written is a Variant of a numeric type, Put writes 2 bytes
identifying the VarType of the Variant and then writes the variable. For example,
when writing a Variant of VarType 3, Put writes 6 bytes: 2 bytes identifying the
Variant as VarType 3 (Long) and 4 bytes containing the Long data. The record
length specified by the Len clause in the Open statement must be at least 2 bytes
greater than the actual number of bytes required to store the variable.
Note: You can use the Put statement to write a Variant array to disk, but you
can't use Put to write a scalar Variant containing an array to disk. You also can't
use Put to write objects to disk.
If the variable being written is a Variant of VarType 8 (String), Put writes 2 bytes
identifying the VarType, 2 bytes indicating the length of the string, and then
writes the string data. The record length specified by the Len clause in the Open
statement must be at least 4 bytes greater than the actual length of the string.
If the variable being written is a dynamic array, Put writes a descriptor whose
length equals 2 plus 8 times the number of dimensions, that is, 2 + 8 *
NumberOfDimensions. The record length specified by the Len clause in the
Open statement must be greater than or equal to the sum of all the bytes
required to write the array data and the array descriptor. For example, the
following array declaration requires 118 bytes when the array is written to disk.
Chapter 6: CitectVBA Function Reference 173
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
Randomize
Syntax Randomize[number]
Randomize
MValue = Int((6 * Rnd) + 1)
Print MValue
ReDim
Description Used to size or resize a dynamic array that has already been declared using the
Dim statement with empty parentheses.
Use the ReDim statement to change the number of elements in and array, but not
to change the number of dimensions in an array or the type of the elements in
the array.
Rem
Right
Description Returns the right most Num characters of Str. The required Str argument is a
String expression from which the rightmost characters are returned. If Str
contains Null, Null is returned.
The required Num argument is a Variant (Long) numeric expression indicating
how many characters to return. If 0, a zero-length string (" ") is returned. If
greater than or equal to the number of characters in string, the entire string is
returned.
Note: To determine the number of characters in a string, use the Len function.
Return Value The Right function returns a variant containing a string data type.
The Right$ function returns a string.
RmDir
Description The RmDir statement deletes the directory specified in the Path parameter.
The required parameter Path must be a string or expression that can represent a
valid DOS file structure path value, must contain a directory name, may contain
a relative path structure, and may contain a drive letter. The Path parameter
must be limited to less than 128 characters.
The RmDir statement is relative to the current directory. If no path structure is
provided, the directory is expected to be a subdirectory of the current directory.
If no drive is specified, the RmDir statement deletes the directory on the current
drive.
The current directory cannot be deleted. To change the current directory to
another directory, use the ChDir statement. The directory to be deleted must be
empty and contain no files or sub-directories. To delete files in a directory, use
the Kill statement.
Note: The file system keeps track of the current drive, and the current directory
of every drive. Use the CurDir statement to determine the current directory. The
current drive letter can be extracted from the Left character returned in the
CurDir statement.
Rnd
Description Generates a decimal fraction number using the optional argument value (Num)
to determine the sequence of the (random) number generation.
Rnd expects the argument (Num) if supplied, to be a valid numeric value.
If Num is less than zero, Rnd generates the same number every time, using Num
as the seed. If Num is equal than zero, Rnd repeats the most recently generated
number. If Num is greater than zero, Rnd generates the next random number in
the sequence. If Num is not supplied, Rnd generates the next random number in
the sequence.
Before calling Rnd, use the Randomize statement without an argument to
initialise the random-number generator with a seed based on the system timer.
Note: The square brackets [ ] in the syntax indicate that the argument is optional.
Do NOT include the square brackets in your code.
Syntax Rnd[(Num)]
Num . . . . . . Number: The argument 'Num ' must contain an Integer or
expression representing a valid numeric value.
Return Value Returns a (random) decimal fraction number influenced by the (Num) provided
in the argument. The return value lies in the range of less than 1 but greater than
or equal to 0.
RTrim
Syntax RTrim(Str)
Str . . . . . . . . String: The argument 'Str ' must be a string or expression that can
represent a valid text value.
Second
Description Calculates the second value from the given time argument passed to the
function.
Syntax Second(Time)
Time. . . . . . . Time: The argument 'Time ' must be a string or expression that can
represent a time value. This includes and combination of time
literals, numbers that look like times, strings that look like times,
and times from functions.
Return Value Returns an integer that is the second portion of the parameter (Time ).
Seek
Description Sets the current position within a file opened using the Open statement, ready
for the next read or write action.
The required FileNum argument must contain an Integer representing any valid
system file number associated with an open file.
The required Position argument must contain an Integer or expression
representing a valid number.
180 Chapter 6: CitectVBA Function Reference
Note: The file system keeps track of all open files and the current position of
access within every file. Every statement or function that accesses the data
within a file, alters the current position within that file. The Loc function can be
used to determine the current position within an open file.
Example 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 The Select Case statement tests the same variable for many different conditions.
The test value provided with the initial Select Case statement is logically tested
against the Case test condition.
The Select Case structure can perform different blocks of statements dependant
upon whichever Case statement test condition (if more than one) first results as
True, through the use of the Case statement block:
Select Case <TestValue>
Case <Condition>
' Case statement block
' perform only if case true
<Statement/s>
Case Else
' Else statement block
Chapter 6: CitectVBA Function Reference 181
containing an integer (ranging from 1 to 7) representing the day of the week, and
we wished to display that value as a string (named strDayOfWeek) containing
the name of the day of the week, assuming in this example, that Sunday is the
first day of the week (1). The Select Case structure would look like this:
Dim strDayOfWeek As String
SendKeys
Description Sends one or more keystrokes to the active window of the active application as if
they had been entered at the keyboard.
The value of the Wait argument determines when the SendKeys function
completes and returns control to CitectVBA. If omitted, Wait is treated as FALSE
by default.
Chapter 6: CitectVBA Function Reference 183
Note: You can't use SendKeys to send keystrokes to an application that is not
designed to run in Microsoft Windows. Sendkeys also can't send the PRINT
SCREEN key {PRTSC} to any application..
Set
Sgn
Description Indicates the sign of a number. Sgn does not round the number, and ignores the
fractional value of the number.
Sgn expects the argument (Num) to be a valid numeric value. If Num is greater
than zero, Sgn returns the value of 1. If Num is equal to zero, Sgn returns the
value of 0. If Num is less than zero, Sgn returns the value of -1.
Syntax Sgn(Num)
Num . . . . . . Number: The argument 'Num ' must contain an Integer or
expression representing a valid numeric value.
Return Value Returns a value indicating the Sign (+ or - ) value of the (Num) provided in the
argument.
Sin
Description Calculates the trigonometric Sine value of an angle. The Sin function expects the
argument (Rad) to be a valid angle value in radians, and calculates the ratio of
two sides of a right-angle triangle. The ratio is the length of the side opposite to
the angle divided by the length of the hypotenuse.
To convert degrees to radians, multiply degrees by Pi/180 . To convert radians to
degrees, multiply radians by 180/Pi. For more information, see Circle Maths.
Syntax Sin(Rad)
Rad . . . . . . . Radians: The argument 'Rad ' must be expressed in radians, and
must be a valid numeric value.
Return Value Returns the Sine value of the angle (Rad) provided in the argument. The result
lies in the range - 1 to + 1.
Space
Description Creates a String consisting of the specified number Num of spaces. The Space
function is useful for formatting output and clearing data in fixed-length strings.
Syntax Space(Num)
Num . . . . . . Number: The argument 'Num ' must contain an Integer or
expression representing a valid numeric value.
Sqrt
Description Calculates the square root of a number. Sqrt expects the argument (Num) to be a
valid numeric value greater than or equal to 0.
Syntax Sqrt(Num)
Num . . . . . . Number: The argument 'Num ' must contain an Integer or
expression representing a valid numeric value.
Return Value Returns the square root value of the (Num) provided in the argument.
Example Variable=Sqrt(4);
! Sets Variable to 2.
Static
Description The Static statement allocates storage for—and declares the data type of—
variables and arrays that will retain their values between subsequent references.
Static variables are more commonly used within procedures (subroutines and
functions), and have local scope.
<DataType> represents the optional CitectVBA data type declaration for the
variable
Stop
Description Ends execution of the program. The Stop statement can be placed anywhere in
your code.
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 Converts a numeric value to a text string containing numeric characters. The Str
function expects the argument (Num ) to be a valid numeric value.
The Str function is often used to prepare a numerical value for display as a string
in a caption, label, string field, or string expression.
The Str function performs the opposite of the Val function, which converts a text
string containing numeric characters to a numeric value.
188 Chapter 6: CitectVBA Function Reference
Note: Be careful of data type coercion issues with variant data types. See
Variants.
Num . . . . . . Number: The argument 'Num ' must contain an Integer or
expression representing a valid numeric value. SyntaxStr(Num)
Return Value Returns a string containing the numeric character representation of the numeric
(Num) value provided in the argument.
The Str function always reserves the first return string character for the sign of
Num. If Num is positive, a leading space is used and the plus sign is implied.
StrComp
Description Returns an integer that is the result of the comparison of two strings.
The required String1 argument is any valid string expression. The required
String2 argument is any valid string expression.
The optional Compare argument is a numeric expression that specifies the type of
string comparison. It can be omitted, 0, or 1. Specify 0 (default) to perform a
binary comparison. Specify 1 to perform a textual comparison. If compare is
Null, an error occurs.
Return Value Returns a variant containing an integer data type indicating the result of the
string compare:
Returns –1 where String1 is less than String2.
Chapter 6: CitectVBA Function Reference 189
String
Description Creates a string that consists of one character repeated a specific number of
times.
The required Num argument is Long numeric expression indicating how many
characters to return. If Num contains Null, Null is returned.
The required Character argument is a String expression from which the first
character is repeated and returned, or is a Variant (Long) representing a valid
character code. If character contains Null, Null is returned.
Syntax String(Num)
Num . . . . . . Number: The argument 'Num ' must contain an Integer or
expression representing a valid numeric value.
Sub
Description Declares and defines a subroutine procedure, its name, parameters, and code to
be enacted upon when the subroutine is called. Subroutines differ from
functions in that functions return a value, whereas subroutines do not.
The required SubroutineName is the name of the subroutine being declared.
The optional ArgList is the list of arguments used within the subroutine.
A CitectVBA subroutine starts with the SUB statement and finishes with the
END SUB statement. All other statements that lie between the SUB and END
SUB statements, will be executed by the subroutine, when called to do so.
Syntax Sub
Sub TestColor2
Dim I as integer
For I = 1 to 10
Print GetColor2(I)
Next I
Chapter 6: CitectVBA Function Reference 191
End Sub
Tan
Description Calculates the trigonometric Tangent value of an angle. The Tan function expects
the argument (Rad) to be a valid angle value in radians, and calculates the ratio
of two sides of a right-angle triangle. The ratio is the length of the side opposite
to the angle divided by the length of the side adjacent to the angle.
Note: To convert degrees to radians, multiply degrees by Pi/180. To convert
radians to degrees, multiply radians by 180/Pi.
Syntax Tan(Rad)
Rad . . . . . . . Radians: The argument 'Rad ' must be expressed in radians, and
must be a valid numeric value.
Return Value Returns the Tangent value of the angle (Rad) provided in the argument. Tan will
return as a double.
Time
Description Determines the current system time according to the setting of the computer's
clock. Unlike other functions, Time does not require trailing parentheses.
The required timevalue argument is any numeric expression, string expression,
or any combination, that can represent a time value.
The Time() function (brackets included) determines the current system time
according to the setting of the computer's clock.
Syntax Time[()]
Return Value The Time() function returns a variant (Date) indicating the current system time.
Time (statement)
Timer
Description The Timer event is used to track elapsed time or can be displayed as a stopwatch
in a dialog.
Syntax Timer()
TS = Timer
MsgBox "Starting Timer"
TE = Timer
TT = TE - TS
Print TT
Chapter 6: CitectVBA Function Reference 193
TimeSerial
Description Constructs a time value serially from the given Hrs, Mins, and Secs arguments
passed to the function. The TimeSerial Function expects all three arguments to
be valid.
Syntax TimeSerial()
Return Value Returns a Variant (of date data type) containing a time value corresponding to
the Hrs, Mins, and Secs values that were passed in to the function.
TimeValue
Description Calculates a time. The TimeValue function expects the argument value (Time ) to
be a string or any expression that can represent a time value.
Syntax TimeValue(Time)
Time. . . . . . . Time: The argument 'Time ' must be a string or expression that can
represent a time value. This includes and combination of time
literals, numbers that look like times, strings that look like times,
and times from functions.
Return Value Returns a variant (of date data type) corresponding to the parameter (Time ).
Trim
Description Strips any leading and trailing spaces from Str variable.
194 Chapter 6: CitectVBA Function Reference
Syntax Trim(Str)
Str . . . . . . . . String: The argument 'Str ' must be a string or expression that can
represent a valid text value.
Ubound
Description Determines the value of the largest subscript for the (ArrayDimension) of the
(ArrayName) provided in the argument. Ubound expects the required argument
(ArrayName) to be a valid variable array name.
The optional argument (ArrayDimension) must be a whole long number
indicating which dimension's lower bound is to be returned. Use 1 for the first
dimension, 2 for the second, and so on. If ArrayDimension is omitted, 1 is
assumed.
UCase
Description Converts all lowercase letters in Str to uppercase letters. All uppercase letters
and non-letter characters remain unchanged.
Syntax UCase(Str)
Str . . . . . . . . String: The argument 'Str ' must be a string or expression that can
represent a valid text value.
Val
Description Converts a text string containing numeric characters to a numeric value. The Val
function expects the argument (Str ) to be a valid string expression. The Val
function stops reading the string when it reaches a non numeric character.
Symbols such as dollar signs and commas are not recognised; however, radix
prefixes for octal (&0) and hexadecimal (&H) are. Blanks, tabs and linefeeds are
stripped out from the return.
196 Chapter 6: CitectVBA Function Reference
The Val function performs the opposite of the Str function, which converts a
numeric value to a text string containing numeric characters.
Syntax Val(Str)
Str . . . . . . . . String: The argument 'Str ' must be a string or expression that can
represent a valid text value.
Return Value Returns the numeric value of a string of characters extracted from the (Str )
provided in the argument.
VarType
Syntax VarType(VarName)
VarName . . . Variable Name: The argument 'VarName ' must be a string
representing a valid variable name.
0 Empty
5 Double
6 Not Applicable
7 Date/Time
8 String
VbCallOpen function
Description The VbCallOpen function is a Cicode function used to call a CitectVBA function
or subroutine from Cicode. It is used to initiate a call to the CitectVBA function
or subroutine and returns a handle (of OBJECT data type) to that opened
function call.
VbCallOpen is used in conjunction with VbCallRun and VbCallReturn
functions, which can all be nested to implement the entire function set with a
single line of Cicode. For further information, see the section “Calling CitectVBA
from Cicode”.
Return Value VbCallOpen returns an Object data type containing a handle to the CitectVBA
function being called. If the function fails the return value is zero.
198 Chapter 6: CitectVBA Function Reference
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
VbCallRun function
Description Used to execute the CitectVBA function or subroutine (previously opened with
the Cicode VbCallOpen function), and requires the handle returned from the
VbCallOpen function call.
The VbCallRun function provides an opportunity for the opened CitectVBA
function to complete and return a value in the multi-threaded Citect/SCADA
environment. It passes its argument value (of OBJECT data type) through as its
return value upon completion.
VbCallRun is used in conjunction with VbCallOpen and VbCallReturn
functions, which can all be nested to implement the entire function set with a
single line of Cicode. For details, see Calling CitectVBA from Cicode.
Return Value VbCallRun (passes through and) returns a Object data type containing a handle
to the CitectVBA function being called.
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
VbCallReturn function
Description Used to obtain the return value of the completed CitectVBA function (previously
opened with the Cicode VbCallOpen function), and requires the handle
returned from the VbCallRun function call.
VbCallReturn is used in conjunction with VbCallOpen and VbCallRun
functions, which can all be nested to implement the entire function set with a
single line of Cicode. For further information, see the section “Calling CitectVBA
from Cicode”.
Return Value VbCallReturn returns the completed return value for the CitectVBA function.
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
WeekDay
Description Calculates the weekday value of the given date argument passed to the function.
Date values in CitectVBA are evaluated using the Gregorian Calendar.
Syntax WeekDay(Date)
Date . . . . . . . Date: The argument 'Date ' must be a string or expression that can
represent a date value. This includes any combination of date
literals, numbers that look like dates, strings that look like dates,
and dates from functions.
Return Value Returns an integer between the range of 1–7 inclusive representing the whole
number for the weekday:
Return Value Description
1 Sunday
2 Monday
3 Tuesday
4 Wednesday
5 Thursday
Chapter 6: CitectVBA Function Reference 201
While…Wend
Description The While...Wend loop conditional statement is similar to the Do While loop
statement. The condition is checked before executing the block of statements
comprising the loop.
Write #
Description Write # statement writes data to a Sequential file opened in output or append
mode and reads that data from a list of variables.
The Write # statement has two parameters FileNum and VarList. The required
FileNum argument is the associated file number used in the Open statement
when the file was opened. The required VarList argument is a comma delimited
list of variables that are assigned values read from the file.
Note: The file system keeps track of all open files and the current position of
access within every file. Every statement or function that accesses the data
202 Chapter 6: CitectVBA Function Reference
within a file, alters the current position within that file. The Loc function can be
used to determine the current position within an open file.
Data written to a file with the Write # statement is usually read with the Input #
statement.
Note: When saving data to a file for future reading with the Input # statement,
use the Write # statement instead of the Print # statement to write the data to the
file. Using Write # ensures the integrity of each separate data field by properly
delimiting it, so it can be read back in using Input #. Using Write # also ensures it
can be correctly read in any locale.
Year
Description Calculates the year from the given date argument passed to the function. Date
values in CitectVBA are evaluated using the Gregorian Calendar.
Syntax Year(Date)
Date . . . . . . . Date: The argument 'Date ' must be a string or expression that can
represent a date value. This includes any combination of date
literals, numbers that look like dates, strings that look like dates,
and dates from functions.
Chapter 6: CitectVBA Function Reference 203