+ All Categories
Home > Documents > Actuate Basic Reference

Actuate Basic Reference

Date post: 11-Apr-2015
Category:
Upload: api-3729631
View: 4,891 times
Download: 0 times
Share this document with a friend
500
Actuate Basic Language Reference
Transcript
Page 1: Actuate Basic Reference

Actuate Basic Language Reference

Page 2: Actuate Basic Reference

Information in this document is subject to change without notice. Examples provided are fictitious. No part of this document may be reproduced or transmitted in any form, or by any means, electronic or mechanical, for any purpose, in whole or in part, without the express written permission of Actuate Corporation.

© 1995 - 2003 by Actuate Corporation. All rights reserved. Printed in the United States of America.

Contains information proprietary to:

Actuate Corporation701 Gateway BoulevardSouth San Francisco, CA 94080http://www.actuate.com

The software described in this manual is provided by Actuate Corporation under an Actuate License agreement. The software may be used only in accordance with the terms of the agreement.

Actuate Corporation trademarks and registered trademarks:Actuate, the Actuate logo, e.Analysis, e.Report, e.Reporting, e.Spreadsheet, Formula One, Internet Spreadsheet, Live Report Document, ReportCast, Report Encyclopedia, ReportingEngines, the ReportingEngines logo, Reportlet, Spreadsheets Everywhere, Tidestone Technologies, and XML reports.

Third party trademarks or registered trademarks of their respective owners, companies, or organizations:Apache Software Foundation (http://www.apache.org/): Crimson, Tomcat, Xalan, and Xerces. Apple Computer, Inc.: TrueType. BEA Systems, Inc.: BEA WebLogic Server. Bits Per Second, Ltd. and Graphics Server Technologies, L.P.: Graphics Server. Borland Software Corporation: JBuilder. Bristol Technology, Inc.: XPrinter. Bruno Lowagie and Paulo Soares: iText, licensed under the Mozilla Public License (MPL). Component One, LLC.: VSFlexGrid Pro. Fred L. Drake, Jr. (http://sourceforge.net/projects/expat): Expat XML parser, created by James Clark, licensed under the MIT License. Hewlett-Packard Company: HP-UX. IBM Corporation: 1-2-3 , AIX, DB2, Informix-ESQL/C, ICU, Lotus, and WebSphere. Indiana University Extreme! Lab (http://www.extreme.indiana.edu): XML Pull Parser and XPP. InstallShield Corporation: InstallShield. InterNetivity Inc.: Databeacon. JDBM Project (http://jdbm.sourceforge.net): JDBM. LEAD Technologies, Inc.: LEADTOOLS. Linus Torvalds: Linux. Microsoft Corporation: ActiveX, Microsoft, MS-DOS, MSN, Windows, Windows NT. Netscape Communications Corporation, Inc.: Netscape, Netscape Communications, Netscape Communicator, Netscape Enterprise Server, and Netscape Navigator. Oracle Corporation: Oracle Call Interface. Progress Software Corporation: Progress. Quadralay Corporation: WebWorks. Rogue Wave Software, Inc.: NobleNet RPC and Rogue Wave SourcePro. SAP AG: SAP. Sun Microsystems, Inc.: 100% Pure Java, iPlanet, J2EE, Java and all Java-based marks, JavaServer Pages, ONC, Solaris, SPARC, Sun, Sun Microsystems, and Sun ONE. Sybase, Inc.: CT-Library. Symantec Corporation: Visual Cafe. Unicode, Inc.: Unicode. World Wide Web Consortium (W3C): HTML Tidy and tidy.c. X/Open Company, Ltd.: UNIX. Zero G Software, Inc.: InstallAnywhere. Zope Corporation: Digital Creations and DCLC.

All other brand or product names are trademarks or registered trademarks of their respective owners, companies or organizations.Document No. 030430-2-130331 April 21, 2003

Page 3: Actuate Basic Reference

i

ContentsIntroduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .ixUnderstanding Actuate 7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix

Addressing diverse customer profiles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xAddressing customer requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xSupporting international information delivery requirements . . . . . . . . . . . . . . . . . . xProviding a scalable, high performance server . . . . . . . . . . . . . . . . . . . . . . . . . . xProviding a complete information delivery solution . . . . . . . . . . . . . . . . . . . . . . . xi

Introducing the Actuate 7 and ReportingEngines product suite . . . . . . . . . . . . . . . . . xiiAbout Actuate e.Report Designer Professional product . . . . . . . . . . . . . . . . . . . . . . xvAbout the Actuate Basic Language Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xviiOnline documentation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xviii

Using online manuals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xviiiUsing online help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xviii

Using context-sensitive online help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xixUsing the Actuate online help system. . . . . . . . . . . . . . . . . . . . . . . . . . . . . xixUsing report-specific online help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxi

Typographical conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxiSyntax conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxii

Chapter 1Language summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2Classes and instances . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2Controlling program flow. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2Converting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Date and time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4Error trapping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5File input and output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5Finances . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6Graphics and printing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6Math . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8Variables and constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

Page 4: Actuate Basic Reference

ii

Chapter 2Statements and functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11Using the code examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12Abs function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14AddValueIndex function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15Asc function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18AscW function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19Assert statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20Atn function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20Beep statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22Call statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22CCur function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24CDate function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26CDbl function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29ChDir statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31ChDrive statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32Chr, Chr$ functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34ChrW, ChrW$ functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36CInt function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37Class statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39ClearClipboard function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40CLng function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41Close statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43Command, Command$ functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45Const statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46ConvertBFileToString function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47ConvertStringToBFile function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48CopyInstance statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49Cos function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50CreateJavaClassHandle function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50CreateJavaObject function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51CreateObject function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52CSng function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53CStr function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55CurDir, CurDir$ functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57CVar function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58CVDate function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60Date, Date$ functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63DateAdd function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64DateDiff function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66DatePart function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69DateSerial function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72

Page 5: Actuate Basic Reference

iii

DateValue function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .75Day function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .78DDB function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .81Declare statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .83Declare...End Declare statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .86Decode, Decode$ functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .88Dim statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .89Do...Loop statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .91Encode, Encode$ functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .94End statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .94Environ, Environ$ functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .96EOF function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .98Erase statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100Erl function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101Err function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102Err statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103Error, Error$ functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105Error statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106Exit statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107Exp function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110ExtendSearchPath function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111FileAttr function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112FileCopy statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113FileDateTime function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115FileExists function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116FileLen function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117FileTimeStamp function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119FindFile function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120Fix function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122FollowHyperlink statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123Format, Format$ functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125For...Next statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137FreeFile function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140Function...End Function statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141FV function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146Get statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149GetAFCROXVersion function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152GetAppContext function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153GetAttr function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154GetClassID function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157GetClassName function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158GetClipboardText function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160GetDisplayHeight function (Windows only) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161

Page 6: Actuate Basic Reference

iv

GetFactoryVersion function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163GetHeadline function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163GetJavaException function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164GetLocaleAttribute function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164GetLocaleName function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165GetMessageArgument function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166GetOSUserName function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166GetReportContext function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167GetReportScalingFactor function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168GetROXVersion function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168GetSearchFormats function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169GetServerName function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170GetServerUserName function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171GetUserAgentString function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171GetValue function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172GetValueType function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174GetVariableCount function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176GetVariableName function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178GetViewContext function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180GetViewPageFormats function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180GetVSTempFileName function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182Global statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182GoTo statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185Hex, Hex$ functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187Hour function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188If...Then...Else statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192IIf function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194Input # statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195Input, Input$ functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198InputB, InputB$ functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199InputBox, InputBox$ functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201InStr function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202InStrB function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204Int function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206IPmt function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207IRR function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210IsDate function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212IsEmpty function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214IsKindOf function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215IsNull function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216IsNumeric function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217IsPersistent function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218IsSearchFormatSupported function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218

Page 7: Actuate Basic Reference

v

IsViewPageFormatSupported function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219Kill statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220LBound function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222LCase, LCase$ functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224Left, Left$ functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225LeftB, LeftB$ functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226Len function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228LenB function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229Let statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230Line Input # statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232ListToArray function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234Loc function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234Lock...Unlock statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236LOF function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240Log function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241LSet statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242LTrim, LTrim$ functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243Mid, Mid$ functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245Mid, Mid$ statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246MidB, MidB$ functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247MidB, MidB$ statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249Minute function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250MIRR function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253MkDir statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255Month function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257MsgBox function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260MsgBox statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263Name statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266NewInstance function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268NewPersistentInstance function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269Now function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270NPer function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271NPV function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273Oct, Oct$ functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275On Error statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276Open statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278Option Base statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284Option Compare statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285ParseDate function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287ParseNumeric function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291Pmt function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292PPmt function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294Print # statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297

Page 8: Actuate Basic Reference

vi

Put statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300PV function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304QBColor function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307Randomize statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308Rate function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310ReDim statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312Rem statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315ReportCustomFailure function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316Reset statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317Resume statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317ReturnCustomFormat function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319RevInStr function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320RGB function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323Right, Right$ functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325RightB, RightB$ functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326RmDir statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328Rnd function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330RSet statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331RTrim, RTrim$ functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332SafeDivide function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334Second function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334Seek statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337Seek2 function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339Select Case statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341Set statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344SetAttr statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346SetBinding function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348SetClipboardText function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349SetDefaultPOSMFile function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350SetHeadline statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351SetMessageArguments function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351SetStructuredFileExpiration function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351SetValue function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353SetVSTempFile function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355Sgn function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355Shell function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356ShowFactoryStatus statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358Sin function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359Sleep statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360SLN function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361Space, Space$ functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362Sqr function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363Static statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364

Page 9: Actuate Basic Reference

vii

Stop statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366Str, Str$ functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366StrComp function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368String, String$ functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370StringW, StringW$ functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371StrLoad, StrLoad$ functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372StrSubst function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373Sub...End Sub statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373SYD function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377Tab function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379Tan function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381Time, Time$ functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381Timer function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382TimeSerial function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383TimeValue function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386Trim, Trim$ functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388Type...End Type statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389Type...As statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392UBound function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394UCase, UCase$ functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395Val function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396VarType function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397Weekday function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399While...Wend statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401Width # statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403Write # statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404Year function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407

Appendix AActuate Basic data types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411Any data type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412CPointer data type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412Currency data type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412Date data type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412Double data type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413Integer data type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413Long data type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413Single data type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414String data type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414User-defined data type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414Variant data type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415

Page 10: Actuate Basic Reference

viii

Appendix BKeywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 417

Appendix COperators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419* operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420+ operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421- operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 422/ operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424\ operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424^ operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425Mod operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425Comparison operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426& operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429And operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429BAnd operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 430Eqv operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431Imp operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432Not operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433BNot operator. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434Or operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435BOr operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436XOr operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437Is operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437Like operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438

Appendix DTrigonometric identities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441

Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443

Page 11: Actuate Basic Reference

I n t r o d u c t i o n ix

I n t r o d u c t i o n

Understanding Actuate 7Actuate® is the leading provider of information application platform solutions for Global 9000 companies and packaged application software vendors. This release addresses two key needs presented by our customers:

■ Controlled empowerment of their users

■ Leveraging existing assets

In the current business climate, our customers need to reconcile reduced staffing and the ever-present IT backlog with the demand for increasingly complex and customized information.

Empowering the business user as a way to reduce IT backlog has always been an appealing solution. In this time of reduced staffing and project funding, the business user can then leverage information the IT staff develops to meet his additional, and perhaps unique, needs. At the same time, today’s information manager needs increased visibility into what his business users are doing with the information he provides because of internal requirement for greater accountability. For example, new SEC regulations add to the demand on the corporate information management infrastructure.

Actuate technology ensures that users have business agility: access to the right information in the right form to take the right action. Actuate customers also need tools that ensure IT organizations maintain the appropriate level of control over the corporate information assets. To meet these requirements, Actuate’s information application platform includes three key elements:

■ An information server

■ An information application development environment

■ User empowerment tools

Page 12: Actuate Basic Reference

x A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

Addressing diverse customer profilesActuate’s customer list continues to include leaders in aerospace, commercial banking, defense, entertainment, federal government, financial services, health care, high technology, insurance, life sciences, pharmaceuticals, retail, securities, and telecommunications.

Our infrastructure software provides the foundation for applications that support business analysis, customer relationship management, customized interactive reporting, e.billing, e.procurement, executive dashboards, human resources, information portals, key performance indicators, service automation, spreadsheet reporting, supply chain management, and systems management. In the e.Business environment, our structured content technology seamlessly integrates into corporate web sites and packaged applications.

Addressing customer requirementsCustomers use Actuate 7 to retrieve business information from corporate databases. Capturing, validating, and storing information remain vitally important. In addition, customers now require an information application that takes their data and delivers it as interactive web pages and Excel spreadsheets that their customers, partners, and employees can use. Actuate customers need to:

■ Be able to combine data from multiple data sources associated with multiple transaction applications.

■ Have confidence in the consistency and maintainability of the Excel sheets on their business users’ desktops and their customers’ web pages.

Supporting international information delivery requirementsTo meet the growing international needs of our customer base, Actuate 7 continues to provide an unprecedented level of support for multilingual reporting including full Unicode support and an extensive list of locales.

Providing a scalable, high performance serverIndependent analysis confirms that Actuate iServer is a highly scalable, highly available, high-performance server that further extends our lead in implementing enterprise-class information delivery systems. Enhanced integration capabilities support personalized and customizable portal development, web services, and spreadsheet reporting.

Page 13: Actuate Basic Reference

I n t r o d u c t i o n xi

Providing a complete information delivery solutionActuate’s information application platform provides the content users need in the format in which they need it in a secure, timely, and cost-effective manner. In the following table, we summarize the three types of e.Business applications for which Actuate provides an opportunity for seamless integration through its application platform.

Actuate 7 continues to offer core solutions for fundamental enterprise reporting and information delivery challenges, as described in the following table.

Infrastructure element Function Actuate role

Databases Organize data. Actuate’s design tools support accessing, managing, and updating data.

Content management systems

Manage structured content.

Actuate iServer supports publishing structured content such as electronic catalogs.

Application servers Deploy online applications.

Actuate web applications, including Actuate Active Portal and Management Console, support conducting complex transactions, managing supply chains, and interacting with customers.

Challenge Actuate solution

Deliver high resolution information. Solve complex data access and presentation problems across a broad range of data sources.

View structured content. Support viewing DHTML and spreadsheet reports in standard browsers to eliminate plug-in installation for millions of users.

Page 14: Actuate Basic Reference

xii A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

Introducing the Actuate 7 and ReportingEngines product suite

The following section describes the products available from Actuate Corporation.

Actuate End User Desktop

An application used by end users to request, generate, view, and print report documents. The ReportQuery™ capabilities enable seamless transfer of data from an Actuate report to any productivity or analysis tool.

Actuate e.Report Designer

An application that complements e.Report Designer Professional and supports business users in designing and distributing a variety of reports. These reports require no programming. This application supports both modifying complex reports and using sophisticated components from libraries.

Meet varied information display requirements.

Provide:■ Template-based design and

display.■ Complex formatting capabilities.■ Spreadsheet reporting.

Meet exploding requirements for web-based content delivery.

Support well over one million hits a day on a single CPU.

Deliver personalized, secure information.

Provide open security directory integration and page-level security.

Reuse existing integrated content. Provide access to content from other applications using open server technology.

Maintain data integrity between online and hard copy.

Provide high-resolution printed copy from PostScript and PDF.

Transfer information among applications.

Provide XML output to support access to data across applications.

Meet increasing requirements for server-based reporting

Support clustering and failover.

Challenge Actuate solution

Page 15: Actuate Basic Reference

I n t r o d u c t i o n xiii

Actuate e.Report Designer Professional

An object-oriented application used by professional developers of structured content to design, build, and distribute information objects and report object designs. The Actuate Basic Language and Actuate Foundation Class Library support extensive customization capabilities.

Actuate Client Integration Technology is part of Actuate e.Report Designer Professional and consists of the following products:

■ Actuate ActiveX Controls embed Actuate reporting functionality into custom applications.

■ Actuate Requester API accesses attributes and values of report parameters, changes the values of report parameters, controls how and when a report generates, displays and prints reports, and configures report print setup. Users access the Requester API using Actuate Basic, Visual Basic, C, or C++.

■ Actuate Search Extension API supports developing search extensions to transfer data to any third-party productivity or analysis tool.

■ Actuate information objects support retrieving information from data sources based on a predefined query. With the Acutate iServer Actuate Query Option, users can customize an information object's query to filter and sort the information retrieved from the data source.

Actuate e.Spreadsheet Designer

An application that supports designing, creating, and distributing custom spreadsheets over the web. Users can dynamically generate richly formatted Excel and spreadsheet-based reports from Actuate iServer. These spreadsheets can be part of an application, an applet, or a JavaBean.

Actuate iServer System

A server application that generates information objects and report documents, manages them in the Encyclopedia® volume, and makes them available to users. Actuate iServer System supports managing a cluster consisting of multiple Actuate servers. Actuate iServer System includes the following products:

■ Actuate Active Portal for JSP, Actuate Active Portal for .NET, and Actuate ReportCast™ transform the Encyclopedia volume into a dynamic, secure web site. They provide the foundation for Channels and seamless integration with other web sites.

■ Management Console, an application that system and network administrators use to manage and control one or more Actuate servers.

■ Actuate Server Integration Technology includes:

Page 16: Actuate Basic Reference

xiv A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

■ Actuate Information Delivery API integrates Actuate web services into existing corporate applications, automates routine or time-consuming iServer integration tasks, and implements new feature groupings for custom business processes. The Actuate Information Delivery API is based on XML and supports the SOAP messaging protocol.

■ Actuate Report Server Security Extension supports the use of third-party security tools.

■ The Actuate archive driver supports the use of third-party archiving software and hardware.

■ Actuate Report Server API implements common Encyclopedia volume functionality using C++.

Actuate 7 supports the following iServer options:

■ Actuate e.Analysis Option

An application used to transform data from an Actuate report into interactive information. Users can view and analyze data to determine relationships and trends.

■ Actuate e.Report Option

A Basic and Java option that provides Encyclopedia volume functionality for e.Report Designer, e.Report Designer Professional, and Formula One e.Report Designer.

■ Actuate e.Spreadsheet Option

An open server application that generates Excel spreadsheets from e.Spreadsheet Designer files. Using this product, customers manage spreadsheet reports and analysis within the Actuate iServer and save Actuate reports as richly formatted Excel spreadsheets.

■ Actuate Query Option

A web-based tool that supports ad hoc queries based on predefined data streams.

■ Multi-Application Option

An option that supports using more than one Encyclopedia volume in the Actuate iServer System.

■ Page Level Security Option

An option that supports personalizing viewing privileges at the user level for reports and parts of reports.

■ Progress Option

A server application that supports working exclusively with Progress databases to generate Live Report Documents, manage them in the Encyclopedia volume, and make them available to users.

Page 17: Actuate Basic Reference

I n t r o d u c t i o n xv

Actuate Live Report Extension (LRX)

An application for end users that works with both Microsoft Internet Explorer and Netscape Navigator to support report viewing and printing on the web. Use Actuate LRX with Actuate ReportCast.

Actuate Viewer

An application end users can use to find, view, and print report documents.

Formula One e.Report Engine

A flexible Java tool for extracting, formatting, and delivering data from a variety of data sources including databases, Enterprise JavaBeans, Java objects inside applications, and text files. Users can deploy completed reports from any J2EE application, WebLogic, WebSphere, or web server in perfectly formatted, actionable DHTML, e-mail, HTML, PDF, and XML formats. The application data handler supports accessing Java objects inside applications. The reporting capabilities include extensive support for XML data sources and output.

This product includes the Formula One e.Report Designer, which is a report development application used by Java developers. The designer delivers DHTML, Excel, HTML, PDF, and XML reports in multiple viewing and printing formats.

Formula One e.Spreadsheet Engine

An application that supports creating, designing, and distributing custom spreadsheets over the web. Users can dynamically generate richly formatted Excel and spreadsheet-based reports. The application supports reading and writing fully formatted Excel files, a scalable calculation engine, standard spreadsheet formulas and functions, risk modeling, dynamic chart generation, and an embeddable spreadsheet interface.

About Actuate e.Report Designer Professional product

Actuate e.Report Designer Professional documentation includes printed manuals, installation guides, online help, user documentation as PDF and HTML files, and release notes. Information about the product that we cannot include before the book printing deadline is in the release notes.

The Actuate web site, http://www.actuate.com, contains late-breaking news about the product and its features as well as product update information. To obtain the password necessary to access the portion of the web site available

Page 18: Actuate Basic Reference

xvi A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

only to customers, telephone Actuate Customer Support. The engineers in Actuate Customer Support can also help you with technical questions about the product according to your service contract. The Customer Support telephone number and e-mail information can be found among the printed materials in the product box.

The Example folder in the product directory contains report examples. Each sample report folder contains a variety of files, often including a text file that discusses how the example works. In addition, Client Integration Technology includes sample applications. The samples demonstrate how to use the APIs.

The printed and online documentation includes the following manuals.

For information about this topic See the following resource

Installation Installation guide

Late-breaking information about the software and documentation

Release notes

Overview of Actuate reporting conceptsHow to build your first reportHow to design reports using the graphical user interface

Conceptual information about how to program with Actuate Foundation ClassesCustomizing e.reportsActuate Basic programming fundamentalsProgramming in the Windows environmentActuate’s C++ APIs

Accessing, viewing, running, printing and searching reports

Developing Advanced e.Reports

Developing Advanced e.Reports

Programming e.Reports

Using e.Reports

Page 19: Actuate Basic Reference

I n t r o d u c t i o n xvii

About the Actuate Basic Language Reference The Actuate Basic Language Reference guide provides information for using the functions and statements in the Actuate Basic programming language.

Formatting report data for multiple localesUnderstanding report encodingDesigning reports with right to left orientation

Actuate Foundation Classes, their properties, variables, and methods

Actuate Basic statements and functions

Terminology mapGlossary

For information about this topic See the following resource

Working with Multiple Locales

Actuate Foundation Class Reference

Actuate Basic Language Reference

Actuate 7 Glossary

Page 20: Actuate Basic Reference

xviii A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

The Actuate Basic Language Reference includes the following chapters:

■ Introduction. This chapter provides an overview of this guide, the Actuate e.Report Designer Professional documentation, and the typographical conventions used.

■ Chapter 1. Language summary. This chapter provides grouped lists of functions and statements that are frequently used together to perform specific programming tasks.

■ Chapter 2. Statements and functions. This chapter contains an alphabetical reference for all functions and statements.

■ Appendix A. Actuate Basic data types. This appendix contains information about data types supported by Actuate Basic.

■ Appendix B. Keywords. This appendix contains information about Actuate Basic keywords.

■ Appendix C. Operators. This appendix contains information about Actuate Basic operators.

■ Appendix D. Trigonometric identities. This appendix contains information about trigonometric identities.

Online documentationThe information in the printed manuals is also available as Adobe Acrobat PDF files and in the online help system for Actuate products. For products without a Windows interface, such as Actuate iServer System, we provide HTML help files. You can view these files using a standard web browser.

Using online manualsThe online manuals install automatically with the product in the Manuals directory. The items in the table of contents and the page numbers in the index both contain links to the appropriate topics in the text. In the index, you access the link by positioning the pointer over the page number, not the topic.

Using online helpActuate products provide both context-sensitive online help about the product and report-specific online help about the report you are viewing. Actuate 7 makes it possible for developers to create customized, report-specific online help.

Page 21: Actuate Basic Reference

I n t r o d u c t i o n xix

Using context-sensitive online helpSections from the printed manuals link directly to the software interface to make relevant information available while you work. Dialogs that need additional explanation about how to use them have a help button. To access online help for other elements, use the Help menu on the menu bar or press F1.

Using the Actuate online help systemUse two panes to access and view information in the Actuate 7 help system. The left pane displays the table of contents or the index. The right pane displays the contents of the online help topics.

The tabs at the top of the left pane access different views. Use these tabs to switch views among Contents, Index, Search, and Favorites.

Page 22: Actuate Basic Reference

xx A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

The following illustration shows an example of the index and the result of an index search.

The following illustration shows the result of a search as it appears in the left pane. To view the topic in the right pane, double-click the topic in the list. The topic appears in the right pane.

Type the keyword for which to search the index

Choose Index to view the topics

Select a topic from the list and choose Display to view its contents

Type the keyword for which to search

Select a topic from the list and choose Display to view its contents

Choose Search

Page 23: Actuate Basic Reference

I n t r o d u c t i o n xxi

Using report-specific online helpDuring the design phase, report developers have the option of including report-specific online help. For example, the report developer can add comments to provide details about a specific report object or to explain a calculation.

For detailed information about report-specific online help, see Chapter 3, “Viewing an e.report,” in Using e.Reports.

Typographical conventionsThe following table describes the typographical conventions in this guide.

Report-specific online help

Item Convention Example

Code examples Sans serif Dim Text1 As String

File names Initial letter capitalized, except Formula One e.Report Designer, where file names are case sensitive

Detail.roi

Key combination A + sign between keys means to press both keys at the same time

Ctrl+Shift

Menu items Capitalized, no bold File

Submenu items Separated from the main menu item with a small arrow

File➛New

User input or user response

Sans serif M*16*

User input in XML and Java code

Italics chkjava.exe cab_name.cab

Page 24: Actuate Basic Reference

xxii A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

Syntax conventionsThe following table describes the symbols used to present syntax.

Symbol Description Example

[ ] Optional item [Alias<alias name>]

Array subscript matrix[ ]

< > Argument you must supply

<expression to format>

Delimiter in XML <xsd:sequence>

{ } Groups two or more mutually exclusive options or arguments, when used with a pipe

{While | Until}

Defines array contents {0, 1, 2, 3}

Delimiter of code block public ACJDesigner( ){}

| Separates mutually exclusive options or arguments in a group

Exit {Do | For | Function | Sub}

Java OR operator int length |4

Page 25: Actuate Basic Reference

C h a p t e r 1 , L a n g u a g e s u m m a r y 1

C h a p t e r

1Chapter 1Language summary

This chapter provides grouped lists of functions and statements that are frequently used together to perform specific programming tasks:

■ Arrays

■ Classes and instances

■ Controlling program flow

■ Converting

■ Date and time

■ Environment

■ Error trapping

■ File input and output

■ Finances

■ Graphics and printing

■ Math

■ Operators

■ Procedures

■ Strings

■ Variables and constants

Page 26: Actuate Basic Reference

2 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

Arrays

Classes and instances

Controlling program flow

Programming task Function/Statement

Change default lower limit Option Base

Declare and initialize Dim, Global, ReDim, Static

Test the limits LBound, UBound

Reinitialize Erase, ReDim

Programming task Function/Statement

Declare classes Class

Create an instance of a class NewInstance, NewPersistentInstance, IsPersistent, CreateJavaObject, CreateJavaClassHandle

Access class variables GetClassID, GetClassName, GetValue, GetValueType, GetVariableCount, GetVariableName, IsKindOf, SetBinding

Copy class variable values CopyInstance

Programming task Function/Statement

Branch FollowHyperlink, GoTo, On Error

Exit or pause the program End, Stop

Loop Do...Loop, For...Next, While...Wend

Make decisions If...Then...Else, IIf, Select Case

Page 27: Actuate Basic Reference

C h a p t e r 1 , L a n g u a g e s u m m a r y 3

Converting

Date and time

Programming task Function/Statement

ANSI value to string Chr[$]

Binary image file to string ConvertBFileToString

Date to serial number DateSerial, DateValue

Decimal numbers to others Hex[$], Oct[$]

Number to string Format[$], Str[$]

Lists of values into an array. ListToArray

One data type to another data type CCur, CDate, CDbl, CInt, CLng, CSng, CStr, CVar, CVDate, Fix, Int

Serial number to date Day, Month, Weekday, Year

Serial number to time Hour, Minute, Second

String to ANSI value Asc

String to binary image file ConvertStringToBFile

String to number Val

Time to serial number TimeSerial, TimeValue

Programming task Function/Statement

Control how dates are converted ParseDate

Convert date to serial number DateSerial, DateValue

Convert serial number to date CVDate, Day, Month, Weekday, Year

Convert serial number to time Hour, Minute, Second

Convert time to serial number TimeSerial, TimeValue

Convert to date data type CDate, CVDate

Determine whether or not an argument can be converted to a date.

IsDate

Get current date or time Date[$], Now, Time[$], IsDate

Manipulate date or time DateAdd, DateDiff, DatePart

Time process Timer

Page 28: Actuate Basic Reference

4 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

Environment

Programming task Function/Statement

Clear Clipboard ClearClipboard

Display comments in the status line of the factory dialog box

ShowFactoryStatus

Find environment variables Environ[$]

Get Clipboard text GetClipboardText

Get command-line arguments Command[$]

Get login name of user logged into iServer

GetServerUserName

Get machine name of user logged into iServer

GetServerName

Get name of Actuate application currently running

GetAppContext

Get operating system (login) name of the user

GetOSUserName

Get scaling factor GetReportScalingFactor

Get stage of a report’s lifecycle GetReportContext

Get user agent string GetUserAgentString

Get version number of the AFC library

GetAFCROXVersion

Get version number of the factory the .rox is using

GetFactoryVersion

Get version number of .rox file GetROXVersion

OLE CreateObject

Run other programs Shell

Temporarily suspend report execution

Sleep

Set Clipboard text SetClipboardText

Sound beep Beep

Page 29: Actuate Basic Reference

C h a p t e r 1 , L a n g u a g e s u m m a r y 5

Error trapping

File input and output

Programming task Function/Statement

Get error messages Error, Error$, GetJavaException

Get error status Err, Erl

Insert explanatory remarks Rem

Prevent division-by-zero error SafeDivide

Prevent logic error by predetermining whether a condition is true

Assert

Set Err function to a given value Err

Simulate run-time errors Error

Trap errors while program is running

Assert, On Error, Resume

Programming task Function/Statement

Access or create files Open

Add directories to search for included images

ExtendSearchPath

Close files Close, Reset

Control output appearance Space, Tab, Width #

Copy one file to another FileCopy

Determine which open .roi file is the default used when the New Persistent() is called to instantiate an object

SetDefaultPOSMFile

Determine which formats are supported in a DHTML environment for displaying report pages and results of a search operation

GetSearchPageFormats, GetViewPageFormats, IsSearchFormatSupported, IsViewPageFormatSupported

Display dialog boxes InputBox[$], MsgBox

Page 30: Actuate Basic Reference

6 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

Finances

Graphics and printing

Get information on files EOF, FileAttr, FileDateTime, FileExists, FileLen, FileTimeStamp, FreeFile, Loc, LOF, Seek, Seek2

Manage disk drives and directories ChDir, ChDrive, CurDir[$], MkDir, RmDir

Manage files Kill, Lock...Unlock, Name

Read from file Get, Input #, Input[$], InputB[$], Line Input #

Retrieve strings from resource files StrLoad[$]

Search for a file through the existing search path

FindFile

Set object aging rules on an .row file SetStructuredFileExpiration

Set or get file attributes GetAttr, SetAttr

Set read-write position in file Seek

Write to file Print #, Put, Write #

Programming task Function/Statement

Depreciation of assets DDB, SLN, SYD

Get annuity information FV, IPmt, NPer, Pmt, PPmt, PV, Rate

Get net present value and rate of return

IRR, NPV, MIRR

Programming task Function/Statement

Decode string into binary image file ConvertStringToBFile

Encode binary image file into string ConvertBFileToString

Dynamically adjust the height of a container to accomodate a large amount of text

GetDisplayHeight (Windows only)

Programming task Function/Statement

Page 31: Actuate Basic Reference

C h a p t e r 1 , L a n g u a g e s u m m a r y 7

Math

Operators

Procedures

Print text Print #, Write #

Work with colors QBColor, RGB

Programming task Function/Statement

General calculation Exp, Log, Sqr

Generate random numbers Randomize, Rnd

Get absolute value Abs

Get the sign of expressions Sgn

Numeric conversions Fix, Int

Trigonometry Atn, Cos, Sin, Tan

Programming task Function/Statement

Arithmetic *, +, -, \, /, ^, Mod

Comparison <, =<, >, >=, =, <>, Is

Concatenation &

Logical expressions And, BAnd, Eqv, Imp, Not, BNot, Or, BOr, Xor

Pattern matching Like

Programming task Function/Statement

Call Sub procedure Call

Declare references to external procedures

Declare

Programming task Function/Statement

Page 32: Actuate Basic Reference

8 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

Strings

Define procedures Function...End Function, Sub...End Sub

Exit from procedures Exit, Function...End Function, Sub...End Sub

Programming task Function/Statement

Assign value Let

Compare two strings StrComp

Convert to lowercase or uppercase letters

LCase[$], UCase[$]

Copy to and from Clipboard SetClipboardText, GetClipboardText

Create strings of repeating characters Space[$], String[$], StringW[$]

Find the length of an expression in bytes

LenB

Find the length of a string Len

Format strings Format[$]

Justify strings LSet, RSet

Manipulate strings InStr, Left[$], LTrim[$], Mid[$], RevInStr, Right[$], RTrim[$], Trim[$]

Manipulate bytes InStrB, LeftB[$], RightB[$], MidB[$]

Replace part of a string with a different substring

StrSubst

Set string comparison rules Option Compare

Translate from one language to another

Open[$]

Work with UCS-2 encoding values AscW, ChrW[$]

Work with ASCII and ANSI values Asc, Chr[$]

Programming task Function/Statement

Page 33: Actuate Basic Reference

C h a p t e r 1 , L a n g u a g e s u m m a r y 9

Variables and constants

Programming task Function/Statement

Add search indexes on variables of components

AddValueIndex

Assign object references to variables Set

Declare aliases for existing object types

Type...As

Declare user-defined variables or record structures

Type...End Type

Declare variables and constants Const, Dim, Global, Static

Get information about Variant variables

IsDate, IsEmpty, IsNull, IsNumeric, VarType

Page 34: Actuate Basic Reference

10 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

Page 35: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 11

C h a p t e r

2Chapter 2Statements and functionsThis chapter contains an alphabetical reference for all Actuate Basic functions and statements.

Page 36: Actuate Basic Reference

12 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

Using the code examplesThe easiest way to use the Actuate Basic code examples is to copy the code from the Code Example window in online help into the Method Editor in the e.Report Designer Professional.

Not all examples have a Declaration section. If the example you are using does not include a Declare,...End Declare statement, you do not have to paste anything into the .bas file.

To open an example in the online help, do the following:

1 Choose Help➛Contents.

2 In the Table of Contents, scroll to Actuate Basic Language Reference, “Using the code examples.”

3 Under the topic title, choose Example.

The code example displays.

To use a code example in an e.Report Designer Professional report design, do the following:

1 Create a Basic source (.bas) file by choosing Tools➛Library Organizer.

Library Organizer appears.

2 Choose New.

New Library appears.

3 In File name, type the name for the new file. In Save as type, choose Source file (.bas). Choose Save.

The source file appears under Libraries included in your report.

4 In the Library Organizer, choose OK.

5 Move your cursor back to the Code Example window of the online help.

6 Select the code.

7 Copy and paste the code you wish to use into your .bas file.

8 Save the .bas file.

Next, in the e.Report Designer Professional application, do the following:

1 Use the Drawing/Graphics Rectangle tool to draw an object in the report.

2 Double-click the object to open the Component Editor.

3 Choose Methods.

4 Navigate to Function OnLButtonDblClk.

Page 37: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 13

5 Choose Override. If you are modifying an existing object, choose Edit.

6 In the Method Editor, paste the selected code under ’Insert your code here.

7 Choose Update to save your changes.

To compile and run your report, do the following:

1 Choose Report➛Build and run.

2 In the Requester choose OK.

Your report displays.

To run your Actuate Basic function, do the following:

1 Double-click the object in your report.

The function runs and the message box displays several prompts.

2 Answer the prompts.

The function displays the final result.

Example The following example demonstrates the FV function. The example shows you where exactly to paste the different parts of a code example. To use this example, perform the following steps:

1 Paste the following code into your Actuate Basic source code (.bas) file:

DeclareGlobal Const ENDPERIOD = 0Global Const BEGINPERIOD = 1

End Declare

2 Paste the following code into the OnLButtonDblClk() method of a label or other control under ’Insert your code here:

Dim EachPmt As Double, APR As DoubleDim TotalPmts As Single, PayWhen As IntegerDim PresentVal As Double, FutureVal As DoubleDim Msg as String, Fmt As String

Fmt = "$###,###,##0.00" ' Specify money format' Get user inputMsg = "How much will you save each month?"EachPmt = InputBox(Msg)Msg = "What is the annual percentage rate for the interest?"APR = InputBox(Msg)

If APR > 1 Then ' Ensure proper form as %APR = APR / 100

End If

Page 38: Actuate Basic Reference

14 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

A b s f u n c t i o n

Msg = "For how many months will you save?"TotalPmts = InputBox(Msg)Msg = "Will you make payments at month’s end?"PayWhen = MsgBox(Msg, MB_YESNO)

If PayWhen = IDNO ThenPayWhen = BEGINPERIOD

ElsePayWhen = ENDPERIOD

End If

Msg = "What amount is in this savings account now?"PresentVal = InputBox(Msg)' Now do the real workFutureVal = FV(APR / 12, TotalPmts, -EachPmt, -PresentVal, PayWhen)' Format the resulting information for the userMsg = "Starting with " & Format(PresentVal, Fmt) & " "Msg = Msg & " and saving " & Format(EachPmt, Fmt) & " every month at"Msg = Msg & " an interest rate of " & Format(APR, "##.0%")Msg = Msg & " for a period of " & TotalPmtsMsg = Msg & " months will give you " & Format(FutureVal, Fmt) & "."MsgBox Msg

3 Build, run, and view your report.

4 Double-click the label or control and follow the prompts.

Abs functionReturns the absolute value for a number or expression.

Syntax Abs(<number expression>)

Parameters <number expression>Number, numeric expression, or Variant of VarType 8 (String) that specifies the number for which you want to find the absolute value.

Rule: If <number expression> is a String, it is parsed according to the formatting rules of the current run time locale.

Example: The following statement returns 123.456 on a French run time locale and 123456.00 on an English run time locale:

Abs("123,456")

Returns Number, numeric expression, or Variant of VarType 8 (String)

■ If <number> evaluates to Null, Abs returns a Null.

Page 39: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 15

A d d V a l u e I n d e x f u n c t i o n

Example The following example demonstrates the return value of Abs:

Function OnLButtonDblClk ( )MsgBox Abs(25) ' Returns 25MsgBox Abs(-25) ' Returns 25

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Sgn function

AddValueIndex functionAdds a search index on a variable of a component.

Syntax AddValueIndex(<intFileID>, <strClassName>, <strAttrName>)

Parameters <intFileID>Integer expression. The file ID of the .roi (POSM file) to which you want to add the new index. The value returned from creating or opening an .roi.

This is in most cases the .roi file opened in the Factory. An easy way to get this ID is from any persistent object in your .roi file. To do so, use code like the following:

Dim roiFile As IntegerroiFile = GetPosmFile( thePersistentObject )AddValueIndex( roiFile, "yourClass", "yourVar" )

Rules:

■ Must designate a valid .roi file.

■ Must designate an .roi file open in the Factory.

<strClassName>String expression. The fully qualified name of the class of the component with the variable you want to index.

Rules:

■ Must specify an existing class.

■ Class must have persistent instances.

■ Must be the fully qualified name of the class.

Page 40: Actuate Basic Reference

16 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

A d d V a l u e I n d e x f u n c t i o n

To determine the fully qualified class name, use one of the following techniques:

■ Consult the Class tab of the Property Sheet for the component to find its name and scope. Specify <strClassName> according to the form: "scope1::scope2::name".

■ If you have an instance of the class, call GetClassName( ) on the object.

<strAttrName>String expression. The name of a variable in the class to be indexed.

Rules:

■ Must be a variable in the class specified by <strClassName>.

■ Must be a variable, not a property. The variable can have the same name as a property.

■ Cannot be a structure such as Size or Rectangle.

■ Must be of a simple scalar data type such as Integer, Date, Currency, String, or Double. Can also be a type alias for a scalar type such as Boolean or Twips.

Returns Boolean

■ True, if all arguments are correct.

■ False, if any of the arguments are invalid.

Description Use AddValueIndex() to add a search index to an .roi file. A search index speeds the retrieval of information when searching a report, although at the cost of a somewhat larger .roi file and somewhat longer Factory run.

Each index speeds access to one variable in one class. The easiest way to create an index is to set the Searchable property of a class to True. This adds an index on the DataValue variable of that class. Use AddValueIndex() to search on any other variable and add an index on that variable.

A typical circumstance in which you specify a different variable is when a hyperlink specifies a value that is related to the data stored in the DataValue variable. For example, a data control displays a customer's name, while an associated hyperlink uses the customer's ID. When indexing this hyperlink, specify an additional variable, perhaps called LinkTag, that contains the customer’s ID.

Rules ■ AddValueIndex() must be called in the Factory, during report generation. You cannot add an index to an .roi file once it is created.

■ You must create a separate index for each variable you want indexed. For each, you must specify the .roi file in which to create the index, the class name, and the variable name within the class.

Page 41: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 17

A d d V a l u e I n d e x f u n c t i o n

Tips ■ A convenient place to insert calls to AddValue is in the Finish( ) method for your subclass of AcReport, the top component in the Structure View.

■ Hyperlinks use the search engine. Therefore, to improve your report’s performance when executing hyperlinks, use AddValueIndex() to index hyperlinks.

■ Do not confuse properties and variables of an object. They often have the same names, especially when a property specifies the default value for a variable. To avoid confusion, use the Component Editor's Variables page to see what variables are available.

■ To facilitate debugging, use Verify to ensure that, if any argument to AddValueIndex is invalid, the Factory will halt. For example, use code like the following:

Verify(AddValueIndex( 0, "ItemFrame::ItemCode", "DataValue" ))

Example The following example assumes you have a report that displays a list of customers by name. Each customer is identified by a customer number variable, but you do not want to display this number, so you have created a CustomerNumber variable on the CustomerName control, which is in the CustomerFrame. The root AcReport component is CustomerListing.

Add an index on the CustomerNumber variable using the following code in the Finish method of CustomerListing:

Sub Finish( )Dim theROIFile As IntegerSuper::Finish( )

theROIFile = GetPOSMFile( me ) ’ Determine the .roi file handle for the .roi ’ file that contains this component

Verify( AddValueIndex( theROIFile,+ "CustomerListing::CustomerFrame::CustomerNumber",+ "CustomerNumber" ) ' Add a custom index for the CustomerNumber

’ variable in the’ CustomerListing::CustomerFrame::CustomerName’ control

' Quit the Factory if something goes wrongEnd Sub

For information about using the code examples, see “Using the code examples” earlier in this chapter.

Page 42: Actuate Basic Reference

18 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

A s c f u n c t i o n

Asc functionReturns the ANSI code that corresponds to the given character.

Syntax Asc(<string expression>)

Parameters <string expression>String expression that represents a character to translate to a corresponding code in the ANSI character set.

Rules:

■ If <string expression> is longer than one character, Asc translates only the first character.

■ If <string expression> evaluates to Null, Asc returns a Null.

■ If the string in <string expression> does not match the run time encoding, Asc might return an incorrect value. For example, if the report runs on a system that uses English (ASCII) encoding, passing a Japanese string produces incorrect results because Japanese characters cannot be converted to ASCII.

Example:The following statements are equivalent. Each returns the numeric value 90.

Function OnLButtonDblClk ( )MsgBox Asc("Z")MsgBox Asc(Mid$("XYZ",3,1))MsgBox Asc(UCase$("zebra"))

End Function

Returns Integer between 0 and 65535.

Rule: The return value is the character code value produced by converting <string expression> from Unicode to Multibyte character set (MBCS) using the current run time encoding.

Tips ■ To translate an ANSI code number to its corresponding character, use Chr$.

■ If the run time encoding is UCS-2, Asc behaves in the same way as AscW.

Example The following example prompts the user for his or her name and displays the ANSI value of each letter in that name:

Function OnLButtonDblClk ( )Dim I, Msg, NL, UserNameNL = Chr$(10)UserName = InputBox$("Please type your name.")For I = 1 To Len(UserName)

Msg = Msg & Mid$(UserName, I, 1) & " ---> "

Page 43: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 19

A s c W f u n c t i o n

Msg = Msg & Asc(Mid$(UserName, I, 1)) & NLNext IMsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also AscW functionChr, Chr$ functionsChrW, ChrW$ functions

AscW functionReturns the code point of the given character in UCS-2 encoding.

Syntax AscW(<string expression>)

Parameters <string expression>String expression that represents a character to translate to a corresponding code point in UCS-2 encoding.

Rules:

■ If <string expression> is longer than one character, AscW translates only the first character.

Returns Integer between 0 and 65535.

■ If <string expression> evaluates to Null, AscW returns a Null.

Example The following example prompts the user for his or her name and displays the ANSI value of each letter in that name:

Function OnLButtonDblClk ( )Dim I, Msg, NL, UserNameNL = ChrW$(10)UserName = InputBox$("Please type your name.")For I = 1 To Len(UserName)

Msg = Msg & Mid$(UserName, I, 1) & " ---> "Msg = Msg & AscW(Mid$(UserName, I, 1)) & NL

Next IMsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also ChrW, ChrW$ functions

Page 44: Actuate Basic Reference

20 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

A s s e r t s t a t e m e n t

Assert statementHalts the program and displays an error message when a given condition is False.

Syntax Assert(<condition>)

Parameters <condition>Any numeric or string expression that can be evaluated. When <condition> evaluates to zero or Null, the condition is False, otherwise <condition> is True.

Description When <condition> is True, Assert does nothing. When False, Assert halts the program and displays an error message.

Tip Use Assert to trap errors.

Example The following example uses Assert to halt a program before a function attempts to divide a number by zero. This prevents the program from even attempting to perform the illegal operation:

Function PercentOf(num As Integer, denom As Integer) As IntegerAssert(denom <> 0)PercentOf = num * 100 / denom

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Erl functionErr functionError statementError, Error$ functionsOn Error statement

Atn functionGives the arctangent of a number.

Syntax Atn(<number>)

Parameters <number >Number, numeric expression, or Variant of VarType 8 (String) that specifies, in radians, the ratio for which you want to find the arctangent. The ratio is the length of the side opposite the angle divided by the length of the side adjacent to the angle.

Page 45: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 21

A t n f u n c t i o n

Rule: If <number> is a String, it is parsed according to the formatting rules of the current run time locale.

Example: The following statement returns 123.456 on a French run time locale and 123456.00 on an English run time locale:

Atn("123,456") returns

Returns Double

■ If <number> evaluates to Null, Atn returns a Null.

Tip To convert between radians and degrees, use radians = degrees * Pi/180.

Example The following example prompts the user for a trigonometric angle expressed in radians, and returns the value of that angle in degrees and the arctangent of the angle. The Do ... Loop structure traps errors, such as blank, Null, or non-numeric input, by repeating the user prompt until no error condition exists:

Function OnLButtonDblClk( )

Dim dblUserInput As Double, dblDegree As DoubleDim ValidFlag As Boolean, strMsg As String, strNL As StringstrNL = Chr$(10)

DoValidFlag = True'Get user inputdblUserInput = InputBox("Type an angle in radians")'Trap Nulls, zeros, and non-numeric stringsIf (IsNull(dblUserInput)) Or (dblUserInput= 0) Then

ValidFlag = FalseEnd If

Loop While ValidFlag = False

strMsg = "You entered " & dblUserInput & " radians," & strNL'Convert to degree formatdblDegree = dblUserInput * (180/Pi)

strMsg = strMsg & "or " & dblDegree & " degrees." & strNLstrMsg = strMsg & "The arctangent is " & Atn(dblUserInput) & strNLMsgBox strMsg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Cos functionSin functionTan function

Page 46: Actuate Basic Reference

22 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

B e e p s t a t e m e n t

Beep statementSounds a short tone through the computer’s speaker.

Syntax Beep

Rules ■ You cannot control the tone or the duration of the sound using Beep.

■ Sound must be turned on in the sounds section of the Windows Control Panel.

Example The following example prompts the user for a number. If the number falls outside a certain range recognized as valid, the computer beeps and displays a message:

Function OnLButtonDblClk ( )Dim UserAns, MsgDo

UserAns = InputBox("Please enter a value from 1 to 5.")If UserAns >= 1 And UserAns <= 5 Then ' Validate range

Exit DoElse

Beep ' Beep if not in rangeMsgBox "Sorry, that number is out of range!"

End IfLoopMsgBox "Thank you!"

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

Call statementTransfers program control to an Actuate Basic Sub procedure or to a Windows dynamic-link library (DLL) procedure.

Syntax [Call] <procedure name> [(<argument list>)]

Parameters CallOptional keyword that indicates that Actuate Basic is to transfer program control to another procedure.

<procedure name>Specifies the name of the procedure to which the program is to transfer control.

Page 47: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 23

C a l l s t a t e m e n t

<argument list>List of variables, arrays, or expressions to pass to the procedure as arguments.

Default: Arguments in list are passed by reference.

Tip: To pass an entire array, use its name followed by empty parentheses.

Examples:The following statement transfers control to a Sub procedure called ManyBeeps and passes the value 15 to it as an argument:

Call ManyBeeps (15)

The following statement transfers control to a Sub procedure called ManyBeeps and passes the value 15 to it as an argument, but without using the Call keyword:

ManyBeeps (15)

The following statement transfers control to a Sub procedure called MySortArray, and passes the integer array NewColors% to it:

Call MySortArray (NewColors%( ))

Description ■ You are never required to use the Call keyword when you call a procedure.

■ You pass variable arguments to <procedure name> in two ways, by reference or by value.

■ When you pass variables by reference, Actuate Basic assigns their contents (values) actual addresses. The called procedure can alter the variables.

■ When you pass variables by value, Actuate Basic assigns their contents (values) temporary addresses. The called procedure cannot alter the contents of the variables.

Rule If you use the Call keyword to call a procedure that requires arguments, <argument list> must be enclosed in parentheses.

Tip If you are having trouble passing arguments to DLL procedures, use the ByVal keyword to pass them by value. In many cases, external DLL routines might not support all Actuate Basic data types, and using ByVal to call such a DLL routine allows the routine to convert the arguments so that it can accept them.

Example The example shows two ways you can call the MessageBeep procedure in User.exe, a Microsoft Windows DLL. First, you must declare the procedure MessageBeep from the Windows dynamic link library at or near the beginning of your Actuate Basic source code (.bas) file:

Declare Sub MessageBeep Lib "User32" (ByVal N As Integer)

Page 48: Actuate Basic Reference

24 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

C C u r f u n c t i o n

Then type this example in the Method Editor:

Function OnLButtonDblClk ( )Dim I As IntegerCall MessageBeep(0) ' Call Windows procedureFor I = 1 To 500: Next I ' Insert delay between callsMessageBeep (0) ' Call again without Call keyword

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Declare statement

CCur functionConverts a numeric expression to the Currency data type.

Syntax CCur(<numeric expression>)

Parameters <numeric expression>Numeric expression to convert from the Date, Integer, Long, Single, Double, String, or Variant data type to the Currency data type.

Rules:

■ If <numeric expression> is Null, CCur returns Null.

■ If <numeric expression> is a String or Variant, it must be interpretable as a number.

■ If <numeric expression> is a String, it is parsed according to the formatting rules of the current run time locale.

Examples:Each of the following statements returns 123. In the second statement, the string 123 enclosed in double quotes is considered a numeric expression because it can be interpreted as a number. In the third statement, four cannot be interpreted as a number:

CCur(123)CCur("123")CCur("123four")

The following statement first converts the string 123four using Val to convert the number 123. Val ignores the string component (four):

CCur(Val("123four"))

Page 49: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 25

C C u r f u n c t i o n

The following statement returns 123.456 on a French run time locale and 123456.00 on an English run time locale:

CCur("123,456")

Returns Currency

■ One of eight Actuate Basic data type conversion functions.

■ If <numeric expression> lies outside the acceptable range for Currency, an overflow error occurs.

Tips ■ To convert an expression to currency without explicitly using CCur, assign the expression to a variable that is the Currency data type.

■ To declare the data type of a variable, use Dim with the As clause.

■ To declare the data type of a variable dynamically—without using Dim or one of the conversion functions—append the data type declaration character to the variable’s name. For example, if you want a variable Income to contain only Currency data, refer to it as Income@. If you want it to contain only Integer data, refer to it as Income%.

■ To round a number to precisely the number of decimal places you want and discard anything residual, use Format$.

■ To be sure you pass the correct data type to a Sub procedure or to a Windows Dynamic Link Library (.dll), use data type conversion functions.

Example The following example prompts the user for a number, converts that number using each of the conversion functions in turn, and displays the result:

Function OnLButtonDblClk()Dim Orig As String, Msg As String, NL As StringNL = Chr$(10)Orig = InputBox$("Please enter a number.")Msg = "Your number is: " & Orig & NL & NLMsg = Msg & "CCur(Orig) yields ----> " & CCur(Orig) & NLMsg = Msg & "CDate(Orig) yields ----> " & CDate(Orig) & NLMsg = Msg & "CDbl(Orig) yields ----> " & CDbl(Orig) & NLMsg = Msg & "CInt(Orig) yields ----> " & CInt(Orig) & NLMsg = Msg & "CLng(Orig) yields ----> " & CLng(Orig) & NLMsg = Msg & "CSng(Orig) yields ----> " & CSng(Orig) & NLMsg = Msg & "CStr(Orig) yields ----> " & CStr(Orig) & NLMsg = Msg & "CVar(Orig) yields ----> " & CVar(Orig) & NLMsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

Page 50: Actuate Basic Reference

26 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

C D a t e f u n c t i o n

See also CDate functionCInt functionCInt functionCLng functionCSng functionCStr functionCVar functionCVDate functionFormat, Format$ functions

CDate functionConverts an expression to a Date.

Syntax CDate(<date expression>)

Parameters <date expression>Date expression, or any numeric or string expression that can be interpreted as a date, a time, or both a date and a time:

■ Can be a string such as November 12, 1982 8:30 P.M., 12 Nov., 1982 08:30 PM, 11/12/82, 08:30pm, or any other string that can be interpreted as a date, a time, or both a date and a time in the valid range.

■ Can be a date serial number such as 30267.854, which corresponds to November 12, 1982 at 8:30 P.M., or any other number that can be mapped to a date, time, or both a date and a time in the valid range.

■ For date serial numbers, the integer component represents the date itself while the decimal component represents the time of day on that date, where January 1, 1900 at precisely noon has the date serial number 2.5, and negative numbers represent dates prior to December 30, 1899 (0).

Default date if none specified: 0 (Dec. 30, 1899)Default time if none specified: 00:00:00 (midnight)

Rules:

■ <date expression> must not be empty or zero-length.

■ <date expression> cannot contain a day of week.

■ <date expression> must specify a date within the range January 1, 100 through December 31, 9999, inclusive.

■ <date expression> is parsed according to the formatting rules of the current run time locale.

Page 51: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 27

C D a t e f u n c t i o n

■ If <date expression> includes a time of day, it must be a valid time, even if CDate is not being used to return anything having to do with a time of day. A valid time is one that is in the range 0:00:00 (12:00:00 A.M.) through 23:59:59 (11:59:59 P.M.). Either the 12- or 24-hour clock can be used. The time must be in one of the following formats:

hh:mm:ss

hh:mm

hh

■ <date expression> cannot include a day of week.

■ If <date expression> is a numeric expression, it must be in the range -657434 to +2958465, inclusive.

The following assumes that the AC_CENTURY_BREAK property is set to the default value of 30. For information about using AC_CENTURY_BREAK, see Chapter 7, “Using a query data stream,” in Developing Advanced e.Reports.

■ For abridged date expressions ending in 00 through 29 that do not specify the century, relevant date functions estimate the unabridged year by adding 2000. For example, while Year(4/30/1910) returns 1910, the abridged expression Year(4/30/10) returns 2010 (10 + 2000).

■ For abridged date expressions ending in 30 through 99 that do not specify the century, relevant date functions estimate the unabridged year by adding 1900. For example, while Year(11/12/2082) returns 2082, the abridged expression Year(11/12/82) returns 1982 (82 + 1900).

Note that there are abridged dates like Nov. 12, 1982 as opposed to November 12, 1982, that do specify the century. Note also that both abridged and unabridged dates are dates ending in 00 through 99.

Examples:The following statements are equivalent. Each assigns 11/12/82 8:30:00 P.M., with its underlying serial number to the variable BDate:

BDate = CDate("11/12/82 8:30 pm")BDate = CDate("12 Nov 1982 20:30")BDate = CDate("November 12, 1982 8:30PM")BDate = CDate(30267.854167)

Returns Date

■ If <date expression> is Null, CDate returns a Null.

■ If <date expression> contains a day of week, CDate returns a Null.

■ If <date string> contains only numbers separated by valid date separators, CDate recognizes the order for month, day, and year according to the settings of the current run time locale.

■ If <date expression> cannot be evaluated to a date, CDate returns a Null.

Page 52: Actuate Basic Reference

28 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

C D a t e f u n c t i o n

■ If <date expression> fails to include all date components, such as day, month, and year, CDate returns a Null.

■ If <date expression> contains only the time and the time is valid, CDate returns December 30, 1899 with the time.

Rules ■ Do not use CDate to convert a long date format that also contains a day-of-the-week string, like Friday, Nov. 12, 1982, the function does not recognize such strings as dates.

■ Avoid supplying CDate with a date in a format other than the format the locale map specifies.

Tips ■ To determine if either a numeric or string expression that looks like a date can be converted to a date, use IsDate. However, IsDate cannot determine whether or not a string that looks like a number can be converted to a date, even if the number is in the correct range for date serial numbers.

■ If you use a date expression in one locale, it might be misinterpreted in another locale. For instance, in the United States, 1/2/2005 means January 2nd, 2005, but in France, it means February 1st, 2005. To avoid such ambiguities, use DateSerial to specify all dates.

Example The following example prompts the user for a date, date and time, a time, or a date serial number. For any valid entry, it displays both a date and a date serial number:

Function OnLButtonDblClk()Dim NL As String, DateMeme As String, ConvDateMeme As DateDim Msg As StringNL = Chr$(10)Msg = "Please type a date, a date and time, "Msg = Msg & "a time, or a date serial number."DateMeme = InputBox(Msg)ConvDateMeme = CDate(DateMeme)MsgBox "The date you gave me was: " & ConvDateMeme & NLMsgBox "The serial number for that date is: " & CDbl(ConvDateMeme)

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also CCur functionCInt functionCInt functionCLng functionCSng functionCStr functionCVar function

Page 53: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 29

C D b l f u n c t i o n

CVDate functionFormat, Format$ functionsIsDate function

CDbl functionConverts a numeric expression to the Double data type.

Syntax CDbl(<numeric expression>)

Parameters <numeric expression>Numeric expression to be converted from the Currency, Date, Integer, Long, Single, String or Variant data type to the Double data type.

Rules:

■ If <numeric expression> is a String or Variant, it must be interpretable as a number.

■ If <numeric expression> is a String, it is parsed according to the formatting rules of the current run time locale.

Examples:Each of the following statements returns the value 123. In the second statement, the string 123 enclosed in double quotes is considered a numeric expression because it can be interpreted as a number. In the third statement, four cannot be interpreted as a number:

CDbl(123)CDbl("123")CDbl("123four")

The following statement uses Val to convert the string 123four to the number 123. Val ignores the string component (four):

CDbl(Val("123four"))

The following statement returns 123.456 on a French run time locale and 123456.00 on an English run time locale:

CDbl("123,456") returns

Returns Double

■ One of nine data type conversion functions.

■ If <numeric expression> lies outside the acceptable range for a Double data type, an overflow error occurs.

■ If <numeric expression> is Null, CDbl returns a Null.

Page 54: Actuate Basic Reference

30 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

C D b l f u n c t i o n

Tips ■ To convert an expression to double without explicitly using CDbl, assign the expression to a variable that is the Double data type.

■ To declare the data type of a variable, use Dim with the As clause.

■ To declare the data type of a variable dynamically—without using Dim or one of the conversion functions—append the data type declaration character to the variable’s name. For example, if you want a variable called Income to contain only Currency data, refer to it as Income@. If you want it to contain only Double type data, refer to it as Income#.

■ To round a number to precisely the number of decimal places you want and discard anything residual, use Format$().

■ To be sure you pass the correct data type to a subprocedure or to a Windows Dynamic Link Library (DLL), use data type conversion functions.

Example The following example prompts the user for a number, converts that number using each of the conversion functions in turn, and displays the result:

Function OnLButtonDblClk()Dim Orig As String, Msg As String, NL As StringNL = Chr$(10)Orig = InputBox$("Please enter a number.")Msg = "Your number is: " & Orig & NL & NLMsg = Msg & "CCur(Orig) yields ----> " & CCur(Orig) & NLMsg = Msg & "CDate(Orig) yields ----> " & CDate(Orig) & NLMsg = Msg & "CDbl(Orig) yields ----> " & CDbl(Orig) & NLMsg = Msg & "CInt(Orig) yields ----> " & CInt(Orig) & NLMsg = Msg & "CLng(Orig) yields ----> " & CLng(Orig) & NLMsg = Msg & "CSng(Orig) yields ----> " & CSng(Orig) & NLMsg = Msg & "CStr(Orig) yields ----> " & CStr(Orig) & NLMsg = Msg & "CVar(Orig) yields ----> " & CVar(Orig) & NLMsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also CCur functionCDate functionCInt functionCLng functionCSng functionCStr functionCVar functionCVDate functionDim statement

Page 55: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 31

C h D i r s t a t e m e n t

Format, Format$ functionsFormat, Format$ functionsInt function

ChDir statementChanges the current working directory on the specified or current drive.

Syntax ChDir <path name>

Parameters <path name>String expression that specifies the name of the target directory.

Rules:

■ <path name> must contain fewer than 259 characters.

■ <path name> must be a valid directory.

<path name> has the following syntax:[<drive:>] [\] [<directory>\<directory>]... (Windows)[/] [<directory>/<directory>]... (UNIX)

<drive:>Character, followed by a colon, that specifies the drive (Windows only.)

<directory>String expression of the name of the directory or subdirectory to make the current directory.

Examples:The following statement changes the current working directory on drive D: to Mydocs, even if the current drive is C:, but does not change the current drive to D:

ChDir "D:\Mydocs"

Together, the following two statements change the current directory on the current drive to \Myfiles\Mailbox:

DirName$ = "\Myfiles\Mailbox"ChDir DirName$

Description ■ If you do not specify <drive:>, ChDir uses the current drive.

■ If you specify a drive other the than current one, Actuate Basic only changes the current directory on that drive; it does not change the current drive to <drive:>.

Page 56: Actuate Basic Reference

32 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

C h D r i v e s t a t e m e n t

Tips ■ To make sure you have set the correct working directory before you issue commands that do not specify full path names, use ChDir.

■ To change the current drive, use ChDrive.

■ ChDir affects the operation of file-related commands like Open and Kill, which use the current working, or default, drive and directory unless you specify a full path name.

Example The following example changes the current directory to the root, then changes it back to whatever it was originally:

Function OnLButtonDblClk()Dim UserAns As Integer, Msg As String, NL As String, UsersPath As StringNL = Chr$(10) ' Define newlineUsersPath = CurDir ' Save the current pathChDir "\" ' Reset to a new pathMsg = "The current directory has been changed to "Msg = Msg & CurDir & NL & NLMsg = Msg & "Press OK to change back "Msg = Msg & "to the previous current directory."UserAns = MsgBox(Msg) ' Get user responseChDir UsersPath ' Change back to user default directoryMsg = "The current directory has been reset to " & UsersPath & "."MsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also ChDrive statementCurDir, CurDir$ functionsMkDir statementRmDir statement

ChDrive statementChanges the current default drive.

Syntax ChDrive <drive letter>

Parameters <drive letter>String expression, consisting of a single letter that specifies the drive that is to become the default drive (Windows only).

Rules:

■ <drive letter> must correspond to the letter of a valid drive.

Page 57: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 33

C h D r i v e s t a t e m e n t

■ <drive letter> must be in the range A to <lastdrive>, where <lastdrive> is the maximum drive letter in your computer.

Examples:The following statement changes the current working (default) drive to A:

ChDrive "A"

Together, the following two statements change the current drive to C:

DriveSpec$ = "C"ChDrive DriveSpec$

Tips ■ To ensure that you have set the correct working directory before you issue commands that do not specify full path names, use ChDir.

■ To change the current directory, use ChDir.

■ To determine the current drive and directory, use CurDir.

■ ChDir and ChDrive affect the operation of file-related commands like Open and Kill, which use the current working, or default, drive and directory unless you specify a full path name.

■ ChDrive is ignored when the Basic program is running on UNIX.

Example The following example changes the default directory to a drive the user specifies. If it cannot change the directory, it responds with an error message:

Function OnLButtonDblClk()On Error Resume NextDim CurrPath As String, Drive As StringDim HasColon As Integer, Msg As StringDim NewDrive As String, NL As StringNL = Chr$(10) ' Define new lineCurrPath = CurDir ' Get current pathIf Err = 68 Then ' If current drive

Drive = "Invalid" ' is invalidErr = 0 ' Reset error to 0

ElseDrive = Left(CurrPath, 2) ' Get drive letter

End IfMsg = "Your current drive is "& Drive & ". "Msg = Msg & "Please type the letter of another drive "Msg = "to make it the current drive."NewDrive= InputBox(Msg) ' Prompt for new driveHasColon = InStr(1, NewDrive, ":") ' Check for colonIf Not HasColon Then ' If there is no colon, append one

NewDrive = Left$(NewDrive, 1) & ":"End IfChDrive NewDrive ' Change driveSelect Case Err

Page 58: Actuate Basic Reference

34 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

C h r , C h r $ f u n c t i o n s

Case 44 ' Device unavailable errorMsg = "Sorry, that drive is not available. "Msg = Msg & "No drive change was made."

Case 71 ' Disk not ready errorMsg = "Please close the door on your drive and try again"

Case 10 ' Illegal function callMsg = "Sorry, you probably did not type a drive letter. "Msg = Msg & "No drive change was made."

Case ElseMsg = "Drive changed to " & UCase$(NewDrive)

End SelectMsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also ChDir statementCurDir, CurDir$ functionsMkDir statementRmDir statement

Chr, Chr$ functionsReturns the character that corresponds to the specified character code in the current run time encoding.

Syntax Chr(<character code>)

Chr$(<character code>)

Parameters <character code>A numeric expression that represents the character code you want Chr[$] to translate to a character.

Rules:

■ If <character code> is not an Integer, Chr[$] rounds it to the nearest Integer before returning the character. In the United States, <character code> usually refers to ANSI codes.

■ <character code> must be between 0 and 65535.

■ <character code> is interpreted according to the current run time encoding.

Examples:

Chr$(65) returns AChr$(227) returns γ on a Greek locale

Page 59: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 35

C h r , C h r $ f u n c t i o n s

Chr$(5, 227) returns ä on an English localeChr$(Sqr(4) * 45) returns ZChr$(90.11) returns Z

The following statement prints or displays the copyright symbol (©):

Chr$(169)

Returns Chr: VariantChr$: String

■ Chr$ returns nonprintable as well as printable characters.

■ Character codes from 0 to 31, inclusive, are the same as the standard, nonprintable ASCII codes.

■ Character codes 8, 9, 10, and 13 convert, respectively, to backspace, tab, linefeed, and carriage return characters. You cannot see them graphically. Depending on the application, they can affect the visual display of text.

Tips ■ To force a message either to start or to continue to print on a new line, use Chr$(10), which inserts the linefeed character.

■ To insert double quotes (“) inside a message, use Chr$(34).

■ To send special control codes to your printer or to another device, use Chr$ with a print statement directed to that device.

■ To translate from a character to its character code number, use Asc.

■ If the run time encoding is UCS-2, Chr behaves in the same way as ChrW.

Example The following example returns the character corresponding to the number the user types. It also shows the use of the nonprintable newline character represented by Chr$(10). The example displays the user-selected character, if it can be displayed at all, on a new line by itself:

Function OnLButtonDblClk()Dim AnsiNum As Integer, NL As String, Msg As StringNL = Chr$(10) ' Define newlineAnsiNum = InputBox("Please type a number between 0 and 255.")Msg = "The character that corresponds to " & AnsiNum & " is this:"Msg = Msg & NL ' Insert newlineMsg = Msg & Chr$(AnsiNum) ' Show character by itselfMsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Asc functionAscW functionChrW, ChrW$ functions

Page 60: Actuate Basic Reference

36 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

C h r W , C h r W $ f u n c t i o n s

ChrW, ChrW$ functionsTranslates a UCS-2 code value into a character.

Syntax ChrW(<character code>)

Chrw$(<character code>)

Parameters <character code>A numeric expression that represents the character code in UCS-2 you want ChrW[$] to translate to a character.

Rules:

■ <character code> must be a valid UCS-2 code.

■ If <character code> is not an Integer, ChrW[$] rounds it to the nearest Integer before returning the character. In the United States, <character code> usually refers to ANSI codes.

■ <character code> must be between 0 and 65535.

Example:

The following statement returns A:

ChrW$(65)

The following statement returns γ:

ChrW(947)

Returns ChrW: VariantChrW$: String

Example The following example returns the character corresponding to the number the user types. It also shows the use of the nonprintable newline character represented by ChrW$(10). The example displays the user-selected character, if it can be displayed at all, on a new line by itself:

Function OnLButtonDblClk()Dim AnsiNum As Integer, NL As String, Msg As StringNL = ChrW$(10) ' Define newlineAnsiNum = InputBox("Please type a number between 0 and 255.")Msg = "The character that corresponds to " & AnsiNum & " is this:"Msg = Msg & NL ' Insert newlineMsg = Msg & ChrW$(AnsiNum) ' Show character by itselfMsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also AscW function

Page 61: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 37

C I n t f u n c t i o n

CInt functionConverts a numeric expression to the Integer data type.

Syntax CInt(<numeric expression>)

Parameters <numeric expression>Numeric expression to convert from the Currency, Date, Double, Long, Single, String, or Variant data type to the Integer data type.

Rules:

■ If <numeric expression> is Null, CInt returns a Null.

■ If <numeric expression> is a String or Variant, it must be interpretable as a number.

■ If <numeric expression> is a String, it is parsed according to the formatting rules of the current run time locale.

Examples:Each of the following statements returns 123. In the second statement, the string 123 enclosed in double quotes is considered a numeric expression because it can be interpreted as a number. In the third statement, four cannot be interpreted as a number:

CInt(123)CInt("123")CInt("123four")

The following statement first converts the string 123four using Val to convert the number 123. Val ignores the string component (four):

CInt(Val("123four"))

The following statement returns 123.456 on a French run time locale and 123456.00 on an English run time locale:

CInt("123,456")

Returns Integer

■ One of eight Actuate Basic data type conversion functions.

■ CInt rounds the fractional part of <numeric expression>, while Fix and Int truncate it.

■ If the fractional part of <numeric expression> is exactly 0.5, CInt rounds to the nearest even number.

CInt(1.5) = 2CInt(2.5) = 2CInt(0.5) = 0

Page 62: Actuate Basic Reference

38 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

C I n t f u n c t i o n

■ If <numeric expression> lies outside the acceptable range for an Integer, an overflow error occurs.

Tips ■ To convert an expression to an Integer without using CInt, assign the expression to a variable that is the Integer data type.

■ To declare the data type of a variable, use Dim with the As clause.

■ To declare the data type of a variable dynamically—without using Dim or one of the conversion functions—append the data type declaration character to the variable’s name. For example, if you want a variable called Income to contain only Currency data, refer to it as Income@. If you want it to contain only Integer data, call it Income%.

■ To round a number to precisely the number of decimal places you want and discard anything residual, use Format$.

■ To be sure you pass the correct data type to a sub procedure or to a Windows Dynamic Link Library (.dll), use data type conversion functions.

Example The following example prompts the user for a number, converts that number using each of the conversion functions in turn, and displays the result:

Function OnLButtonDblClk()Dim Orig As String, Msg As String, NL As StringNL = Chr$(10)Orig = InputBox$("Please enter a number.")Msg = "Your number is: " & Orig & NL & NLMsg = Msg & "CCur(Orig) yields ----> " & CCur(Orig) & NLMsg = Msg & "CDate(Orig) yields ----> " & CDate(Orig) & NLMsg = Msg & "CDbl(Orig) yields ----> " & CDbl(Orig) & NLMsg = Msg & "CInt(Orig) yields ----> " & CInt(Orig) & NLMsg = Msg & "CLng(Orig) yields ----> " & CLng(Orig) & NLMsg = Msg & "CSng(Orig) yields ----> " & CSng(Orig) & NLMsg = Msg & "CStr(Orig) yields ----> " & CStr(Orig) & NLMsg = Msg & "CVar(Orig) yields ----> " & CVar(Orig) & NLMsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also CCur functionCDate functionCInt functionCLng functionCSng functionCStr functionCVar function

Page 63: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 39

C l a s s s t a t e m e n t

CVDate functionDim statementFormat, Format$ functionsFormat, Format$ functionsInt function

Class statementDeclares and defines a class in Actuate Basic.

Syntax Class <name of class> [Subclass Of <name of superclass>]...[,<name of superclass>...]]

<variable(s)>

<nested class(es)>

<method(s)>

End Class

Parameters <name of class>The name you assign to the class.

Rule: You must supply a class name.

<Subclass Of <name of superclass>>Specifies a superclass from which this class can be derived.

<variable(s)>Variable belonging to the class. A class can contain any number of variables using one of the following declarations styles.

Dim <variable> [([<subscripts>])] [As <data type>]Defines an instance variable. Each instance of your class has a copy of each instance variable.

Static <variable> [([<subscripts>])] [As <data type>]Defines a static variable. All instances of this class and all instances of derived classes share a single copy of the variable.

<variable>Name of the variable to declare.

As <data type>Clause that declares the data type of <variable>.

Page 64: Actuate Basic Reference

40 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

C l e a r C l i p b o a r d f u n c t i o n

Rule: <data type> can specify any valid Actuate Basic data type, user-defined data type, or class name, for example:

Dim SalesTax Customer As String, Amount As Currency

<nested class(es)>Any number of other class definitions. Actuate automatically creates nested classes for controls within frames, and for sections and frames within the report object.

<method(s)>Procedure that performs actions on the objects of the class. Your class can contain any number of methods. Each method is defined using the Sub or Function statements.

Tip Class statements can be recursive. Actuate Basic sets a run-time stack limit of 200. A report using recursion with a large number of iterations might exceed this limit.

See also Dim statementFunction...End Function statementStatic statementSub...End Sub statement

ClearClipboard functionClears the contents of the operating environment Clipboard.

Syntax ClearClipboard( )

Returns Integer

■ Returns 1 (True) if the Clipboard was successfully cleared.

■ Returns 0 (False) if the Clipboard could not be cleared.

Example The following example places the current date on the Clipboard and then displays the contents of the Clipboard:

Function OnLButtonDblClk ( )Dim Msg As String, UserContent, DoMoreOn Error Resume NextMsg = "The Clipboard currently contains: " & GetClipboardText()MsgBox MsgMsg = "Choose OK to load today's date onto the Clipboard."MsgBox Msg

Page 65: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 41

C L n g f u n c t i o n

ClearClipboard()SetClipboardText(Format$(Date, "dddd, mm/dd/yyyy"))Msg = "Today's date is on the Clipboard. Choose OK to get the "Msg = Msg & "date back from the Clipboard and put it in a message."MsgBox Msg

Msg = GetClipboardText()MsgBox "The Clipboard currently contains: " & MsgDoMore = MsgBox("Put something else on the clipboard?", MB_YESNO)If DoMore = IDNO Then

MsgBox "The date is still on the Clipboard."Else

UserContent = InputBox("Put what?")SetClipboardText(UserContent)

End IfMsgBox "The Clipboard currently contains: " & GetClipboardText()

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also GetClipboardText functionSetClipboardText function

CLng functionConverts a numeric expression to the Long data type.

Syntax CLng(<numeric expression>)

Parameters <numeric expression>Numeric expression to convert from the Currency, Date, Double, Integer, Single, String, or Variant data type to the Long (Long integer) data type.

Rules:

■ If String or Variant, <numeric expression> must be interpretable as a number.

■ If <number expression> is a String, it is parsed according to the formatting rules of the current run time locale.

Examples:Each of the following statements returns the value 123. In the second statement, the string 123 enclosed in double quotes is considered a numeric expression because it can be interpreted as a number:

CLng(123)CLng("123")

Page 66: Actuate Basic Reference

42 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

C L n g f u n c t i o n

The following statement generates an error. The string 123four is not considered a numeric expression because four cannot be interpreted as a number:

CLng("123four")

The following statement first converts the string 123four using Val to convert the number 123. Val ignores the string component (four):

CLng(Val("123four"))

The following statement returns 123.456 on a French run time locale and 123456.00 on an English run time locale:

CLng("123,456")

Returns Long

■ One of eight Actuate Basic data type conversion functions.

■ If <numeric expression> lies outside the acceptable range for a Long data type, an overflow error occurs.

■ If <numeric expression> is Null, CLng returns a Null.

Tips ■ To convert an expression to long without using CLng, assign the expression to a variable that is the Long data type.

■ To declare the data type of a variable, use Dim with the As clause.

■ To declare the data type of a variable dynamically—without using Dim or one of the conversion functions — append the data type declaration character to the variable’s name. For example, if you want a variable called Income to contain only currency data, refer to it as Income@. If you want it to contain only Long data, refer to it as Income&.

■ To round a number to precisely the number of decimal places you want and discard anything residual, use Format$.

■ To be sure you pass the correct data type to a sub procedure or to a Windows Dynamic Link Library (.dll), use data type conversion functions.

Example The following example prompts the user for a number, converts that number using each of the conversion functions in turn, and displays the result:

Function OnLButtonDblClk()Dim Orig As String, Msg As String, NL As StringNL = Chr$(10)Orig = InputBox$("Please enter a number.")Msg = "Your number is: " & Orig & NL & NLMsg = Msg & "CCur(Orig) yields ----> " & CCur(Orig) & NLMsg = Msg & "CDate(Orig) yields ----> " & CDate(Orig) & NLMsg = Msg & "CDbl(Orig) yields ----> " & CDbl(Orig) & NLMsg = Msg & "CInt(Orig) yields ----> " & CInt(Orig) & NLMsg = Msg & "CLng(Orig) yields ----> " & CLng(Orig) & NL

Page 67: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 43

C l o s e s t a t e m e n t

Msg = Msg & "CSng(Orig) yields ----> " & CSng(Orig) & NLMsg = Msg & "CStr(Orig) yields ----> " & CStr(Orig) & NLMsg = Msg & "CVar(Orig) yields ----> " & CVar(Orig) & NLMsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also CCur functionCDate functionCInt functionCInt functionCSng functionCStr functionCVar functionCVDate functionDim statementFormat, Format$ functions

Close statementConcludes input/output to a file.

Syntax Close [ [#] <open file number> ] ... [, [#] <open file number> ] . . .

Parameters <open file number>Numeric expression for the number you used in a previously issued Open statement that opened the target file to be closed.

Default: All open files are closed.

Examples:The following statement closes the file previously opened as #1:

Close #1

The following statement closes the files opened as 1, 5, and 7:

Close 1, 5, 7

The following statement closes all open files:

Close

Description ■ If you use Close for a file that was opened for Output or Append, Actuate Basic flushes the buffers associated with the file and writes any remaining data in them to disk.

Page 68: Actuate Basic Reference

44 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

C l o s e s t a t e m e n t

■ The association of a file with <open file number> ends when Close is executed. You can then reopen the file using the same or a different file number, or you can reuse the file number to open a different file.

■ Once a file has been closed, the file number cannot be referenced by any other file-related statements (such as Get or Put) until you issue another Open with that file number.

■ If <open file number> does not refer to a currently open file, Actuate Basic ignores the Close statement and continues with the next command.

■ Close with no arguments closes all open files.

■ Actuate Basic automatically closes all open files at program termination, whether or not you use Close.

Tip You should close each open file before ending your program.

Example The following example generates three test files on disk by opening the test files, writing to the test files, and closing the test files. In this example OnLButtonDblClk( ) is overridden to generate the three test files and prompt the user to delete the test files. The procedure Make3Files( ) should be typed after the End Function of the OnLButtonDblClk( ) procedure or saved in an Actuate Basic source code (.bas) file:

Function OnLButtonDblClk()Dim Msg As StringMake3Files ' Create test filesMsg = "Three test files have been created on your disk. "Msg = Msg & "Choose OK to delete them."MsgBox MsgKill "TESTFIL?" ' Remove files from disk

End Function'' The following procedure creates the sample data files.Sub Make3Files()

Dim I As Integer, FreeNum As Integer, TestFileName As StringMsgBox "We are now in the Make3Files sub."For I = 1 to 3

FreeNum = FreeFile ' Get next free file handleTestFileName = "TESTFIL" & FreeNum' Opening the file automatically creates itOpen TestFileName For Output As FreeNumPrint # FreeNum, "This is a test file." ' Print one line of text in the file

Next IClose ' Close all files

End Sub

For information about using the code examples, see “Using the code examples” earlier in this chapter.

Page 69: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 45

C o m m a n d , C o m m a n d $ f u n c t i o n s

See also Open statementReset statementStop statement

Command, Command$ functionsReturns the argument component of the command line of Designer.exe or Viewer.exe.

Syntax Command

Command$

In the following example, commandargs represents what Command returns if you launched Actuate Basic with the following command:

Designer.exe /CMD commandargsViewer.exe /CMD commandargs

The function returns commandargs Secondcomm 32, the launch argument—assuming you launched the application with the following command:

Viewer commandargs Secondcomm 32

Returns Command: VariantCommand$: String

Actuate Basic Compiler does not generate an .exe file. Instead, it generates an .rox file which either runs in the .rox compiler (the Factory), is built in the e.Report Designer Professional and the End User Desktop or through iServer.

Example The following example displays the command-line arguments of Viewer or Designer you are currently using:

Function OnLButtonDblClk()Dim Msg As StringIf Command = "" Then

Msg = "Sorry, no command-line arguments were "Msg = Msg & "used to launch this program."

ElseMsg = "The command-line string you passed to this "Msg = Msg & "program when you launched it is "Msg = Msg & Command

End IfMsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

Page 70: Actuate Basic Reference

46 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

C o n s t s t a t e m e n t

Const statementDeclares symbolic constants to be used in place of literal values.

Syntax Global Const <const name> = <exprs> [, <const name> = <exprs>]...

Parameters [Global]Keyword indicating that the <const name>s can be accessed by all procedures in the program.

<const name>Name of the constant to which the value of <exprs> is assigned.

Rule: Must follow standard variable naming conventions.

<exprs>Expression assigned to <const name>. Can consist of literals, other constants, or any arithmetic or logical operators.

Rules:

■ Cannot contain or use any of the following:■ Variables■ User-defined functions■ Intrinsic Actuate Basic functions such as Chr[$]

Description ■ Unlike a variable, a constant cannot be changed while your program is running.

■ You can use a constant anywhere you might use an expression.

■ The data type of <const name> is based on <exprs> if there is no type declaration postfix specified. A string <exprs> always yields a String <const name>, but a numeric <exprs> yields the simplest data type that can represent it once it has been evaluated.

■ A constant declared in a sub or function procedure is local to that procedure.

Rules ■ Const must be in a Declare section.

■ Any <const name> you use must be defined by Const before you can refer to it.

■ A constant cannot be a Variant, and its data type cannot change.

Tips ■ To simplify maintenance and debugging, put Global Const definitions in a single module.

■ To make constants easier to recognize when debugging, use all uppercase letters for your constant names.

Page 71: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 47

C o n v e r t B F i l e T o S t r i n g f u n c t i o n

■ To declare the data type of a constant, use a type declaration postfix like %, &, !, #, @, or $.

Example The following example defines the constant PI, prompts the user for a radius, then uses PI to compute the circumference and area of a circle. To use this example, paste this portion at or near the beginning of your Actuate Basic source code (.bas) file.

DeclareGlobal Const PI = 3.141592654 ' Define constant

End Declare

Then, enter this function into the Method Editor:

Function OnLButtonDblClk()Dim Area, Circum, Msg, RadiusMsg = "Please type the radius of a circle in centimeters."Radius = InputBox(Msg)Circum = 2 * PI * Radius ' Compute circumferenceArea = PI * (Radius ^ 2) ' Compute areaMsg = "The circumference of the circle is "Msg = Msg & Circum & " cm. Its area is "Msg = Msg & Area & " cm."MsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Dim statementGlobal statementLet statementStatic statement

ConvertBFileToString functionEncodes a binary image file into a string.

Syntax ConvertBFileToString(<filename>)

Parameters <filename>String expression that specifies the binary file to convert. Can include optional drive and path information.

Default path: Current default drive and directory.

Page 72: Actuate Basic Reference

48 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

C o n v e r t S t r i n g T o B F i l e f u n c t i o n

Rules for <filename>:

■ Cannot include wildcard characters.

■ Must refer to an existing file.

Example for <filename>:

ConvertBFileToString("image1.bmp")ConvertBFileToString(ROIimage1)

Returns String

Description Use ConvertStringToBFile to conditionally embed different images in your report instances—based upon different data or run-time parameters.

Use ConvertStringToBFile, and the complementary function ConvertBFileToString, to send the same report design to two different customers, A and B, and include image A in the report to A, and image B in the report to B. Instead of embedding either image in a given report, or creating two slightly different reports, you write conditional code in a single report. The instances of your report display different images at run time as required.

Rule ConvertBFileToString should be used only in conjunction with its complementary function, ConvertStringToBFile.

See also ConvertStringToBFile functionRoiimage example in the e.Report Designer Professional Examples\Roiimage directory

ConvertStringToBFile functionDecodes a string from Actuate’s internal representation back into a binary file.

Syntax ConvertStringToBFile(<stringval>)

Parameters <stringval>String expression that specifies the string to convert into a binary file, usually an image file.

Returns String

Description Use ConvertStringToBFile to conditionally embed different images in your report instances—based upon different data or run-time parameters.

Use ConvertStringToBFile, and the complementary function ConvertBFileToString, to send the same report design to two different customers, A and B, and include image A in the report to A, and image B in the report to B. Instead of embedding either image in a given report, or creating two slightly different reports, you write conditional code in a single report. The instances of your report display different images at run time as required.

Page 73: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 49

C o p y I n s t a n c e s t a t e m e n t

Rules ■ ConvertStringToBFile should be used only in conjunction with its complementary function, ConvertBFileToString.

■ The parameter you pass in (<stringval>) must be the return from the complimentary function ConvertBFileToString.

■ The returned file name is the name of the temporary file. Remove the temporary file when it is no longer needed.

Tip ConvertStringToBFile creates a temporary file. Be sure to include code that will clean up the temporary file after it is no longer needed.

See also ConvertBFileToString functionRoiimage example in the e.Report Designer Professional Examples\Roiimage directory

CopyInstance statementCopies the values of the variables from one instance to another instance, even when the classes of the two instances are unrelated.

Syntax CopyInstance(<source>, <destination>, <excludeProperty>)

Parameters <source>Any instance (object). The instance that contains the variables from which you want to copy values.

<destination>Any instance (object). The instance that contains the variables to which you want to copy the values from <source>.

The classes of the two instances do not need to be related.

CopyInstance matches variables on name and data type.

For example, in the case of a variable in <source> named Amount with type Currency, CopyInstance copies the variable’s value from <source> to <destination> only if <destination> has a variable with the same name and type.

CopyInstance ignores or skips variables that do not match on both name and data type.

<excludeProperty>String that specifies the properties to be excluded when copying an instance.

Rule Both the names and data types of the variables in <source> must match the names and data types of the corresponding variables in <destination>.

Page 74: Actuate Basic Reference

50 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

C o s f u n c t i o n

Tip CopyInstance is useful when you work with multi-input filters. CopyInstance simplifies writing complex data streams, for example, when creating a union.

See also SetBinding function

Cos functionReturns the cosine of an angle.

Syntax Cos(<angle>)

Parameters <angle>Number, numeric expression, or Variant of VarType 8 (String) that specifies, in radians, the ratio for which you want to find the cosine.

Rule: If <angle> is a String, it is parsed according to the formatting rules of the current run time locale.

Returns Double

■ If <angle> evaluates to Null, Cos returns a Null.

Tip To convert between radians and degrees, use: radians = degrees * Pi/180.

Example In the following example the user is prompted to enter an angle expressed in radians. The code then returns the cosine of the angle:

Function OnLButtonDblClk ( )Dim UserAnsUserAns = InputBox("Type a number representing an angle in radians")MsgBox "The cosine of " & UserAns & " is: " & Cos(UserAns)

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Atn functionSin functionTan function

CreateJavaClassHandle functionCreates a handle to a Java class.

Syntax CreateJavaClassHandle("<class identifier>")

Page 75: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 51

C r e a t e J a v a O b j e c t f u n c t i o n

Parameters <class identifier>java.lang.String expression that specifies the name of the Java class. The Java class must be located in a path defined in the CLASSPATH environment variable. If the class identifier contains a package name and a class name, only the class name is used in invoking the class constructor.

Returns A Basic object which is a handle to the Java class object if the method succeeded.

An undefined handle if the call failed.

Description Use CreateJavaClassHandle() to access static class fields and static class methods. You can also use CreateJavaClassHandle() to create an instance of the class by invoking a class constructor method via the class handle.

CreateJavaClassHandle() throws a user error for the following problems:

■ CLASSPATH environment variable not found

■ Java Virtual Machine not found or cannot be created

■ Class not found

■ Method or field not found

Example On the first line in the following example, the variable theClassHandle is declared as a type Object. On the second line, CreateJavaClassHandle is used to create the handle to the Java class java.lang.String and assign it to theClassHandle:

Dim theClassHandle As ObjectSet theClassHandle = CreateJavaClassHandle( "java.lang.String" )

The following example shows how to create a Java class handle and how to use that handle to invoke a constructor to create an instance of the class:

Dim theClassHandle As ObjectSet theClassHandle = CreateJavaClassHandle("java.lang.String")Dim theInstanceHandle As ObjectSet theInstanceHandle = theClassHandle.String( "Hello")

For information about using the code examples, see “Using the code examples” earlier in this chapter.

CreateJavaObject functionCreates an instance of a class without invoking a constructor.

Syntax CreateJavaObject("<class identifier>")

Page 76: Actuate Basic Reference

52 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

C r e a t e O b j e c t f u n c t i o n

Parameters <class identifier>String expression that specifies the name of the Java class. The Java class must be located in a path defined in the CLASSPATH environment variable. The class identifier must be either the class name or the class name and package name. The class identifier cannot contain a partial path.

Description CreateJavaObject() allocates an object of the given ClassIdentifier. The call does not invoke any constructor, including default constructor, of the class. Instance fields of the class are not initialized in the allocated object. To initialize the instance, either call an initialization method on the instance or invoke the constructor through a handle to the class.

CreateJavaObject() throws a user error for the following problems:

■ CLASSPATH environment variable not found

■ Java Virtual Machine not found or cannot be created

■ Class not found

■ Object creation failed

CreateJavaObject() cannot receive a Null instance.

Returns A Basic object which is a handle to the instance if the method succeeded.

An undefined handle if the call failed.

Example In the following example, the variable theObject is dimensioned as a type Object on the first line. On the second line, CreateJavaObject is used to create the Java object named "readfile" and assign it to theObject:

Dim theObject As ObjectSet theObject = CreateJavaObject("readfile")

For information about using the code examples, see “Using the code examples” earlier in this chapter.

CreateObject functionCreates an OLE Automation object.

Syntax CreateObject("<application name>.<object type>")

Parameters <application name>.<object type>String expression that specifies the name of the application providing the object as established in the registry.

Returns An instance of an OLE object.

Page 77: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 53

C S n g f u n c t i o n

Every application that supports OLE Automation provides at least one type of object. For example, a word-processing application might provide an application object, a document object, and a toolbar object.

Example:On the first line in the following example, the variable MyObject is declared as a type Object. On the second line, CreateObject is used to create the OLE Automation object that is assigned to MyObject:

Dim MyObject As ObjectSet MyObject = CreateObject("Wordproc.Document")

When you run this code, if the application that created the object, in this example Wordproc.exe, is not already running, Actuate Basic launches it and creates an object of the specified type.

Unlike what happens with a linked or embedded object using the OLE control, Actuate Basic does not display the object’s image anywhere, nor does it maintain its data.

Once you create an OLE object, reference it in Actuate Basic code using the object variable to which you assigned it. In the following example, the properties and methods of the new object are accessed using the object variable MyObject:

MyObject.BoldMyObject.Insert "Hello, world."MyObject.PrintMyObject.SaveAs "C:\Wordproc\Docs\Test.doc"

Tip To get a list of OLE Automation objects supported by an application, consult that application’s documentation.

CSng functionConverts a numeric expression to the Single data type.

Syntax CSng(<numeric expression>)

Parameters <numeric expression>Numeric expression to convert from the Currency, Date, Double, Integer, Long, String, or Variant data type to the Single (or single precision floating-point) data type.

Rules:

■ If <numeric expression> is a String or Variant, it must be interpretable as a number.

■ If <numeric expression> is a String, it is parsed according to the formatting rules of the current run time locale.

Page 78: Actuate Basic Reference

54 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

C S n g f u n c t i o n

Examples:Each of the following statements returns 123. In the second statement, the string 123 enclosed in double quotes is considered a numeric expression because it can be interpreted as a number:

CSng(123)CSng("123")

The following statement generates an error. The string 123four is not considered a numeric expression because four cannot be interpreted as a number:

CSng("123four")

The following statement first converts the string 123four using Val to convert the number 123. Val ignores the string component, four:

CSng(Val("123four"))

The following statement returns 123.456 on a French run time locale and 123456.00 on an English run time locale:

CSng("123,456")

Returns Single

■ One of eight Actuate Basic data type conversion functions.

■ If <numeric expression> lies outside the acceptable range for a Single data type, an overflow error occurs.

■ If <numeric expression> is Null, CSng returns a Null.

Tips ■ To convert an expression to single without using CSng, assign the expression to a variable that is the Single data type.

■ To declare the data type of a variable, use Dim with the As clause.

■ To declare the data type of a variable dynamically—without using Dim or one of the conversion functions—append the data type declaration character to the variable’s name. For example, if you want a variable called Income to contain only Currency data, refer to it as Income@. If you want it to contain only Single data, refer to it as Income!.

■ To round a number to precisely the number of decimal places you want and discard anything residual, use Format[$].

■ To be sure you pass the correct data type to a sub procedure or to a Windows Dynamic Link Library (.dll), use data type conversion functions.

Example The following example prompts the user for a number, converts that number using each of the conversion functions in turn, and displays the result:

Page 79: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 55

C S t r f u n c t i o n

Function OnLButtonDblClk()Dim Orig As String, Msg As String, NL As StringNL = Chr$(10)Orig = InputBox$("Please enter a number.")Msg = "Your number is: " & Orig & NL & NLMsg = Msg & "CCur(Orig) yields ----> " & CCur(Orig) & NLMsg = Msg & "CDate(Orig) yields ----> " & CDate(Orig) & NLMsg = Msg & "CDbl(Orig) yields ----> " & CDbl(Orig) & NLMsg = Msg & "CInt(Orig) yields ----> " & CInt(Orig) & NLMsg = Msg & "CLng(Orig) yields ----> " & CLng(Orig) & NLMsg = Msg & "CSng(Orig) yields ----> " & CSng(Orig) & NLMsg = Msg & "CStr(Orig) yields ----> " & CStr(Orig) & NLMsg = Msg & "CVar(Orig) yields ----> " & CVar(Orig) & NLMsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also CCur functionCDate functionCInt functionCInt functionCLng functionCStr functionCVar functionCVDate functionDim statementFormat, Format$ functions

CStr functionConverts an expression to the String data type.

Syntax CStr(<valid expression>)

Parameters <valid expression>Expression to convert from the Currency, Date, Double, Integer, Long, Single, or Variant data type to the String data type.

Examples:The following statement returns the string 123four:

CStr(123) & "four"

Page 80: Actuate Basic Reference

56 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

C S t r f u n c t i o n

The following statement generates an error, because it mixes string and numeric data types:

CStr(123) + 5

The following statement returns 123.456 on a French run time locale and 123456.00 on an English run time locale:

CStr("123,456")

Returns String

■ One of eight Actuate Basic data type conversion functions.

■ If <valid expression> is Null, CStr returns a Null.

Tips ■ To declare the data type of a variable, use Dim with the As clause.

■ To declare the data type of a variable dynamically—without using Dim or one of the conversion functions—append the data type declaration character to the variable’s name. For example, if you want a variable called MyVar to contain only Currency data, refer to it as MyVar@. If you want it to contain only String type data, refer to it as MyVar$.

■ To be sure you pass the correct data type to a sub procedure or to a Windows Dynamic Link Library (.dll), use data type conversion functions.

Example The following example prompts the user for a number, converts that number using each of the conversion functions in turn, and displays the result:

Function OnLButtonDblClk()Dim Orig As String, Msg As String, NL As StringNL = Chr$(10)Orig = InputBox$("Please enter a number.")Msg = "Your number is: " & Orig & NL & NLMsg = Msg & "CCur(Orig) yields ----> " & CCur(Orig) & NLMsg = Msg & "CDate(Orig) yields ----> " & CDate(Orig) & NLMsg = Msg & "CDbl(Orig) yields ----> " & CDbl(Orig) & NLMsg = Msg & "CInt(Orig) yields ----> " & CInt(Orig) & NLMsg = Msg & "CLng(Orig) yields ----> " & CLng(Orig) & NLMsg = Msg & "CSng(Orig) yields ----> " & CSng(Orig) & NLMsg = Msg & "CStr(Orig) yields ----> " & CStr(Orig) & NLMsg = Msg & "CVar(Orig) yields ----> " & CVar(Orig) & NLMsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also CCur functionCInt functionCInt function

Page 81: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 57

C u r D i r , C u r D i r $ f u n c t i o n s

CLng functionCSng functionCVar functionCVDate functionDim statementFormat, Format$ functions

CurDir, CurDir$ functionsReturns the current default directory for the specified drive, or for the current drive.

Syntax CurDir[(<drive:>)]

CurDir$[(<drive:>)]

Parameters <drive:>String expression, consisting of a single character followed by a colon that specifies the drive for which you want to determine the current directory.Default: The current drive.

Rules:

■ First character of <drive:> must correspond to the letter of a valid DOS drive.

■ First character of <drive:> must be in the range A to <lastdrive>, where <lastdrive> is the maximum drive letter you set in your Config.sys file.

Examples:The following statement assigns to the variable DefaultVar a string containing the current directory path on the default drive:

DefaultVar = CurDir

The following statement assigns to the variable B$ a string containing the current directory path on drive A:

B$ = CurDir("A")

The following statement assigns to the variable PlaceMark a string containing the current directory path on drive C:

PlaceMark = CurDir$("C:")

Returns CurDir: VariantCurDir$: String

While DOS, Windows 95, or Windows NT always maintains a distinct current directory for each drive in the system, UNIX keeps only the current directory under the current drive. The current directory is the one the system searches

Page 82: Actuate Basic Reference

58 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

C V a r f u n c t i o n

first for a file name whenever you start such a search without specifying a path name.

Tips ■ Since the path CurDir[$] returns includes the drive letter, it also determines which drive is currently the current drive.

■ To be sure you have set the correct working directory before you issue commands that do not specify full path names, use CurDir[$], ChDrive, and ChDir.

■ <drive> is ignored when the Basic program is running on a UNIX server.

Example The following example displays a message box indicating the current directory on the current drive:

Function OnLButtonDblClk()Dim Msg As String, NL As StringNL = Chr$(10) ' Define newlineMsg = "The current directory is: "Msg = Msg & NL & CurDir ' Get current directoryMsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also ChDir statementChDrive statementMkDir statementRmDir statement

CVar functionConverts a numeric expression to the Variant data type.

Syntax CVar(<valid expression>)

Parameters <valid expression>Expression to convert to the Variant data type from the Currency, Date, Double, Integer, Long, Single, or String data type.

Rule: If <valid expression> is Null, CVar returns a Null.

Examples:The following statements return True, nonzero:

Page 83: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 59

C V a r f u n c t i o n

CVar(123) & "four" = "123four"CVar(123) + 5 = 128CVar(123) + 5 & "append" = "128append"

Returns Variant

■ One of eight data type conversion functions.

■ If <any valid expression> lies outside the acceptable range for a Variant data type, an overflow error occurs.

Tips ■ To convert an expression to variant without explicitly using CVar, assign the expression to a variable that is the Variant data type.

■ To declare the data type of a variable, use Dim with the As clause.

■ To be sure you pass the correct data type to a Sub procedure or to a Windows Dynamic Link Library (.dll), use data type conversion functions.

Example The following example prompts the user for a number, converts that number using each of the conversion functions in turn, and displays the result:

Function OnLButtonDblClk()Dim Orig As String, Msg As String, NL As StringNL = Chr$(10)Orig = InputBox$("Please enter a number.")Msg = "Your number is: " & Orig & NL & NLMsg = Msg & "CCur(Orig) yields ----> " & CCur(Orig) & NLMsg = Msg & "CDate(Orig) yields ----> " & CDate(Orig) & NLMsg = Msg & "CDbl(Orig) yields ----> " & CDbl(Orig) & NLMsg = Msg & "CInt(Orig) yields ----> " & CInt(Orig) & NLMsg = Msg & "CLng(Orig) yields ----> " & CLng(Orig) & NLMsg = Msg & "CSng(Orig) yields ----> " & CSng(Orig) & NLMsg = Msg & "CStr(Orig) yields ----> " & CStr(Orig) & NLMsg = Msg & "CVar(Orig) yields ----> " & CVar(Orig) & NLMsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also CCur functionCDate functionCInt functionCInt functionCLng functionCSng functionCStr functionCVDate functionDim statement

Page 84: Actuate Basic Reference

60 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

C V D a t e f u n c t i o n

CVDate functionConverts an expression to a Variant of VarType 7 (Date).

Syntax CVDate(<date expression>)

Parameters <date expression>Date expression, or any numeric or string expression that can be interpreted as a date, a time, or both a date and a time:

■ Can be a String such as November 12, 1982 8:30 P.M., 12 Nov., 1982 08:30 P.M., 11/12/82, 08:30P.M., or any other String that can be interpreted as a date, a time, or both a date and a time in the valid range.

■ Can be a date serial number such as 30267.854, which corresponds to November 12, 1982 at 8:30 P.M., or any other number that can be mapped to a date, a time, or both a date and a time in the valid range.

■ For date serial numbers, the Integer component represents the date itself while the decimal component represents the time of day on that date, where January 1, 1900 at precisely noon has the date serial number 2.5, and negative numbers represent dates prior to December 30, 1899 (0).

Default date if none specified: 0 (Dec. 30, 1899)

Default time if none specified: 00:00:00 (midnight)

Rules:

■ If <date expression> includes a time of day, it must be a valid time, even if CVDate is not being used to return anything having to do with a time of day. A valid time is one that is in the range 0:00:00 (12:00:00 A.M.) through 23:59:59 (11:59:59 P.M.). Either the 12- or 24-hour clock can be used.

■ If <date expression> is a numeric expression, the numeric expression must be in the range -657434 to +2958465, inclusive.

■ <date expression> cannot contain a day of week.

■ <date expression> must not be empty or zero-length.

■ <date expression> must specify a date within the range January 1, 100 through December 31, 9999, inclusive.

■ <date expression> is parsed according to the formatting rules of the current run time locale.

The following assumes that the AC_CENTURY_BREAK property is set to the default value of 30. For information about using AC_CENTURY_BREAK, see Chapter 7, “Using a query data stream,” in Developing Advanced e.Reports.

Page 85: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 61

C V D a t e f u n c t i o n

■ For abridged date expressions ending in 00 through 29 that do not specify the century, relevant date functions estimate the unabridged year by adding 2000. For example, while Year(4/30/1910) returns 1910, the abridged expression Year(4/30/10) returns 2010 (10 + 2000).

■ For abridged date expressions ending in 30 through 99 that do not specify the century, relevant date functions estimate the unabridged year by adding 1900. For example, while Year(11/12/2082) returns 2082, the abridged expression Year(11/12/82) returns 1982 (82 + 1900).

Note that there are abridged dates like Nov. 12, 1982 as opposed to November 12, 1982, that do specify the century. Note also that both abridged and unabridged dates are dates ending in 00 through 99.

Examples:The following statements are equivalent. Each assigns 11/12/82 8:30:00 P.M., with its underlying serial number, to the variable BDate:

BDate = CVDate("11/12/82 8:30 pm")BDate = CVDate("12 Nov 1982 20:30")BDate = CVDate("November 12, 1982 8:30PM")BDate = CVDate(30267.854167)

Returns Date

■ If <date expression> is Null, CVDate returns a Null.

■ If <date expression> cannot be evaluated to a date, CVDate returns a Null.

■ If <date expression> contains a day of week, CVDate returns a Null.

■ If <date expression> fails to include all date components, such as day, month, and year, CVDate returns a Null.

■ If <date string> contains only numbers separated by valid date separators, CVDate recognizes the order for month, day, and year according to the settings of the current run time locale.

Tips ■ Do not use CVDate to convert a long date format that also contains the day-of-the-week string, like Friday, Nov. 12, 1982. The function does not recognize such strings as dates.

■ Avoid supplying CVDate with a date in a format other than formats specified in the locale map.

■ To determine if either a numeric or string expression that looks like a date can be converted to a date, use IsDate. However, IsDate cannot determine whether a string that looks like a number can be converted to a date, even if the number is in the correct range for date serial numbers.

■ If you use a date expression in one locale, it might be misinterpreted in another locale. For instance, in the United States, 1/2/2005 means January 2nd, 2005, but in France, it means February 1st, 2005. To avoid such ambiguities, use DateSerial to specify all your dates.

Page 86: Actuate Basic Reference

62 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

C V D a t e f u n c t i o n

Example The following example prompts the user for a date, a date and time, a time, or a date serial number. For any valid entry, it displays both a date and a date serial number:

Function OnLButtonDblClk()Dim NL As String, DateMeme As String, ConvDateMeme As DateDim Msg As StringNL = Chr$(10)Msg = "Please type a date, a date and time, "Msg = Msg & "a time, or a date serial number."DateMeme = InputBox(Msg)ConvDateMeme = CVDate(DateMeme)MsgBox "The date you gave me was: " & ConvDateMeme & NLMsgBox "The serial number for that date is: " & CDbl(ConvDateMeme)

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also CCur functionCDate functionCInt functionCInt functionCLng functionCSng functionCStr functionCVar functionFormat, Format$ functionsIsDate functionParseDate function

Page 87: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 63

D a t e , D a t e $ f u n c t i o n s

Date, Date$ functionsReturns the current system date.

Syntax Date

Date$

Example:The following statement assigns the current system date to a variable.

CurrDate = Date

Returns Date: VariantDate$: String

■ Date returns a Variant of VarType 7 (Date) that contains a date stored internally as a Double.

■ Date$ returns a date within the range January 1, 1980 through December 31, 2036, inclusive.

■ Date$ returns a 10-character string in the form mm-dd-yyyy, where mm represents the current month (01-12), dd the day (01-31), and yyyy the year (1980-2036).

Example The following example looks at the system date and determines how many business days are left in the current week, not counting today:

Function OnLButtonDblClk()' Dimension CurrentDay and BusDaysLeft as Variants so we can' perform arithmetic operations on themDim CurrentDay, BusDaysLeftDim Verb As String, DayNoun As String, Msg As StringCurrentDay = Weekday(Date) ' Weekday returns an IntegerBusDaysLeft = 6 - CurrentDayIf BusDaysLeft < 0 or BusDaysLeft > 5 Then BusDaysLeft = 0Select Case BusDaysLeft

Case Is = 1Verb = "is "DayNoun = "day "

Case ElseVerb = "are "DayNoun = "days "

End SelectMsg = "Today is " & Format$(Date, "dddd") & "."Msg = Msg & "There " & Verb & BusDaysLeft & " business " & DayNounMsg = Msg & "left in the current week, not counting today."MsgBox Msg

End Function

Page 88: Actuate Basic Reference

64 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

D a t e A d d f u n c t i o n

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also CVDate functionFormat, Format$ functionsNow functionTime, Time$ functions

DateAdd functionReturns a date to which a specified time interval has been added.

Syntax DateAdd(<interval code>, <number of intervals>, <date expression>)

Parameters <interval code>String expression that specifies the interval of time, such as quarter, month, or second to add.

Rule: You can use only one <interval code> at a time.

The following table lists each valid time period and the <interval code> that corresponds to it.

<number of intervals>Numeric expression that specifies the number of intervals to add. Use a positive number to get future dates and a negative number to get past dates.

<date expression>String expression that specifies the date to add to, or a variant expression that contains a valid date.

Time period <interval code>

Year yyyy

Quarter q

Month m

Day of the Year y

Day of the Month d

Day of the Week w

Week of the Year ww

Hour h

Minute n

Second s

Page 89: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 65

D a t e A d d f u n c t i o n

Rules:

■ <date expression> must specify a date within the range January 1, 100 through December 31, 9999, inclusive.

■ <date expression> cannot contain a day of week.

■ <date expression> is parsed according to the formatting rules of the current run time locale.

Returns Variant

■ If you subtract more years than are in <date expression>, an error occurs.

■ If <date expression> cannot be evaluated to a date, DateAdd returns a Null.

■ If <date expression> fails to include all date components, such as day, month, and year, DateAdd returns a Null.

■ If <date expression> contains a day of week, DateAdd returns a Null.

■ If <number of intervals> is not a Long value, DateAdd follows the rules for Fix function and rounds <number of intervals> to the nearest whole number.

The following assumes that the AC_CENTURY_BREAK property is set to the default value of 30. For information about using AC_CENTURY_BREAK, see Chapter 7, “Using a query data stream,” in Developing Advanced e.Reports.

■ For abridged date expressions ending in 00 through 29 that do not specify the century, relevant date functions estimate the unabridged year by adding 2000. For example, while Year(4/30/1910) returns 1910, the abridged expression Year(4/30/10) returns 2010 (10 + 2000).

■ For abridged date expressions ending in 30 through 99 that do not specify the century, relevant date functions estimate the unabridged year by adding 1900. For example, while Year(11/12/2082) returns 2082, the abridged expression Year(11/12/82) returns 1982 (82 + 1900).

Note that there are abridged dates such as Nov. 12, 1982 as opposed to November 12, 1982, that do specify the century. Note also that both abridged and unabridged dates are dates ending in 00 through 99.

Tips ■ Use DateAdd to add a specified time interval to a date. For example, you can use DateAdd to calculate a date 30 days from a transaction date to display a Send Late Payment Notice field.

■ To calculate the difference between two dates, use DateDiff.

■ If you use a date expression in one locale, it might be misinterpreted in another locale. For instance, in the United States, 1/2/2005 means January 2nd, 2005, but in France, it means February 1st, 2005. To avoid such ambiguities, use DateSerial to specify all your dates.

Page 90: Actuate Basic Reference

66 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

D a t e D i f f f u n c t i o n

Example The following example prompts the user to enter a date, adds 30 days to that date, and displays the result:

Function OnLButtonDblClk ( )Dim TransactionDate, MsgTransactionDate = InputBox("Type a date in the pattern 1/1/82.")Msg = DateAdd("d", 30, TransactionDate)MsgBox Msg & " is 30 days after the date " & TransactionDate

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also DateDiff function

DateDiff functionCalculates and returns the time difference between two specified dates.

Syntax DateDiff(<interval >, <date to subtract>, <date to subtract from>)

Parameters <interval>String expression that specifies the interval of time, such as quarter, month, or second, to use in calculating the difference between two specified dates.

Rule: You can use only one <interval> at a time.

The following table lists valid values for <interval> and describes how DateDiff uses each in calculations.

Interval Time period Description

yyyy Year DateDiff uses the year portion in calculation.

q Quarter DateDiff uses the following quarters: January - March, April - June, July - September, and October - December. DateDiff calculates the difference by determining the quarter into which each date falls, then subtracting the quarters.

m Month DateDiff uses the month portion of dates in calculation.

y Day of the Year DateDiff counts the number of days in the specified years.

Page 91: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 67

D a t e D i f f f u n c t i o n

<date to subtract>String expression that specifies the date to subtract, or the name of a variant expression containing the valid date.

Rules:

■ <date to subtract> must specify a date within the range January 1, 100 through December 31, 9999, inclusive.

■ <date to subtract> cannot contain a day of week.

■ <date to subtract> is parsed according to the formatting rules of the current run time locale.

<date to subtract from>String expression that specifies the date to subtract from, or the name of a variant expression containing the valid date.

Rules:

■ <date to subtract from> must specify a date within the range January 1, 100 through December 31, 9999, inclusive.

■ <date to subtract from> cannot contain a day of week.

■ <date to subtract from> is parsed according to the formatting rules of the current run time locale.

The following assumes that the AC_CENTURY_BREAK property is set to the default value of 30. For information about using AC_CENTURY_BREAK, see Chapter 7, “Using a query data stream,” in Developing Advanced e.Reports.

■ For abridged date expressions ending in 00 through 29 that do not specify the century, relevant date functions estimate the unabridged year by adding 2000. For example, while Year(4/30/1910) returns 1910, the abridged expression Year(4/30/10) returns 2010 (10 + 2000).

d Day of the Month DateDiff counts the number of days in the specified months.

w Day of the Week DateDiff counts the number of Mondays.

ww Week of the Year DateDiff counts the number of Sundays.

h Hour DateDiff counts the number of hours.

n Minute DateDiff counts the number of minutes.

s Second DateDiff counts the number of seconds.

Interval Time period Description

Page 92: Actuate Basic Reference

68 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

D a t e D i f f f u n c t i o n

■ For abridged date expressions ending in 30 through 99 that do not specify the century, relevant date functions estimate the unabridged year by adding 1900. For example, while Year(11/12/2082) returns 2082, the abridged expression Year(11/12/82) returns 1982 (82 + 1900).

Note that there are abridged dates such as Nov. 12, 1982 as opposed to November 12, 1982 that do specify the century. Note also that both abridged and unabridged dates are dates ending in 00 through 99.

Returns Variant

■ If <date to subtract> refers to a later point in time than <date to subtract from>, DateDiff returns a negative number.

■ If <date to subtract> cannot be evaluated to a date, DateDiff returns a Null.

■ If <date to subtract from> cannot be evaluated to a date, DateDiff returns a Null.

■ If <date to subtract> fails to include all date components (day, month, and year), DateDiff returns a Null.

■ If <date to subtract from> fails to include all date components (day, month, and year), DateDiff returns a Null.

■ If <date to subtract> contains a day of week, DateDiff returns a Null.

■ If <date to subtract from> contains a day of week, DateDiff returns a Null.

■ If <interval> is w (weekday), DateDiff returns the number of weeks by counting the number of Mondays between the two dates. If <date to subtract from> falls on a Monday, DateDiff does not include that Monday in the calculation. In the following example, both specified dates fall on a Monday. The result DateDiff returns is 2:

DateDiff("w", "6/26/95", "7/10/95")

■ If <interval> is ww (week), DateDiff returns the number of weeks by counting the number of Sundays between the two dates. If <date to subtract from> falls on a Sunday, DateDiff does not include that Sunday in the calculation. In the following example, both specified dates fall on a Sunday. The result DateDiff returns is 2:

DateDiff("ww", "6/25/95", "7/9/95")

■ DateDiff uses the year portion of dates in calculation. For this reason, the following example returns 1, although the dates are one day apart:

DateDiff ("yyyy", "12/31/95", "1/1/96")

■ DateDiff uses the month portion of dates in calculation. For this reason, the following example returns 1, although the dates are one day apart:

DateDiff ("m", "12/31/95", "1/1/96")

Page 93: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 69

D a t e P a r t f u n c t i o n

■ DateDiff calculates the difference by checking which quarters the specified dates fall in. For this reason, the following example returns 1, although the dates are one day apart:

DateDiff ("q", "12/31/95", "1/1/96")

■ The actual display format of date and time is set using the Windows Control Panel.

Tips ■ Use DateDiff to calculate the difference between two dates to display in a calculated field. For example, you can use DateDiff to calculate the number of days between a pre-sales date and a transaction date to display in a Sales Response field.

■ If you are calculating the number of weeks between two dates, you can use either weekday (w) or week (ww) as the interval. Because each starts the calculations from a different day, the results can be different.

■ To add a specified time interval to a date, use DateAdd.

■ If you use a date expression in one locale, it might be misinterpreted in another locale. For instance, in the United States, 1/2/2005 means January 2nd, 2005, but in France, it means February 1st, 2005. To avoid such ambiguities, use DateSerial to specify all your dates.

Example The following example uses two valid date expressions called PreSalesDate and TransactionDate. DateDiff finds the difference, in days, between PreSalesDate and TransactionDate, and displays the result:

Function OnLButtonDblClk ( )Dim PreSalesDate, TransactionDate, DDiff, MsgPreSalesDate = InputBox("Type the pre-sales date in the pattern 1/1/82.")TransactionDate = InputBox("Type the transaction date.")DDiff = DateDiff("d", PreSalesDate, TransactionDate)Msg = "The pre-sales date is "Msg = Msg & DDiff & " days before the transaction date."MsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also DateAdd function

DatePart functionReturns a specified component of a given date.

Syntax DatePart(<interval code>, <date exprs>)

Page 94: Actuate Basic Reference

70 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

D a t e P a r t f u n c t i o n

Parameters <interval code>String expression that specifies the interval of time such as quarter, month, or second you want to determine.

Rule: You can use only one <interval code> at a time.

The following table lists valid time periods for <interval code>.

<date exprs>Date expression, or any numeric or string expression that can be interpreted as a date, a time, or both a date and a time:

■ Can be a string expression such as November 12, 1982 8:30 P.M., Nov. 12, 1982 08:30 PM, 11/12/82 8:30pm, 20:30, or any other string that can be interpreted as a date, a time, or both a date and a time in the valid range.

■ Can be a date serial number such as 30267.854, which corresponds to November 12, 1982 at 8:30 P.M., or any other number that can be mapped to a date, a time, or both a date and a time in the valid range.

■ For date serial numbers, the integer component represents the date itself while the decimal component represents the time of day on that date, where January 1, 1900 at precisely noon has the date serial number 2.5, and negative numbers represent dates prior to December 30, 1899 (0).

Default time of day if none specified: 00:00:00 (midnight)Default date if none specified: December 30, 1899

Rules:

■ <date exprs> must be in the range January 1, 100 through December 31, 9999, inclusive.

■ If <date exprs> is a numeric expression, it must be in the range -657434 to +2958465, inclusive.

Time period <interval code> Range of return value

Year yyyy 100 - 9999

Quarter q 1 - 4

Month m 1 - 12

Day of the Year y 1 - 366

Day of the Month d 1 - 31

Day of the Week w 1 - 7

Week of the Year ww 1 - 53

Hour h 0 - 23

Minute n 0 - 59

Second s 0 - 59

Page 95: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 71

D a t e P a r t f u n c t i o n

■ If <date exprs> is a variable containing a date serial number, the variable must be explicitly declared as one of the numeric types.

■ If <date exprs> includes a time of day, it must be a valid time, even when you are not using DatePart to return anything having to do with time of day. A valid time is one that is in the range 00:00:00 (12:00:00 A.M.) through 23:59:59 (11:59:59 P.M.). Either the 12- or 24-hour clock format may be used.

■ <date exprs> cannot contain a day of week.

■ <date exprs> is parsed according to the formatting rules of the current run time locale.

The following assumes that the AC_CENTURY_BREAK property is set to the default value of 30. For information about using AC_CENTURY_BREAK, see Chapter 7, “Using a query data stream,” in Developing Advanced e.Reports.

■ For abridged date expressions ending in 00 through 29 that do not specify the century, relevant date functions estimate the unabridged year by adding 2000. For example, while Year(4/30/1910) returns 1910, the abridged expression Year(4/30/10) returns 2010 (10 + 2000).

■ For abridged date expressions ending in 30 through 99 that do not specify the century, relevant date functions estimate the unabridged year by adding 1900. For example, while Year(11/12/2082) returns 2082, the abridged expression Year(11/12/82) returns 1982 (82 + 1900).

Note that there are abridged dates such as Nov. 12, 1982 as opposed to November 12, 1982, that do specify the century. Note also that both abridged and unabridged dates are dates ending in 00 through 99.

Examples:Each of the following statements returns True:

Print 11 = DatePart("m", "11/12/82 8:30:01 pm")Print 12 = DatePart("d", "11/12/82 8:30:01 pm")Print 316 = DatePart("y", "11/12/82 8:30:01 pm")

Returns Integer

■ If <date exprs> is Null, DatePart returns a Null.

■ If <date exprs> cannot be evaluated to a date, DatePart returns a Null.

■ If <date exprs> fails to include all date components, such as day, month, and year, DatePart returns a Null.

■ If <date exprs> contains a day of week, DatePart returns a Null.

■ If DatePart ("w", <date exprs>) returns 1, the day of the week for <date exprs> is Sunday. If DatePart returns 2, the day of the week is Monday, and so on.

Tips ■ To return more than one interval at a time and to exercise more control over output, use Format instead of DatePart.

Page 96: Actuate Basic Reference

72 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

D a t e S e r i a l f u n c t i o n

■ If you use a date expression in one locale, it might be misinterpreted in another locale. For instance, in the United States, 1/2/2005 means January 2nd, 2005, but in France, it means February 1st, 2005. To avoid such ambiguities, use DateSerial to specify all your dates.

Example The following example prompts the user for a date or date and time, then displays all ten values DatePart can return:

Function OnLButtonDblClk()Dim UserDate As String, NL As StringDim InputMsg As String, Msg As StringNL = Chr$(10) ' Define newlineInputMsg = "Please type a date or date and time" ' Set a string for msgboxInputMsg = InputMsg & " like Nov 12, 1982 8:32pm."UserDate = InputBox(InputMsg) ' Get user inputMsg = "The year is: " & DatePart("yyyy", UserDate) & NLMsg = Msg & "The quarter is: " & DatePart("q", UserDate) & NLMsg = Msg & "The month is: " & DatePart("m", UserDate) & NLMsg = Msg & "The day of the year is: " & DatePart("y", UserDate) & NLMsg = Msg & "The day of the month is: " & DatePart("d", UserDate) & NLMsg = Msg & "The day of the week is: " & DatePart("w", UserDate) & NLMsg = Msg & "The week of the year is: " & DatePart("ww", UserDate) & NLMsg = Msg & "The hour is: " & DatePart("h", UserDate) & NLMsg = Msg & "The minute is: " & DatePart("n", UserDate) & NLMsg = Msg & "The second is: " & DatePart("s", UserDate) & NLMsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also DateAdd functionDateDiff functionDay functionFormat, Format$ functionsFormat, Format$ functionsNow functionWeekday functionYear function

DateSerial functionReturns a date variant based on the specified year, month, day, hour, minute, and second.

Page 97: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 73

D a t e S e r i a l f u n c t i o n

Syntax DateSerial(<year>, <month>, <day>)

DateSerial(<year>, <month>, <day>, <hour>, <minute>, <second>)

Parameters <year>Numeric expression that specifies the year of a date. 0 through 99 represent the years 1900-1999.

Rule:

■ <year> must be in the range 100 through 9999, inclusive.

■ To represent a year outside the range 1900-1999, you must use all four of its digits.

<month>Numeric expression that specifies the month of a date.

Rule: Must be in the range 1 through 12, inclusive.

<day>Numeric expression that specifies the day of a date.

Rule: Must be in the range 1 through 31, inclusive.

<hour>Numeric expression that specifies the hour of a day.

Rule: Must be in the range 0-23, inclusive.

<minute>Numeric expression that specifies the minute of a hour.

Rule: Must be in the range 0-59, inclusive.

<second>Numeric expression that specifies the second of a minute.

Rule: Must be in the range 0-59, inclusive.

Examples:The following statements are equivalent, each stores 11/12/82 into the variable DateVar:

DateVar = DateSerial(82, 11, 12)DateVar = DateSerial(1982, 11, 12)

Each of the following statements stores the underlying date serial number for November 12, 1982 (which is 30267) into the double-precision variable DateVar#:

DateVar# = CDbl(DateSerial(82, 11, 12))DateVar# = DateSerial(82, 11, 12) * 1

Page 98: Actuate Basic Reference

74 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

D a t e S e r i a l f u n c t i o n

Returns Date

■ The value DateSerial returns usually looks like a date but is stored internally as a double-precision number known as a date serial number, which is a number that represents a date and/or time from midnight January 1, 100 through December 31, 9999, inclusive.

■ The integer component of any date serial number represents the date, such as day, month, and year itself while the decimal or fractional component represents the time of day on that date as a proportion of a wholeday—where January 1, 1900 at precisely noon has the date serial number 2.5, and where negative numbers represent dates prior to December 30, 1899.

■ The actual display format of date and time is set using the Windows Control Panel.

Tips ■ DateSerial can return a new date based on calculations done on a given date. In the following example, DateSerial returns a date that is thirty days before November 12, 1982—that is, 10/13/82—and assigns it to the variable DateNew:

DateNew = DateSerial(1982, 11, 12)-30

■ If you use a date expression in one locale, it might be misinterpreted in another locale. For instance, in the United States, 1/2/2005 means January 2nd, 2005, but in France, it means February 1st, 2005. To avoid such ambiguities, use DateSerial to specify all your dates.

Example The following example prompts the user to enter a date and displays the day of the week for that date:

Function OnLButtonDblClk()Dim Msg As String, UserDate As DoubleDim DateGiven As String, Verb As StringDim ValidFlag As IntegerDim DD As Integer, MM As Integer, YY As IntegerDim DayOfWeek As String

Msg = "Please type a date in the format mm/dd/yyyy."Do ValidFlag = True ' Assume the best

DateGiven = InputBox(Msg) ' Get user inputIf Len(DateGiven) <> 10 Then DateGiven = Format(Now, "mm/dd/yyyy")MM = Left(DateGiven, 2) ' Extract month numberIf MM <1 Or MM > 12 Then ValidFlag = FalseDD = Mid(DateGiven, 4, 2) ' Extract day numberIf DD <1 Or DD > 31 Then ValidFlag = FalseYY = Right(DateGiven, 4) ' Extract year numberIf YY < 1753 Or YY > 2078 Then ValidFlag = False

Page 99: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 75

D a t e V a l u e f u n c t i o n

Loop While ValidFlag = False

UserDate = DateSerial(YY, MM, DD) ' Determine date serial

Select Case UserDate ' Find correct verb' Now is the date serial for the current moment. We need only the' integer component of it to compare with what the user entered to' determine if date entered was before today, today, or in the future

Case Is < Int(Now): Verb = " was a "Case Is > Int(Now): Verb = " will be a "Case Else: Verb = " is a "

End Select

DayOfWeek = Format(UserDate, "dddd") ' Returns a day of weekMsg = DateGiven & Verb & DayOfWeek & "."MsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also DateValue functionDay functionMonth functionNow functionTimeSerial functionTimeValue functionWeekday functionYear function

DateValue functionReturns a date variant that represents the date of the specified string.

Syntax DateValue(<date string>)

Parameters <date string>String expression that specifies a date. Can be any string that can be interpreted as a date.

Rules:

■ <date string> must be in the range January 1, 100 through December 31, 9999, inclusive.

■ If a time is appended to the date it must be a valid time, even though DateValue does not return a time.

Page 100: Actuate Basic Reference

76 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

D a t e V a l u e f u n c t i o n

■ <date string> is parsed according to the formatting rules of the current run time locale.

The following assumes that the AC_CENTURY_BREAK property is set to the default value of 30. For information about using AC_CENTURY_BREAK, see Chapter 7, “Using a query data stream,” in Developing Advanced e.Reports.

■ For abridged date expressions ending in 00 through 29 that do not specify the century, relevant date functions estimate the unabridged year by adding 2000. For example, while Year(4/30/1910) returns 1910, the abridged expression Year(4/30/10) returns 2010 (10 + 2000).

■ For abridged date expressions ending in 30 through 99 that do not specify the century, relevant date functions estimate the unabridged year by adding 1900. For example, while Year(11/12/2082) returns 2082, the abridged expression Year(11/12/82) returns 1982 (82 + 1900).

Note that there are abridged dates such as Nov. 12, 1982 as opposed to November 12, 1982, that do specify the century. Note also that both abridged and unabridged dates are dates ending in 00 through 99.

Examples:The following statements are equivalent. If the default Short Date format for the current run time locale is mm/dd/yy, each stores 11/12/10 into the variable DateVar:

DateVar = DateValue("November 12, 2010")DateVar = DateValue("Nov 12, 2010")DateVar = DateValue("Nov 7, 2010") + 5DateVar = DateValue("11/12/10")DateVar = DateValue("11-12-2010")

Each of the following statements stores the underlying date serial number for November 12, 1982 (which is 30267) into the double-precision variable DateVar#:

DateVar# = DateValue("Nov 12, 1982")DateVar# = DateValue("Nov 12, 1982") * 1

Returns Date

■ If <date string> contains only numbers separated by valid date separators, DateValue recognizes the order for month, day, and year according to the Short Date setting of the current run time locale.

■ If <date string> cannot be evaluated to a date, DateValue returns a Null.

■ If <date string> fails to include all date components, such as day, month, and year, DateValue returns a Null.

■ If a day of week is specified, DateValue returns a Null.

Page 101: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 77

D a t e V a l u e f u n c t i o n

■ The value DateValue returns usually looks like a date but is stored internally as a double-precision number known as a date serialnumber—that is, a number that represents a date and/or time from midnight January 1, 100 through December 31, 9999, inclusive.

■ The integer component of any date serial number represents the date (day, month, and year) itself while the decimal or fractional component represents the time of day on that date as a proportion of a whole day, where January 1, 1900, at precisely noon has the date serial number 2.5, and negative numbers represent dates prior to December 30, 1899.

Tip If you use a date expression in one locale, it might be misinterpreted in another locale. For instance, in the United States, 1/2/2005 means January 2nd, 2005, but in France, it means February 1st, 2005. To avoid such ambiguities, use DateSerial to specify all your dates.

Example The following example displays the day of the week for any date the user specifies:

Function OnLButtonDblClk()Dim Msg As String, UserDate As DoubleDim DateGiven As String, Verb As StringDim ValidFlag As IntegerDim DD As String, MM As String, YY As StringDim DayOfWeek As String

Msg = "Please type a date in the format mm/dd/yyyy"Do ValidFlag = True ' Assume the best

DateGiven = InputBox(Msg) ' Get user inputIf Len(DateGiven) <> 10 Then DateGiven = Format(Now, "mm/dd/yyyy")MM = Left(DateGiven, 2) ' Extract month numberIf MM < "01" Or MM > "12" Then ValidFlag = FalseDD = Mid(DateGiven, 4, 2) ' Extract day numberIf DD < "01" Or DD > "31" Then ValidFlag = FalseYY = Right(DateGiven, 4) ' Extract year numberIf YY < "1753" Or YY > "2078" Then ValidFlag = False

Loop While ValidFlag = False

UserDate = DateValue(DateGiven) ' Determine date value

Select Case UserDate ' Find correct verb' Now is the date serial for the current moment. We need only the' integer component of it to compare with what the user entered to' determine if date entered was before today, today, or in the future

Case Is < Int(Now): Verb = " was a "Case Is > Int(Now): Verb = " will be a "Case Else: Verb = " is a "

Page 102: Actuate Basic Reference

78 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

D a y f u n c t i o n

End Select

DayOfWeek = Format(UserDate, "dddd") ' Returns a day of weekMsg = DateGiven & Verb & DayOfWeek & "."MsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also DateSerial functionDay functionMonth functionNow functionTimeSerial functionTimeValue functionWeekday functionYear function

Day functionReturns an integer between 1 and 31, inclusive, that represents the day of the month for a specified date argument.

Syntax Day(<date exprs>)

Parameters <date exprs>Date expression, or any numeric or string expression that can evaluate to a date. Specifies a date and/or time:

■ Can be a string such as November 12, 1982, Nov. 12, 1982, 11/12/82, 11-12-82, or any other string that can be interpreted as a date in the valid range.

■ Can be a date serial number such as 30267.854, which corresponds to November 12, 1982 at 8:30 P.M., or any other number that can be mapped to a date in the valid range.

■ For date serial numbers, the integer component represents the date itself while the decimal component represents the time of day on that date, where January 1, 1900 at precisely noon has the date serial number 2.5, and negative numbers represent dates prior to December 30, 1899 (0).

Rules:

■ If <date exprs> is a string expression, it must specify a date in the range January 1, 100 through December 31, 9999, inclusive.

Page 103: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 79

D a y f u n c t i o n

■ <date exprs> is parsed according to the formatting rules of the current run time locale.

■ If <date exprs> is a numeric expression, it must be in the range -657434 to +2958465, inclusive.

■ If <date exprs> is a variable containing a date serial number, the variable must be explicitly declared as one of the numeric types.

Examples:The following statements are equivalent. Each assigns 7 to the variable UserDay:

UserDay = Day("6/7/64")UserDay = Day("June 7, 1964 2:35 PM")UserDay = Day("Jun 7, 1964")UserDay = Day(23535)UserDay = Day(4707*5)

Returns Integer

■ If <date exprs> cannot be evaluated to a date, Day returns a Null.

Example:

Day (“This is not a date.“) returns Null.

■ If <date exprs> fails to include all date components, such as day, month, and year, Day returns a Null.

Examples:

Day (“Nov 12, 1982“) returns 12, but Day (“Nov 1982“) returns Null

■ If <date exprs> is Null, Day returns a Null.

The following assumes that the AC_CENTURY_BREAK property is set to the default value of 30. For information about using AC_CENTURY_BREAK, see Chapter 7, “Using a query data stream,” in Developing Advanced e.Reports.

■ For abridged date expressions ending in 00 through 29 that do not specify the century, relevant date functions estimate the unabridged year by adding 2000. For example, while Year(4/30/1910) returns 1910, the abridged expression Year(4/30/10) returns 2010 (10 + 2000).

■ For abridged date expressions ending in 30 through 99 that do not specify the century, relevant date functions estimate the unabridged year by adding 1900. For example, while Year(11/12/2082) returns 2082, the abridged expression Year(11/12/82) returns 1982 (82 + 1900).

Tip If you use a date expression in one locale, it might be misinterpreted in another locale. For instance, in the United States, 1/2/2005 means January 2nd, 2005, but in France, it means February 1st, 2005. To avoid such ambiguities, use DateSerial to specify all your dates.

Page 104: Actuate Basic Reference

80 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

D a y f u n c t i o n

Example The following example uses various interrelated date functions to display the year, the month, the day, and the weekday for a date the user enters. Finally, it gives the date’s serial number. The code for the function Suffix should be pasted after the End Function statement for the event:

Function OnLButtonDblClk ( )Dim UserEntry As String, UserYear As Integer, UserMonth As IntegerDim UserDay As Integer, UserDOW As Integer, DOWName As StringDim Msg As String, NL As String, LeapYear As String

NL = Chr$(10) ' Define newlineUserEntry = InputBox("Please type a date.") ' Get user inputUserEntry = CDate(UserEntry)UserYear = Year(UserEntry) ' Calculate yearUserMonth = Month(UserEntry) ' Calculate monthUserDay = Day(UserEntry) ' Calculate dayUserDOW = Weekday(UserEntry) ' Calculate day of weekDOWName = Format$ (UserEntry, "dddd") ' Convert to name of day

' Determine if the year is a leap year or a centesimalIf UserYear Mod 4 = 0 And UserYear Mod 100 = 0 Then

If UserYear Mod 400 = 0 Then ' Evenly divisible by 400?LeapYear = "is a leap year."

Else ' Not evenly divisibleLeapYear = "is a centesimal but not a leap year."

End IfElseIf UserYear Mod 4 = 0 Then

LeapYear = "is a leap year."Else

LeapYear = "is not a leap year."End If

' Display results for the user after the pattern:' The given year 1982 is not a leap year. The weekday number for' the 12th day of the 11th month in 1982 is 3, which means that ' day was a Tuesday.'' The date serial number for 11/12/82 is: 30267'MsgBox "The given year, " & UserYear & ", " & LeapYearMsg = "The weekday number for the " Msg = Msg & UserDay & Suffix(UserDay) & " day "Msg = Msg & "of the " & UserMonth & Suffix(UserMonth) & " month "Msg = Msg & "in " & UserYear & " is " & UserDOWMsg = Msg & ", which means that day is a " & DOWName & "." & NL & NLMsg = Msg & "The date serial number for " & UserEntry & " is: "Msg = Msg & CDbl(DateSerial(UserYear, UserMonth, UserDay))

Page 105: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 81

D D B f u n c t i o n

MsgBox MsgEnd Function' The following function called in the previous procedure tells us what' suffix (1st, 2nd, 3rd) to use with a numberFunction Suffix (DateNum) As String

Select Case DateNumCase 1

Suffix = "st"Case 2

Suffix = "nd"Case 3

Suffix = "rd"Case Else

Suffix = "th"End Select

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Date, Date$ functionsHour functionMinute functionMonth functionNow functionSecond functionWeekday functionYear function

DDB functionReturns the depreciation of an asset for a given, single period using the double-declining balance method.

Syntax DDB(<initial cost>, <salvage value>, <asset lifespan>, <single period>)

Parameters <initial cost>Numeric expression that specifies the initial cost of the asset.

<salvage value>Numeric expression that specifies the value of the asset at the end of its useful life.

<asset lifespan>Numeric expression that specifies the length of the useful life of the asset.

Page 106: Actuate Basic Reference

82 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

D D B f u n c t i o n

Rule for <asset lifespan>: Must be given in the same units of measure as <single period>. For example, if <single period> represents a month, then <asset lifespan> must be expressed in months.

<single period>Numeric expression that specifies the period for which you want DDB to calculate the depreciation.

Rule for <single period>: Must be given in the same units of measure as <asset lifespan>. For example, if <asset lifespan> is expressed in months, then <single period> must represent a period of one month.

Example:The following example calculates the depreciation for the first year under the double-declining balance method for a new machine purchased at $1400, with a salvage value of $200, and a useful life estimated at 10 years. The result ($280) is assigned to the variable Year1Deprec:

Year1Deprec = DDB(1400, 200, 10, 1)

Returns Double

Double-declining balance depreciation is an accelerated method of depreciation that results in higher depreciation charges and greater tax savings in the earlier years of the useful life of a fixed asset than are given by the straight-line depreciation method (SLN), where charges are uniform throughout.

The method uses the following formula:

Depreciation over <single period> = ((<initial cost> - total depreciation from prior periods) * 2) / <asset lifespan>.

Rules ■ <asset lifespan> and <single period> must both be expressed in terms of the same units of time.

■ All parameters must be positive numbers.

Example The following example prompts the user for various particulars about an asset, then returns the asset’s double-declining balance depreciation for any single period:

Function OnLButtonDblClk()Dim Fmt As String, InitCost As Double, SalvageVal As DoubleDim MonthLife As Double, LifeSpan As Double, DepYear As DoubleDim PeriodDepr As Double, Msg As String, YearMonthsYearMonths = 12Fmt = "###,##0.00" ' Define money format' Get user inputInitCost = InputBox("What is the initial cost of the asset?")

Page 107: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 83

D e c l a r e s t a t e m e n t

SalvageVal = InputBox("What is the asset's value at the end of its life?")MonthLife = InputBox("What is the asset's useful life in months?")Do While MonthLife < YearMonths ' Ensure period is >= 1 year

MsgBox "Asset life must be a year or more."MonthLife = InputBox("What is the asset's useful life in months?")

Loop

LifeSpan = MonthLife / YearMonths ' Convert months to yearsIf LifeSpan <> Int(MonthLife / YearMonths) Then

LifeSpan = Int(LifeSpan + 1) 'Round up to nearest yearEnd If

DepYear = CInt(InputBox("For which year do you want depreciation?"))Do While DepYear < 1 Or DepYear > LifeSpan

MsgBox "You must type at least 1 but not more than " & LifeSpanDepYear = CInt(InputBox("For which year do you want depreciation?"))

Loop

PeriodDepr = DDB(InitCost, SalvageVal, LifeSpan, DepYear)Msg = "The depreciation for year " & DepYear & " is "Msg = Msg & Format(PeriodDepr, Fmt) & "."MsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also SLN functionSYD function

Declare statementInforms Actuate Basic that you are using, and how you are using, an external procedure in a dynamic link library (.dll). A procedure that returns a value is declared as a Function; a procedure that does not return a value is declared as a Sub.

Syntax Declare Sub <proc> Lib <lib name> [Alias <alias name>] [([<arg list>])]

Declare Function <proc> Lib <lib name> [Alias <alias name> ] [([<arg list>])] [As <function data type>]

Parameters SubKeyword indicating that the procedure does not return a value.

Page 108: Actuate Basic Reference

84 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

D e c l a r e s t a t e m e n t

FunctionKeyword indicating that the procedure returns a value and therefore can be used in an expression.

<proc>The name of the sub or function you are declaring as it is named in the .dll where it is defined. For function procedures, the data type of the procedure determines the data type it returns. Unless you use an As clause, <proc> can include a type-declaration character indicating the data type returned by the procedure.

Rules for <proc>:

■ Must follow standard variable naming conventions.

■ Cannot be the name of any other procedure.

■ Cannot include a type-declaration character if you use the As clause.

LibKeyword before the name of the DLL, <lib name>, that contains the procedure being declared.

<lib name>String literal of the DOS filename of the .dll that contains <proc> or <alias name>.

Rule for <lib name>: If not in the current directory on the current drive, <lib name> must specify the full path name.

AliasKeyword indicating the sub or function as it is named in the .dll.

Rules for Alias:

■ Must be used when the DLL procedure name is the same as an Actuate Basic reserved word.

■ Must be used when a DLL procedure has the same name as a global variable, constant, or any other procedure in the same scope.

■ Must be used if any characters in the DLL procedure name are not allowed in Actuate Basic names.

<alias name>String literal for the alternative name of <proc> as it appears within <lib name>.

<arg list>List of variables representing arguments that are passed to the sub or function procedure when it is called. <arg list> has the following syntax:

Page 109: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 85

D e c l a r e s t a t e m e n t

[ByVal] <arg variable> [ As <arg data type>] [,[ByVal] <arg variable> [ As <arg data type>] ] . . .

Arguments may be passed by value (using the keyword ByVal) or by reference.

ByValKeyword indicating that the argument is passed by value rather than by reference. The following table summarizes the behavior of ByVal.

Default: String descriptor is sent to the called DLL procedure.

Rule for ByVal: Cannot be used with an array, user-defined type, or class variable.

<arg variable>Any valid Actuate Basic variable name.

Rules for <arg variable>:

■ Must conform to standard variable naming conventions.

■ If it includes a type-declaration character, you cannot use the As <arg data type> clause.

As <arg data type>Clause that declares the data type of <arg variable> as Any, CPointer, Currency, Date, Double, Integer, Long, Single, String, Variant, a user-defined type, or any class.

Rules for As <arg data type>:

■ If you use this clause, do not use a type-declaration character as part of <arg variable>.

■ Use the Any data type in an As clause only to override type checking for that argument.

Default: Variant

<arg variable> Behavior of ByVal

Numeric expression Converts <arg variable> to the data type indicated by its type-declaration character, if any, or else by its associated As clause.Passes the converted value to the DLL procedure.

Null-terminated string Passes the address of the string data to the DLL procedure.

Page 110: Actuate Basic Reference

86 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

D e c l a r e . . . E n d D e c l a r e s t a t e m e n t

As <function data type>Clause that declares the data type of the value returned by a function procedure, and not valid with declarations of sub procedures. The argument <function data type> can be Integer, Long, Single, Double, Currency, String (variable-length only), or Variant.

Description Use Declare to declare external procedures—procedures contained in a DLL. Declare needs to appear at or near the beginning of the Actuate Basic source code (.bas) file. DLL procedures declared in any module are available to all procedures in all modules.

Empty parentheses indicate that the sub or function procedure has no arguments and that arguments should be checked to ensure that none are passed. In the following example, the sub First takes no arguments:

Declare Sub First Lib "MyLIB"()

If you use arguments in a call to First, an error occurs. The following example code would return an error for a sub First that takes no arguments:

Declare Sub First Lib "MyLIB" (arg%)

When an argument list appears, the number and type of arguments are checked each time the procedure is called. In the following example, the sub procedure Second takes one Long argument:

Declare Sub Second Lib "MyLIB" (X&)

Rule If the name of the procedure in the .dll does not conform to Actuate Basic naming conventions, you must use an Alias clause to specify it as it appears in the .dll. From that point on, <alias name> is the name used in Actuate Basic.

Example The following example shows a Declare statement that substitutes a shorter name (WinDir) for the full name of a Windows function that retrieves the Windows directory (GetWindowsDirectory). The function takes two arguments that are declared here by value and returns an integer:

Declare Function WinDir Lib "Kernel" Alias "GetWindowsDirectory" (ByVal ? lpBuffer As String, ByVal nSize As Integer) As Integer

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Call statement

Declare...End Declare statementDeclares global constants, global variables, and user-defined variable types.

Page 111: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 87

D e c l a r e . . . E n d D e c l a r e s t a t e m e n t

Syntax Declare

<declaration statements>

End Declare

Parameters <declaration statements>Any number of valid Actuate Basic global variable, global constant, or user-defined data type declaration statements.

Rule To declare global constants, global variables, and user-defined variable types in Actuate Basic, you must bookend your declarations with Declare and End Declare, as shown in the Example section that follows the Tips.

Tips ■ Do not confuse this multi-line Declare... End Declare statement with the single-line Declare statement that allows you to access functions in external dynamic link library files (DLLs).

■ You can use as few or as many Declare... End Declare blocks as you need. It is good programming practice, however, to position all such statements in one group at or near the beginning of your code.

Example The following code in a user Basic file contains several different types of declarations within a single Declare... End Declare block:

Declare

' Global dynamic array:Global CarModelsCount( )

' Global fixed array with 366 elements:Global Birthdays(366)

' Global Integer variable:Global PrintFlag as Integer

' Global constant:Global Const PI = 3.14159265359

' User-defined (non-intrinsic) variable type:Type FullName

FirstName As StringMiddleName As StringLastname As StringExactAge As Double

End Type

' A declaration based on the new non-instrinsic type above. Like an alias:Type PenName As FullName

Page 112: Actuate Basic Reference

88 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

D e c o d e , D e c o d e $ f u n c t i o n s

' Two similar user-defined variable types, but based on intrinsic types this time:

Type CustomerCount As IntegerType LiquidMeasure As Double

End Declare

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Const statementDeclare statementGlobal statementType...As statementType...End Type statement

Decode, Decode$ functionsConverts a value previously encoded using Encode from the internal encoding, and returns the string in the encoding format you specify.

This function is not supported. Use the Open statement encoding_name clause instead of this function to specify file encoding.

Syntax Decode(<value>, <encoding format>)

Decode$(<value>, <encoding format>)

Parameters <value>String expression encoded in the internal encoding format.

<encoding format>String expression that specifies the name of the encoding format you want the value to be encoded into, such as ASCII.

Examples:The United States locale can use the following encoding formats:

"ISO 8859-1", "USASCII", "ASCII"

Returns Decode: VariantDecode$: String

■ If <value> is Null, Decode[$] returns Null.

See also Open statement

Page 113: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 89

D i m s t a t e m e n t

Dim statementDeclares variables and allocates memory. Dim is an abbreviation for the Basic term dimension.

Syntax Dim <varname> [([<subscripts>])] [As [{Volatile|Transient|Persistent}] <type>] [, <varname> [([<subscripts>])] [As [{Volatile|Transient|Persistent}] <type>]]...

Parameters <varname>A name you create for the new variable.

<subscripts>Describes array dimensions according to the following syntax:

[<lower> To] <upper>[,[<lower> To]<upper>]...

Rules for <subscripts>:

■ If you do not supply subscript values between parentheses, Actuate Basic declares a dynamic array.

■ Range from <lower> to <upper> can be from -2147483648 to 2147483647, inclusive.

Examples of <subscripts>:The following statements are equivalent if you do not use Option Base:

Dim P(7,5)Dim P(0 TO 7, 0 TO 5)Dim P(7, 0 TO 5)

The following example declares a dynamic array:

Dim TestArray( )

[{Volatile|Transient|Persistent}]These keywords are optional. When omitted, the variable is Persistent by default.

You probably do not want to use these keywords in your own code, and Actuate does not support their use in the Variables dialog box. They are documented here to help you understand AFC source code more thoroughly.

Persistent—The variable is to be written to the .roi file subject to standard .roi compression.

Transient—The variable is used only in the Factory and is not written to the .roi file. When the object is read from the .roi file, Transient variables are set to their default values. Marking variables as Transient results in a smaller .roi file, and improves object locality.

Page 114: Actuate Basic Reference

90 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

D i m s t a t e m e n t

Volatile—Like a Persistent variable, the variable is written to the .roi file. However, unlike Persistent, Volatile variables are not subject to .roi compression. Marking variables as Volatile improves object locality for objects with variables that change frequently during a report run, at the cost of taking additional space in the .roi file.

As <type>Specifies a data type or class for the variable. If you specify a class, <varname> can hold a reference to an instance of that class or descendant classes; otherwise, if you do not specify As <type>, <varname> is of type Variant.

Description When you dimension variables with Dim, they are initialized as follows.

Rules ■ To declare variables that are available to all procedures within the module, use Global.

■ To declare variables that are available only in the procedure, use Dim at the procedure level.

■ You cannot redimension an array variable with ReDim if you explicitly specified its size using Dim.

Tips ■ To avoid assigning incorrect variable types, use the As clause to declare variable types.

■ To declare dynamic arrays, use Dim with empty parentheses after the variable name. Later, to define the number of dimensions and elements in the array, use ReDim:

Dim TestArray( )

■ To set the value of an instance handle to an instance of a class, use Set.

See also ReDim statementSet statement

Type Initialized as:

Numeric 0

Variant Empty

Variable-length strings Zero-length strings

CPointer Null

User-defined Separate variables

Object reference Nothing (before Set)

Page 115: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 91

D o . . . L o o p s t a t e m e n t

Do...Loop statementRepeats a block of instructions while a specified condition is True or until a specified condition becomes True.

Syntax Syntax 1

Do [{While | Until } <expression to reevaluate>]

<statements>

[Exit Do]

<statements>

Loop

Syntax 2

Do

<statements>

[Exit Do]

<statements>

Loop [{While | Until } <expression to reevaluate>]

Parameters WhileKeyword indicating that every time Actuate Basic begins or repeats the instructions between Do and Loop, Actuate Basic must determine whether <expression to reevaluate> is True or False.

Rules:

■ If <expression to reevaluate> is True, the program executes the loop.

■ If <expression to reevaluate> is False, or has become False during the last trip through the loop, Actuate Basic skips the intervening statements and passes control to the statement following Loop.

UntilKeyword indicating that every time Actuate Basic begins or repeats the instructions between Do and Loop, Actuate Basic must determine whether <expression to reevaluate> is True or False.

Rules:

■ If <expression to reevaluate> is False, the program executes the loop.

Page 116: Actuate Basic Reference

92 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

D o . . . L o o p s t a t e m e n t

■ If <expression to reevaluate> is True, or has become True during the last trip through the loop, Actuate Basic skips the intervening statements and passes control to the statement following Loop.

Example:The following example assumes Counter starts at 1 and increments by 1 each time through the loop, the following statement fragments are equivalent. In either case, the associated loop is executed nine times.

Do While Counter < 10Loop Until Counter = 10

If Counter is instead incremented by 2 each time, the first associated loop is executed five (1, 3, 5, 7, 9) times. The second loop, however, never stops executing because Counter increments from 9 to 11 and so never exactly equals 10. A minor correction can address this issue. In the following example, Counter is incremented by 2 each time and the loop executes only five times:

Do Until Counter >= 10

Exit DoA keyword indicating that the program must immediately interrupt the loop at the point at which the keyword occurs, and pass control to the statement following Loop.

<expression to reevaluate>Any valid numeric or string expression that evaluates to True or False.

<statements>Zero or more valid Actuate Basic statements.

Description If the condition to evaluate is placed at the bottom of the loop (after Loop), the loop executes at least once. If the condition to evaluate is placed after Do, the loop does not execute at all if the condition is initially false.

Tips ■ To stop a loop from continuing based upon whether a given expression is True or False, use Exit Do within a conditional structure like If Then.

■ Exit Do does not automatically exit all nested loops. When Do...Loop statements are nested, an Exit Do in a loop transfers control to the loop that is logically nested one level above the current one. For example, if you want to provide users with a way to back out of a complicated structure, map out a logical backtracking path in the form of several Exit Do statements, one at each level to which they are backtracking.

■ Evaluate Boolean variables using the keywords True or False.

Example The following example asks the user whether to display Demo 1 or Demo 2 first. In Demo 1, the program prompts the user to type a number within a certain range. If the number typed falls outside the range, the Demo repeats the prompt. In Demo 2, the program prints the numbers from 1 to 11:

Page 117: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 93

D o . . . L o o p s t a t e m e n t

Function OnLButtonDblClk()Dim DemoNum As Integer, Counter As IntegerDim NL As String, FirstShown As IntegerDim SecondShown As Integer, BothShown As IntegerDim UserTyped As Integer, Msg As String

' Get user inputDemoNum = InputBox("Choose whether to start with Demo 1 or 2.")

' Initialize flags and counters before the top of the loopCounter = 1 ' Initially set Counter to 1NL = Chr$(10) ' Define newlineFirstShown = False ' Assume Demo 1 has not been shownSecondShown = False ' Assume Demo 2 has not been shownBothShown = False ' Assume neither have been shown

' The outer loop will execute until the exit condition BothShown is trueDo Until BothShown

' First inner loop is executed if the user typed 1 Do While DemoNum = 1

' This is the first demoUserTyped = InputBox("Please type a number between 1 and 9.")If UserTyped >= 1 And UserTyped <= 9 Then

DemoNum = 2 ' Remember Demo 1 has been shownFirstShown = True ' User is ready for Demo 2Exit Do ' Exit first inner loop

End IfLoop

' The second inner loop is executed when the user type 2' but only if user hasn’t seen the second demo (SecondShown is false)Do While DemoNum = 2 And Not SecondShown

' This nested loop will execute 11 times and return to 2nd inner loopDo Until Counter = 12

Msg = Msg & Counter & NLCounter = Counter + 1

LoopDemoNum = 1SecondShown = True ' Exit condition for second inner loopMsgBox Msg

Loop' Set up final exit condition from outer loopIf FirstShown and SecondShown then BothShown = True

LoopMsgBox "Both demos have been shown. Goodbye!"

End Function

Page 118: Actuate Basic Reference

94 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

E n c o d e , E n c o d e $ f u n c t i o n s

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Exit statementIf...Then...Else statementWhile...Wend statement

Encode, Encode$ functionsConverts an internally encoded value into the encoding format you specify and returns the string in the new encoding format.

This function is not supported. Use the Open statement encoding_name clause instead of this function to specify file encoding.

Syntax Encode(<value>, <encoding format>)

Encode$(<value>, <encoding format>)

Parameters <value>String expression encoded in the internal encoding format.

<encoding format>String expression that specifies the name of the encoding format you want the value to be encoded into, such as ASCII.

Examples:The United State locale can use the following encoding formats:

"ISO 8859-1", "USASCII", "ASCII"

Returns Encode: VariantEncode$: String

■ If <value> is Null, Encode[$] returns Null.

See also Open statement

End statementSignals the completion of a multiline If...Then...Else statement, a Select Case statement, a block of Function or Sub statements, a Declare section, a Type or Class definition, or terminates the entire program.

Syntax End [{ Class | Declare | Function | If | Select | Sub | Type }]

Page 119: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 95

E n d s t a t e m e n t

Parameters EndKeyword that terminates the entire program.

End ClassKeyword that signifies the completion of a Class statement.

Rule: End Class must terminate every Class statement.

End DeclareKeyword that completes a multiple-line Declare statement.

Rule: End Declare must terminate a Declare statement that is in a multiline or block format.

End FunctionKeyword that completes a Function definition.

Rule: End Function must terminate every Function statement. Actuate Basic automatically supplies End Function when you type a Function statement.

End IfKeyword that completes a multiple-line If...Then...Else statement.

Rule: End If must terminate every If...Then...Else statement that is in multiline or block format.

End SelectKeyword that completes a Select Case statement.

Rule: End Select must terminate every Select Case statement.

End SubKeyword that completes a Sub procedure.

Rule: End Sub must terminate every Sub statement. Actuate Basic automatically supplies End Sub when you type a Sub statement.

End TypeKeyword that completes a Type statement.

Rule: End Type must terminate every Type statement.

Example The following example uses a Select Case block to return the name of the day of the week for the current day. To try this example, remove the End statement and run the example. The example generates an error message that says: Select Case without End Select:

Function OnLButtonDblClk()Dim DayNumber As Integer, DayName As StringDayNumber = Weekday(Date)

Page 120: Actuate Basic Reference

96 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

E n v i r o n , E n v i r o n $ f u n c t i o n s

Select Case DayNumberCase 1

DayName = "Sunday"Case 2

DayName = "Monday"Case 3

DayName = "Tuesday"Case 4

DayName = "Wednesday"Case 5

DayName = "Thursday"Case 6

DayName = "Friday"Case 7

DayName = "Saturday"End SelectMsgBox DayName

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Class statementDeclare statementFunction...End Function statementIf...Then...Else statementSelect Case statementStop statementSub...End Sub statementType...End Type statement

Environ, Environ$ functionsReturns the setting of a specified environment variable.

Syntax Environ$(<environment variable name>)

Environ[$](<environment variable name>)

or

Environ$(<table entry number>)

Environ[$](<table entry number>)

Page 121: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 97

E n v i r o n , E n v i r o n $ f u n c t i o n s

Parameters <environment variable name>String expression that specifies the name of an environment variable about which you want to know the settings. An environment variable is an Internal variable an operating system uses to hold information about the computer system in which your program is running. These variables contain information about the current drive and path, and special information needed by various programs. Although each computer system has a different set of environment variables with different values, few common ones exist, such as PATH.

Rule: Must not contain a space.

<table entry number>Numeric expression that specifies the variable’s entry number. This number corresponds to its position in the environment table, where the first line in the table is line 1.

Rule: Must be greater than zero.

Example:

PathToJavaClasses = Environ("CLASSPATH")

Returns Environ: VariantEnviron$: String

■ If <table entry number> is greater than the number of lines in the table, Environ[$] returns a Empty string.

■ If you call Environ[$] using <environment variable name>, the function returns only the content of the variable, not its name.

■ If you call Environ[$] using <table entry number>, the function returns both the content of the variable in that position and its name.

Example The following Windows-based code looks for the PATH environment variable in the user’s system. If it finds the variable, it then displays its entry number and the length of the string it contains:

Function OnLButtonDblClk ( )Dim EnvString As String, LineNumber As IntegerDim Msg As String, Pathlen As IntegerLineNumber = 1 ' Initialize line index to 1Do

EnvString = Environ(LineNumber) ' Get environment variableIf Left(EnvString, 5) = "PATH=" Then ' Is it the PATH entry?

Pathlen = Len(Environ("PATH")) ' If so, get its lengthMsg = "The PATH entry occurs at position " & LineNumber & ". "Msg = Msg & "Its length is " & Pathlen & "."Exit Do

Else' Not the PATH entry, so ...increment line counter

Page 122: Actuate Basic Reference

98 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

E O F f u n c t i o n

LineNumber = LineNumber + 1End If

Loop Until EnvString = ""If Pathlen > 0 Then

MsgBox MsgElse

MsgBox "This system is not using a PATH environment variable."End If

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Command, Command$ functions

EOF functionReturns a value that indicates whether the end of a file being input has been reached.

Syntax EOF(<open file number>)

Parameters <open file number>Numeric expression that is the file descriptor used in the previously issued Open statement to open the target file.

Rules:

■ Must be the number of a currently open file.

■ Must refer to a disk file.

Examples:The following code opens an existing disk file and then uses EOF repeatedly to test whether or not the end of the file has yet been reached:

Open "c:\Vb\Tests\test.fil" For Input As #1Do While Not EOF(1)'Test for end of file. Input #1, FileData 'Read line of data.Loop

Returns Integer (0 for False or 1 for True)

EOF behaves differently depending upon the mode of access you use for the file:

■ For sequential files, EOF returns True if the end of the file has been reached. Otherwise, EOF returns False.

Page 123: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 99

E O F f u n c t i o n

■ For random or binary files, EOF returns True if the last executed Get statement was unable to read an entire record. Otherwise, EOF returns False.

Tip Use EOF when you handle sequential files to avoid an error generated when you try to access a file’s contents past the end of a file.

Example The following example creates a test file on disk that contains random numbers. The procedure opens the test file, reports the last value in the test file, and deletes the sample file from the disk. In this example OnLButtonDblClk( ) is overridden to generate the test file, report the value, and prompt the user to delete the test file. The procedure MakeDataFile( ) should be typed after the End Function of the OnLButtonDblClk( ) procedure or saved in an Actuate code module (.bas file):

Function OnLButtonDblClk()Dim NL As String, TempVar As Integer, Msg As StringNL = Chr$(10) ' Define newlineMakeDataFile ' Generate sample fileOpen "Test.fil" For Input As #1 ' Open sample for inputDo While Not EOF(1) ' Check for end of file

Input #1, TempVar ' Read dataLoopClose #1 ' Close test fileMsg = "The last value in the test file was "Msg = Msg & TempVar & "." & NLMsg = Msg & NL & "Select OK to delete the created test file."MsgBox MsgKill "Test.fil" ' Delete test file

End Function''Here is the procedure that generates the test file'Sub MakeDataFile ( )

Dim I As IntegerOpen "Test.fil" For Output As #1 ' Open file for outputFor I = 0 To 250 ' Generate random values

Print #1, Int(711 * Rnd)Next IClose #1 ' Close test file

End Sub

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Loc functionLOF functionOpen statement

Page 124: Actuate Basic Reference

100 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

E r a s e s t a t e m e n t

Erase statementDeallocates memory reserved for dynamic arrays, or reinitializes the elements in a fixed array.

Syntax Erase <array name>... [, <array name> ]

Parameters <array name>Any valid array name.

Example:

Erase BigArray

Description Erase behaves differently depending upon whether <array name> refers to a fixed or to a dynamic array:

■ When Erase refers to a fixed array, Erase reinitializes the contents of the array but does not free up memory.

■ When Erase refers to a dynamic array, Erase recovers the memory previously allocated to the array.

Erase reinitializes fixed arrays as follows.

Tips ■ If you erase a dynamic array, you can use Dim or ReDim to create a new dynamic array with the same name as the old one.

■ You do not need to erase a dynamic array before you redimension it with ReDim.

Example The following example creates an array, fills it with values, and then erases it:

Static Function OnLButtonDblClk()' Declare variablesDim I As Integer, J As Integer, Total As Long, MsgDim Matrix(50, 50) As Integer ' Create 2-D integer array

Type of fixed array Array element set to

Numeric 0 (Zero)

String (variable-length) Empty

Variant Empty

User-Defined The value as shown here for each component type, taken separately

Object Nothing

CPointer Null

Page 125: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 101

E r l f u n c t i o n

For I = 1 To 50For J = 1 To 50

Matrix(I, J) = J ' Put some values into arrayNext J

Next IErase Matrix ' Erase arrayTotal = 0 ' Initialize total counterFor I = 1 To 50

For J = 1 To 50Total = Total + Matrix(I, J) ' Sum elements after Erase

Next J ' to make sure all are setNext I ' to zeroMsg = "An array has been created, filled, and erased. When the "Msg = Msg & "Erase statement was executed, zeros replaced the "Msg = Msg & "previous contents of each element. The total of "Msg = Msg & "all elements is now " & Total & ", "Msg = Msg & "demonstrating that all elements have been cleared."MsgBox Msg ' Display message

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Dim statementReDim statement

Erl functionReturns the line number for the most recent run-time error.

Syntax Erl

Returns Integer

■ When it runs an application, Actuate Basic uses Erl to report the number of the line at which the most recent error occurred, or of the line most closely preceding it.

■ When Erl is 0, it means one of three things:■ No run-time error has occurred.■ An error could have occurred, but there was no line number just before

the point at which the error occurred, or your program contains no line numbers.

■ Actuate Basic has reset Erl to 0 because it executed Resume or On Error, or because it executed Exit Sub or Exit Function from within an error handling routine.

Page 126: Actuate Basic Reference

102 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

E r r f u n c t i o n

■ Erl returns only a line number, not a line label.

Tips ■ To preserve the value of Erl before it gets reset to 0, immediately assign it to a variable.

■ To set the value of Erl indirectly, simulate an error condition using an Error statement.

Example In the following example, the program generates an error because it attempts to divide a number by zero. It then displays a message to the user indicating the line number of the error:

Function OnLButtonDblClk ( )Dim XVar, YVar, ZVarOn Error GoTo ErrorHandler ' Set up error handlerYVar = 1' Now cause division by zero error: XVar = YVar / ZVarExit Function

ErrorHandler: ' Error handler starts hereMsgBox "Error occurred at program line " & ErlResume Next

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Err statementError statementOn Error statementResume statement

Err functionReturns the code number for the most recent run-time error.

Syntax Err

Returns Integer

■ Returns an Integer between 0 and 2,147,483,647.

■ When it runs an application, Actuate Basic uses Err to report the occurrence of a run-time error and its error code.

■ When Err is 0, it means no run-time error has occurred.

Page 127: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 103

E r r s t a t e m e n t

■ Actuate Basic sets or resets Err to 0 whenever it executes Resume or On Error, or whenever it executes Exit Sub or Exit Function from within an error handling routine.

Tips ■ To preserve the value of Err before it gets reset to 0, immediately assign it to a variable.

■ To set the value of Err directly, use an Err statement. To set it indirectly, simulate an error condition using an Error statement.

Example In the following example, the program generates an error because it attempts to divide a number by zero. It then displays the code number of the error:

Function OnLButtonDblClk()Dim XVar, YVar, ZVarOn Error GoTo ErrorHandler ' Set up error handler

YVar = 1' Now cause division by zero error:XVar = YVar / ZVar

Exit Function'ErrorHandler: ' Error handler starts here

MsgBox "Error number " & Err & " occurred"Resume Next

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Erl functionErr statementError statementOn Error statementResume statementError, Error$ functionsError statement

Err statementSets Err to a given value.

Syntax Err = <error code>

Parameters <error code>Numeric expression between 0 and 2,147,483,647 indicating the code of the most recent run-time error.

Page 128: Actuate Basic Reference

104 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

E r r s t a t e m e n t

Description ■ When it runs an application, Actuate Basic uses Err to record the occurrence of a run-time error and its error code.

■ When Err is 0, it means no run-time error has occurred.

■ Actuate Basic sets or resets Err to 0 whenever it executes Resume or On Error, or whenever it executes Exit Sub or Exit Function from within an error handling routine.

Tips ■ To define and use your own error code, use a value for <error code> that is greater than any of the standard Actuate Basic error codes. You can work down from error code 2,147,483,647 to find an available user-defined error number. Write a routine that assigns that number to Err whenever certain error conditions that you define are true. Also write an error handling routine that translates the error number into an understandable message for the user.

■ There are many user-defined codes among the standard ones.

■ The Error statement can set Err to any value, because it simulates any run-time error.

■ To preserve the value of Err before it gets reset to 0, immediately assign it to a variable.

Example The following example prompts the user for a filename, attempts to open the file to verify its existence, then handles a range of errors that might result:

Function OnLButtonDblClk ( )Dim FileName As StringOn Error Resume Next ' Set up error handlerFileName = InputBox("Please type a file name: ")Do

Err = 0 ' Clear any errorOpen FileName For Input As #1 ' Attempt to open fileSelect Case Err ' Handle error, if any

Case 0 ' No error = success!MsgBox UCase$(FileName) & " was found."

Case 14 ' I/O errorsFileName = InputBox("File not found. Please try again.")

Case Else ' Handle all other casesMsgBox "Error: Sorry! Cannot continue!"Exit Do ' Don't try again = failed!

End SelectLoop Until Err = 0Close #1 ' Clean up

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

Page 129: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 105

E r r o r , E r r o r $ f u n c t i o n s

See also Erl functionErr functionError, Error$ functionsError statement

Error, Error$ functionsReturns the error message for the most recent run-time error, or for a specified error number.

Syntax Error[(<error code>)]

Error$[(<error code>)]

Parameters <error code>Numeric expression between 1 and 2,147,483,647 that is the error number to be displayed as a message string by Error[$].

Rule: If <error code> is not defined by Actuate Basic, Error[$] returns the message string: User-defined error.

Default: The message string for the most recent run-time error, if an error has occurred, or a zero-length string, if no error has occurred.

Rule: <error code> must be between 1 and 2,147,483,647, inclusive.

Returns Error: VariantError$: String

■ With <error code>, the Error[$] function returns the message for the specified error number. In cases where context-sensitive information is inserted in the message at run-time, the context-sensitive string is replaced with a space character. For example, in the following message, a space is inserted where the array element index number would normally appear:

Control array element ' ' doesn’t exist.

■ Without <error code>, the Error[$] function returns the message for the most recent run-time error. If no error has occurred, the Error[$] function returns an empty string.

Example The following example shows error messages for user input number errors:

Function OnLButtonDblClk ( )' Demo of Error$ function and Error statementDim Msg, NL, UserError, TempUserOn Error GoTo ErrorHandler ' Set up error handlerNL = Chr$(10) ' Define newlineTempUser = InputBox("Please type the number of an error to simulate.")

Page 130: Actuate Basic Reference

106 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

E r r o r s t a t e m e n t

UserError = Int(TempUser) ' Convert response to integerError UserError ' Simulate given errorExit Function

ErrorHandler: ' Error handler starts hereMsg = "The message for error number "Msg = Msg & Err & " is:" & NL & NLMsg = Msg & Error(Err)MsgBox MsgResume Next

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Erl functionErr functionError statement

Error statementSimulates the occurrence of an error. Also, generates a user-defined error.

Syntax Error <error code>[ ,<message> [ ,<message>....]]

Parameters <error code>Integer between 1 and 2,147,483,647 that is the error you wish to artificially generate.

Example:The following statement causes Actuate Basic to stop your program and display the message Division by zero, whether or not your program has actually attempted to divide anything by zero:

Error 8

<message>You can pass any number of arguments in order to replace standard error messages. All extra messages are converted to strings and concatenated together. Then, the concatenated message is displayed instead of the standard error message.

Description ■ By setting the value of Err to <error code>, this statement simulates the occurrence of a specified error. It then passes control to whatever error-handling routine you have enabled, if any, so that in a debugging session you can verify whether or not that error-handler works.

■ If you have not enabled an error-handler when your program executes this statement, Actuate Basic stops your program and displays its own internal

Page 131: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 107

E x i t s t a t e m e n t

error message if it has one corresponding to <error code>, or User-defined error if it does not.

Tips ■ To define your own error code, use a value for <error code> that is greater than any of the standard Actuate Basic error codes. You can work down from error code 2,147,483,647 to find an available user-defined error number.

■ You will find many user-defined codes among the standard error codes Actuate Basic uses.

Example The following example prompts the user for an error number, simulates the appropriate error, and passes control to an error handler, which then retrieves the corresponding message:

Function OnLButtonDblClk ( )' Demo of Error$ function and Error statementDim Msg, NL, UserError, TempUserOn Error GoTo ErrorHandler ' Set up error handlerNL = Chr$(10) ' Define newlineTempUser = InputBox("Please type the number of an error to simulate.")UserError = Int(TempUser) ' Convert response to integerError UserError ' Simulate given errorExit Function

ErrorHandler: ' Error handler starts hereMsg = "The message for error number "Msg = Msg & Err & " is:" & NL & NLMsg = Msg & Error(Err)MsgBox MsgResume Next

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Erl functionErr functionErr statementOn Error statementResume statement

Exit statementTerminates execution of the instructions specified in a Do Loop or For Next structure, or in a Function or Sub procedure.

Page 132: Actuate Basic Reference

108 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

E x i t s t a t e m e n t

Syntax Exit { Do | For | Function | Sub }

Parameters Exit DoKeyword used to terminate a Do...Loop statement.

Rules for Exit Do:

■ When it encounters Exit Do, Actuate Basic transfers control to the statement following the Loop keyword.

■ If it encounters Exit Do within a nested loop, the program transfers control to the loop that is nested one level above the one in which it occurs.

■ Use Exit Do only within a Do Loop statement.

Exit ForKeyword used to terminate a For...Next statement.

Rules for Exit For:

■ When it encounters Exit For, Actuate Basic transfers control to the statement following the Next keyword.

■ If it encounters Exit For within a nested loop, the program transfers control to the loop that is nested one level above the one in which it occurs.

■ Use Exit For only within a For Next statement.

Exit FunctionKeyword used to terminate a Function statement.

Rule for Exit Function: When it encounters Exit Function, Actuate Basic transfers control to the statement following the one that called the current Function statement.

Exit SubKeyword used to terminate a Sub statement.

Rule: When it encounters Exit Sub, Actuate Basic transfers control to the statement following the one that called the current Sub statement.

Tips ■ To stop a loop from continuing or repeating based upon whether or not a given expression is true, use Exit Do within a conditional structure like an If...Then...Else statement.

■ Do not confuse Exit with End. Use End to define the completion of a structure.

Example The following example shows how to use nested statements with Exit. When a random number generated matches one of those specified in the first Case clause, Actuate Basic exits the For...Next statement and the Do...Loop statement in two separate steps via both Exit For and Exit Do. When the random number matches one of those in the second Case clause, Actuate Basic

Page 133: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 109

E x i t s t a t e m e n t

exits the both statements in only one step, using Exit Do alone. A message reports in which Case clause the loops were terminated:

Function OnLButtonDblClk()Dim I As Integer, Num As Integer, Msg As StringDim NL As String, BumpOut As Integer

NL = Chr$(10) ' Define newlineBumpOut = False ' Set a flag for ultimate exitRandomize Timer ' Generate random numbersDo ' Set up an infinite loop

If BumpOut Then Exit Do ' If we exited FOR, let's also exit DOFor I = 1 To 1000

Num = Int(Rnd * 100) ' Generate random numberSelect Case Num

Case 7, 11, 13, 25' This case causes an immediate exit from the For loop and ' will cause an exit from the Do loop on the next iterationBumpOut = True ' Set flag for exit from Do next timeExit For

Case 29, 35, 87' This case causes an immediate exit from both loops but leaves' BumpOut set to false so we can tell where the exit occurredExit Do ' Directly exit in one step

End SelectNext I

LoopIf BumpOut Then ' We exited in the first Case clause

Msg = "Exited because of " & Num & " (1st case: Two-step exit)."Else

Msg = "Exited because of " & Num & " (2nd case: One-step exit)."End IfMsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Do...Loop statementEnd statementFor...Next statementFunction...End Function statementSub...End Sub statement

Page 134: Actuate Basic Reference

110 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

E x p f u n c t i o n

Exp functionRaises e to the specified power.

Syntax Exp(<power>)

Parameters <power>Number, numeric expression, or Variant of VarType 8 (String) that specifies the exponent.

Rules:

■ <power> cannot be greater than 709.782712893.

■ If <power > is a String, it is parsed according to the formatting rules of the current run time locale.

Returns Double

■ If <power> evaluates to Null, Exp returns a Null.

Tip Exp is the inverse of Log.

Example The following example prompts the user for a trigonometric angle expressed in radians, and uses the Exp function to calculate the hyperbolic sin of the angle:

Function OnLButtonDblClk( )

Dim UserAngle As Double, HyperbolicSin As DoubleDim Msg As String

'Get angle in radiansUserAngle = InputBox("Type an angle in radians")

'Calculate hyperbolic sineHyperbolicSin = (Exp(UserAngle) - Exp(-1 * UserAngle)) / 2

Msg = "The hyperbolic sin is " & HyperbolicSinMsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Log function

Page 135: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 111

E x t e n d S e a r c h P a t h f u n c t i o n

ExtendSearchPath functionAdds directories to search for included images and files specified in the FindFile function.

Syntax ExtendSearchPath(<directory>)

Parameters <directory>A directory add to the search path.

Description Call ExtendSearchPath to specify additional directories to search when locating images and files specified in the FindFile function. Call this function once for each directory to be added to the search path.

You can call ExtendSearchPath at factory time, view time, or both. If you call ExtendSearchPath at factory time, the directory is added to the search path only when locating files included at factory time. If you call ExtendSearchPath at view time, the directory is added to the search path only when locating files included at view time.

Example The following example adds C:\Documents and M:\Documents to the complete search path at factory time:

Sub Start()

ExtendSearchPath( "C:\Documents\" )ExtendSearchPath( "M:\Documents\" )

End Sub

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also FindFile function

Page 136: Actuate Basic Reference

112 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

F i l e A t t r f u n c t i o n

FileAttr functionReturns the mode of an open file or its DOS file handle.

Syntax FileAttr(<file number>, <info type>)

Parameters <file number>Numeric expression that is the number you used as a file descriptor when you opened the target file.

Rule: Must evaluate to the number of a currently open file.

<info type>Numeric expression that specifies whether to return the open mode of the file (1), or the DOS file handle (2).

Rule: Must evaluate or round to 1 or 2.

Example:In the following code, Actuate Basic opens a file, then stores values returned by FileAttr in corresponding variables:

Open "TEST" For Input As #1

OpenMode = FileAttr(1,1)

DOSHandle = FileAttr(1,2)

Returns Integer

■ When <info type> is 1, FileAttr returns a number that defines the mode under which the file was opened. The following table lists possible values for FileAttr when <info type> is 1, and the corresponding modes.

■ When <info type> is 2, FileAttr returns the file handle that DOS has assigned to the open file.

Example In the following example, Actuate Basic creates a test file by opening it for Append. Then it displays a message indicating the DOS handle and open mode of the file:

Return value Mode for which file was opened

1 Input

2 Output

4 Random

8 Append

32 Binary

Page 137: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 113

F i l e C o p y s t a t e m e n t

Function OnLButtonDblClk( )

Dim FileNum As Integer, DOSHandle As Long

Dim OpenMode As String, Msg As String

' Get next available file number

FileNum = FreeFile

Open "TESTFILE" For Append As FileNum ' Create sample file

DOSHandle = FileAttr(FileNum, 2) ' Get file DOS handle

Select Case FileAttr(FileNum, 1) ' Determine OpenMode

Case 1: OpenMode = "Input"

Case 2: OpenMode = "Output"

Case 4: OpenMode = "Random"

Case 8: OpenMode = "Append"

Case 32: OpenMode = "Binary"

End Select

Close FileNum ' Close test file

Msg = "The file assigned DOS file handle " & DOSHandle

Msg = Msg & " was opened for " & OpenMode & "."

MsgBox Msg

Kill "TESTFILE" ' Delete test file

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also GetAttr functionOpen statementSetAttr statement

FileCopy statementCopies a file. Similar to the DOS command Copy.

Syntax FileCopy <source>, <destination>

Parameters <source>String expression that specifies the file to copy. Can include optional drive and path information.

Default path: Current default drive and directory.

Rules for <source>:

■ Cannot include wildcard characters.

■ Must refer to an existing file.

Page 138: Actuate Basic Reference

114 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

F i l e C o p y s t a t e m e n t

<destination>String expression that specifies where <source> is to be copied. Can include optional drive and path information.

Default path: Current default drive and directory.

Rules for <destination>:

■ Must conform to platform’s file naming conventions. Platform can be Windows 3.1, Windows NT, Windows 95, and UNIX.

■ Cannot include wildcard characters.

<source> or <destination> can optionally specify full path information, in which case either has the following syntax:

[<drive:>] [ \ ]<directory>[\<directory>]...(Windows)

[ / ]<directory>[/<directory>]...(UNIX)

<drive:>Character, followed by a colon. Specifies the drive (Windows only).

<directory>String expression that specifies the name of a directory or subdirectory.

Example:Assuming a file name Temp.fil exists on a Windows system, and that it is located on the current drive and in the current directory, the following code copies it, places the new copy on drive D in the subdirectory \Files\Archives, and names that copy Temp.arc, while leaving Temp.fil alone where it is:

NewName = "D:\Files\Archives\Temp.arc"

FileCopy "Temp.fil", NewName

Example In the following example, Actuate Basic prompts the user for the names of a source and destination file, then copies the source to the destination:

Function OnLButtonDblClk ( )

Dim SourceFile As String, DestFile As String, Msg As String

On Error GoTo ErrHandler

SourceFile = InputBox("Copy what file?")

DestFile = InputBox("To where?")

FileCopy SourceFile, DestFile ' Copy file to destination

Exit Function

ErrHandler:

Select Case Err

Case 48 ' Path not found

MsgBox "Sorry! Path not found."

Case 40

MsgBox "Sorry! Permission denied, or drive not available."

End Select

Page 139: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 115

F i l e D a t e T i m e f u n c t i o n

Msg = "An error occurred. Try specifying the full path "

Msg = Msg & "name of the source file, of the destination file, "

Msg = Msg & "or of both. If referring to a floppy drive, be sure "

Msg = Msg & "the correct disk is in the drive."

MsgBox Msg

Resume Next

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Kill statementName statement

FileDateTime functionReturns a string that indicates the date and time a specified file was created or last modified. The date is formatted according to the formatting rules of the current run time locale.

Syntax FileDateTime(<file spec>)

Parameters <file spec>String expression that specifies the name of a valid file. Can include optional drive and path information.

Default path: Current default drive and directory.

Rules:

■ <file spec> must be an unambiguous specification. Wildcard characters are not allowed.

■ Indicated file or files must exist.

■ Path, if specified, must exist.

<file spec> can optionally specify full path information, in which case it has the following syntax:

[<drive:>] [ \ ]<directory>[\<directory>]... (Windows)

[ / ]<directory>[/<directory>]... (UNIX)

<drive:>Character, followed by a colon, that specifies the drive on which the file is located (Windows only).

Page 140: Actuate Basic Reference

116 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

F i l e E x i s t s f u n c t i o n

<directory>String expression that specifies the name of a directory or subdirectory that constitutes a branch in the full path specification of <file spec>.

Example:The following statement determines when the file Mydata.mdb on a Windows system in the subdirectory C:\Access was last modified, and converts the returned string to a date variant:

LastSaved = CVDate(FileDateTime("C:\Access\Mydata.mdb"))

Returns String

Example The following example prompts the user for the name of a file and displays the date and time the file was created or last modified and its size in bytes:

Function OnLButtonDblClk ( )

Dim Msg As String, TimeStamp As String, UserFile As String

On Error Goto ErrHandler

UserFile = InputBox("Please type a file name.") ' Get file name

TimeStamp = FileDateTime(UserFile) ' Get file date/time

Msg = UCase$(UserFile) & " was created or last modified on "

Msg = Msg & Format(TimeStamp, "dddd, mmmm dd, yyyy") & " at "

Msg = Msg & Format(TimeStamp, "h:nn AM/PM") & ". Its size is "

Msg = Msg & FileLen(UserFile) & " bytes." ' Get file size

MsgBox Msg

Exit Function

ErrHandler:

MsgBox "Sorry! An error occurred. Please check the file name."

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also FileLen functionFileTimeStamp functionGetAttr functionLOF function

FileExists functionDetermines whether or not a given file or directory exists.

Syntax FileExists(<filename or dirname> [As String]) [As Boolean]

Parameters <filename or dirname>String expression enclosed in double quotes that is the name of the file, directory, or subdirectory the existence of which you wish to determine.

Page 141: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 117

F i l e L e n f u n c t i o n

Default path: Current drive and directory.

<filename or dirname> can optionally specify a full path, in which case it has the following syntax:

[<drive:>][\]<directory>[\<directory>]...(Windows)

[/]<directory>[/<directory>]...(UNIX)

<drive:>Character, followed by a colon, that specifies the drive (Windows only).

<directory>String expression that specifies the name of a directory or subdirectory.

Returns Boolean

True if the file or directory exists, False otherwise.

Tip It is good programming practice to evaluate Boolean variables by using the keywords True or False, instead of by inspecting their content for a nonzero (True) or zero (False) numeric value.

Example Assuming a file called Readme.txt exists in the current directory, the following statement assigns the value True to the variable FileAlreadyInstalled:

FileAlreadyInstalled = FileExists("Readme.txt")

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also FileDateTime functionGetAttr functionKill statementName statementOpen statement

FileLen functionReturns the length of a given file in bytes.

Syntax FileLen(<file spec>)

Parameters <file spec>String expression that specifies the name of a valid file. Can include optional drive and path information.

Default path: Current default drive and directory.

Page 142: Actuate Basic Reference

118 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

F i l e L e n f u n c t i o n

Rules:

■ Must be an unambiguous specification. Wildcard characters are not allowed.

■ Indicated file or files must exist.

■ Path, if specified, must exist.

<file spec> can optionally specify full path information, in which case it has the following syntax:

[<drive:>] [ \ ]<directory>[\<directory>]... (Windows)

[ / ]<directory>[/<directory>]... (UNIX)

<drive:>Character, followed by a colon that specifies the drive on which the file is located (Windows only).

<directory>String expression that specifies the name of a directory or subdirectory that constitutes a branch in the full path specification of <file spec>.

Example:The following statement determines the length of the file Mydata.mdb on a Windows system in the subdirectory C:\Access, and assigns the value to a variable:

SizeOfFile = FileLen("C:\Access\Mydata.mdb")

Returns Integer

Rule: If the file specified in <file spec> is open when you call FileLen, the value FileLen returns represents the length of the file before it was opened.

Example The following example prompts the user for the name of a file, then displays the date and time the file was last created or modified, and its size in bytes:

Function OnLButtonDblClk ( )

Dim Msg As String, TimeStamp As String, UserFile As String

On Error Goto ErrHandler

UserFile = InputBox("Please type a file name.") ' Get file name

TimeStamp = FileDateTime(UserFile) ' Get file date/time

Msg = UCase$(UserFile) & " was created or last modified on "

Msg = Msg & Format(TimeStamp, "dddd, mmmm dd, yyyy") & " at "

Msg = Msg & Format(TimeStamp, "h:nn AM/PM") & ". Its size is "

Msg = Msg & FileLen(UserFile) & " bytes." ' Get file size

MsgBox Msg

Exit Function

ErrHandler:

MsgBox "Sorry! An error occurred. Please check the file name."

End Function

Page 143: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 119

F i l e T i m e S t a m p f u n c t i o n

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also FileDateTime functionGetAttr functionLOF function

FileTimeStamp functionReturns the date and time the specified file was created or last modified.

Syntax FileTimeStamp(<file spec>)

Parameters <file spec>String expression that specifies the name of a valid file. Can include optional drive and path information.

Default path: Current default drive and directory.

Rules:

■ <file spec> must be an unambiguous specification. Wildcard characters are not allowed.

■ Indicated file or files must exist.

■ Path, if specified, must exist.

<file spec> can optionally specify full path information, in which case it has the following syntax:

[<drive:>] [ \ ]<directory>[\<directory>]... (Windows)

[ / ]<directory>[/<directory>]... (UNIX)

<drive:>Character, followed by a colon, that specifies the drive on which the file is located (Windows only).

<directory>String expression that specifies the name of a directory or subdirectory that constitutes a branch in the full path specification of <file spec>.

Example:The following statement determines when the file Mydata.mdb on a Windows system in the subdirectory C:\Access was last modified, and converts the returned string to a date variant:

LastSaved = CVDate(FileTimeStamp("C:\Access\Mydata.mdb"))

Page 144: Actuate Basic Reference

120 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

F i n d F i l e f u n c t i o n

Returns Date

Example The following example prompts the user for the name of a file, then displays the date and time the file was last created or modified, and its size in bytes:

Function OnLButtonDblClk ( )

Dim Msg As String, TimeStamp As Date, UserFile As String

On Error Goto ErrHandler

UserFile = InputBox("Please type a file name.") ' Get file name

TimeStamp = FileTimeStamp(UserFile) ' Get file date/time

Msg = UCase$(UserFile) & " was created or last modified on "

Msg = Msg & Format(TimeStamp, "dddd, mmmm dd, yyyy") & " at "

Msg = Msg & Format(TimeStamp, "h:nn AM/PM") & ". Its size is "

Msg = Msg & FileLen(UserFile) & " bytes." ' Get file size

MsgBox Msg

Exit Function

ErrHandler:

MsgBox "Sorry! An error occurred. Please check the file name."

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also FileDateTime functionFileLen functionGetAttr function

FindFile functionResolves a relative file name by searching for the file through the existing search path.

Syntax FindFile(<filename>)

Parameters <filename>The relative file path.

Returns ■ If the file is found, the absolute path to the file.

■ If the file is not found, an empty string.

Description Call FindFile to resolve a relative file name by searching for the file through the existing search path.

You can call FindFile at factory time, view time, or both. If you call FindFile at factory time, Actuate searches for the specified file only at run time. In this case, Actuate searches the following:

Page 145: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 121

F i n d F i l e f u n c t i o n

1 If the referring .rod file is open, the design search path.

For information about the design search path, see Chapter 5, “Customizing the design environment,” in Developing Advanced e.Reports.

2 The search path specified in the ExtendSearchPath function when ExtendSearchPath is called at factory time.

3 Global search path.

For information about the global search path, see Chapter 5, “Customizing the design environment,” in Developing Advanced e.Reports.

4 Configuration file search path.

For information about the configuration file search path, see Appendix A, “Using a configuration file,” in Developing Advanced e.Reports.

If you call FindFile at view time, Actuate searches for the specified file only at view time. In this case, Actuate searches the following:

1 The search path specified in the ExtendSearchPath function when ExtendSearchPath is called at view time.

2 Global search path.

For information about the global search path, see Chapter 5, “Customizing the design environment,” in Developing Advanced e.Reports.

3 Configuration file search path.

For information about the configuration file search path, see Appendix A, “Using a configuration file,” in Developing Advanced e.Reports.

Example The following example sends Data.txt as a relative path and calls ExtendSearchPath to add C:\Documents\: and M:\Documents\ to the search path:

dim RelativeFile as String

dim FullFileName as String

RelativeFile = "Data.txt"

ExtendSearchPath( "C:\Documents\" )

ExtendSearchPath( "M:\Documents\" )

FullFileName = FindFile( RelativeFile )

If FullFileName = "" Then

ShowFactoryStatus( "File not found!" )

Else

Open FullFileName as #1

End If

Page 146: Actuate Basic Reference

122 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

F i x f u n c t i o n

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also ExtendSearchPath function

Fix functionRemoves the fractional part of a numeric expression and returns the integer that remains.

Syntax Fix(<number to truncate>)

Parameters <number to truncate>A numeric expression from which the fractional part is removed so that only the integer component is returned.

Returns ■ Int and Fix are functionally similar but not identical. For negative values, Int returns the first negative integer less than or equal to <number to round>. Fix returns the first negative integer greater than or equal to <number to round>. CInt is also similar, but not identical, to both Int and Fix.

■ Using some sample values as arguments, the following table shows the differences between Int, Fix, and CInt.

Data type of <number to truncate> Data type returned

Variant of VarType 8 (String) that can convert to a number

Variant of VarType 5 (Double). If a String, it is parsed according to the formatting rules of the current run time locale. For example:

Fix("123,456") returns 123.456 on a French locale

Fix ("123,456") returns 123456.00 on an English locale

Any other data type Same data type as <number to truncate>

Null Null

Value Int (Value) Fix (Value) CInt (Value)

3.7 3 3 4

3.2 3 3 3

Page 147: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 123

F o l l o w H y p e r l i n k s t a t e m e n t

Tip Fix is equivalent to Sgn (<number to round>) * Int (Abs (<number to round>)).

Example The following example prompts the user for a number and displays the return values from Int, Fix, and CInt:

Function OnLButtonDblClk()

Dim Num As Double, Msg As String, NL As String

NL = Chr$(10) ' Define newline

' Get user input and strip off any surrounding spaces

Num = InputBox("Please type a number.")

Msg = "Int(" & Num & ") = " & Int(Num) & NL

Msg = Msg & "Fix(" & Num & ") = " & Fix(Num) & NL

Msg = Msg & "CInt(" & Num & ") = " & CInt(Num) & NL

MsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also CInt functionInt function

FollowHyperlink statementOpens a new document specified by a given URL in a given browser target window.

Syntax FollowHyperlink(<hyperlink>, <target window name>)

Parameters <hyperlink>String expression. Specifies the URL of the new document to open.

Rules for <hyperlink>:

■ Must be a valid URL.

■ If you call FollowHyperlink from Actuate LRX, <hyperlink> must be a Web-style link, not a link using rotp protocol.

3 3 3 3

-3 -3 -3 -3

-3.2 -4 -3 -3

-3.7 -4 -3 -4

Value Int (Value) Fix (Value) CInt (Value)

Page 148: Actuate Basic Reference

124 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

F o l l o w H y p e r l i n k s t a t e m e n t

Examples:

FollowHyperlink("http://www.yahoo.com/","")

FollowHyperlink("Sales East/Index.htm","")

FollowHyperlink("Sales East/East Forecast Detail.roi","")

<target window name>String expression. The name of the browser window in which to display the new document.

Rules for <target window name>:

■ Must be a valid window name, or an empty string. For information about how to construct and use window names, see your browser’s documentation.

■ Works in LRX for Netscape Navigator.

■ Ignored by LRX for Microsoft Internet Explorer.

■ Ignored by standard clients.

Description Use FollowHyperlink() to build hyperlink expressions at run time. FollowHyperlink() behaves differently depending upon whether you call it from Actuate Viewer, or Actuate LRX.

If you call FollowHyperlink() from Actuate Viewer, Actuate opens a new window to display the document.

If you call FollowHyperlink() from Actuate LRX:

■ The linked document displays in the same browser instance.

■ If <target window name> is empty, or matches the name of the window containing Actuate LRX, the linked document replaces Actuate LRX.

■ If <target window name> is the name of another window, the document appears in the named window, and Actuate LRX remains visible.

Actuate calls FollowHyperlink() automatically to open a hyperlink you specify in the LinkExp property of a control.

Tips ■ Use FollowHyperlink() to add additional hyperlinks to the context menu for a component, or to change the value of the hyperlink dynamically based on view time code.

■ Use FollowHyperlink() to dynamically populate a component’s context menu so that the menu offers appropriately different URLs to which the user can jump—URLs that vary as a function of the run-time value of the component.

Page 149: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 125

F o r m a t , F o r m a t $ f u n c t i o n s

Example The following example uses a component called OfficesRegion. In the example you override the AddMenuCommands method of this component and add a new method, LinkToDetail().

At view time, if the value of OfficesRegion is East, and you right-click OfficesRegion, you see a context menu labeled Eastern Detail.

Choosing Eastern Detail launches LinkToDetail(), this method in turn calls FollowHyperlink(), which in turn launches your web browser and opens the HTML page called Index.htm, located in the subfolder Sales East:

Sub AddMenuCommands( menu As AcPopupMenu )

Select Case DataValue

Case "East"

menu.AddItem( "Eastern Detail", me, "LinkToDetail")

Case "West"

menu.AddItem( "Western Detail", me, "LinkToDetail")

End Select

menu.AddSeparator ()

Super::AddMenuCommands( menu )

End Sub

Sub LinkToDetail( )

' This subroutine links to the appropriate detail report. The

' subroutine is invoked by the context menu created in the

' AddMenuCommands subroutine.

Select Case DataValue

Case "East"

FollowHyperlink("Sales East/Index.htm","")

Case "West"

FollowHyperlink("Sales West/West Forecast Detail.roi","")

End Select

End Sub

For information about using the code examples, see “Using the code examples” earlier in this chapter.

Format, Format$ functionsFormats a numeric expression, date variant, or string according to the specified pattern and locale.

Syntax Format(<exprs to format>)

Format(<exprs to format>, <format pattern>)

Format$(<exprs to format>, <format pattern>, <locale>)

Page 150: Actuate Basic Reference

126 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

F o r m a t , F o r m a t $ f u n c t i o n s

Parameters <exprs to format>Expression to display according to the specified <format pattern>.

Format[$] works differently depending on whether <exprs to format> is numeric, date, or string data.

Format[$] parses numeric values specified as a String according to the current run time locale before applying <format pattern>. For example, in the French run time locale, the following string:

Format( "1234,56", "Currency", pt_PT")

results in the following output:

€ 1.234

This is because Format [$] parses the string according to the French locale, which uses the comma (,) as a decimal separator then uses the specified locale, Portugal, for formatting and output.

<format pattern>A keyword that has been predefined in Actuate Basic or a string of format characters that specifies how the expression displays. The <locale> argument, if specified, determines <format pattern>.

Rules:

■ Do not mix different types format expressions, such as numeric, date/time or string in a single <format pattern> argument.

■ Numeric values specified as an Integer or Double must use a period (.) as a decimal separator and cannot include a thousands separator. For example, 32434.28 is valid, but 3,2434.28 and 3434,28 are invalid.

■ Numeric values specified as a String must use the user-specified locale format for decimal and thousands separator.

■ Enclose <format pattern> within quotes.

<locale>String expression that specifies the locale to use for determining <format pattern> and the output format.

Rule: If not specified, Null, or invalid, Format[$] uses the current run time locale.

Returns Format: VariantFormat$: String

Rule: If <format pattern> is omitted or is zero-length, and <exprs to format> is a numeric expression, Format[$] does the same thing as Str$. Positive numbers converted to strings using Format[$] lack a leading space, whereas those converted using Str$ retain a leading space.

Page 151: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 127

F o r m a t , F o r m a t $ f u n c t i o n s

Using Format[$] with numeric dataFormat numeric data using one of the following methods:

■ Use the format keywords that have been predefined in Actuate Basic.

■ Create your own user-defined formats using standard characters or symbols that have special functional meanings when used in a Format[$] expression.

The following table shows the predefined numeric format keywords you can use, and Format[$] examples and their results.

Keyword and Description Example/Result

General numberReturns as is, without rounding or applying any formats.

Format(3434.2899, "General number")Returns 3434.2899

CurrencyReturns as a string with thousands separators and rounded to the nearest hundredth if needed. Two digits to the right of the decimal separator. Encloses negative numbers in parentheses. If <locale> is specified, the currency format depends on the specified locale. If <locale> is not specified, the currency format of the current run time locale is used.

Format(3434.2899, "Currency")Returns $3,434.29 on en_US run time locale

FixedReturns at least one digit to the left and two digits to the right of the decimal separator. Rounds to the nearest hundredth.

Format(3434.2899, "Fixed")Returns 3434.29

Format(.3122, "Fixed")Returns 0.31

StandardReturns with thousands separators and rounded to the nearest hundredth, if needed. At least two digits to the right of the decimal separator.

Format(3434.2899, "Standard")Returns 3,434.29

Page 152: Actuate Basic Reference

128 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

F o r m a t , F o r m a t $ f u n c t i o n s

User-defined numeric formats

A format expression for numbers can have up to four sections, separated by semicolons. You can use double quotes (") for adding literal strings and back slashes (\) to add literal characters.

PercentReturns * 100 with a percent sign to the right. Two digits to the right of the decimal separator. Rounds to the nearest hundredth. The return type is a string. Do not use in a method for formatting AcDoubleControl and AcIntegerControl controls.

Format(0.2899, "Percent")Returns 28.99%

Format(0.28999, "Percent")Returns 29.00%

ScientificReturns in standard scientific notation, appropriately rounded. The return type is a string. Do not use in a method for formatting AcDoubleControl and AcIntegerControl controls.

Format(3434.2899, "Scientific")Returns 3.43E+03

Yes/NoReturns No if zero, Yes otherwise.

Format(3434.2899, "Yes/No")Returns Yes

True/FalseReturns False if zero, True otherwise.

Format(3434.2899, "True/False")Returns True

On/OffReturns Off if zero, On otherwise.

Format(3434.2899, "On/Off")Returns On

Keyword and Description Example/Result

Page 153: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 129

F o r m a t , F o r m a t $ f u n c t i o n s

The following table shows the symbols or characters you can use to create your own user-defined formats, and the effect of each symbol on the resulting format string.

Symbol and Description Examples/Results

0Zero-digit placeholder. If <exprs to format> has fewer digits than <format pattern>, the empty digits are filled with zeros. If <exprs to format> has more digits to the right of the decimal than <format pattern>, the result is rounded to the number of places in <format pattern>; if it has more digits to the left of the decimal, the extra digits are displayed without modification.

Format(3434.2899, "000.000")

Returns 3434.290

Format(129.557, "0000.00")

Returns 0129.56

#Null digit placeholder. If <exprs to format> has fewer digits than the format pattern, empty digits become Null, not filled with blanks. Therefore, the resulting string can be shorter than the original format pattern.

Format(3434.2899, "#,###,##0.0")

Returns 3,434.3

Format(3434.2899, "000###0.00")

Returns 0003434.29

%Percentage placeholder. Multiplies <exprs to format> by 100 and appends a % character.

Format(.75, "##%")

Returns 75%

Format(.75, "0##.000%")

Returns 075.000%

.Decimal placeholder. Indicates where to place the decimal point. If <locale> is specified, the decimal separator character of the specified locale is used. Otherwise, the current run time locale is used.

Format(3434.28, "0.0")

Returns 3434.3

Format(3434.28, "0.00")

Returns 3434.28

,Thousands separator. If <locale> is specified, the thousands separator character of the specified locale is used. Otherwise, the current run time locale is used.

Format(3434.2899, "#,##0.00")

Returns 3,434.29

Page 154: Actuate Basic Reference

130 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

F o r m a t , F o r m a t $ f u n c t i o n s

Format[$] with Format sections

Unless <format pattern> specifies one of the predefined format keywords, a format expression for numbers can have up to four sections, separated by semicolons. If you use semicolons with nothing between them, the missing section is printed using the format of the positive value.

E- or e-Returns <exprs to format> in scientific notation. You must place a digit placeholder (0 or #) to the immediate left of the symbol. Place an appropriate number of digit placeholders to the right of the symbol to display the exponent. A minus sign is displayed if the result has a negative exponent.

Format(1500000, "0.0E-")

Returns 1.5E6

Format(1500000, "#0.0E-")

Returns 15.0E5

E+ or e+Same as E-. The plus sign causes the polarity of the exponent to display whether positive (+) or negative (-).

Format(1500000, "0.0E+")

Returns 1.5E+6

Format(1500000, "#0.0e+")

Returns 15.e+5

$Currency symbol. Displays the currency symbol based on the specified locale.

Format(total,”($) #,##0.00”,”de_DE”) or

Format(total,”€ #,##0.00”,”de_DE”)

Returns € 8.790,00

Format(total,”($) #,##0.00”,”en_US”)

Returns $ 8,790.00

-, (, ), [space], +Literal characters that do not affect the format of the expression. [space] is Chr$(32).

Format$(5551212, "##0-0000")

Returns 555-1212

Format$(1111111111, "(###) ##0-0000")

Returns (111) 111-1111

Format$(150,"+##0")

Returns +150

Symbol and Description Examples/Results

Page 155: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 131

F o r m a t , F o r m a t $ f u n c t i o n s

The following examples assume settings in the user’s Control Panel are for the United States.

Using Format[$] for date dataNumbers can be used to represent date and time information. You can format date and time serial numbers using either date and time formats or numeric formats because date/time serial numbers are stored as floating-point values.

To format date and time, use one of the following methods:

■ Use the format keywords that have been predefined in Actuate Basic.

■ Create your own user-defined formats using standard characters or symbols that have special functional meanings when used in a format expression.

If <locale> is specified, symbols are formatted according to formatting rules of the specified locale. Otherwise, symbols are formatted according to the formatting rules of the current run time locale.

Use and description Example/Result

1 section only:<format pattern> applies to all values.

Format$(4.15, "$#,##0.00")

Returns $4.15

Format$(-4.15, "$#,##0.00")

Returns -$4.15

2 sections:(1) Applies to positive values and zero.(2) Applies to negative values.

Format$(-7, "$#,##0.00;$(#,##0.00)")

Returns $(7.00)

Format$(-7, "$#,##0.00;\L\o\s\s: #,##0.00")

Returns Loss: 7.00

3 sections:(1) Applies to positive values.(2) Applies to negative values.(3) Applies to zero.

Format$(0, "#,###;(#,###);\Z\e\r\o!")

Returns Zero!

4 sections:(1) Applies to positive values.(2) Applies to negative values.(3) Applies to zero.(4) Applies to Null.

Format$(-25, "#;(#);\Z\e\r\o;\N\i\l")

Returns (25)

Format$(25-25, "#;(#);\Z\e\r\o;\N\i\l")

Returns Zero

Format$(Null, "#;(#);\Z\e\r\o;\N\i\l")

Returns Nil

Page 156: Actuate Basic Reference

132 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

F o r m a t , F o r m a t $ f u n c t i o n s

The following table shows the predefined date and time format keywords you can use and the effects of each on the resulting format pattern.

User-defined date formats

You can use double quotes (") for adding literal strings and back slashes (\) to add literal characters. The following table shows the symbols or characters you can use to create your own user-defined date formats, and the effect of each symbol on the resulting format string.

In all cases, assume DateVar = CVDate(“11/12/82”) or DateVar = CVDate(“9/9/82”) to demonstrate use of leading zeros, unless noted otherwise.

If <locale> is specified, the results are formatted according to the format of the specified locale. Otherwise, the results are formatted according to the formatting rules of the current run time locale.

Keyword and description Example/Result

"General date"Returns a date and time.

Format$(30267.83681, "General date")

Returns 11/12/82 8:05:00 PM

"Long date"Returns a Long Date as defined in the user’s Control Panel.

Format$(30267.83681, "Long date")

Returns Friday, November 12, 1982

"Medium date"Returns a date with the month name abbreviated to 3 letters.

Format$(30267.83681, "Medium date")

Returns 12-Nov-82

"Short date"Returns a Short Date as defined in the user’s Control Panel.

Format$(30267.83681, "Short date")

Returns 11-12-82

"Long time"Returns a Long Time as defined in the user’s Control Panel. Includes hours, minutes, and seconds.

Format$(0.83681, "Long time")

Returns 8:05:00 PM

"Medium time"Returns hours and minutes in 12-hour format, including the A.M./P.M. designation.

Format$(0.83681, "Medium time")

Returns 8:05 PM

"Short time"Returns hours and minutes in 24-hour format.

Format$(0.83681, "Short time")

Returns 20:05

Page 157: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 133

F o r m a t , F o r m a t $ f u n c t i o n s

Note that the symbol for minute is n, not m, which is the symbol for month.

Symbol and description Example/Result

/, -Date separator.

Format$(DateVar, "mm/dd/yy")

Returns 11/12/82

Format$(DateVar, "mm-dd-yy")

Returns 09-09-82

dDay of the month without leading zero (1-31).

Format$(DateVar, "/d/")

Returns /12/

Format$(DateVar, "/d/")

Returns /9/

ddDay of the month with leading zero if needed (01-31).

Format$(DateVar, "/dd/")

Returns /12/

Format$(DateVar, "/dd/")

Returns /09/

dddThree-letter abbreviation for day of the week.

Format$(DateVar, "ddd")

Returns Fri

ddddFull name of day of the week.

Format$(DateVar, "dddd, mm/dd")

Returns Friday, 11/12

dddddShort Date string, as defined in the user’s Control Panel.

Format$(DateVar, "ddddd")

Returns 11/12/82

ddddddLong Date string, as defined in the user’s Control Panel.

Format$(DateVar, "dddddd")

Returns November 12, 1982

wDay of the week as a number (Sunday = 1, Saturday = 7).

Format$(DateVar, "w")

Returns 6

wwWeek of the year as a number (1-53).

Format$(DateVar, "ww")

Returns 46

Page 158: Actuate Basic Reference

134 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

F o r m a t , F o r m a t $ f u n c t i o n s

Using Format[$] with time dataThe fractional part of a number that represents a date represents a time of day on that date.

mNumber of the month without leading zero (1-12).

Format$(DateVar, "m")

Returns 11

mmNumber of the month with leading zero (01-12).

Format$(DateVar, "mm")

Returns 11

Format$(DateVar, "mm")

Returns 09

mmmThree-letter abbreviation for month name.

Format$(DateVar, "mmm")

Returns Nov

mmmmFull name of the month.

Format$(DateVar, "mmmm")

Returns November

qNumber of the quarter (1-4).

Format$(DateVar, "q")

Returns 4

"Quarter" & Format$(DateVar, "q")

Returns Quarter 4

yNumber of the day of the year(1-366).

Format$(DateVar, "y")

Returns 316

Val(Format$(DateVar, "y") + 19)

Returns 335

yyLast two digits of the year (00-99).

Format$(DateVar, "yy")

Returns 82

yyyyAll four digits of the year (100-9999).

Format$(DateVar, "yyyy")

Returns 1982

cDate variant as ddddd ttttt.

Format$(DateVar, "c")

Returns 11/12/82

Symbol and description Example/Result

Page 159: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 135

F o r m a t , F o r m a t $ f u n c t i o n s

For example, the CVDate function converts numbers to date variants. CVDate(30632) is 11/12/83. No time of day is returned because 30632 has no fractional part. By contrast, CVDate(30632.83) returns 11/12/83 7:55:12 P.M., because 30632.83 does have a fractional part, and the fractional part, .83, corresponds to about 7:55 P.M. (0.83 hours * 24 = 19.92 hours from midnight, or 7:55:12P.M.).

The following table assumes DateVar = “11/12/82 20:05:07”. Times returned by Format[$] are in 24-hour format unless you use one of the A.M./P.M. format symbols. Note that the symbol for minute is n, not m, which is the symbol for month.

Symbol and description Example/Result

:Time separator.

Format$(DateVar, "hh:nn:ss")

Returns 20:05:00

hHour without leading zero (0-23).

Format$(DateVar, "h:nn AM/PM")

Returns 8:05 PM

hhHour with leading zero (00-23).

Format$(DateVar, "hh:nn AM/PM")

Returns 08:05 PM

nMinute without leading zero (0-59).

Format$(DateVar, "h:n AM/PM")

Returns 8:5 PM

nnMinute with leading zero (00-59).

Format$(DateVar, "hh:nn AM/PM")

Returns 08:05 PM

sSecond without leading zero (0-59).

Format$(DateVar, "h:n:s AM/PM")

Returns 8:5:7 PM

ssSecond with leading zero (00-59).

Format$(DateVar, "h:nn:ss AM/PM")

Returns 8:05:07 PM

AM/PM or am/pmDesignation AM/am for any hour before noon and PM/pm for any hour after. Case-sensitive.

Format$(DateVar, "hh:nn:ss am/pm")

Returns 08:05:07 pm

Page 160: Actuate Basic Reference

136 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

F o r m a t , F o r m a t $ f u n c t i o n s

Using Format[$] with string dataYou can format strings with Format[$].

The following table shows the symbols or characters you can use to create your own user-defined formats, and the effect of each symbol on the resulting format string.

A/P or a/pDesignation A/a for any hour before noon and P/p for any hour after. Case-sensitive.

Format$(DateVar, "hh:nn:ss A/P")

Returns 08:05:07 P

AMPMUses formats set by 11:59 and 23:59 as defined in the user’s Control Panel. Default is AM/PM.

Format$(DateVar, "hh:nn AMPM")

Returns 08:05 PM

tttttUses format set by Time as defined in the user’s Control Panel. Default is h:nn:ss.

Format$(DateVar, "h:nn ttttt")

Returns 8:05 PM

Symbol and description Example/Result

@, &Character placeholders. Returns a character, or a space if there is no character in the corresponding position. Placeholders are filled from right to left unless <format pattern> uses a ! character.

Format$("1111212111","(@@@) @@@-@@@@")

Returns (111) 121-2111

Format$("6789999","(&&&) &&&-&&&&")

Returns ( ) 678-9999

<Lowercase conversion. Converts <exprs to format> to lowercase.

Format$("Smith, John","<")

Returns smith, john

Symbol and description Example/Result

Page 161: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 137

F o r . . . N e x t s t a t e m e n t

See also CVDate functionDateValue functionParseDate functionStr, Str$ functions

For...Next statementRepeats a block of instructions a specified number of times.

Syntax For <counter variable> = <start> To <end> [ Step <step size> ]

[<statement block>]

[Exit For]

[<statement block>]

Next [<counter variable >]

Parameters <counter variable>Numeric variable that keeps track of the number of times the set of statements between For and Next has been executed.

<start>Numeric expression indicating the first number at which <counter variable> is to begin counting; the initial value of <counter variable>.

<end>Numeric expression indicating the number at which <counter variable> is to stop counting; the final value of <counter variable>. As soon as <counter variable> stops execution, Actuate Basic skips everything between the For and Next keywords, and transfers control to the statement following Next.

>Uppercase conversion. Converts <exprs to format> to uppercase.

Format$("Smith, John",">")

Returns SMITH, JOHN

!Specifies that placeholders are to be filled from left to right.

Format$("5551212","(&&&) &&&-&&&&")

Returns ( ) 555-1212

Format$("5551212","!(&&&) &&&-&&&&")

Returns (555) 121-2

Symbol and description Example/Result

Page 162: Actuate Basic Reference

138 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

F o r . . . N e x t s t a t e m e n t

StepKeyword that specifies what number to add to <counter variable> every time after the loop finishes executing. The sum of <counter variable> and <step size> returns the next, new value for <counter variable>.

<step size>The number the program adds to <counter variable>, at the end of every trip through the loop, in order to determine the next value of <counter variable>.

Default: 1(start < end)Default: -1(start > end)

<statement block>Any valid Actuate Basic statements.

Exit ForKeyword that causes Actuate Basic to terminate the loop immediately, and to transfer control to the statement following Next. Exit For statement can be placed anywhere in the loop any number of times, although only one will be executed.

Next Keyword that defines the completion of a For...Next statement, and causes the program to add <step size> to <counter variable>.

Default: If you omit <counter variable> on the Next line, Actuate Basic adds the value of <step size> to the <counter variable> associated with the most recent For statement.

Description ■ First, Actuate Basic sets <counter variable> to <start>.

■ The following table summarizes what Actuate Basic does next, which depends upon the sign of <step size>.

■ If Actuate Basic executes the loop, it adds <step size> to <counter variable> at the line starting with Next.

■ Then Actuate Basic compares this new value of <counter variable> to <end>.

■ If the conditions described in the table are satisfied, Actuate Basic executes the loop again.

■ Otherwise, Actuate Basic skips everything between the For and Next keywords and transfers control to the statement immediately following Next.

<step size> Loop executes when. . . Stops execution when....

Positive or 0 <counter variable> <= <end> <counter variable> > <end>

Negative <counter variable> >= <end> <counter variable> < <end>

Page 163: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 139

F o r . . . N e x t s t a t e m e n t

Rule If we say that a For...Next loop is opened by its For clause and closed by its corresponding Next clause, nested loops must be closed in the reverse order in which they were opened:

Example:Loop 1

For I = 1 To 10

For J = 1 To 10

For K = 1 To 10

L = I + J + K

Next K

Next J

Next I

When you nest For...Next statements, you must use a different counter variable for each block. Traditionally, the letters I, J, K, and so forth, declared as Integers are used as counter variables.

Tips ■ To avoid confusion when you debug, do not change the value of <counter variable> from inside the loop.

■ To make your program more efficient, dimension <counter variable> as an Integer.

■ To evaluate a certain condition and then determine whether or not a loop continues, use Exit For within a conditional structure like If...Then...Else.

■ To ascertain or set the contents of a multidimensional array, use nested For...Next loops.

Example The following example uses two nested loops to put seven lines of the uppercase alphabet into a message box:

Function OnLButtonDblClk()

Dim I As Integer, Msg As String, NL As String, Rep As Integer

NL = Chr$(10) ' Define new line

For Rep = 7 To 1 Step -1 ' Perform seven repetitions

For I = Asc("A") To Asc("Z") ' Convert alpha to numeric values

Msg = Msg & Chr$(I) ' Convert back, append letters to string

Next I

Msg = Msg & NL ' Add newline after each repetition

Next Rep

MsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Do...Loop statementExit statementWhile...Wend statement

Page 164: Actuate Basic Reference

140 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

F r e e F i l e f u n c t i o n

FreeFile functionReturns the next unused system file number.

Syntax FreeFile

Returns Integer

When you open a file, you must supply a number by which to reference it throughout the program. This number must not already be in use by another currently open file. FreeFile eliminates the need for you to keep track of which file numbers are currently in use by finding the next available number.

Tip The number that FreeFile returns does not change until you actually open a file with it. So to be sure FreeFile is always current, immediately open a file with the number it gives you, instead of waiting until later to do so.

Example In the following statements, the return value of FreeFile is assigned to the variable FileNum%, then FileNum is used to open the file Test.dat:

FileNum% = FreeFile

Open "Test.dat" for Output As FileNum%

In the following example, a test file is created and opened to determine an unused file number:

Function OnLButtonDblClk()

Dim NL As String, FileNumber As Integer, Msg As String

NL = Chr$(10) ' Define newline

Open "Test1.fil" For Output As #1 ' Open a file

FileNumber = FreeFile ' Get unused file number

Open "Test2.fil" For Output As FileNumber ' Create a test file

Close ' Close all files

Msg = "The file number FreeFile returned was: "

Msg = Msg & FileNumber & "." & NL & NL

Msg = Msg & "Choose OK to delete the test files."

MsgBox Msg

Kill "Test1.fil" ' Delete files from disk

Kill "Test2.fil"

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Open statement

Page 165: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 141

F u n c t i o n . . . E n d F u n c t i o n s t a t e m e n t

Function...End Function statementDeclares and defines the name, code, and arguments that constitute an Actuate Basic function, and returns a value to the calling expression or statement.

Syntax [Static] Function <name of function> [(<list of arguments>)] [As <data type>]

[<statements>]

[Exit Function]

[<statements>]

<name of function> = <return value>

Parameters End Function

StaticKeyword that instructs Actuate Basic to preserve the values of the procedure's local variables between calls.

Rules:

■ You cannot use Static to affect variables declared outside the procedure.

■ You should avoid using Static in recursive procedures.

<name of function>The name you assign to the procedure.

Rules for <name of function>:

■ Subject to the same constraints as variable names, as well as to the following additional constraints:■ Can include a type declaration character.■ Cannot be the same as any other name recognized at the global or

module level, such as that of:- A procedure in a declared dynamic-link library (DLL)- A variable- A constant

■ Can be overloaded. That is, you can define another function or procedure that has the same name, as long as the respective arguments are unique. For example, the following are both permissible in the same program:

Sub Potato(intTomato As Integer)

..

End Sub

Page 166: Actuate Basic Reference

142 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

F u n c t i o n . . . E n d F u n c t i o n s t a t e m e n t

Sub Potato(intTomato As Double)

..

End Sub

<list of arguments>The variable name or names that the function uses internally to store and manipulate the values (arguments) that you pass to it from the calling statement.

Each of the <variable name> components of the <list of arguments> corresponds to a value or variable that is in the same relative position in the calling statement. It does not matter what you call the variable that is passed to the function; the function will process the value it receives as an argument. The <statements> in the procedure process arguments it receives to produce the single value that is returned to the calling procedure.

In the following example, the function Square ( ) expects to be supplied with a single argument, a numeric expression, which it squares:

Function Square(X)

Square = X ^ 2

End Function

The following statements will pass the value 4 to the function Square ( ) and receive back the value 16 after Square ( ) has completed. The statement will then continue; it will multiply the value it received from the function Square ( ) times 2 and print the resulting value:

MyNumber = 4

Print #1, Square(MyNumber) * 2

Here are the steps in the process:

1 First, the value 4 is assigned to the variable MyNumber.

2 The value of MyNumber is passed to the function Square ( ). Square ( ) assigns the value it receives from the calling statement to the variable X.

3 Square ( ) processes X and assigns the resulting value to the name of the function itself—Square—and returns control to the statement that called it.

4 The calling statement continues processing the new value of MyNumber (16); it multiplies it by 2, and prints the result (32).

<statements>One or more valid Actuate Basic statements. These statements constitute the body of the function procedure.

<return value>The value the function returns to the calling statement after the function has completed. Usually, <return value> is a variable that contains the final result of all the changes the argument or arguments underwent in the course of the execution of the <statements>.

Page 167: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 143

F u n c t i o n . . . E n d F u n c t i o n s t a t e m e n t

Exit FunctionKeyword that signals Actuate Basic to terminate the function procedure and transfer control to the statement following the one that called the procedure. You can use multiple Exit Function statements, anywhere in a function procedure, but only one is executed.

<list of arguments> has the following syntax:

[ByVal] <variable name> [As <data type>] [,[ByVal] <variable name>[As <data type>]...

ByValKeyword that instructs Actuate Basic to pass the argument to the procedure by value rather than by reference, so that whatever change the function makes to the argument variable has no affect on its original value in the calling procedure.

Rule for ByVal: Cannot be used with a variable of user-defined type, object type, or with an array variable.

<variable name>Name of the variable to pass as an argument. If the function changes the value of <variable name> internally, then it also changes its value externally.

Rules for <variable name>:

■ You must use ByVal if you do not want the function’s changes to an argument variable to affect the variable’s value in the calling statement.

Example:

Function SquareRoot (ByVal UserNum)

■ For array variables, use the parentheses but omit the number of dimensions.

Example:

Function SalesTax (MyArray( ))

■ If <variable name> is undeclared within the function but has the same name as another procedure, a Global or module-level constant or variable, or an object, Actuate Basic assumes your function refers to that external name. This can cause name conflicts. To avoid such conflicts, explicitly declare each <variable name> within the function.

As <data type>Clause that declares the data type of <variable name>. You can also specify the data type of <returned value> by appending this clause after the <list of arguments>.

Rule for As <data type>: <data type> can specify any valid Actuate Basic or user-defined data type except fixed-length String.

Page 168: Actuate Basic Reference

144 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

F u n c t i o n . . . E n d F u n c t i o n s t a t e m e n t

Examples:

Function SalesTax(Customer As String, Amount As Currency)

Function SalesTax(ByVal Customer As String, Amount)

Description Like a Sub statement, a Function can take arguments, execute a series of statements, and change the values of its arguments. However, unlike a Sub statement, a Function can also return a value directly and can be used in an expression.

You can use the same name for two or more different procedures, as long as you make sure the procedures take a different number of arguments, or that the arguments are of different data types. For example, you can write two different square root functions—one that operates on integers, and another that operates on doubles. Their respective first lines might look like the following:

Function SquareRoot(intParam As Integer) As Integer

Function SquareRoot(dblParam As Double) As Double

Actuate Basic will know which procedure you mean by the type of value you pass when you call the procedure. For instance, if you write a call to SquareRoot(5), the compiler will choose the first SquareRoot function. But if you call SquareRoot(5.1234567), or SquareRoot(5.000), it will execute the second one.

Rules ■ You cannot define a Function statement from within another Function statement.

■ You cannot use GoTo to enter or exit a Function statement.

Tips ■ Functions can be recursive. Actuate Basic sets a run-time stack limit of 200. A report using recursion with a large number of iterations might exceed this limit.

■ To avoid possible name conflicts between <variable name> and the names of other variables, constants, procedures, or objects, explicitly declare all variables within the function with Dim, ReDim, or Static. That way, you can use a common variable name like SaleDate within a function procedure, even if there is a global variable named SaleDate. Name conflicts can arise only when you use a variable in a procedure that you did not explicitly declare within the procedure.

■ To distinguish between a variable and a function with the same name in your code, use the function’s name with parentheses and the variable’s name without parentheses. Where the function takes no parameters, append an empty pair of parentheses. For example:

'Assign global variable Homonym to CopyVar1

CopyVar1 = Homonym

'Assign the return value of the function Homonym to CalculatedVar2

CalculatedVar2 = Homonym()

Page 169: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 145

F u n c t i o n . . . E n d F u n c t i o n s t a t e m e n t

■ To evaluate a condition and then determine whether or not the function procedure should continue, use Exit Function within a conditional structure like If...Then...Else.

■ To guard against the wrong data type being passed to or returned from a function, use As <data type> clauses.

Example The following example prompts the user to type a number, then calls a user-defined function that returns the number’s square root. The function SquareRoot should be typed after the End Function of the procedure or saved in your Actuate code module (.bas file):

Function OnLButtonDblClk()

Dim Msg As String, NumRoot

Dim UserNum As Double

UserNum = InputBox("Please type a number.")

' Call the SquareRoot function here to process UserNum

NumRoot = SquareRoot(UserNum)

' NumRoot has now been set to the square root of UserNum

Msg = "The square root of " & UserNum

Select Case NumRoot

Case 0: Msg = Msg & " is zero."

Case -1: Msg = Msg & " is an imaginary number."

Case Else: Msg = Msg & " is " & NumRoot

End Select

MsgBox Msg

End Function

'

' This function finds the square root of a number. It takes one input argument

' X (data type Double) and returns a value that is also data type Double.

'

Function SquareRoot (X As Double) As Double

' Sgn returns 1 if a number is positive, -1 if it's negative, and 0 if it's zero

' Important here since we only want to operate on a number greater

' than zero

Select Case Sgn(X) ' Evaluate sign of argument

Case 1

SquareRoot = Sqr(X)

Exit Function ' OK if positive, so exit

Case 0

SquareRoot = 0

Case -1

SquareRoot = -1

End Select

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

Page 170: Actuate Basic Reference

146 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

F V f u n c t i o n

See also Dim statementStatic statementSub...End Sub statement

FV functionReturns the future value of an annuity based on periodic, constant payments, and on an unvarying interest rate.

Syntax FV(<rate per period>,<number pay periods>,<each pmt>,<present value>, <when due>)

Parameters <rate per period>Numeric expression that specifies the interest rate that accrues per period.

Rule for <rate per period>: Must be given in the same units of measure as <number pay periods>. For instance, if <number pay periods> is expressed in months, then <rate per period> must be expressed as a monthly rate.

<number pay periods>Numeric expression that specifies the total number of payment periods in the annuity.

Rule for <number pay periods>: Must be given in the same units of measure as <rate per period>. For instance, if <rate per period> is expressed as a monthly rate, then <number pay periods> must be expressed in months.

<each pmt>Numeric expression that specifies the amount of each payment.

Rule for <each pmt>: Must be given in the same units of measure as <rate per period>. For instance, if <rate per period> is expressed in months, then <each pmt> must be expressed as a monthly payment.

<present value>Numeric expression that specifies the value today of a future payment, or stream of payments.

Example for <present value>: If you put $23.94 in the bank today and leave it there for 15 years at an interest rate of 10% compounded annually, you end up with about $100. The present value of $100 is approximately $23.94.

<when due>Numeric expression that specifies whether each payment is made at the beginning (1), or at the end (0) of each period.

Default 0

Rule for <when due>: Must be 0 or 1.

Page 171: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 147

F V f u n c t i o n

Examples:The following example assumes you deposit $10,000 in a savings account for your daughter when she is born. If the account pays 5.7% compounded daily, how much will she have for college in 18 years? The answer, $27,896.60, is assigned to the variable TotalValue:

TotalValue = FV(0.057/365, 18*365, 0, -10000, 1)

The following example is almost the same as the previous one. In this one, however, assume that the interest is compounded monthly instead of daily, and that you have decided to make an additional monthly deposit of $55 into the account. The future value assigned to TotalValue in this case is $48,575.82:

TotalValue = FV(0.057/12, 18*12, -55, -10000, 1)

Returns Double

An annuity is a series of cash payments, constant in value, made over a period of time. An annuity can be an investment, such as a monthly savings plan, or a loan, such as a home mortgage. The future value of an annuity is the cash balance you want after you have made your final payment.

Examples:

■ You set up a savings plan with a goal of having $75,000 in 18 years to pay for your child’s education. For this plan, the future value is $75,000.

■ You take out a loan for $11,000. The future value is $0.00, as it is for any typical loan.

Rules ■ <rate per period>, <number pay periods>, and <each pmt> must all be expressed in terms of the same units, weekly/weeks, monthly/months, yearly/years, and so on.

■ You must express cash paid out, such as deposits to savings, using negative numbers, and cash received, such as dividend checks, using positive numbers.

Example The following example prompts the user to supply an amount to save or invest each month, the annual percentage rate (APR) of the interest, the total number of payments, and when during the month payments will be made. Then it tells the user what the future value of such a savings plan or investment will be.

To use this example, paste the first portion at or near the beginning of your Actuate Basic source code (.bas) file:

Declare

Global Const ENDPERIOD = 0

Global Const BEGINPERIOD = 1

End Declare

'

Function OnLButtonDblClk()

Page 172: Actuate Basic Reference

148 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

F V f u n c t i o n

Dim EachPmt As Double, APR As Double

Dim TotalPmts As Single, PayWhen As Integer

Dim PresentVal As Double, FutureVal As Double

Dim Msg as String, Fmt As String

Fmt = "$###,###,##0.00" ' Specify money format

' Get user input

Msg = "How much will you save each month?"

EachPmt = InputBox(Msg)

Msg = "What is the annual percentage rate for the interest?"

APR = InputBox(Msg)

If APR > 1 Then ' Ensure proper form as %

APR = APR / 100

End If

Msg = "For how many months will you save?"

TotalPmts = InputBox(Msg)

Msg = "Will you make payments at month’s end?"

PayWhen = MsgBox(Msg, MB_YESNO)

If PayWhen = IDNO Then

PayWhen = BEGINPERIOD

Else

PayWhen = ENDPERIOD

End If

Msg = "What amount is in this savings account now?"

PresentVal = InputBox(Msg)

' Now do the real work

FutureVal = FV(APR / 12, TotalPmts, -EachPmt, -PresentVal, PayWhen)

' Format the resulting information for the user

Msg = "Starting with " & Format(PresentVal, Fmt) & " "

Msg = Msg & " and saving " & Format(EachPmt, Fmt) & " every month at"

Msg = Msg & " an interest rate of " & Format(APR, "##.0%")

Msg = Msg & " for a period of " & TotalPmts

Msg = Msg & " months will give you " & Format(FutureVal, Fmt) & "."

MsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also IPmt functionNPer functionPmt functionPPmt functionPV functionRate function

Page 173: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 149

G e t s t a t e m e n t

Get statementReads data from a disk file into a variable.

Syntax Get [#] <open file number>, [<record number>], <receiving variable>

Parameters <open file number>Numeric expression that is the number you assigned as a descriptor for the target file when you opened it.

<record number>Numeric expression between 1 and 2,147,483,647:

■ For files opened in Random mode, <record number> is the number of the record to be read.

■ For files opened in Binary mode, it is the byte position at which reading starts, where the first byte in a file is at position 1, the second byte at position 2, and so on.

Default: The next record or byte—that is, the one following the last Get or Put statement, or the one pointed to by the last Seek function.

Rule for <record number>: If you omit <record number> you must still include the delimiting commas that would have been on either side of it had you included it.

<receiving variable>String expression that specifies the variable that is to receive input from the open file.

Rules for <receiving variable>:

■ Cannot be an object variable.

■ Cannot be an array variable that refers to an entire array, although you can use a variable that denotes a single element of an array.

Description You can use the Get statement to read from files opened only in random or binary mode. You cannot use the Get statement to read from files opened in input mode. The behavior of Get varies depending upon the mode in which the file was opened.

For files opened in random mode

If the length of the data you read is less than the length specified in the Len clause of the Open statement, the next Get skips the data you did not read and reads subsequent records starting at the record-length boundary, specified by Len.

Page 174: Actuate Basic Reference

150 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

G e t s t a t e m e n t

Example:The first Get stores bytes 1-4 of the disk file Myfile.txt into the variable HoldingVar1. The second Get skips to the record-length boundary (20) and starts counting from there, which means it stores bytes 21-25 into HoldingVar2. The intervening bytes (5-20) are ignored:

Dim HoldingVar1 As String

Dim HoldingVar2 As String

HoldingVar1 = "1234"

HoldingVar2 = "1234"

Open "Myfile.txt" for Random As #1 Len = 20

Get #1, , HoldingVar1

Get #1, , HoldingVar2

The following table summarizes how Get behaves depending on the data type of <receiving variable>. Open here refers to the particular statement that opened the file in question.

<receiving variable> Get reads, in order Rules

Variable-length string

1 2-byte descriptor containing string length

2 Data that goes into <receiving variable>

Record length specified in the Len clause of Open must be at least 2 bytes greater than the actual length of the string.

Numeric Variant (Variant Types0-7)

1 2-byte descriptor identifying VarType of the Variant

2 the data that goes into <receiving variable>

Len clause length must be at least 2 bytes greater than the actual number of bytes required to store the variable.

String Variant(Variant Type 8)

1 2-byte VarType descriptor

2 2 bytes indicating the string length

3 Data that goes into <receiving variable>

Len clause length must be at least 4 bytes greater than the actual length of the string.

Any other type of variable

1 Data that goes into <receiving variable>

Len clause length must be greater than or equal to the length of the data.

User-defined type

1 As though each element were being read individually

Len clause length must be greater than or equal to the sum of all bytes for the individual elements.

Page 175: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 151

G e t s t a t e m e n t

For files opened in binary modeAll the Random descriptions and rules above apply except that the Len clause in the Open statement has no effect.

Example:The first statement stores the first 4 bytes of the disk file Myfile.txt into the variable HoldingVar1. The second stores the next 5 bytes into HoldingVar2. No data is ignored:

Dim HoldingVar1 As String

Dim HoldingVar2 As String

Open "Myfile.txt" for Binary As #1

Get #1, , HoldingVar1

Get #1, , HoldingVar2

For variable-length strings that are not elements of user-defined types, Get does not expect a 2-byte descriptor to tell it how many bytes to read; it reads the number of bytes equal to the number of characters already in the string.

Example:The following statements reads 12 bytes from file #1:

VariLen$ = String$(12, "*")

Get #1, , VariLen$

Tip To avoid corrupting or misreading data, be sure your record lengths and variable lengths match the lengths of the data you want to read or write.

Example The following example prompts the user to type three customer names. It writes each name to a test file and then reads the names back:

Function OnLButtonDblClk()

Dim CustName As String

Dim I As Integer, Max As Integer, Msg As String

' Create a sample data file

Open "Testfile.dat" For Random As #1 Len = 50

' Ask user to type a few records

For I = 1 to 3

CustName = InputBox(“Please type a customer name: “)

Put #1, I, CustName ' Put record into file on disk

Next I

Close #1

' Close the file we’ve written into and open again for reading

Open "Testfile.dat" For Random As #1 Len = 50

Max = LOF(1) / 50 ' Calc total # of records

Max = Max + 1

For I = Max To 1 Step -1 ' Read file backwards

Seek #1, I ' Seek statement used

Get #1, , CustName ' Get record at that position

Msg = "Record #" & (Seek2(1) - 1) & " contains: "

Msg = Msg & CustName

Page 176: Actuate Basic Reference

152 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

G e t A F C R O X V e r s i o n f u n c t i o n

MsgBox Msg

Next I

Close #1 ' Close test file

Msg = "Choose OK to remove the test file."

MsgBox Msg

Kill "Testfile.dat" ' Delete file from disk

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Open statementPut statementSeek statementType...End Type statement

GetAFCROXVersion functionReturns either the integer or the decimal component of the version number of the AFC library (Afcnnnn.rox).

Syntax GetAFCROXVersion(<numpart>)

Parameters <numpart>Number or numeric expression that tells GetAFCROXVersion whether you want to know the integer part of the version number, or the decimal part.

Rule: Must be either 0 or 1.

Returns Integer

If <numpart> is 0, GetAFCROXVersion returns the integer (major) component of the version number.

If <numpart> is 1, GetAFCROXVersion returns the decimal (minor) component of the version number.

Example The code in the example determines both parts of the version number of the AFC library, and puts the parts together, interpolating the decimal point where it belongs:

Dim AFCMajor As Integer, AFCMinor As Integer, AFCTotal as String

AFCMajor = GetAFCROXVersion(0)

AFCMinor = GetAFCROXVersion(1)

’Now put the two parts together and prepend some identifying text:

AFCTotal = "AFC Version: " & (AFCMajor) & "." & (AFCMinor)

For information about using the code examples, see “Using the code examples” earlier in this chapter.

Page 177: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 153

G e t A p p C o n t e x t f u n c t i o n

See also GetAppContext functionGetFactoryVersion functionGetOSUserName functionGetROXVersion functionGetServerName functionGetServerUserName function

GetAppContext functionIndicates which Actuate application is currently running.

Syntax GetAppContext

Returns AppContext

You interpret the GetAppContext’s return value depending on whether GetAppContext is called from a client or a server machine at run time.

On a client, GetAppContext returns the context of the Actuate application being used—for example the Administrator Desktop, End User Desktop, or the e.Report Designer Professional.

On a server, GetAppContext returns the context of server, and not the context of the Administrator, End User Desktop, or e.Report Designer Professional.

The following table maps the return value from GetAppContext to the corresponding Actuate application.

Example The following code illustrates how you might use GetAppContext to determine which Actuate application is running at the time you call the function:

GetAppContext value Application

ADTContext Administrator Desktop (ADT)

ARDContext e.Report Designer (ERD)

DWBContext e.Report Designer Professional (ERDPro)

EUDTContext End User Desktop (EUDT)

LRXContext Live Report Extension (Plug-in)

ServerContext Server

ViewerContext Viewer

ViewServer View Server

Page 178: Actuate Basic Reference

154 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

G e t A t t r f u n c t i o n

Dim ApplicationContext As AppContext, MyValue As String

MyValue = "Application Context = "

ApplicationContext = GetAppContext

Select Case ApplicationContext

Case ServerContext

MyValue = MyValue & "Server"

Case LRXContext

MyValue = MyValue & "Live Report Extension (Plugin)"

Case ViewerContext

MyValue = MyValue & "Viewer"

Case ADTContext

MyValue = MyValue & "Administrator Desktop"

Case EUDTContext

MyValue = MyValue & "End User Desktop"

Case DWBContext

MyValue = MyValue & "e.Report Designer Professional"

End Select

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also GetAFCROXVersion functionGetFactoryVersion functionGetOSUserName functionGetROXVersion functionGetServerName functionGetServerUserName function

GetAttr functionDetermines the attributes of a file, directory, or volume.

Syntax GetAttr(<file dir or vol name>)

Parameters <file dir or vol name>String expression that specifies the file, directory, or volume for which you wish to determine what attributes are set.

Default path: Current drive and directory.

Rules:

■ Must refer to a valid file, directory, or volume.

■ Reference must be unambiguous.

Page 179: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 155

G e t A t t r f u n c t i o n

<file dir or vol name> can optionally specify a full path, in which case it has the following syntax:

[<drive:>][ \ ]<directory>[\<directory>]...(Windows)

[ /]<directory>[/<directory>]...(UNIX)

<drive:>Character, followed by a colon, that specifies the drive (Windows only).

<directory>String expression that specifies the name of a directory or subdirectory.

Example:Assuming Testfile.dat has both the system and read-only attributes set, the following statement assigns the value 5 (4 + 1) to the variable ATTRIBS:

ATTRIBS = GetAttr("Testfile.dat")

Returns Integer

■ The operating system assigns one or more attributes to each file, directory, and volume. These attributes indicate whether the item is a normal, read-only, hidden, or system file; a volume label; a directory; whether it has been modified since the last backup; or some combination of these.

■ If the file has multiple attributes, the return value will be the bit-wise AND of all the values that apply. For example, a return value of 3 indicates a file is both read-only and hidden (1 + 2).

■ The following table shows certain constant names that are defined in Header.bas, and their corresponding return values and attributes. The return value of GetAttr is the sum of one or more return values. The return values not supported under UNIX will be 0.

Return value Constant name File attribute Operating system

0 ATTR_NORMAL Normal Windows, UNIX

1 ATTR_READONLY Read-only Windows, UNIX

2 or 0 ATTR_HIDDEN Hidden Windows

4 or 0 ATTR_SYSTEM System file Windows

8 or 0 ATTR_VOLUME Volume label Windows

16 ATTR_DIRECTORY Directory label Windows, UNIX

32 or 0 ATTR_ARCHIVE Changed since last backup

Windows

Page 180: Actuate Basic Reference

156 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

G e t A t t r f u n c t i o n

Tip To determine—without having to do any arithmetic—whether a file has a particular, single attribute, use the BAnd operator to perform a bitwise test. If this statement evaluates to nonzero you know that, whatever other attributes it has, the file is read-only:

GetAttr("TESTFILE.DAT") BAnd ATTR_READONLY

Example In the following Windows example, Actuate Basic prompts the user to type a file name, then displays a message indicating the attributes of the given file:

Function OnLButtonDblClk()

Dim Attr As Integer, FName As String, Msg As String

On Error Goto ErrorHandler

' Get a file name from the user

FName = InputBox("Please type the name of a file.")

' Determine the file's attributes

Attr = GetAttr(FName)

MsgBox "The value returned by GetAttr is: " & Attr

' Disregard the Archive attribute

If Attr > 7 And Attr <> 16 Then

If Attr BAnd ATTR_ARCHIVE Then

Attr = Attr BAnd BNot ATTR_ARCHIVE

Else

Attr = Attr BOr ATTR_ARCHIVE

End If

End If

' Correlate some attribute codes and code sums to messages

Select Case Attr

Case ATTR_NORMAL

Msg = "Normal"

Case ATTR_READONLY

Msg = "Read-only"

Case ATTR_HIDDEN

Msg = "Hidden"

Case ATTR_HIDDEN + ATTR_READONLY

Msg = "Hidden and Read-only"

Case ATTR_SYSTEM

Msg = "System"

Case ATTR_READONLY + ATTR_SYSTEM

Msg = "Read-only and System"

Case ATTR_HIDDEN + ATTR_SYSTEM

Msg = "Hidden and System"

Case ATTR_READONLY + ATTR_HIDDEN + ATTR_SYSTEM

Msg = "Read-only, Hidden, and System"

Case ATTR_DIRECTORY

Msg = "Directory"

End Select

MsgBox UCase$(FName) & " is a " & Msg & " file."

Exit Function

Page 181: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 157

G e t C l a s s I D f u n c t i o n

ErrorHandler:

Msg = "Sorry, an error occurred. Please check the name or path "

Msg = Msg & "of the file and try again."

MsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also FileDateTime functionFileLen functionSetAttr statement

GetClassID functionReturns the ID number that Actuate assigns automatically to all classes. Objects of the same class have the same ID number.

Syntax GetClassID(<object reference>, <offset>)

Parameters <object reference>The name of the variable that refers to the object for which you want the ID.

<offset>An integer that indicates the level of the class hierarchy for which you want the ID. Must be 0 or a negative number. Specify 0 to return only the class ID, -1 to return the ID of the classes’ superclass, and so on.

Returns Integer that is the class ID.

Null if <offset> is a positive number or a negative number higher than the class hierarchy.

Tips ■ Use GetClassID when you want to check if an object is of a given type without the overhead of a string compare.

■ To find out an object’s class, use GetClassName.

■ To find out if an object is an instance of a specified class or is an instance of a subclass of a specified class, use IsKindOf.

Example The following procedure displays the Class Name and Class ID of the current component, creates two new label components, and displays the Class Name and Class ID of each of the new components:

' Create a new label in the Design Editor and override its

' OnLButtonDblClk method. Paste the following code at

' the point where it says: Insert your code here.

Page 182: Actuate Basic Reference

158 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

G e t C l a s s N a m e f u n c t i o n

Dim ClassIDVar, ClassNameVar

Dim MyLabel1 As AcLabelControl, MyLabel2 As AcLabelControl

Dim NL As String, Msg As String

NL = Chr$(10) ' Set newline

ClassIDVar = GetClassID(Me, 0)

ClassNameVar = GetClassName(Me, 0)

Msg = "My Class ID is: " & ClassIDVar & NL

Msg = Msg & "My Class Name is: " & ClassNameVar

MsgBox Msg

Set MyLabel1 = New AcLabelControl

Set MyLabel2 = New AcLabelControl

Msg = "The Class Name for MyLabel1 is: "

Msg = Msg & GetClassName(MyLabel1) & NL

Msg = Msg & "Its Class ID is: "

Msg = Msg & GetClassID(MyLabel1) & NL & NL

Msg = Msg & "The Class Name for MyLabel2 is: "

Msg = Msg & GetClassName(MyLabel2) & NL

Msg = Msg & "Its Class ID is: " & GetClassID(MyLabel2)

MsgBox Msg

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also GetClassName functionIsKindOf function

GetClassName functionReturns the name of the object’s class.

Syntax GetClassName(<object reference>, <offset>)

Parameters <object reference>The name of the variable that refers to the object for which you want the class name.

<offset>An integer that indicates the level of the class hierarchy for which you want the class name. Must be 0 or a negative number. Specify 0 to return only the class name, -1 to return the name of the classes’ superclass, and so on.

Page 183: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 159

G e t C l a s s N a m e f u n c t i o n

Returns String

The name of the class. If the class is nested, the name is the fully qualified name, for example, MyReport::MyFrame::MyControl.

Null if <offset> is a positive number or a negative number higher than the class hierarchy.

Tips ■ Use GetClassName to test for a specific class before performing an action.

■ To find out if an object is an instance of a specified class or is an instance of a subclass of a specified class, use IsKindOf.

Example The following procedure displays the Class Name and Class ID of the current component, creates two new label components, and displays the Class Name and Class ID of each of the new components:

' Create a new label in the Design Editor and override its

' OnLButtonDblClk method. Paste the following code at

' the point where it says: Insert your code here.

Dim ClassIDVar, ClassNameVar

Dim MyLabel1 As AcLabelControl, MyLabel2 As AcLabelControl

Dim NL As String, Msg As String

NL = Chr$(10) ' Set newline

ClassIDVar = GetClassID(Me, 0)

ClassNameVar = GetClassName(Me, 0)

Msg = "My Class ID is: " & ClassIDVar & NL

Msg = Msg & "My Class Name is: " & ClassNameVar

MsgBox Msg

Set MyLabel1 = New AcLabelControl

Set MyLabel2 = New AcLabelControl

Msg = "The Class Name for MyLabel1 is: "

Msg = Msg & GetClassName(MyLabel1) & NL

Msg = Msg & "Its Class ID is: "

Msg = Msg & GetClassID(MyLabel1) & NL & NL

Msg = Msg & "The Class Name for MyLabel2 is: "

Msg = Msg & GetClassName(MyLabel2) & NL

Msg = Msg & "Its Class ID is: " & GetClassID(MyLabel2)

MsgBox Msg

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also GetClassID functionIsKindOf function

Page 184: Actuate Basic Reference

160 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

G e t C l i p b o a r d T e x t f u n c t i o n

GetClipboardText functionReturns a text string from the operating environment Clipboard.

Syntax GetClipboardText(<format>)

Parameters <format>One of the following Clipboard formats recognized by Actuate Basic.

If <format> is omitted, CF_TEXT is assumed.

Returns String

If there is no text string on the Clipboard that matches the expected format, a zero-length string (““) is returned.

Example The following example places the current date on the Clipboard and then displays the contents of the Clipboard:

Function OnLButtonDblClk ( )

Dim Msg As String, UserContent, DoMore

On Error Resume Next

Msg = "The Clipboard currently contains: " & GetClipboardText()

MsgBox Msg

Msg = "Choose OK to load today's date onto the Clipboard."

MsgBox Msg

ClearClipboard()

SetClipboardText(Format$(Date, "dddd, mm/dd/yyyy"))

Msg = "Today's date is on the Clipboard. Choose OK to get the "

Msg = Msg & "date back from the Clipboard and put it in a message."

MsgBox Msg

Msg = GetClipboardText()

MsgBox "The Clipboard currently contains: " & Msg

DoMore = MsgBox("Put something else on the clipboard?", MB_YESNO)

If DoMore = IDNO Then

MsgBox "The date is still on the Clipboard."

Else

UserContent = InputBox("Put what?")

SetClipboardText(UserContent)

End If

Symbolic constant Value Clipboard format

CF_LINK &HBF00 DDE conversation information

CF_TEXT 1 Text

Page 185: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 161

G e t D i s p l a y H e i g h t f u n c t i o n ( W i n d o w s o n l y )

MsgBox "The Clipboard currently contains: " & GetClipboardText()

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also ClearClipboard functionSetClipboardText function

GetDisplayHeight function (Windows only)Returns the height required to display a given text string without truncating it, in twips.

Can be used to dynamically adjust the height of a container when you have a large amount of text that might otherwise overflow.

Syntax GetDisplayHeight (<context>, <width>, <theText>, <theFont>, <format>)

Parameters <context>String expression. Specifies whether to return the height for display, or for the default printer.

Rule: Must be either display or default_printer.

<width>Integer expression. Specifies the width of the control displaying the text, in twip. <width> is used to determine the height of the control to display all the text for this control. GetDisplayHeight assumes that at least one character fits on each line.

Rule: Must be a positive Integer.

<theText>String expression. The text whose height you want to determine.

Rule: Must not be empty.

<theFont>AcFont data type.

<format>AcTextPlacement data type.

Returns Integer

■ The height of the formatted text in twips for the specified device.

Page 186: Actuate Basic Reference

162 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

G e t D i s p l a y H e i g h t f u n c t i o n ( W i n d o w s o n l y )

■ When negative, an error has occurred. The following table shows the meaning of the error codes.

Description Different devices display or print fonts slightly differently. This means, for example, that a visual box filled with text may look correct on the screen, but incorrect in a printed report because the target device truncates some of the text.

GetDisplayHeight supports calculating exactly how tall the formatted text will be when a given display or printer device renders it.

Rule GetDisplayHeight does not work under UNIX.

Tip GetDisplayHeight works only under Windows. Therefore, be sure to write error-handling code that checks whether the function returns -1 when the report is run in a non-Windows environment.

Return value of -1 means that the report is not running under Windows. In this case, you must change your code accordingly.

Error code Description of errors

-1 Not running Windows

-2 Wrong number of parameters passed

-3 <context> is not a string, or represents a nonsupported context

-4 <width> is not a positive integer

-5 <theText> is not a string, or it is an empty string

-6 <AcFont.FaceName> is an empty string

-7 <AcFont.Size> is not a positive integer

-8 <AcFont.Bold> internal error

-9 <AcFont.Italic> internal error

-10 <AcFont.Underline> internal error

-11 <AcFont.StrikeThrough> internal error

-12 <AcTextPlacement.MultiLine> internal error

-13 <AcTextPlacement.WordWrap> is not 0, 2, or 3

-14 Default printer is selected, but no default printer has been set

-15 Implementation failed to get information on the device

-16 Operation caused an exception

Page 187: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 163

G e t F a c t o r y V e r s i o n f u n c t i o n

GetFactoryVersion functionReturns either the integer or the decimal component of the version number of the Factory the .rox is using.

Syntax GetFactoryVersion(<numpart>)

Parameters <numpart>Number or numeric expression that tells GetFactoryVersion whether you want to know the integer part of the Factory’s version number, or the decimal part.

Rule: Must be either 0 or 1.

Returns Integer

■ If <numpart> is 0, GetFactoryVersion returns the integer (major) component of the Factory’s version number.

■ If <numpart> is 1, GetFactoryVersion returns the decimal (minor) component of the Factory’s version number.

Example The code in this example determines both parts of the version number of the Factory your .rox is using, and it puts the parts together, interpolating the decimal point where it belongs:

Dim FactVerMajor As Integer, FactVerMinor As Integer

Dim FactVerTotal As String

FactVerMajor = GetFactoryVersion(0)

FactVerMinor = GetFactoryVersion(1)

’Now put the two parts together and prepend some identifying text:

FactVerTotal = "Factory Version: " & (FactVerMajor) & "." & (FactVerMinor)

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also GetAppContext functionGetAFCROXVersion functionGetOSUserName functionGetROXVersion functionGetServerName functionGetServerUserName function

GetHeadline functionReturns the headline associated with the completed request for a report.

Syntax GetHeadline

Page 188: Actuate Basic Reference

164 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

G e t J a v a E x c e p t i o n f u n c t i o n

Returns String

The current text of the headline.

Description Headlines are associated with the completed request for a report, and are visible only in the ReportCast when viewing channels.

By default, the headline is set to the value of the Headline parameter that appears in the Output Options section of the Requester. Use GetHeadline to programmatically determine the headline text.

Rules ■ GetHeadline and SetHeadline do not work in the Viewer.

■ To change the headline use SetHeadline, do not change the Headline parameter itself.

See also SetHeadline statement

GetJavaException functionAccesses the last Java exception thrown by the application.

Syntax GetJavaException()

Returns A Basic object which is a handle to the Java Exception object if the method succeeded.

An undefined handle if the call failed.

GetLocaleAttribute functionRetrieves locale attributes. You can use this information, for example, in formatting functions and functions that parse strings.

Syntax GetLocaleAttribute (<locale>, <attrib>)

Parameters <locale>The name of the locale for which to retrieve attributes.

<attrib>The enum value of the attribute to retrieve:

■ AC_LOCALE_CURRENCY■ AC_LOCALE_CURRENCY_FORMAT■ AC_LOCALE_CURRENCY_RADIX■ AC_LOCALE_CURRENCY_THOUSAND_SEPARATOR■ AC_LOCALE_DATE_LONG

Page 189: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 165

G e t L o c a l e N a m e f u n c t i o n

■ AC_LOCALE_DATE_SEPARATOR■ AC_LOCALE_DATE_SHORT■ AC_LOCALE_MONTHS_LONG■ AC_LOCALE_MONTHS_SHORT■ AC_LOCALE_NUM_RADIX■ AC_LOCALE_NUM_THOUSAND_SEPARATOR■ AC_LOCALE_TIME_AM_STRING■ AC_LOCALE_TIME_FORMAT■ AC_LOCALE_TIME_PM_STRING■ AC_LOCALE_TIME_SEPARATOR■ AC_LOCALE_WEEKDAYS_LONG■ AC_LOCALE_WEEKDAYS_SHORT

Returns String

Example The following example returns the names of valid days of the week:

’Parse the numeric string "1.001,99" specified in French locale

sep1000 = GetLocaleAttribute(“fr”,AC_LOCALE_NUM_THOUSAND_SEPARATOR)

radix = GetLocaleAttribute(“fr”, AC_LOCALE_NUM_RADIX)

ParseNumeric(“1.001,99”, sep1000, radix)

’Get the names of valid days of week in short format for the current run time locale

weekNames = GetLocaleAttributes(GetLocaleName(), AC_LOCALE_ WEEKDAYS_SHORT)

’In the English locale, the following string is returned

"Mon,Tue,Wed,Thu,Fri,Sat,Sun"

For information about using the code examples, see “Using the code examples” earlier in this chapter.

GetLocaleName functionRetrieves the name of the current run time locale.

Syntax GetLocaleName()

Description This function retrieves the name of the current run time locale.

Returns String

Page 190: Actuate Basic Reference

166 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

G e t M e s s a g e A r g u m e n t f u n c t i o n

GetMessageArgument functionRetrieves the value of one parameter passed by the browser or the SetMessageArguments function.

Syntax Function GetMessageArgument(key As String) As String

Parameters keyThe key of the parameter to retrieve. Key is case-sensitive.

Description This function retrieves one parameter at a time. Call this function multiple times to retrieve multiple parameters.

When calling this function from e.Report Designer Professional, you must call SetMessageArguments before calling GetMessageArgument.

Returns If called from the View process, the value passed by the browser.

If called from e.Report Designer Professional, the value passed by the SetMessageArguments function.

See also SetMessageArguments function

GetOSUserName functionReturns the operating system (login) name of the user. For server, returns the login name of the account running the server.

Syntax GetOSUserName

Returns String

The login name of the user, or the login name of the account running the server.

Rule You cannot use GetOSUserName in a 16-bit environment.

Example The following example retrieves the login name of the user and puts it in a variable along with some identifying text:

Dim OSUserName As String

OSUserName = "OS User Name is: " & (GetOSUserName)

For information about using the code examples, see “Using the code examples” earlier in this chapter.

Page 191: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 167

G e t R e p o r t C o n t e x t f u n c t i o n

See also GetAppContext functionGetAFCROXVersion functionGetFactoryVersion functionGetROXVersion functionGetServerName functionGetServerUserName function

GetReportContext functionReturns the value of the global ReportContext variable, which tells you whether the report is in the Factory, Viewing, or Printing stage of the lifecycle.

Syntax GetReportContext()

Returns ReportContext

One of the following values defined in Header.bas:

Global Const UnknownReportContext = 0

Global Const FactoryReportContext = 1

Global Const ViewerReportContext = 2

Global Const PrintReportContext = 3

Description Use GetReportContext() in conjunction with GetAppContext.

The following table gives some examples of how these two functions work together to determine what Actuate application is being used, and what the report context is at the moment.

Example The following example determines whether the report is running in the view process:

InViewServer = ((GetReportContext( ) = ViewerReportContext) And (GetAppContext( ) = ServerContext))

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also GetAppContext function

If GetAppContext returns this:

And GetReportContext returns this: Then you are in the:

ServerContext ViewerReportContext View process

ServerContext FactoryReportContext Factory server

ServerContext PrintReportContext Factory server

Page 192: Actuate Basic Reference

168 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

G e t R e p o r t S c a l i n g F a c t o r f u n c t i o n

GetReportScalingFactor functionReturns the scaling factor.

Syntax GetReportScalingFactor()

Description Use GetReportScalingFactor to retrieve the scaling factor and adjust the size of the browser scripting control’s rectangle based on the current scaling factor.

When the scaling factor changes, the DHTML converter scales controls on the report page, but does not scale or change the output of custom browser code. Make sure that the output of custom browser code can be viewed with different scaling factors, especially 75% and 100%.

Returns Double

1.0 corresponds to a 100% zoom.

Example The following example shows how to use GetReportScalingFactor to change the width and height of the HTML element produced by the custom browser code:

Dim dhtmlCode As StringDim zoom As Double

zoom = GetReportScalingFactor()dhtmlCode = "<SPACER TYPE=""block"" HEIGHT=" + Str$(150 * zoom)dhtmlCode = dhtmlCode + " WIDTH=" + Str$(250 * zoom) + ">"

BrowserCode = dhtmlCode

For information about using the code examples, see “Using the code examples” earlier in this chapter.

GetROXVersion functionReturns either the integer or the decimal component of the version number of the report .rox file.

Syntax GetROXVersion(<numpart>)

Parameters <numpart>Number or numeric expression that tells GetROXVersion whether you want to know the integer part of the version number, or the decimal part.

Rule: Must be either 0 or 1.

Returns Integer

■ If <numpart> is 0, GetROXVersion returns the integer (major) component of the version number.

Page 193: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 169

G e t S e a r c h F o r m a t s f u n c t i o n

■ If <numpart> is 1, GetROXVersion returns the decimal (minor) component of the version number.

Example The code determines both parts of the version number of the .rox and puts the parts together, interpolating the decimal point where it belongs:

Dim ROXMajor As Integer, ROXMinor As Integer, ROXTotal As Srting

ROXMajor = GetROXVersion(0)

ROXMinor = GetROXVersion(1)

’Now put the two parts together and prepend some identifying text:

ROXTotal = "ROX Version: " & (ROXMajor) & "." & (ROXMinor)

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also GetAFCROXVersion functionGetAppContext functionGetFactoryVersion functionGetOSUserName functionGetServerName functionGetServerUserName function

GetSearchFormats functionRetrieves a list of supported DHTML search formats, places the supported formats into a string array, and returns the number of elements in the string array.

Syntax GetSearchFormats (<formatArray>( ) As String ) As Integer

Parameters <formatArray>String array to contain the list of supported search formats. The search formats determine how the DHTML viewing environment presents search results.

Returns The number of elements in the array.

The supported formats that GetSearchFormats() returns depend upon the formats available in a particular viewing environment. For example, the following formats might be supported:

■ XMLDisplay (DISPLAY)

■ Download formats:■ CSV■ TSV■ ANALYSIS

Page 194: Actuate Basic Reference

170 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

G e t S e r v e r N a m e f u n c t i o n

Example The following example shows how to retrieve a list of supported formats:

Function BrowserCode() As String

Dim formatArray() As String

Dim count As Integer

Dim i As Integer

Dim DhtmlStr As String

DhtmlStr = "<SELECT NAME=’search_format’>"

count = GetSearchPageFormats(formatArray)

For i = 1 To count

DhtmlStr = DhtmlStr + "<OPTION VALUE=" + formatArray(i) + ">" +

formatArray(i)

DhtmlStr = DhtmlStr + "</OPTION>"

Next i

DhtmlStr = DhtmlStr + "</SELECT>"

BrowserCode = dhtmlStr

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also IsSearchFormatSupported function

GetServerName functionReturns the name of the machine on which iServer is running.

Syntax GetServerName

Returns String

Example The following code illustrates how you might use GetServerName to display the user’s login name in a control:

Dim ServerName as String

ServerName = "Server Name: " & (GetServerName)

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also GetAFCROXVersion functionGetAppContext functionGetFactoryVersion functionGetOSUserName functionGetROXVersion functionGetServerUserName function

Page 195: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 171

G e t S e r v e r U s e r N a m e f u n c t i o n

GetServerUserName functionReturns the login name of the user logged into iServer.

Syntax GetServerUserName

Returns String

Example The following code illustrates how you might use GetServerUserName to display the user’s login name in a control:

This example displays the login name of the user logged into iServer.

Function OnLButtonDblClk( )

Dim ServerUserName as String

ServerUserName = "Server User Name: " & GetServerUserName()

MsgBox ServerUserName

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also GetAFCROXVersion functionGetAppContext functionGetFactoryVersion functionGetOSUserName functionGetROXVersion functionGetServerName function

GetUserAgentString functionReturns the unparsed user agent string sent by a web browser with every HTTP request.

Syntax GetUserAgentString

Returns String

Example The following example generates different output for Microsoft Internet Explorer and Netscape Navigator:

Page 196: Actuate Basic Reference

172 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

G e t V a l u e f u n c t i o n

Function GetText( ) As String

Dim str As StringDim NL As StringNL = Chr$(10)str = GetUserAgentString( )If Len(str) = 0 Then

GetText = "...Not in a web browser."Else

If InStr(str, "MSIE") = 0 Then'Not MSIE.

GetText = str + NL + "...In Netscape"Else

GetText = str + NL + "...In MSIE"End If

End IfEnd Function

GetValue functionFinds the value of a variable in an object dynamically at run-time.

Syntax GetValue(<object reference>, <variable name>|<index>)

Parameters <object reference>AnyClass expression that specifies an object which has a variable whose value you want to find.

<variable name>String expression that specifies the name of the variable whose value you want to find.

<index>Integer expression that specifies the index of the variable whose value you want to find.

Indexing starts at 1. The index order puts all superclass variables before those defined in a subclass.

Within a given class, the index order of variables is the order in which the variables are defined in the Actuate Basic source. If e.Report Designer Professional generates the Basic source for a class, it lists the variables in alphabetical order.

Description You typically use GetValue in conjunction with GetVariableCount, GetVariableName, GetValueType, and SetValue to work with variables in objects whose types you do not know in advance.

Page 197: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 173

G e t V a l u e f u n c t i o n

Returns Variant.

The value of the specified variable if it exists. If the specified variable does not exist, GetValue returns Null. It is not an error if the variable does not exist.

Tip You cannot use the value GetValue returns to determine whether or not the specified variable exists by checking whether the returned value is Null. This is because GetValue will also return Null if the variable exists but has a value of Null. Instead, use GetValueType to check whether the variable exists.

If you know the class of the object, you should use the following technique to provide improved performance and compile-time error checking. You can access the variables in a class by declaring an object variable reference that points to an instance of that class, then access the variables through that object reference variable. For example, sometimes you are given an object reference variable that points to a base class, such as AcDataRow, but you are interested in a derived class, such as CustomerRow. You declare a temporary object reference variable of the derived class and set it equal to the reference to the base class as shown in the following example:

Sub OnRow(row as AcDataRow)

Dim custRow As CustomerRow Set custRow = row MyVariable = custRow.CustomerNameEnd Sub

Example 1 The following example shows how to use GetVariableCount, GetVariableName, GetValueType, GetValue, and SetValue together.

' Simulate the behavior of the CopyInstance statement,

' but only copy integers > 0 whose names begin "Z_"

Dim vCount As Integer

Dim vName As String

Dim vType As Integer

Dim vValue As Variant

Dim i As Integer

vCount = GetVariableCount( fromObject )

For i = 1 To vCount

vName = GetVariableName( fromObject, i )

vType = GetValueType( fromObject, vName )

If (Left( vName, 2 ) = "Z_") And (vType = V_INTEGER) Then

vValue = GetValue( fromObject, vName )

If (vValue > 0) Then

SetValue( toObject, vName, vValue )

End If

End If

Next i

For information about using the code examples, see “Using the code examples” earlier in this chapter.

Page 198: Actuate Basic Reference

174 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

G e t V a l u e T y p e f u n c t i o n

Example 2 If you have the following classes:

Class MyBaseRow As AcDataRow

Dim AVar As Integer

Dim BVar As Integer

End Class

Class MyRow Subclass Of MyBaseRow

Dim CVar As Integer

Dim DVar As Integer

End Class

And you declare a row as follows:

Dim row As MyRow

You can call AVar with any of the following statements:

x = row.AVar

x = row.GetValue( "AVar" )

x = row.GetValue( 2 )

The ordering sequence is now:

1 = AcDataRow::RowNumber

2 = MyBaseRow::AVar

3 = MyBaseRow::BVar

4 = MyRow::CVar

5 = MyRow::DVar

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also GetValueType functionGetVariableCount functionGetVariableName functionSetValue function

GetValueType functionFinds the data type of a variable in an object dynamically at run-time.

Syntax GetValueType( <object reference>, <variable name>|<index>)

Parameters <object reference>AnyClass expression that specifies an object which has a variable whose data type you want to find.

Page 199: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 175

G e t V a l u e T y p e f u n c t i o n

<variable name>String expression that specifies the name of the variable whose data type you want to find.

<index>Integer expression that specifies the index of the variable whose data type you want to find.

Indexing starts at 1. The index order puts all superclass variables before those defined in a subclass. Within a given class, the index order of variables is the order in which the variables are defined in the Actuate Basic source. If e.Report Designer Professional generates the Basic source for a class, it lists the variables in alphabetical order.

Description You typically use GetValueType in conjunction with GetVariableCount, GetVariableName, GetValue, and SetValue to work with variables in objects whose types you do not know in advance.

Returns Integer indicating the data type of the specified variable, if it exists. If the specified variable does not exist, GetValueType returns Null. It is not an error if the variable does not exist.

The following table shows the values returned by VarType, the Variant data types they indicate, and the names of the corresponding symbolic constants stored in Header.bas.

Tip Test the value GetValueType returns with the IsNull function to determine whether or not the specified variable exists. For example:

Dim valueType As Integer

valueType = GetValueType( anObject, "SomeVariable" )

Assert( Not IsNull( valueType ), "SomeVariable not found!" )

GetValueType returns Data type of variable Symbolic constant

0 Empty V_EMPTY

1 Null V_NULL

2 Integer V_INTEGER

3 Long V_LONG

4 Single V_SINGLE

5 Double V_DOUBLE

6 Currency V_CURRENCY

7 Date V_DATE

8 String V_STRING

Page 200: Actuate Basic Reference

176 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

G e t V a r i a b l e C o u n t f u n c t i o n

Example The following example shows how to use GetVariableCount, GetVariableName, GetValueType, GetValue, and SetValue together.

' Simulate the behavior of the CopyInstance statement,

' but only copy integers > 0 whose names begin "Z_"

Dim vCount As Integer

Dim vName As String

Dim vType As Integer

Dim vValue As Variant

Dim i As Integer

vCount = GetVariableCount( fromObject )

For i = 1 To vCount

vName = GetVariableName( fromObject, i )

vType = GetValueType( fromObject, vName )

If (Left( vName, 2 ) = "Z_") And (vType = V_INTEGER) Then

vValue = GetValue( fromObject, vName )

If (vValue > 0) Then

SetValue( toObject, vName, vValue )

End If

End If

Next i

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also GetValue functionGetVariableCount functionGetVariableName functionSetValue function

GetVariableCount functionReturns the number of variables in an instance. Used in conjunction with GetVariableName.

Syntax GetVariableCount(<object reference>)

Parameters <object reference>Any class expression. An object variable that refers to the object that has the variables you want to count.

Indexing of variables starts at 1. The index order puts all superclass variables before those defined in a subclass. For a data row, variable 1 is the standard RowNumber variable defined in AcDataRow.

Page 201: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 177

G e t V a r i a b l e C o u n t f u n c t i o n

Within a given class, the index order of variables is the order in which the variables are defined in the Actuate Basic source. If Actuate generates the Basic source, as is standard for a data row, then Actuate lists the variables in alphabetical order.

Returns Integer

Tip Use GetVariableName and GetVariableCount to loop over all the variables in an instance, and get both the variables’ names and values. You can write highly customized reports, or general purpose libraries using these functions.

Example 1 The following example shows how to use GetVariableCount, GetVariableName, GetValueType, GetValue, and SetValue together.

' Simulate the behavior of the CopyInstance statement,

' but only copy integers > 0 whose names begin "Z_"

Dim vCount As Integer

Dim vName As String

Dim vType As Integer

Dim vValue As Variant

Dim i As Integer

vCount = GetVariableCount( fromObject )

For i = 1 To vCount

vName = GetVariableName( fromObject, i )

vType = GetValueType( fromObject, vName )

If (Left( vName, 2 ) = "Z_") And (vType = V_INTEGER) Then

vValue = GetValue( fromObject, vName )

If (vValue > 0) Then

SetValue( toObject, vName, vValue )

End If

End If

Next i

For information about using the code examples, see “Using the code examples” earlier in this chapter.

Example 2 The following example shows how GetVariableName and GetVariableCount relate to each other.

Suppose you have the following classes:

Class MyBaseRow As AcDataRow

Dim AVar As Integer

Dim BVar As Integer

End Class

Class MyRow Subclass Of MyBaseRow

Dim CVar As Integer

Dim DVar As Integer

End Class

Page 202: Actuate Basic Reference

178 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

G e t V a r i a b l e N a m e f u n c t i o n

And suppose you declare a row as follows:

Dim row As MyRow

You can get at AVar with any of the following:

x = row.GetValue( "AVar" )

x = row.GetValue( 2 )

In the ordering sequence, we have:

1 = AcDataRow::RowNumber

2 = MyBaseRow::AVar

3 = MyBaseRow::BVar

4 = MyRow::CVar

5 = MyRow::DVar

The following returns AVar, the name of the variable at index 2:

GetVariableName( row, 2 )

The following returns the integer 5:

GetVariableCount(row)

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also GetValue functionGetValueType functionGetVariableName function SetValue function

GetVariableName functionReturns the name of the variable at a given index.

Syntax GetVariableName(<object reference>, <index>)

Parameters <object reference>Any class expression. An object variable that refers to the object that has the variable whose name you want to find.

<index>Integer that specifies the index of a variable.

Indexing starts at 1. The index order puts all superclass variables before those defined in a subclass. For a data row, variable 1 is the standard RowNumber variable defined in AcDataRow.

Page 203: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 179

G e t V a r i a b l e N a m e f u n c t i o n

Within a given class, the index order of variables is the order in which the variables are defined in the Actuate Basic source. If Actuate generates the Basic source, as is standard for a data row, then Actuate lists the variables in alphabetical order.

Returns String

Tip Use GetVariableName and GetVariableCount to loop over all the variables in an instance, and get both the variables’ names and values. You can write highly customized reports or general purpose libraries using these functions.

Example 1 The following example shows how to use GetVariableCount, GetVariableName, GetValueType, GetValue, and SetValue together.

' Simulate the behavior of the CopyInstance statement,

' but only copy integers > 0 whose names begin "Z_"

Dim vCount As Integer

Dim vName As String

Dim vType As Integer

Dim vValue As Variant

Dim i As Integer

vCount = GetVariableCount( fromObject )

For i = 1 To vCount

vName = GetVariableName( fromObject, i )

vType = GetValueType( fromObject, vName )

If (Left( vName, 2 ) = "Z_") And (vType = V_INTEGER) Then

vValue = GetValue( fromObject, vName )

If (vValue > 0) Then

SetValue( toObject, vName, vValue )

End If

End If

Next i

For information about using the code examples, see “Using the code examples” earlier in this chapter.

Example 2 If you have the following classes:

Class MyBaseRow As AcDataRow

Dim AVar As Integer

Dim BVar As Integer

End Class

Class MyRow Subclass Of MyBaseRow

Dim CVar As Integer

Dim DVar As Integer

End Class

And you declare a row as follows:

Dim row As MyRow

Page 204: Actuate Basic Reference

180 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

G e t V i e w C o n t e x t f u n c t i o n

Then, you can call AVar with any of the following statements:

x = row.AVar

x = row.GetValue( "AVar" )

x = row.GetValue( 2 )

The ordering sequence is now as follows:

1 = AcDataRow::RowNumber

2 = MyBaseRow::AVar

3 = MyBaseRow::BVar

4 = MyRow::CVar

5 = MyRow::DVar

The following statement returns AVar, the name of the variable at index 2:

GetVariableName( row, 2 )

The following returns the integer 5:

GetVariableCount(row)

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also GetValue function GetValueType functionGetVariableCount functionSetValue function

GetViewContext functionIndicates which viewing environment is used.

Syntax GetViewContext() As ViewContext

Returns ReportCastContext if the viewing environment is ReportCast.

ActivePortalContext if the viewing environment is Active Portal.

GetViewPageFormats functionRetrieves a list of supported DHTML viewing formats, places the supported viewing formats into a string array, and returns the number of elements in the string array.

Syntax GetViewPageFormats(<formatArray>) As Integer

Page 205: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 181

G e t V i e w P a g e F o r m a t s f u n c t i o n

Parameters <formatArray>String array to contain the list of supported DHTML viewing formats. The viewing formats determine how the DHTML viewing environment presents a report.

Returns The number of elements in the array.

The supported viewing formats that GetViewPageFormats() returns depend upon the viewing formats available in a particular viewing environment. For example, your DHTML viewing environment might support the following viewing formats:

■ XMLDisplay

■ XMLCompressedDisplay

■ DHTML

■ DHTMLLong

■ DHTMLRaw

■ PDF

The viewing formats are display formats. Formats such as CSS and XMLStyle might be supported, but are not display formats. The GetViewPageFormats() function returns only display formats.

You can use GetViewPageFormats() to dynamically build a view page URL such as ?ViewPage&format=PDF.

Example The following example shows how to retrieve a list of supported viewing formats:

Function BrowserCode() As String

Dim formatArray() As String

Dim count As Integer

Dim i As Integer

Dim DhtmlStr As String

DhtmlStr = "<SELECT NAME=’view_format’>"

count = GetViewPageFormats(formatArray)

For i = 1 To count

DhtmlStr = DhtmlStr + "<OPTION VALUE=" + formatArray(i) + ">" +

formatArray(i)

DhtmlStr = DhtmlStr + "</OPTION>"

Next i

DhtmlStr = DhtmlStr + "</SELECT>"

BrowserCode = dhtmlStr

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

Page 206: Actuate Basic Reference

182 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

G e t V S T e m p F i l e N a m e f u n c t i o n

See also IsViewPageFormatSupported function

GetVSTempFileName functionReturns the name of the temporary file to which the Excel file is to be written.

Syntax Function GetVSTempFileName() As String

Description This function retrieves from the View process the unique file name to which the Excel file is to be written. Use this name rather than a hard-coded file name. This is because the View process is multi-threaded. If you use a hard-coded file name, two threads might compete to write to the same file, leading to unpredictable results.

Returns If called from the View process, the unique file name in the view server temp directory.

If called from e.Report Designer Professional, the name of the Excel file to which to write.

Global statementDeclares and allocates memory for variables, and declares the variables to be available to all procedures in all modules.

Syntax Global <variable name> [([<subscripts>])] [As <type>] [, <variable name> [([<subscripts>])] [As <type>]]...

Parameters <variable name>A name you create for the new variable.

<subscripts>Each <subscripts> argument specifies the number of elements in a dimension. The number of <subscripts> arguments specifies the number of dimensions in the array.

Array dimensions using the following syntax:

[<lower>] To <upper>],[<lower>] To <upper>]...

Rules for <subscripts>:

■ If you do not specify <subscripts> between parentheses, Actuate Basic declares a dynamic array.

■ <lower> and <upper> can range from -32,768 to 32,767 inclusive.

■ <lower> must always be less than <upper>.

Page 207: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 183

G l o b a l s t a t e m e n t

■ Use no more than 60 dimensions in a Global statement.

■ Do not later use ReDim to declare more than 8 dimensions for a dynamic array you declared with Global.

Examples:The statements within the following Declare...End Declare block are equivalent if you do not use Option Base:

Declare

Global P(7,5)

Global P(0 to 7, 0 to 5)

Global P(7, 0 to 5)

End Declare

The following example declares a dynamic array:

Global TestArray( )

As <type>Specifies a data type or class for the variable. If you specify a class, the variable can hold a reference to an instance of that class or descendant classes.

Rule for As <type>: If you do not specify As <type>, Actuate Basic uses the data type you declared with Dim or defaults to a Variant.

Rule Use Global within a Declare...End Declare block in your .bas source file.

Tips ■ To avoid assigning incorrect variable types, use the As clause to declare variables.

■ To create a dynamic array with more than eight dimensions, declare it with ReDim, not Global or Dim.

■ Use global variables sparingly; declare variables in local scope if at all possible. Global variables are most useful when values must be shared or accessed by several tasks. Adding a lot of Global variables makes debugging more complicated; in addition, variables with Global scope must be kept in memory while the application is running.

■ To avoid debugging problems, note that variables declared with Global are automatically initialized as follows.

Type Initialized as

Numeric 0

Variant Empty

Variable-length strings Zero-length String

CPointer Null

User-defined Separate variables

Object or Class Nothing (before Set)

Page 208: Actuate Basic Reference

184 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

G l o b a l s t a t e m e n t

To initialize one or more of your global variables to some default value (other than zero), write a procedure that initializes the variables, then call that procedure from the OnStartViewer( ) method of the report.

Example The following Declare statement uses Global to declare two variables. The first is a global dynamic array variable called TestArray. The second is a global integer variable called PrintFlag, which is checked by several parts of the application to determine whether a print action has been completed.

Paste the following lines (Declare block and Sub block) at or near the beginning of your Actuate Basic code module (.bas) file:

Declare

Global TestArray( ) ' Global dynamic array

Global PrintFlag as Integer ' Global integer variable

End Declare

Sub LoadGlobalArray ( )

Dim I As Integer, Size As Integer, Msg As String, NL As String

NL = Chr$(10)

' First check if the global array has already been printed.

If PrintFlag Then

Msg = "That information has already been printed."

MsgBox Msg

Else

' Otherwise, set up TestArray for printing

Size = Int(10 * Rnd + 1)

ReDim TestArray(Size)

For I = 1 to Size

TestArray(I) = Int(10 * Rnd + 1)

Msg = Msg & TestArray(I) & NL

Next I

MsgBox Msg

' Finally set the print flag to true to notify the whole application

PrintFlag = True

End If

End Sub

Paste the following line into the OnLButtonDblClick( ) method of a label or other component in the Method Editor under ’Insert your code here. After compiling, double-click the component.

LoadGlobalArray

Page 209: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 185

G o T o s t a t e m e n t

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Const statementDim statementGetAFCROXVersion functionGetAppContext functionGetFactoryVersion functionGetOSUserName functionGetROXVersion functionGetServerUserName functionOption Base statementReDim statementStatic statementType...End Type statement

GoTo statementBranches to a specified line within a procedure unconditionally and without returning to the calling statement.

Syntax GoTo { <line label> | <line number> }

Parameters <line label>The name of any existing program label that marks the statement to execute next.

Rules for setting up <line label>:

■ Must begin with an alphabetic character and end with a colon.

■ Must not be an Actuate Basic keyword.

■ Must be unique to the module in which it appears.

■ Must be the first non-blank characters on the line.

■ Is not case-sensitive.

Example:

Function OnLButtonDblClk ( )

On Error Goto MyErrorHandler ' Using Goto with a line label

...

Exit Function

MyErrorHandler: ' The line label

...

End Sub

Page 210: Actuate Basic Reference

186 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

G o T o s t a t e m e n t

<line number>The number of any program line that marks the statement to execute next.

Rules for setting up <line number>:

■ Must consist entirely of decimal digits (0 through 9).

■ Must not end with a colon.

■ Must be unique to the module in which it appears.

■ Must not be greater than 2,147,483,647 if you intend to use the Erl function.

■ Can begin in any column, but must be the first non-blank character on the line.

Example:

Function OnLButtonDblClk ( )

500 Dim X, Y, Z

510 On Error GoTo 550 ' Set up error handler

520 Y = 1

'Now cause division by zero error:

530 X = Y / Z

540 Exit Function

550 MsgBox "Error occurred at program line " & Erl' Error handler

560 Resume Next

End Sub

Rule GoTo can branch only to lines that exist within the procedure in which it appears.

Tips ■ Using GoTo in your code makes it difficult to understand and debug. To avoid confusion, use GoTo rarely. Instead, use more structured control statements, such as Do...Loop, For...Next, If...Then...Else, and Select Case, or define Function and Sub procedures.

■ Evaluate Boolean variables by using the keywords True or False.

Example The following example uses GoTo to branch around a subroutine:

Function OnLButtonDblClk()

Dim UserNum as Integer, HalfNum As Double

HalfNum = 0

UserNum = InputBox("Please type a number.")

GoTo ThisPlusColon ' Branch around subroutine

MsgBox "This message never appears."

Routine:

HalfNum = UserNum / 2 ' GoTo detours around this subroutine

ThisPlusColon:

MsgBox "UserNum is: " & UserNum & ". HalfNum is still: " & HalfNum

End Function

Page 211: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 187

H e x , H e x $ f u n c t i o n s

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Erl functionDo...Loop statementFor...Next statementFunction...End Function statementIf...Then...Else statementSelect Case statementSub...End Sub statement

Hex, Hex$ functionsConverts a numeric expression from decimal to hexadecimal notation, and from numeric to string.

Syntax Hex(<numeric expression>)

Hex$(<numeric expression>)

Parameters <numeric expression>Numeric expression to be converted from decimal to hexadecimal notation.

Examples:The following statements are equivalent. Each returns &H010, which is the full form of the hexadecimal equivalent of decimal number 16:

"&H" & Hex$(16)

"&H" & Hex$(2*8)

In the following example, the first statement returns decimal value 32, and the second statement returns decimal value 37:

("&H" & Hex$(16)) * 2

Hex$(16) * 2 + 17

Returns Hex: VariantHex$: String

■ Hex[$] rounds <numeric expression> to the nearest whole number before evaluating it.

■ If <numeric expression> evaluates to Null, Hex[$] returns a Null.

■ If the data type of <numeric expression> is Integer, Variant of VarType 2 (Integer), or Variant of VarType 0 (Empty), Hex[$] returns up to four hexadecimal characters.

■ If <numeric expression> is of any other numeric or Variant data type, Hex[$] returns up to eight hexadecimal characters.

Page 212: Actuate Basic Reference

188 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

H o u r f u n c t i o n

Tips ■ To represent a hexadecimal number directly, precede a number in the correct range with the radical prefix &H. The valid range for hex numbers is &H0 to &HFFFFFFFF. For example, use &H010 * 2 to generate the decimal value 32, &H010 is hexadecimal notation for decimal value 16.

■ To generate the full hexadecimal representation of <numeric expression>, supply the radical prefix &H, because Hex[$] does not return that component.

■ To ensure correct results when you assign the output of Hex to a variable, be sure the variable is of type Variant.

Example The following example prompts the user for a decimal number, then uses Hex[$] to convert that number to hexadecimal notation:

Function OnLButtonDblClk()

Dim Msg, Num

Num = InputBox("Please type a number to convert.") ' Get user input

Msg = Num & " in decimal notation is &H"

Msg = Msg & Hex$(Num) & " in hexadecimal notation."

MsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Oct, Oct$ functionsVal function

Hour functionReturns the hour of the day as an integer from 0 (midnight) to 23 (11:00 P.M.), inclusive, based on a specified date expression.

Syntax Hour(<date expression>)

Parameters <date expression>Date expression, or any numeric or string expression that can be interpreted as a date, a time, or both a date and a time:

■ Can be a string expression such as November 12, 1982 8:30 P.M., Nov. 12, 1982 08:30 PM, 11/12/82 8:30PM, 08:30pm, or any other string that can be interpreted as a date or both a date and a time in the valid range.

■ Can be a date serial number such as 30267.854, which corresponds to November 12, 1982 at 8:30 P.M., or any other number that can be mapped to a date or both a date and a time in the valid range.

Page 213: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 189

H o u r f u n c t i o n

■ For date serial numbers, the integer component to the left of the decimal represents the date itself while the fractional component to the right of the decimal represents the time of day on that date, where January 1, 1900, at precisely noon has the date serial number 2.5, and negative numbers represent dates prior to December 30, 1899 (0).

Default if no time specified: 0

Rules:

■ If <date expression> includes a date, it must be a valid date, even though Hour does not return a date. A valid date is any date in the range January 1, 100 through December 31, 9999, inclusive, expressed in one of the standard date formats.

■ If <date expression> includes a time, it must be in the range 00:00:00 (12:00:00 A.M.) through 23:59:59 (11:59:59 P.M.), in either 12- or 24-hour notation.

■ If <date expression> is a numeric expression, it must be in the range -657,434 to +2,958,465, inclusive.

■ If <date expression> is a variable containing a date serial number, the variable be explicitly declared as one of the numeric types.

■ <date expression> is parsed according to the formatting rules of the current run time locale.

Examples:The following statements are equivalent. Each assigns 14 to the variable UserHour:

UserHour = Hour("6/7/64 2:35pm")

UserHour = Hour("14:35")

UserHour = Hour("June 7, 1964 2:35 PM")

UserHour = Hour("Jun 7, 1964") + 14

UserHour = Hour(23535.6076)

UserHour = Hour(0.6076)

Returns Integer

■ If <date expression> cannot be evaluated to a date, Hour returns a Null.

Example:

Hour("This is not a date.") returns Null

■ If <date expression> fails to include all date components, such as day, month, and year, Hour returns a Null.

Examples:

Hour(“Nov 12, 1982 7:11 AM") returns 7, but

Hour(“Nov 1982 7:11 AM") returns Null

■ If <date expression> is Null, Hour returns a Null.

Page 214: Actuate Basic Reference

190 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

H o u r f u n c t i o n

The following assumes that the AC_CENTURY_BREAK property is set to the default value of 30. For information about using AC_CENTURY_BREAK, please see Chapter 7, “Using a query data stream,” in Developing Advanced e.Reports.

■ For abridged date expressions ending in 00 through 29 that do not specify the century, relevant date functions estimate the unabridged year by adding 2000. For example, while Year(4/30/1910) returns 1910, the abridged expression Year(4/30/10) returns 2010 (10 + 2000).

■ For abridged date expressions ending in 30 through 99 that do not specify the century, relevant date functions estimate the unabridged year by adding 1900. For example, while Year(11/12/2082) returns 2082, the abridged expression Year(11/12/82) returns 1982 (82 + 1900).

Tip If you use a date expression in one locale, it might be misinterpreted in another locale. For instance, in the United States, 1/2/2005 means January 2nd, 2005, but in France, it means February 1st, 2005. To avoid such ambiguities, use DateSerial to specify all your dates.

Example The following example displays the number of hours, minutes, and seconds to midnight:

Function OnLButtonDblClk()

Dim HrDiff As Integer, MinDiff As Integer, SecDiff As Integer

Dim RightNow As Double, Midnight As Double, TotalDiff As Double

Dim TotalMinDiff As Double, TotalSecDiff As DoubleDim Msg As String

'

Midnight = TimeValue("23:59:59")

RightNow = Now ' Get current time

HrDiff = Hour(Midnight) - Hour(RightNow) ' Get diffs re midnight

MinDiff = Minute(Midnight) - Minute(RightNow)

SecDiff = Second(Midnight) - Second(RightNow) + 1

' Restate seconds and minutes if necessary

If SecDiff = 60 Then

MinDiff = MinDiff + 1 ' Add 1 to minute

SecDiff = 0 ' And set 0 seconds

End If

If MinDiff = 60 Then

HrDiff = HrDiff + 1 ' Add 1 to hour

MinDiff = 0 ' And set 0 minutes

End If

' Now get totals

TotalMinDiff = (HrDiff * 60) + MinDiff

TotalSecDiff = (TotalMinDiff * 60) + SecDiff

Page 215: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 191

H o u r f u n c t i o n

TotalDiff = TimeSerial(HrDiff, MinDiff, SecDiff)

' Prepare msg for display

Msg = "There are a total of " & Format(TotalSecDiff, "#,##0")

Msg = Msg & " seconds until midnight. That translates to "

Msg = Msg & HrDiff & " hours, "

Msg = Msg & MinDiff & " minutes, and "

Msg = Msg & SecDiff & " seconds. "

Msg = Msg & "Expressed in standard time notation, it becomes "

' Remember not to use "mm" for minutes! m is for month.

Msg = Msg & Format(TotalDiff, "hh:nn:ss") & "."

MsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Day functionMinute functionMonth functionNow functionSecond functionTime, Time$ functionsWeekday functionYear function

Page 216: Actuate Basic Reference

192 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

I f . . . T h e n . . . E l s e s t a t e m e n t

If...Then...Else statementExecutes an instruction or block of instructions based on a condition or series of conditions.

Syntax Single-line If...Then...Else statement

If <condition> Then <then-statement> Else <else-statement>

Block, multiple-line If...Then...Else statement

If <condition> Then

<then-statement>

[[ElseIf <condition> Then

<then-statement>]]

[Else

[<else-statement>]]]

End If

Parameters <condition>A numeric or string expression that can be evaluated, and that determines whether to execute the associated <statements>. When <condition> evaluates to zero or Null, the condition is False. <condition> is True otherwise.

<then-statement>, <else-statement>One or more Actuate Basic expressions which can include nested If...Then...Else statements. The <then-statement> executes if the preceding <condition> is true. The <else-statement> executes if all previous <conditions> are False. Only one block of <statements> is executed in an If...Then...Else statement: the block of statements following the first <condition> found to be true, or, if no <condition> is found to be true, the <else-statement> block.

IfKeyword that begins every If...Then...Else statement and precedes the first <condition> to be tested.

ThenKeyword that separates <condition> from <then-statement> in an If...Then...Else statement. When <condition> evaluates to True, the <then-statement> is executed. When <condition> evaluates to False, the <then-statement> is ignored, and the program execution tests the next <condition> that it finds.

Page 217: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 193

I f . . . T h e n . . . E l s e s t a t e m e n t

ElseA keyword that tells the program what to do when all previous conditions are False.

ElseIfKeyword that begins an alternative <condition> to be evaluated when the previous <condition> is false. You can use multiple ElseIf clauses. (Tip: if you have several ElseIf clauses, consider using a Select Case statement instead.) Actuate Basic evaluates each ElseIf <condition> in turn, but only until the first true one is encountered. When an ElseIf <condition> evaluates to true, its <then-statements> are executed and control resumes after End If.

End IfKeyword that signals the end of an If...Then...Else statement. A multi-line block If...Then...Else statement must be closed with End If. It is not required for a single-line If...Then...Else statement.

Rule: If, Else, ElseIf, and End If must be the first statement on a line. Else, ElseIf, and End If can be preceded by a line number or a line label.

Tip It is good programming practice to evaluate Boolean variables by using the keywords True or False instead of by inspecting their content for a nonzero (True) or zero (False) numeric value.

Example The following example prompts the user for a number between 0 and 10000. Then it returns the number of digits in the number:

Function OnLButtonDblClk()Dim UserNum As Integer, NumDigits As IntegerDim Msg As String, Unit As StringUserNum = InputBox("Type an integer greater than 0 and less than 10000.")If UserNum < 10 Then

NumDigits = 1 ' 1 digitElseIf UserNum < 100 Then

NumDigits = 2 ' 2 digitsElseIf UserNum < 1000 Then

NumDigits = 3 ' 3 digitsElseIf UserNum < 10000 Then

NumDigits = 4 ' 4 digitsElse

' Prepare the msg for display if none of our conditions was metMsg = "Sorry, the number you typed was too high."

End If' Prepare a msg for display if at least one condition was metIf UserNum < 10000 Then

If NumDigits > 1 ThenUnit = " digits."

Else

Page 218: Actuate Basic Reference

194 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

I I f f u n c t i o n

Unit = " digit."End If

Msg = "The number you typed has " & NumDigits & UnitEnd If' Display messageMsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also End statementExit statementSelect Case statement

IIf functionEvaluates an expression and returns one of two supplied values; if the expression that is the first argument is true, IIf returns the second argument, if false, IIf returns the third.

Syntax IIf(<condition>, <value if true>, <value if false>)

Parameters <condition>Numeric or string expression to be evaluated.

<value if true>Numeric or string expression that specifies the value or expression to return if <condition> is true.

<value if false>Numeric or string expression that specifies the value or expression to return if <condition> is false.

Example:The following statement assigns the double-precision value 112.335577 to the variable ValidMsg if the variable UserAns contains a value less than 5. It assigns the string expression: Sorry, invalid response, if the value of UserAns is greater than or equal to 5:

ValidMsg = IIf(UserAns < 5, 112.335577, "Sorry, invalid response")

Returns Same type as that of <value if true> or <value if false>, depending on which is returned.

Rule All three arguments must be valid. That is, none can generate an error since all three are always evaluated whether <condition> is True or False.

Page 219: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 195

I n p u t # s t a t e m e n t

Example The following example asks the user to type a number less than 5. It then validates the response and displays an appropriate message:

Function OnLButtonDblClk ( )Dim UserAns As Double, ValidMsg As StringUserAns = InputBox("Please type a number smaller than 5.")ValidMsg = IIf(UserAns < 5, "You typed: " & UserAns, "Invalid response")MsgBox ValidMsg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also If...Then...Else statementSelect Case statement

Input # statementReads data from a sequential file and assigns the data to variables.

Syntax Input #<open file number>, <variable list>

Parameters <open file number>Numeric expression that is the file number assigned by Open statement when the target file was opened.

Rules for <open file number>:

■ The number sign (#) preceding the file number is required.

■ The file must be open.

<variable list>Comma-delimited list of the variables that act as containers for values read from the file.

Rules for <variable list>:

■ Cannot contain array variables, but can contain variables that reference an element of an array. For instance, MyArray( ) refers to an entire array and is therefore not allowed, but MyArray(23) refers to a specific element in the array and is therefore a valid variable.

■ Cannot be an object variable, user-defined data type structure, handle to a class, CPointer, or OLE object.

Example:The following code fragment opens an existing file named Test.fil, assigns data from it to a variable called FileData, and constructs a message:

Page 220: Actuate Basic Reference

196 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

I n p u t # s t a t e m e n t

Open "Test.fil" For Input As #1Do While Not EOF(1)

Input #1, FileDataMsg = Msg & FileData & Chr$(10)

Loop

Close #1MsgBox MsgKill "Test.fil"

Description The Input # statement places each data item in the file into one or more of the variables in <variable list>. Data items in the file must appear in the same order as the variables in <variable list> and each variable in <variable list> must be of the same data type as the target data item.

The Input # statement reads each data item and assigns it to its corresponding variable according to its data type. The following two tables summarize the behavior of Input #.

The following table summarizes how Input # decides what Variant type to assign to Variants in <variable list>.

Variable in <variable list> Behavior of Input #

Numeric Assumes first nonspace character it encounters to be the start of a number. Assumes the first space, comma, or end-of-line it encounters to be the end of a number. Inputs blank lines and data of an invalid data type as zero.

String Assumes the first nonspace character it encounters to be the start of a character string. If that character is a double quote (“), it ignores the mark itself and inputs all the succeeding characters until it encounters the next double quote, including spaces and commas. If string data are not delimited by double quotes, it assumes the first line, space, or end-of-line character to be the end of the string. Inputs blank lines as zero-length strings.

Input data Variant type assigned

Valid number. An appropriate numeric Variant (types 2 through 6)

No data, but only a delimiting comma, or a blank line.

VarType 0 (Empty)

The literal Null. VarType 1 (Null)

Page 221: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 197

I n p u t # s t a t e m e n t

Rules ■ Input # generates an error if it reaches the end of file while it is inputting a data item.

■ Data items in a file should appear in the same order as the variables in <variable list> to which they correspond.

Tips ■ To prevent Input # from encountering the end-of-file before it is finished processing data, use it within a loop that tests for the end-of-file condition. For more information, see EOF function.

■ Match data in the file with variables of the proper data type, that is:■ Assign string data to string or Variant variables.■ Assign numeric data to numeric or Variant variables.■ Assign date data to date or Variant variables.■ Assign uniquely Variant data—like Empty and Null values—only to

Variant variables.

Example The following example creates a test file and reads nonnumeric values from the test file into a variable. In this example OnLButtonDblClk( ) is overridden to generate the test file. The procedure MakeSomeData( ) should be typed after the End Function of the OnLButtonDblClk( ) procedure or saved in an Actuate code module (.bas file):

Function OnLButtonDblClk( )Dim FileData As String, Msg As String, NL As StringNL = Chr$(10) ' Define newlineMakeSomeData ' Create test fileOpen "Test.fil" For Input As #1 ' Open to read test fileDo While Not EOF(1)

Input #1, FileData ' Read a line of dataMsg = Msg & FileData & NL ' Construct message

Loop'Close #1 ' Close fileMsgBox MsgKill "Test.fil" ' Delete test file

End Function

Sub MakeSomeData()' This procedure creates the test file used in OnLButtonDblClk'

Date literal. A date of the form yyyy-mm-dd hh:nn:ss).

VarType 7 (Date)Tip: When either the date or time portion is present, the other portion is optional.

None of the above. VarType 8 (String)

Page 222: Actuate Basic Reference

198 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

I n p u t , I n p u t $ f u n c t i o n s

Open "Test.fil" For Output As #1 ' Open to write test fileWrite #1, "This is the first line of the file." ' Write sample dataWrite #1, "This is the second line."Close #1 ' Close test file

End Sub

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Input, Input$ functionsWrite # statement

Input, Input$ functionsReturns a specified number of characters from a sequential file.

Syntax Input(<number of chars>,<file number>)

Input$(<number of chars>, <file number>)

Parameters <number of chars>Numeric expression for the number of characters to read from the file.

Rule for <number of chars>: Must be between 1 and 2,147,483,647.

Example:The following code fragment opens a file in the current directory named Myfile.txt, reads 51 characters from that file into a variable called ReadChunk, then closes the file:

Open "Myfile.txt" For Input As #1ReadChunk = Input$(51, #1)Close #1

<file number>Integer that is the file number assigned by Open statement when the target file was opened.

Rule for <file number>: File must be open.

Returns Input: VariantInput$: String

Returns all the characters it reads, including commas, carriage returns, linefeeds, quotation marks, and leading spaces.

Rules Can be used only with files opened in Input or Binary mode.

Page 223: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 199

I n p u t B , I n p u t B $ f u n c t i o n s

Example The following procedure reads a single character at a time from a file. When it encounters an ANSI character code 10 (linefeed), however, it displays the entire line of text in a message box:

Function OnLButtonDblClk ( )Dim Collector, UsersFile, DisplayMeUsersFile = InputBox("Please type a filename.") ' Request file nameIf Len(UsersFile) Then

Open UsersFile For Input As #1 ' Open specified fileDo While Not EOF(1)

Collector = Input$(1, 1) ' Obtain 1 character' If not a linefeed, then collect itIf Collector <> Chr(10) Then

DisplayMe = DisplayMe & Collector' If it is a linefeed, then display itElse

MsgBox DisplayMeDisplayMe = "" ' Clear the line

End IfLoop ' Loop if not EOFClose #1 ' Close the file

End IfEnd Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Input # statementInputB, InputB$ functions

InputB, InputB$ functionsReturns a specified number of bytes from a sequential file. This function can be used only with files opened in Input or Binary mode.

These functions are provided for backward compatibility with previous Actuate releases. Actuate uses UCS-2 as internal encoding, therefore passing strings consisting of characters from different code pages might produce unexpected results. For this reason, Actuate recommends you use the Input and Input$ functions instead of the InputB and InputB$ functions.

Syntax InputB(<number of bytes>,<file number>)

InputB$(<number of bytes>, <file number>)

Parameters <number of bytes>Numeric expression for the number of bytes to read from the file.

Rule: Must be between 1 and 2,147,483,647.

Page 224: Actuate Basic Reference

200 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

I n p u t B , I n p u t B $ f u n c t i o n s

Example:The following example opens a file in the current directory named Myfile.txt, reads 51 bytes from that file into a variable called ReadChunk, then closes the file:

Open "Myfile.txt" For Input As #1ReadChunk = InputB$(51, #1)Close #1

<file number>Integer that is the file number assigned by Open statement when the target file was opened.

Rule: File must be open.

Returns InputB: VariantInputB$: String

■ Returns all the bytes it reads, including commas, carriage returns, linefeeds, quotation marks, and leading spaces.

Example The following procedure reads a single byte at a time from a file. When it encounters an ANSI character code 10 (linefeed), however, it displays the entire line of text in a message box:

Function OnLButtonDblClk ( )Dim Collector, UsersFile, DisplayMeUsersFile = InputBox("Please type a filename.") ' Request file nameIf Len(UsersFile) Then

Open UsersFile For Input As #1 ' Open specified fileDo While Not EOF(1)

Collector = InputB$(1, 1) ' Obtain 1 byte' If not a linefeed, then collect itIf Collector <> Chr(10) Then

DisplayMe = DisplayMe & Collector' If it is a linefeed, then display itElse

MsgBox DisplayMeDisplayMe = "" ' Clear the line

End IfLoop ' Loop if not EOFClose #1 ' Close the file

End IfEnd Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Input # statementInput, Input$ functions

Page 225: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 201

I n p u t B o x , I n p u t B o x $ f u n c t i o n s

InputBox, InputBox$ functionsDisplays a prompt in a dialog box, waits for the user to type text or select a button, and returns the contents of the text box.

Syntax InputBox[$](<user prompt> [,<box title> ][,<default entry> ])

Parameters <user prompt>String expression that specifies an instruction, message, or prompt to display to the user.

Rule for <user prompt>: Cannot be longer than approximately 255 characters, depending on character width.

<box title>String expression that specifies the text you want to display in the title bar of the dialog box. The default is no text displayed in the title bar.

<default entry>String expression that is the default response if the user supplies no other input. It is placed in the dialog’s text box and is selected, which means that any new entry replaces it. If desired, the most frequently given response can be displayed here. The default is no text displayed in the text box.

Example:The following statement presents a dialog box with Date Entry in the title bar. It prompts the user with, Type a date, and suggests today’s date as the default. The dialog box appears in the upper left corner of the screen. The user’s response is assigned to the variable UDate. If the user types nothing in the text box but chooses OK (or presses Enter), today’s date is assigned to the variable by default:

UDate = InputBox("Type a date.", "Date Entry", Format$(Now, "mm/dd/yy"))

Returns InputBox: VariantInputBox$: String

InputBox[$] displays a dialog box that contains an OK button and a Cancel button, a text box for user input, and the text specified in <user prompt>.

■ If the user chooses OK or Enter, InputBox[$] returns whatever is in the text box.

■ If the user selects Cancel, InputBox[$] returns a zero-length string ("").

Rule You must explicitly type InputBox input variables as numeric if you are expecting numeric input from the user.

Tips ■ Use InputBox[$] when you want a quick way to get data from the user.

Page 226: Actuate Basic Reference

202 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

I n S t r f u n c t i o n

■ If the string in <user prompt> is too long to fit on one line in the dialog box, the text automatically wraps around to the next line. You can force a new line by inserting a line feed (Chr$(10)) in <user prompt>.

Example The following example prompts the user to type a date, and suggests today’s date as the default. Whenever the user fails to type a valid date, it repeats the dialog box. Finally, it displays the day of the week for the supplied date:

Sub InputBoxExample()Dim UserPrompt As String, BoxTitle As String, DefEntry As StringDim UserDate, Msg As String' UserPrompt = "Please type a date in the form mm/dd/yy."BoxTitle = "Date Entry Screen"DefEntry = Format$(Now, "mm/dd/yy")' Do

UserDate = InputBox(UserPrompt, BoxTitle, DefEntry)Loop Until IsDate(UserDate)' Msg = "That date, " & UserDateMsg = Msg & ", was a " & Format$(UserDate, "dddd") & "."MsgBox Msg

End Sub

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also MsgBox functionMsgBox statement

InStr functionReturns the starting position of the occurrence of one string within another.

Syntax Syntax 1

InStr(<string being searched>, <string to find>)

Syntax 2

InStr(<start>, <string being searched>, <string to find>)

Parameters <start>Position (number of characters) within <string being searched> at which to begin searching.

Page 227: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 203

I n S t r f u n c t i o n

Rules for <start>:

■ If you do not supply a <start> position, Actuate Basic begins searching at 1, the first character.

■ Must be a number or numeric expression.

■ Must be between 1 and 2,147,483,647, inclusive.

<string being searched>String you are inspecting to locate <string to find>.

Rule for <string being searched>: Must be a variable string, a literal string, a string constant, the return value of any function that returns a string, or a variant that can evaluate to a string.

<string to find>String you are seeking within <string being searched>.

Rule for <string to find>: Must be a variable string, a literal string, a string constant, the return value of any function that returns a string, or a variant that can evaluate to a string.

Returns Integer

■ If <string to find> is found within <string being searched>, InStr returns the position of the first character at which the match was found.

■ If <string to find> is not found within <string being searched>, InStr returns 0.

■ If <string to find> is zero-length, InStr returns the value of <start>.

■ If <string being searched> is zero-length, InStr returns 0.

■ If <start> is greater than <string being searched>, InStr returns 0.

Example The following example returns the starting position of a some characters within a string:

Function OnLButtonDblClk()Dim MonthList As String, Position As Integer Dim Msg As String, UserInput As String

MonthList = "JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC" Msg = "Please type the 3-letter abbreviation for a month."

' Get user input UserInput = UCase(InputBox(Msg))

' Check user input If Len(UserInput)Then

' Get the positionPosition = InStr(MonthList, UserInput)If Position <> 0 and Len(UserInput)= 3 and ((Position - 1) Mod 3 = 0) Then

Msg = "That month starts at position " & Position & " in the list."

Page 228: Actuate Basic Reference

204 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

I n S t r B f u n c t i o n

ElseMsg = "You did not enter a 3-letter abbreviation for a month!"

End IfElse

Msg = "You did not enter anything at all."End If

MsgBox MsgEnd Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Left, Left$ functionsLen functionMid, Mid$ functionsRight, Right$ functions

InStrB functionReturns the starting byte of the occurrence of one string within another.

This function is provided for backward compatibility with previous Actuate releases. Actuate uses UCS-2 as internal encoding, therefore passing strings consisting of characters from different code pages might produce unexpected results. For this reason, Actuate recommends you use the InStr function instead of the InStrB function.

Syntax Syntax 1

InStrB(<string being searched>, <string to find>)

Syntax 2

InStrB(<start>, <string being searched>, <string to find>)

Parameters <start>Position (byte count) within <string being searched> at which to begin searching.

Rules:

■ If you do not supply a <start> position, Actuate Basic begins searching at 1, the first byte.

■ <start> must be a number or numeric expression.

■ <start> must be between 1 and 2,147,483,647, inclusive.

<string being searched>String you are inspecting to locate <string to find>.

Page 229: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 205

I n S t r B f u n c t i o n

Rule for <string being searched>: Must be a variable string, a literal string, a string constant, the return value of any function that returns a string, or a variant that can evaluate to a string.

<string to find>String you are seeking within <string being searched>.

Rule: Must be a variable string, a literal string, a string constant, the return value of any function that returns a string, or a variant that can evaluate to a string.

Returns Integer

■ If <string to find> is found within <string being searched>, InStrB returns the position of the first byte at which the match was found.

■ If <string to find> is not found within <string being searched>, InStrB returns 0.

■ If <string to find> is zero-length, InStrB returns the value of <start>.

■ If <string being searched> is zero-length, InStrB returns 0.

■ If <start> is greater than <string being searched>, InStrB returns 0.

Example In the following example, InStrB returns the starting position of a some bytes within a string:

Function OnLButtonDblClk()Dim MonthList As String, Position As Integer Dim Msg As String, UserInput As String

MonthList = "JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC"Msg = "Please type the 3-letter abbreviation for a month."' Get user inputUserInput = UCase(InputBox(Msg))' Check user inputIf Len(UserInput)Then

' Get the positionPosition = InStrB(MonthList, UserInput)If Position <> 0 and Len(UserInput)= 3 and ((Position - 1) Mod 3 = 0) Then

Msg = "That month starts at position " & Position & " in the list."Else

Msg = "You did not enter a 3-letter abbreviation for a month!"End If

ElseMsg = "You did not enter anything at all."

End IfMsgBox Msg

End Function

Page 230: Actuate Basic Reference

206 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

I n t f u n c t i o n

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also InStr functionLeftB, LeftB$ functionsLenB functionMidB, MidB$ functions

Int functionReturns the largest integer that is less than or equal to a given numeric expression.

Syntax Int(<number to round>)

Parameters <number to round>Numeric expression from which the fractional part is removed so that an integer value is returned.

Returns ■ If <number to round> is a Variant of type 8 (String) that can convert to a number, Int returns Variant of type 5 (Double). If <number to round> is a String, it is parsed according to the formatting rules of the current run time locale. For example:

Fix("123,456") returns 123.456 on a French localeFix ("123,456") returns 123456.00 on an English locale

■ If <number to round> is not a Variant of type 8 (String) that can convert to a number, Int returns the same data type as <number to round>.

■ If <number to round> is Null, Int returns a Null.

■ Int and Fix are similar but not identical. For negative values, Int returns the first negative integer less than or equal to <number to round> while Fix returns the first negative integer greater than or equal to <number to round>. CInt is also similar to Int and Fix. The following table shows the differences between Int, Fix and CInt using sample values as arguments,.

Value Int(Value) Fix(Value) CInt(Value)

3.7 3 3 4

3.2 3 3 3

3 3 3 3

-3 -3 -3 -3

-3.2 -4 -3 -3

-3.7 -4 -3 -4

Page 231: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 207

I P m t f u n c t i o n

Tip Fix is equivalent to Sgn(<number to round>) * Int(Abs(<number to round>)).

Example The following example prompts the user for a number and displays the return values from Int, Fix and CInt:

Function OnLButtonDblClk()Dim Number, Msg As String, NL As StringNL = Chr$(10) ' Define newline' Get user inputNumber = InputBox("Please type a number.")' Strip off any surrounding spacesNumber = Trim(Number)Msg = "Int(" & Number & ") = " & Int(Number) & NLMsg = Msg & "Fix(" & Number & ") = " & Fix(Number) & NLMsg = Msg & "CInt(" & Number & ") = " & CInt(Number) & NLMsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also CInt functionFormat, Format$ functionsRightB, RightB$ functions

IPmt functionReturns the interest payment for a given period of an annuity, based on periodic, constant payments, and on an unvarying interest rate.

Syntax IPmt(<rate per period>,<single period>, <number pay periods>, <present value>, <future value>, <when due>)

Parameters <rate per period>Numeric expression that specifies the interest rate that accrues per period.

Rule for <rate per period>: Must be given in the same units of measure as <number pay periods>. For instance, if <number pay periods> is expressed in months, then <rate per period> must be expressed as a monthly rate.

<single period>Numeric expression that specifies the particular period for which you want to determine how much of the payment for that period represents interest.

Rule for <single period>: Must be in the range 1 through <number pay periods>.

Page 232: Actuate Basic Reference

208 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

I P m t f u n c t i o n

<number pay periods>Numeric expression that specifies the total number of payment periods in the annuity.

Rule for <number pay periods>: Must be given in the same units of measure as <rate per period>. For instance, if <rate per period> is expressed as a monthly rate, then <number pay periods> must be expressed in months.

<present value>Numeric expression that specifies the value today of a future payment or stream of payments.

Example:If you put $23.94 in the bank today and leave it there for 15 years at an interest rate of 10% compounded annually, you end up with about $100. In this case, the present value of $100 is approximately $23.94.

<future value>Numeric expression that specifies the cash balance you want after you have made your final payment.

Examples:

■ You set up a savings plan with a goal of having $75,000 in 18 years to pay for your child’s education. For this plan, the future value is $75,000.

■ You take out a loan for $11,000. The future value is $0.00, as it is for any typical loan.

<when due>Numeric expression that specifies whether each payment is made at the beginning (1) or at the end (0) of each period.

Default: 0, end of period.

Rule for <when due>: Must be 0 or 1.

Example:The following example assumes you are making monthly payments the first of each month on a loan of $20,000, over 36 months, at an APR of 11.5%. How much of your 5th payment represents interest? The answer, $171.83, is assigned to Interest5:

Interest5 = IPmt(.115/12, 5, 36, -20000, 0, 1)

Returns Double

An annuity is a series of cash payments, constant in value, made over a period of time. An annuity can be an investment, such as a monthly savings plan, or a loan, such as a home mortgage. Each payment consists of two components, principal and interest. IPmt returns the interest component of the payment.

Page 233: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 209

I P m t f u n c t i o n

Rules ■ <rate per period> and <number pay periods> must be expressed in terms of the same units (weekly/weeks, monthly/months, yearly/years).

■ You must express cash paid out, such as deposits to savings, using negative numbers, and cash received, such as dividend checks, using positive numbers.

Example The following example prompts the user to supply various particulars about a loan. It then returns the total amount of interest that will be paid on it. To use this example, paste the first portion at or near the beginning of your Actuate Basic source code (.bas) file. Then copy the procedure into the Method Window for a clickable component:

DeclareGlobal Const ENDPERIOD = 0Global Const BEGINPERIOD = 1

End Declare'Function OnLButtonDblClk()

Dim FutVal As Double, PresVal As DoubleDim APR As Double, TotPmts As IntegerDim PayWhen As Integer, Period As Integer, IntPmt As DoubleDim SumInt As Double, Fmt As String, Payment As DoubleDim Msg as String'Fmt = "$###,###,##0.00" ' Specify money formatFutVal = 0 ' Normally 0 for a loan' Get user inputMsg = "How much will you borrow?"PresVal = InputBox(Msg)Msg = "What is the annual percentage rate (APR) for your loan?"APR = InputBox(Msg)

If APR > 1 Then ' Ensure proper form as %APR = APR / 100

End If

Msg = "How many monthly payments will you make?"TotPmts = InputBox(Msg)Msg = "Will you make payments at month end.?"PayWhen = MsgBox(Msg, MB_YESNO)

If PayWhen = IDNO ThenPayWhen = BEGINPERIOD

ElsePayWhen = ENDPERIOD

End If

Page 234: Actuate Basic Reference

210 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

I R R f u n c t i o n

' Do the computational workFor Period = 1 To TotPmts

IntPmt = IPmt(APR / 12, Period, TotPmts, -PresVal, FutVal, PayWhen)SumInt = SumInt + IntPmt

Next Period

' Set up display for the userMsg = "You will pay a cumulative total of " & Format(SumInt, Fmt)Msg = Msg & " in interest for this loan, which represents about "Msg = Msg & Format(SumInt / PresVal, "##.0%") & " of the "Msg = Msg & Format(PresVal, Fmt) & " you are borrowing."MsgBox Msg

Payment = Pmt(APR / 12, TotPmts, -PresVal, FutVal, PayWhen)MsgBox "Your payments will be " & Format(Payment, Fmt) & " per month."

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also FV functionNPer functionPmt functionPPmt functionPV functionRate function

IRR functionReturns the internal rate of return for a series of periodic cash flows, payments and receipts, in an existing array.

Syntax IRR(<casharray>(),<starting guess>)

Parameters <casharray>()Specifies the name of an existing array of Doubles representing cash flow values.

Rule for <casharray>: Array must contain at least one positive value (receipt) and one negative value (payment).

<starting guess>Numeric expression. Specifies the value you estimate IRR will return. In most cases, this is 0.1 (10 percent).

Page 235: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 211

I R R f u n c t i o n

Example:The following example assumes you have filled the array MyArray() with a series of cash flow values. The internal rate of return is assigned to the variable IRRValue:

IRRValue = IRR(MyArray(), .1)

Returns Double

■ The internal rate of return is the interest rate for an investment consisting of payments and receipts that occur at regular intervals. The cash flow for each period does not need to be constant, as it does for an annuity.

■ IRR is closely related to the net present value function, NPV, because the rate of return calculated by IRR is the interest rate corresponding to a net present value of zero. IRR calculates by iteration. Starting with the value of <starting guess>, it repeats the calculation until the result is accurate to within 0.00001 percent. If it cannot determine a result after 20 iterations, the function fails.

Rules ■ You must express cash paid out, such as deposits to savings, using negative numbers, and cash received, such as dividend checks, using positive numbers.

■ <casharray>() must contain at least one negative and one positive number.

■ In cases where you have both a positive cash flow (income) and a negative one (payment) for the same period, use the net flow for that period.

■ If no cash flow or net cash flow occurs for a particular period, you must type 0 (zero) as the value for that period.

Tips ■ Because IRR uses the order of values within the array to interpret the order of payments and receipts, be sure to type your payment and receipt values in the correct sequence.

■ If IRR fails, try a different value for <starting guess>.

Example The following example returns the internal rate of return for a series of five cash flows contained in the array CashValues(). The first array element is a negative cash flow that represents business start-up costs. The remaining four cash flows represent positive cash flows for the subsequent four years. The variable Guess holds the estimated internal rate of return. Option Base is assumed to be set to zero:

Function OnLButtonDblClk ( )Static CashValues(5) As Double ' Set up the arrayDim Guess As Double, Fmt As StringDim ReturnRate As Double, Msg As String

Guess = .1 ' Start guess at 10%Fmt = "#0.00" ' Define % format

Page 236: Actuate Basic Reference

212 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

I s D a t e f u n c t i o n

CashValues(0) = -80000 ' Business start-up costs' Now type positive cash flows reflecting' income for four successive years:CashValues(1) = 23000: CashValues(2) = 27000CashValues(3) = 31000: CashValues(4) = 35000ReturnRate = IRR(CashValues, Guess) * 100 ' Calc internal rateMsg = "The internal rate of return for these 5 cash flows is: "Msg = Msg & Format(ReturnRate, Fmt) & " percent."MsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also MIRR functionNPV functionOption Base statementRate function

IsDate functionDetermines whether or not the given argument can be converted to a date.

Syntax IsDate(<exprs>)

Parameters <exprs>Variant expression to test to determine whether it is a date, can be evaluated as a date, or can be converted into a date.

Rules:

■ The range of valid dates is January 1, 100, through December 31, 9999, inclusive.

■ Numbers can be converted to a date.

■ <exprs> is parsed according to the formatting rules of the current run time locale.

Examples:The following statements are equivalent. They all return True:

IsDate("11/12/82")IsDate("November 12, 1982")IsDate("Nov 12, 1982")IsDate("N" & "ov " & "12, " & (1980 + 2))IsDate(5)IsDate(5.3)

Page 237: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 213

I s D a t e f u n c t i o n

Returns Integer

■ Returns 1 (True) if <exprs> can be converted to a date. Otherwise, returns 0 (False).

■ If <exprs> fails to include all date components, such as day, month, and year, IsDate returns False.

Tips ■ To convert any number between -657,434 and 2,958,465 into a date, use CVDate. For example, use CVDate(34040.34) to return 3/12/93 7:55:12 A.M.

■ If you use a date expression in one locale, it might be misinterpreted in another locale. For instance, in the United States, 1/2/2005 means January 2nd, 2005, but in France, it means February 1st, 2005. To avoid such ambiguities, use DateSerial to specify all your dates.

Example The following example prompts the user for a string or a number and, if possible, converts that string to a date:

Function OnLButtonDblClk ( )Dim UsrStr As String, NL As String, Msg As String

NL = Chr$(10) ' Define newlineUsrStr = InputBox("Please type a string to display as a date.")If IsDate(UsrStr) Then ' Test the stringMsgBox "The date is: " & Format(CVDate(UsrStr), "dddddd")

ElseIf IsNumeric(UsrStr) Then

If Val(UsrStr) >= -657434 And Val(UsrStr) <= 2958465 ThenMsg = "You typed a number that is not in "Msg = Msg & "date format. However, it will "Msg = Msg & "be interpreted as the following date:" & NL & NLMsg = Msg & Format(CVDate(UsrStr), "dddddd")MsgBox Msg

ElseMsgBox "Sorry, what you typed cannot be converted to a date."

End IfEnd if

End IfEnd Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also CVDate functionIsEmpty functionIsNull functionIsNumeric functionVarType function

Page 238: Actuate Basic Reference

214 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

I s E m p t y f u n c t i o n

IsEmpty functionReports whether the given variable has been initialized.

Syntax IsEmpty(<exprs>)

Parameters <exprs>Variant expression to test whether it has ever been assigned a value.

Returns Integer

■ Returns 1 (True) if <exprs> contains the Empty value. Otherwise, returns 0 (False).

■ Returns 0 (False) if <exprs> contains more than one Variant.

Tip Empty and Null are different. A variable can contain the Null value only if you explicitly assign Null to the variable.

Example The following example tests a variable to determine whether it has ever held any value. If not, it reports that the variable has not been initialized, and asks the user whether to do so or not:

Function OnLButtonDblClk ( )Dim InitYesNo As Integer, MyVar, Msg As String

MsgBox "The value of IsEmpty(MyVar) is now: " & IsEmpty(MyVar)If IsEmpty(MyVar) Then 'Test MyVar

Msg = "MyVar is uninitialized. Should we initialize it now?"InitYesNo = MsgBox(Msg, MB_YESNO + MB_ICONQUESTION)If InitYesNo = IDYES Then ' If user answers Yes

MyVar = 32.5 ' Initialize MyVarMsgBox "MyVar initialized to " & MyVarMsgBox "The value of IsEmpty(MyVar) is now:" & IsEmpty(MyVar)

ElseMsgBox "The value of IsEmpty(MyVar) is still:" & IsEmpty(MyVar)

End IfEnd If

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also IsDate functionIsNull functionIsNumeric functionVarType function

Page 239: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 215

I s K i n d O f f u n c t i o n

IsKindOf functionDetermines if a specified object is an instance of a specified class.

Syntax IsKindOf(<object>, <class>)

Parameters <object>The variable name that refers to the object about which you want information.

<class>The class to test for the membership of an instance of <object>.

Returns Integer

■ Returns 1 (True) if <object> is a member of <class>.

■ Returns 0 (False) if <object> is not a member of <class>.

Tips ■ Use IsKindOf to test if an object is an instance, or an instance of a subclass, of a specified class.

■ To find out an object’s class, use GetClassName.

Example The following example tests if an object is either an instance of MyLabel or an instance of a subclass of MyLabel. If True, the example sets the object’s background color to red:

Function OnLButtonDblClk ( )Dim MyLabel As AcLabelControl, Msg As StringSet MyLabel = New AcLabelControlIf IsKindOf(MyLabel, "AcLabelControl") Then

Msg = "Yes, MyLabel is an AcLabelControl. "Msg = Msg & "We will now set its background color to red."MsgBox MsgMyLabel.BackgroundColor = Red

End IfEnd Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also GetClassID functionGetClassName function

Page 240: Actuate Basic Reference

216 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

I s N u l l f u n c t i o n

IsNull functionReports if the given Variant or Variant expression contains the Null value.

Syntax IsNull(<exprs>)

Parameters <exprs>Variant expression to test. Any expression that contains a Null is itself Null and therefore False. That is why both the following expressions evaluate to False, no matter what value MyVar contains:

If MyVar = NullIf MyVar <> Null

Examples:Assuming you have assigned the Null value to MyVar, the following statements are equivalent. Each returns 1 (True):

IsNull(MyVar)IsNull(MyVar = Null)IsNull(MyVar <> Null)IsNull(MyVar + 5000)

Returns Integer

■ Returns 1 (True) if <exprs> contains the Null value. Otherwise, returns 0 (False).

■ The only way to determine whether a variable contains Null is to use IsNull.

Tip Empty and Null are different. If a variable contains the Empty value, it means it has never yet been assigned any value. A variable can contain the Null value only if you have explicitly assigned Null to it.

Example The following example tests MyVar to determine whether it contains the Null value. The variable MyVar is first initialized to Null but the first time though the loop it is changed to a zero-length string. The second time through the loop, MyVar is again set to Null and the loop exits:

Function OnLButtonDblClk()Dim MyVarMyVar = Null ' Initialize variable as NullDo

If IsNull(MyVar) Then ' Evaluate variableMsgBox "MyVar is Null." ' Report if NullMyVar = "" ' Assign zero-length string

ElseMsgBox "MyVar is not Null." ' Report if not NullMyVar = Null ' Assign Null to variable

Page 241: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 217

I s N u m e r i c f u n c t i o n

End IfLoop Until IsNull(MyVar) ' Loop until MyVar is Null

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also IsDate functionIsEmpty functionIsNumeric functionVarType function

IsNumeric functionTests if the type of a variable is or can be converted to Integer, Long, Single, Double, or Currency.

Syntax IsNumeric(<exprs>)

Parameters <exprs>Variant expression to test to determine if it is, can be evaluated as, or can be converted to a numeric data type. For example, the following are equivalent. Each returns True:

IsNumeric("34040")IsNumeric(34040)IsNumeric(Val("343Haydn"))

Rule: If <exprs> is a String, it is parsed according to the formatting rules of the current run time locale.

ReturnsInteger

■ Returns 1 (True) if <exprs> can be converted to a number. Otherwise, returns 0 (False).

■ Returns 1 (True) if <exprs> is Empty.

■ Returns 0 (False) for any <exprs> assigned to InputBox regardless of the type of data the user supplies in response to the InputBox prompt.

Tip To extract a numeric value from a string that starts with numbers but also contains non-numeric characters, use Val.

Example The following example inspects each of four elements in an array of mixed types and reports whether or not the content of the variable is numeric:

Function OnLButtonDblClk()Dim UserVar(4), Msg, Slot As Integer

Page 242: Actuate Basic Reference

218 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

I s P e r s i s t e n t f u n c t i o n

UserVar(1) = 12UserVar(2) = "twelve"UserVar(3) = "123four"UserVar(4) = Val("123four")For Slot = 1 to 4

If IsNumeric(UserVar(Slot)) ThenMsg = UserVar(Slot) & " is Numeric."

ElseMsg = UserVar(Slot) & " is not Numeric."

End IfMsgBox Msg

Next SlotEnd Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also IsDate functionIsEmpty functionIsNull functionVal functionVarType function

IsPersistent functionReports if an instance of an object is persistent or transient.

Syntax IsPersistent(<object>)

Parameters <object>The variable name that refers to the object about which you want information.

Returns Integer

■ Returns 1 (True) if <object> is persistent.

■ Returns 0 (False) if <object> is transient.

See also NewInstance functionNewPersistentInstance function

IsSearchFormatSupported functionDetermines whether the specified search format is supported or not.

Page 243: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 219

I s V i e w P a g e F o r m a t S u p p o r t e d f u n c t i o n

Syntax IsSearchFormatSupported(<format> As String) As Boolean

Parameters <format>The format for which to determine support. The supported formats depend on the formats available in a particular environment. For example, the following search formats might be supported:

■ XMLDisplay (DISPLAY)

■ Download formats:■ CSV■ TSV■ ANALYSIS

Returns True if the format is supported.

False if the format is not supported.

Example The following example shows how to determine if the ANALYSIS format is supported:

Function CreateSearchURL(format As String) As StringDim URL As StringDim format As StringDim searchCriteria As String

SearchCriteria = "..."format = "ANALYSIS"If Not IsSearchFormatSupported(format) Then

format = "CSV"End IfURL = "http://" format=" + format + searchCriteriaCreateSearchURL = URLEnd Function

See also GetSearchFormats function

IsViewPageFormatSupported functionDetermines whether the specified view format is supported or not.

Syntax IsViewPageFormatSupported(<format> As String) As Boolean

Parameters <format>The DHTML viewing format for which to determine support. The supported formats depend on the formats available in a particular environment. For example, the following viewing formats might be supported:

Page 244: Actuate Basic Reference

220 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

K i l l s t a t e m e n t

■ XMLDisplay (DISPLAY)

■ DHTML

■ PDF

Returns True if the format is supported.

False if the format is not supported.

Example The following example shows how to determine if the ANALYSIS format is supported:

Function CreateSearchURL(format As String) As StringDim URL As StringDim format As StringDim searchCriteria As String

SearchCriteria = "..."format = "PDF"If Not IsViewPageFormatSupported(format) Then

format = "DHTML"End IfURL = "http://" format=" + format + searchCriteriaCreateSearchURL = URLEnd Function

See also GetViewPageFormats function

Kill statementDeletes a specified file or files from a disk.

Syntax Kill <file spec>

Parameters <file spec>String expression that specifies the name or names of the file or files to be deleted. Wildcard characters can be used. Can include optional drive and path information.

Default path: Current default drive and directory.

Rules:

■ Indicated file or files must exist.

■ Path, if specified, must exist.

■ Indicated file must not currently be open by Actuate Basic.

Page 245: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 221

K i l l s t a t e m e n t

<file spec> may optionally specify full path information, in which case it has the following syntax:

[<drive:>] [ \ ]<directory>[\<directory>]...<file spec> (Windows)

[/]<directory>[/<directory>]...<file spec> (UNIX)

<drive:>Character, followed by a colon, that specifies the drive where <file spec> is located (Windows only).

<directory>String expression that specifies the name of a directory or subdirectory where <file spec> is located.

Example:The following statement deletes all files in the Windows directory C:\Discard that have an extension of .doc:

Kill C:\Discard\*.doc

Description Kill is similar to the operating system commands ERASE and DEL.

Tips ■ Be careful in how you use Kill, especially if you include wildcard characters in <file spec>. It is easy to delete files unintentionally, and Kill is irreversible.

■ To delete directories, use RmDir.

Example The following example prompts the user for a file or files to delete, verifies the delete request, then performs the operation if it can, if it cannot, it issues an error message:

Function OnLButtonDblClk()Dim MakeSure As Integer, ChuckFile As String, Msg As StringOn Error GoTo Errhandler55 ' Set up error handler

' Get user inputMsg = "Type the full pathname of the file you want to delete."ChuckFile = UCase$(InputBox(Msg))' Verify file to delete -- if the user has changed mind, immediately exitIf Len(ChuckFile) <= 0 Then

Msg = "You did not enter a file name."MsgBox MsgExit Function

ElseMsg = "Sure you want to delete " & ChuckFile & "?"MakeSure = MsgBox(Msg, MB_YESNO)If MakeSure = IDYES Then ' User chose Yes

Msg = "Deleting " & ChuckFile & " from your disk."

Page 246: Actuate Basic Reference

222 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

L B o u n d f u n c t i o n

Kill ChuckFile ' Delete fileElse

Msg = ChuckFile & " was not deleted."End If

End If

MsgBox MsgExit Function

Errhandler55:MsgBox "Error number " & Err & " occurred. " & Error$(Err)If Err = 48 Then ' "Path not Found"

Msg = "Sorry, the file you named could not be found."Else

Msg = "Sorry, unable to delete file. May be open."End IfResume Next

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Name statement

LBound functionReturns the smallest available subscript for the given dimension of an array.

Syntax LBound(<array name>[,<dimension>])

Parameters <array name>Name of an array variable.

<dimension>Numeric expression that specifies the array dimension for which you want to determine the lower bound.

Rules:

■ If you do not supply a <dimension>, Actuate Basic defaults to 1.

■ Use 1 for the first dimension, 2 for the second, and so on.

■ Must not be larger than the total number of dimensions in <array name>.

■ Must not be zero, negative, or Null.

Page 247: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 223

L B o u n d f u n c t i o n

For example, the table below shows the values LBound returns for an array with these dimensions:

Dim MyArray(1 To 55, 0 To 27, -3 To 42)

Returns Integer

Rule: If <dimension> is not an Integer, LBound rounds <dimension> to the nearest Integer before evaluating it.

Tips ■ To determine the upper bound of an array, use UBound.

■ To determine the total number of elements in a given dynamic array dimension, take the value returned from UBound, subtract the value returned from LBound, and then add 1.

Example The following example determines the lower bounds of an array of 3 dimensions. The use of Rnd simulates changes in lower bounds that the user can make at run time:

Function OnLButtonDblClk()Dim First As Integer, Sec As Integer, Third As IntegerDim Msg As String, NL As String, TabChar As StringDim MyArray() ' Declare array

NL = Chr(10): TabChar = Chr(9) ' Define newline, tab

' Generate random dimensions between 3 and 16 for array size.First = Int(14 * Rnd + 3) ' First dimensionSec = Int(14 * Rnd + 3) ' Second dimensionThird = Int(14 * Rnd + 3) ' Third dimensionReDim MyArray(First To 30, Sec To 30 , Third To 30) ' Set dimensionsMsg = "MyArray has the following lower bounds: " & NLMsg = Msg & TabChar & "Dimension 1 ---> " & LBound(MyArray, 1) & NLMsg = Msg & TabChar & "Dimension 2 ---> " & LBound(MyArray, 2) & NLMsg = Msg & TabChar & "Dimension 3 ---> " & LBound(MyArray, 3)MsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Dim statementUBound function

Statement Returned value

LBound(MyArray, 1) 1

LBound(MyArray, 2) 0

LBound(MyArray, 3) -3

Page 248: Actuate Basic Reference

224 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

L C a s e , L C a s e $ f u n c t i o n s

LCase, LCase$ functionsConverts all uppercase alphabetic characters in a string to lowercase.

Syntax LCase(<string exprs>)

LCase$(<string exprs>)

Parameters <string exprs>String expression to convert to lowercase characters.

For example, the following statements are equivalent. Each returns 6 jane street, 2nd fl:

LCase$("6 JANE STREET, 2ND FL")LCase$("6 Jane Street, 2nd Fl")LCase$("6 jAn" & "E sTreeT, 2nD fL")

Returns LCase: VariantLCase$: String

■ If <string exprs> contains no uppercase alphabetic characters, LCase[$] returns <string exprs> unchanged.

■ LCase[$] has no effect on non-alphabetic characters in <string exprs>.

Tips ■ To ensure uniformity in the data you get from the user so that, for example, name strings like MacManus, Macmanus, or macMaNus are always sorted, compared, or otherwise treated in the same way, first convert strings using LCase[$] or UCase[$].

■ To convert alphabetic characters in <string exprs> to uppercase, use UCase[$].

Example The following example renders a customer’s name in lowercase:

Function OnLButtonDblClk ( )Dim LowerCase As String, UserInput As String, Msg As StringUserInput = InputBox("Please type a customer's name.")LowerCase = LCase$(UserInput) ' Convert to lowercaseMsg = "LCase$ converts """ & UserInput & """ to """Msg = Msg & LowerCase & """."MsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also UCase, UCase$ functions

Page 249: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 225

L e f t , L e f t $ f u n c t i o n s

Left, Left$ functionsReturns a segment of a Variant or String, starting at the leftmost character.

Syntax Left(<string exprs>, <length>)

Left$(<string exprs>, <length>)

Parameters <string exprs>Source string from which you are copying a leftmost portion. Can be a variable string, a literal string, a string constant, the return value of any function that returns a String, or a Variant that can evaluate to a String.

<length>Numeric expression that specifies how many characters to copy from the left of <string exprs>.

Rules:

■ Must be an Integer or expression of type Long.

■ Must be between 0 and 2,147,483,647.

The following statements are equivalent. Both return Widget:

Left$("Widget",6)Left$("Widget",99)

Returns Left: VariantLeft$: String

■ If <length> = 0, returns a zero-length string.

■ If <length> is greater than or equal to the length of <string exprs>, returns an exact copy of <string exprs>.

Tips ■ Use Len to find the number of characters in <string exprs>.

■ Use InStr to find the position of a specified character in <string exprs>.

Example The following example asks the user to input a customer’s first and last names, then returns the first name:

Function OnLButtonDblClk()Dim FName As String, Msg As String, LName As StringDim SpacePos As Integer, UserInput As StringMsg = "Enter a client's first and last name, separated by a space."UserInput = InputBox(Msg) ' Get user’s inputSpacePos = InStr(1, UserInput, " ") ' Find the spaceIf SpacePos Then

FName = Left$(UserInput, SpacePos - 1) ' Get first and last nameLName = Right$(UserInput, Len(UserInput) - SpacePos)

Page 250: Actuate Basic Reference

226 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

L e f t B , L e f t B $ f u n c t i o n s

Msg = "The first name is """ & FName & "." & """"Msg = Msg & " The last name is """Msg = Msg & LName & "." & """"

ElseMsg = "You did not enter a first and last name!"

End IfMsgBox Msg ' Display the message

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also InStr functionLen functionMid, Mid$ functionsRight, Right$ functions

LeftB, LeftB$ functionsReturns a segment of a Variant or String, starting at the leftmost byte.

These functions are provided for backward compatibility with previous Actuate releases. Actuate uses UCS-2 as internal encoding, therefore passing strings consisting of characters from different code pages might produce unexpected results. For this reason, Actuate recommends you use the Left and Left$ functions instead of the LeftB and LeftB$ functions.

Syntax Left(<string exprs>, <length>)

Left$(<string exprs>, <length>)

Parameters <string exprs>Source string. Can be a variable string, a literal string, a string constant, the return value of any function that returns a String, or a Variant that can evaluate to a String.

<length>Numeric expression that specifies how many bytes to copy from the left of <string exprs>.

Rules:

■ <length> must be an Integer or expression of type Long.

■ <length> must be between 0 and 2,147,483,647.

Page 251: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 227

L e f t B , L e f t B $ f u n c t i o n s

Example:The following statements are equivalent. Both return Widget:

LeftB$("Widget",6)LeftB$("Widget",99)

Returns LeftB: VariantLeftB$: String

■ If <length> = 0, the function returns zero-length string.

■ If <length> is greater than or equal to the length of <string exprs>, the function returns an exact copy of <string exprs>.

Tips ■ Use LenB to find the number of bytes in <string exprs>.

■ Use InStrB to find the position of a specified byte in <string exprs>.

Example The following example prompts the user for a string and a number of bytes to show from the left or right side of the string:

Function OnLButtonDblClk( )

Dim UserString As String, BytesToShow As IntegerDim Msg As StringMsg = "Type a string of characters."UserString = InputBox(Msg)Msg = "How many bytes from the left of <" & UserString & "> do you want

to see?"BytesToShow = InputBox(Msg)'Show that many bytes.Msg = LeftB$(UserString, BytesToShow)MsgBox MsgMsg = "How many bytes from the right of <" & UserString & "> do you

want to see?"BytesToShow = InputBox(Msg)Msg = RightB$(UserString, BytesToShow)MsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also InStrB functionLeft, Left$ functionsLenB functionMidB, MidB$ functionsRightB, RightB$ functions

Page 252: Actuate Basic Reference

228 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

L e n f u n c t i o n

Len functionReturns the number of characters in a string expression.

Syntax Len(<string exprs>)

Len(<variable name>)

Parameters <string exprs>String expression to test for character length.

<variable name>Variable to test for character length.

Examples:The following example returns 11:

Len("Smith, John")

The following example, which tests MyVar, a 4-byte Integer, returns 4:

Len(MyVar)

Returns Integer

■ Regardless of its value, if <variable name> is of any numeric data type except Variant, Len returns the number of characters required to store any variable of that data type.

■ Regardless of its Variant type, if <variable name> is a Variant, Len returns the number of characters required to store it as a String.

■ If <string exprs> or <variable name> is Null, Len returns Null.

Tip Use Len to determine record size when you perform file input/output with random-access files using user-defined variable types. Actuate Basic does not notice a type mismatch if you dimension a variable, such as UserInput, as a String, and then later test it as an Integer, such as if UserInput = 0.

Example The following example returns the length of the user’s name:

Function OnLButtonDblClk()Dim UserInput As String, Msg as String' Get user inputUserInput = InputBox("Please type your name.")' Test the user input and continue only if it's not emptyIf Len(UserInput) <= 0 then

Msg = "Maybe another time!"MsgBox MsgExit Function

End ifMsg = "Your name is " & Len(UserInput) & " characters long, "

Page 253: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 229

L e n B f u n c t i o n

Msg = Msg & "including the space(s)."MsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also LenB functionType...End Type statementVarType function

LenB functionReturns the number of bytes in a string expression.

This function is provided for backward compatibility with previous Actuate releases. Actuate uses UCS-2 as internal encoding, therefore passing strings consisting of characters from different code pages might produce unexpected results. For this reason, Actuate recommends you use the Len function instead of the LenB function.

Syntax LenB(<string exprs>)

LenB(<variable name>)

Parameters <string exprs>String expression to test for byte length.

<variable name>Variable to test for byte length.

Returns Integer

■ Regardless of its value, if <variable name> is of any numeric data type except Variant, LenB returns the number of bytes required to store any variable of any value that is of the same data type.

■ Regardless of its Variant type, if <variable name> is Variant, LenB returns the number of bytes required to store it as a String.

■ If <string exprs> or <variable name> is Null, LenB returns Null.

Tip To determine record size when performing file input/output with random-access files using user-defined variable types, use LenB.

Example The following example returns the number of bytes needed to store each of the fundamental data types. Note that regardless of the integer you input, only the last two values change:

Page 254: Actuate Basic Reference

230 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

L e t s t a t e m e n t

Sub LenBFuncUser()Dim IntVar%, LongVar&Dim SingleVar!, DoubleVar#Dim CurrVar@, DynamicVar, UserNum, MercurialDim Msg, NLNL = Chr(10)'Define newline.UserNum = InputBox("Please, enter an integer less than 10000. ")IntVar% = UserNum'IntegerLongVar& = IntVar% ' Long integerSingleVar! = LongVar&'Single-precision, floatingDoubleVar# = SingleVar!'Double-precision, floatingCurrVar@ = DoubleVar#'CurrencyMercurial = CurrVar@'VariantMsg = "Integer values are stored using " & LenB(IntVar%) & " bytes."Msg = Msg & NL & "Long integer values are stored using "Msg = Msg & LenB(LongVar&) & " bytes." & NLMsg = Msg & "Single-precision values are stored using "Msg = Msg & LenB(SingleVar!) & " bytes." & NLMsg = Msg & "Double-precision values are stored using "Msg = Msg & LenB(DoubleVar#) & " bytes." & NLMsg = Msg & "Currency values are stored using "Msg = Msg & LenB(CurrVar@) & " bytes." & NLMsg = Msg & "This Variant requires "Msg = Msg & LenB(Mercurial) & " bytes to store it as a string." & NLMsg = Msg & "This message contains more than "Msg = Msg & LenB(Msg) & " characters."MsgBox Msg

End Sub

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Len functionType...End Type statementVarType function

Let statementAssigns a value to a variable.

Syntax [Let] <variable> = <exprs>

Parameters <variable>The name of any variable to store <exprs>.

<exprs>String or numeric expression to assign to <variable>.

Page 255: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 231

L e t s t a t e m e n t

Rules:

■ If <exprs> is Variant, and <variable> is numeric, Actuate Basic converts <exprs> to a number, if possible, before assigning it to <variable>.

■ If <exprs> is numeric, its value must fall into the range of the data type of <variable>.

Examples:The following statements are equivalent.

Let N = 50N = 50

The following example generates an error, because 2,147,483,647 is the upper limit of the range of the Integer data type variable to which it is being assigned:

N% = 2147483648

Description In some older versions of BASIC, the Let keyword is required to begin a statement that assigns a value to a variable. In Actuate Basic, the use of Let is optional.

Rules ■ If <variable> is a user-defined type declared with Type, <exprs> must be of the same user-defined type.

■ The data types of <variable> and <exprs> must be compatible.

■ In addition to the data type compatibilities listed in the table below, you can assign Null to numeric, String, Variant, or CPointer variables.

Tips ■ Use IsNumeric to determine if a Variant variable converts to numeric.

■ To make assignments between variables of different user-defined types that have been defined by Type...End Type, use LSet or the = operator. Using the = operator to assign an <exprs> of one data type to a <variable> of a different type converts the value of <exprs> into the data type of <variable>.

Example The following example uses Let to assign a value to Pi:

Data type of <variable>

Valid data types for <exprs>

Numeric Numeric Variant that converts to a numeric data type

String String Non-Null Variant

Variant StringNumeric Variant

CPointer CPointer

Page 256: Actuate Basic Reference

232 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

L i n e I n p u t # s t a t e m e n t

Function OnLButtonDblClk()Dim Msg As String, Pi As Double

' Assign a value to Pi with the Let statementLet Pi = 4 * Atn(1)

' Assign a value to Msg without Let statementMsg = "The area of a circle of radius 3 inches is "Msg = Msg & (Pi * (3^2)) & " inches."MsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Const statementIsNumeric functionLSet statement

Line Input # statementReads from a sequential file until it reaches a carriage-return-linefeed (CRLF) pair or the end of the file (EOF), and assigns the information to a variable.

Syntax Line Input #<file number>, <receiving variable>

Parameters <file number>Numeric expression that is the file number assigned to the target file when it was opened in the Input mode.

<receiving variable>String or variant expression to which Line Input # assigns the data it reads from the target file.

Examples:The following example reads one line of data from Notes.txt into the variable A$:

Open "Notes.txt" For Input As #2Line Input #2, A$

The following example reads the first line of Poem.txt into the variable A$, the second line into B$, and the third into C$:

Open "Poem.txt" For Input As #1Line Input #1, A$Line Input #1, B$Line Input #1, C$

Page 257: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 233

L i n e I n p u t # s t a t e m e n t

Description Line Input # reads data from a sequential file one line at a time.

Unlike Input #, Line Input # treats commas, spaces, and quotes no differently than it does any other characters. It is useful for reading plain ASCII files. Line Input # stops reading into <receiving variable> when it encounters a carriage-return-linefeed character-pair (CRLF). It skips the carriage-return-linefeed character-pair itself and—assuming it is called again—continues reading from the first character after the CRLF until it reaches another CRLF or the end of the file (EOF).

Rules ■ <file number> must match the number of a currently open file.

■ The number sign (#) preceding <file number> is required.

■ The file corresponding to <file number> must be open under the Input mode.

■ You must have write access to the open file. That is, the file must not have been opened using a Lock Read or Lock Read Write clause.

Example The following example creates a test file, then reads three lines from the test file, and finally deletes the test file:

Function OnLButtonDblClk()Dim strEachLine(3) as String, strCumeVar As String, NL As StringDim I As IntegerNL = Chr(10)Open "LineInputNum.txt" For Output As #1For I = 1 to 3

Print #1, "This is line number " & I & " in the test file. "Next I

Reset

Open "LineInputNum.txt" For Input As #1For I = 1 to 3

Line Input #1, strEachLine(I)strCumeVar = strCumeVar & strEachLine(I) & NL

Next IReset

MsgBox strCumeVarMsgBox "Press OK to delete the test file."Kill "LineInputNum.txt"

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

Page 258: Actuate Basic Reference

234 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

L i s t T o A r r a y f u n c t i o n

See also Input # statementOpen statementPrint # statement

ListToArray functionConverts a list of values into an array.

Syntax ListToArray(<list>, <array>)

ListToArray(<list>, <array>, <separator>)

Parameters <list>String expression specifying the list to convert to an array.

<array>Dynamic string array to populate with the elements of the list. This array is resized to exactly the number of elements found in the list. The base of the array is 1.

<separator>Optional string expression specifying a single character used to delimit the elements in the list. If omitted or the value is an empty string or Null, a comma is used as the separator character. If the value is more than one character, only the first character is used.

Returns ■ Integer. The number of elements in the list and hence the number of elements in the array.

■ If the list is an empty string, ListToArray returns 1 and the array contains a single empty element.

■ If the list is Null, ListToArray returns 0 and the array is reset to contain no elements.

Description Use ListToArray to convert lists that are in the form of strings with list elements delimited by separator characters into arrays.

Tip String lists are frequently found in external data, such as parameters and database columns. Use arrays as a more convenient format for calculations.

Loc functionReturns the current position in an open file.

Syntax Loc(<file number>)

Page 259: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 235

L o c f u n c t i o n

Parameters <file number>Numeric expression that is the file number used to open the file with Open statement.

Rule: File must be open.

Returns Integer

■ For Sequential files: Returns the current byte position in the file divided by 128.

■ For Random files: Returns the number of the last variable read from or written to the file.

■ For Binary mode files: Returns the position of the last byte read or written.

Tip You can open sequential files with a buffer of a different size if you use the Len parameter in Open. However, this does not change the result of Loc, which always divides by 128 when applied to sequential files.

Example In the following example, the program opens a test file and asks the user how much of it to read. Then it reports the current position in the file:

Function OnLButtonDblClk ( )Dim CountVar As Integer, UserMsg As StringDim NL As String, NowLoc As Integer, TempVar, MaxNumNL = Chr$(10) ' Define newlineRandomize TimerOpen "Testdata.fil" For Output As #1 ' Open file for outputFor CountVar = 1 To 300 ' Generate rnd values

Print #1, CountVar ' Put data in fileNext CountVarClose #1 ' Close test file'Open "Testdata.fil" For Input As #1 ' Open file just createdMaxNum = InputBox("How many items to read? Type a # from 1 to 299.")For CountVar = 1 To MaxNum

Input #1, TempVar ' Read some data from itNext CountVarNowLoc = Loc(1) ' Find location in fileClose #1 ' Close fileUserMsg = MaxNum & " data elements have been read from a file of 300. "UserMsg = UserMsg & "The current location in the Testdata.fil file is: "UserMsg = UserMsg & NowLoc & "." & NL & NLUserMsg = UserMsg & "Choose OK to delete the sample file."MsgBox UserMsgKill "Testdata.fil" ' Delete file from disk

End Function

Page 260: Actuate Basic Reference

236 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

L o c k . . . U n l o c k s t a t e m e n t

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also EOF functionLOF functionOpen statement

Lock...Unlock statementProhibits access by other users or processes to all or part of an open file.

Syntax Lock [#]<open file number> [,{<record> | [<start>] To <end>} ]

[<data process statements>]

Unlock [#]<open file number> [,{<record> | [<start>] To <end>} ]

Parameters <open file number>Numeric expression that is the file number you used to open the target file.

Rules for <open file number>:

■ Must be the number of a currently open file.

■ The number sign (#) before <open file number> is required.

<record>Numeric expression that specifies the number of the record or byte to lock.

Rules for <record>:

■ Must be between 1 and 2,147,483,647.

■ Record length cannot exceed 65,535 bytes.

<start>Numeric expression that specifies the number of the first record or byte to lock.

Default: 1

ToKeyword that separates <start> from <end> in the clause that specifies a range of records or bytes to lock.

<end>Numeric expression that specifies the number of the last record or byte to lock.

Page 261: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 237

L o c k . . . U n l o c k s t a t e m e n t

The terms <record>, or <start> and <end> specify different things according to the mode under which the target file was opened. The following table summarizes these differences.

<data process statements>One or more valid Actuate Basic statements that direct the operations your program performs on the open file while others are temporarily locked out.

Examples:In the following example, Lock restricts other users or processes from accessing any part at all of the file previously opened as #1. When processing of the file is done, Unlock lifts those restrictions:

Lock #1[<data process statements>]

Unlock #1

The following Lock...Unlock statement block prohibits and then permits others’ access to just a single record, namely the 112th in the random access file Maillist.dat:

Open "Maillist.dat" for Random As #1 Len = 32Lock #1, 112

[<data process statements>]Unlock #1, 112

The following Lock...Unlock statement block locks and then unlocks others’ access to byte positions 11 through 25, inclusive, of the binary file Testfile.dat:

Open "Testfile.dat" For Binary As #1Lock #1, 11 TO 25

[<data process statements>]Unlock #1, 11 TO 25

The following Lock...Unlock statement block locks and then unlocks byte positions 1 through 229, inclusive, of the binary file Testfile.dat:

Open "Testfile.dat" For Binary As #1Lock #1, TO 229

[<data process statements>]Unlock #1, TO 229

File mode <record>, or <start> and <end> refer to

Binary The number of a byte relative to the beginning of the open file. The first byte in a file is byte 1.

Random The number of a record relative to the beginning of the open file. The first record is record 1.

Sequential Input or Output

The entire file, no matter what range you specify with <start> To <end>.

Page 262: Actuate Basic Reference

238 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

L o c k . . . U n l o c k s t a t e m e n t

Description Lock restricts multiuser access to a specified area of a file. When you lock part of the file or the whole file, no other user on a network can access it until you Unlock the file or file segment.

Lock and Unlock apply only to files opened with Open by Actuate Basic. They do not apply to Access databases.

Rules ■ The parameters for Lock and Unlock in a Lock...Unlock statement must match exactly.

■ If you use Lock to restrict access to a file, you must Unlock the file before you close that file or terminate your program.

■ You cannot use Lock...Unlock with versions of MS-DOS earlier than 3.1.

■ If you do use MS-DOS, and Share.exe is not already loaded, you must exit Actuate Basic and run Share.exe under DOS to enable locking operations before you can use Lock...Unlock.

Tips ■ Use Lock...Unlock in networked environments, in which several users or processes might need access to the same file.

■ Use Lock...Unlock to ensure that two users simultaneously updating a database record do not accidentally save old data on top of new.

Example The following example creates a sample data file, and accesses a single record (RecNum) which is locked to other users while the record is being updated. Access is permitted again when the update is complete. In this example OnLButtonDblClk( ) is overridden to create the sample data file and later prompt the user to delete the test file. To use this example, paste the Declare statement and the procedure MakeDataFile1216( )at or near the beginning of your Actuate Basic source code (.bas) file. Make sure the Declare statement is pasted at or near the beginning of the .bas file:

DeclareType AcctRecord

Payer As StringAddress As StringCity As StringOwe As Currency

End TypeEnd Declare' Sub MakeDataFile1216()

Dim CustRecord As AcctRecordOpen "Testfile" For Random Shared As #1 Len = 60CustRecord.Payer = "Emilio Enbilliam" ' Put information in...CustRecord.Address = "6 Jane Street" ' ...each field of the recordCustRecord.City = "New York, NY"CustRecord.Owe = 12 ' Initialize amount owed

Page 263: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 239

L o c k . . . U n l o c k s t a t e m e n t

Put #1, 1, CustRecord 'Put record in fileClose #1 ' Close the file

End Sub

Function OnLButtonDblClk ( )Dim CustRecord As AcctRecordDim Change As String, Msg As String, NL As String, RecNum As IntegerNL = Chr$(10) ' Define newlineOn Error GoTo ErrorHandler ' Set up error handlerMakeDataFile1216 ' Create sample data fileOpen "Testfile" For Random Shared As #1 Len = 60Do

' There is only one record, lock the current recordRecNum = 1Lock #1, RecNumGet #1, RecNum, CustRecord ' Read a recordMsg = "Customer " & CustRecord.PayerMsg = Msg & " currently owes: "Msg = Msg & Format(CustRecord.Owe, "$#,##0.00") & NL & NLMsg = Msg & "Please type the net change (+ or - )"Change = InputBox(Msg) ' Show data and get changeIf Len(Change) = 0 Then Change = 0CustRecord.Owe = CustRecord.Owe + ChangePut #1, RecNum, CustRecord ' Update recordUnlock #1, RecNum ' Unlock the record

Loop Until Change = 0Close #1 ' Close the file

Cleanup:Msg = "Transaction complete. Choose OK to delete the sample "Msg = Msg & "data file."MsgBox MsgKill "TESTFILE" ' Remove file from diskExit Function

ErrorHandler:If Err = 70 Then ' Permission denied error

Msg = "Sorry, you must run Share.exe before running this example. Exit "Msg = Msg & "Actuate Basic, Exit Windows, run Share.exe, and "Msg = Msg & "reenter Actuate Basic to run this example. Do not "Msg = Msg & "shell to DOS and run Share.exe or you might not be "Msg = Msg & "able to run other programs until you reboot."

Else ' Some other error occurredMsg = "Error " & Err & " occurred."

End IfMsgBox Msg ' Display error messageReset ' Close files, flush buffers

Page 264: Actuate Basic Reference

240 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

L O F f u n c t i o n

Resume Cleanup ' Do an orderly exitEnd Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Get statementOpen statementPut statement

LOF functionReturns the size of an open file in bytes.

Syntax LOF(<open file number>)

Parameters <open file number>Numeric expression that is the file number you used with Open to open the target file.

Rules for <open file number>:

■ Must be the number of a currently open file.

■ Must refer to a disk file.

Examples:The following example opens an existing disk file named Test.fil and then uses LOF to determine its size in bytes:

Open "Test.fil" For Input As #1SizeOfFile = LOF(1)

Returns Integer

Tip To determine the length of a file that is not open, use FileLen.

Example The following example creates a test file on disk that contains some random numbers. The procedure then reopens the test file and reports its length. In this example OnLButtonDblClk( ) is overridden to generate the test file and prompt the user to delete the test file. The procedure MakeDataFile0314( ) should be typed after the End Function of the OnLButtonDblClk( ) procedure or pasted into your Actuate Basic source code (.bas) file:

Function OnLButtonDblClk ( )Dim Msg As String, NL As String, FileLengthNL = Chr$(10) ' Define newline

MakeDataFile0327 ' Create sample data fileOpen "Test.fil" For Input As #1 ' Open newly created file

Page 265: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 241

L o g f u n c t i o n

FileLength = LOF(1) ' Get length of fileClose #1 ' Close test fileMsg = "The length of the Test.fil file just created is "Msg = Msg & FileLength & " bytes." & NL & NLMsg = Msg & "Choose OK to delete the sample data file."MsgBox MsgKill "Test.fil" ' Delete test file

End Function

Sub MakeDataFile0327()Dim I As IntegerOpen "Test.fil" For Output As #1 ' Open file for outputFor I = 0 To 250 ' Generate values 0-250

Print #1, INext IClose #1 ' Close test file

End Sub

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also EOF functionFileLen functionLoc functionOpen statement

Log functionGives the natural logarithm for a number.

Syntax Log(<number>)

Parameters <number>Numeric expression or Variant of VarType 8 (String) for which you want to find the logarithm.

Rule for <number>: <number> must be greater than 1.

Returns Double

Rule: If <number> evaluates to Null, Log returns a Null.

Tips ■ To calculate logarithms in a base other than e, use Log(<number> divided by Log(<base>), where <base> is the number of the desired base otherthan e.

■ Log is the inverse of Exp.

Page 266: Actuate Basic Reference

242 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

L S e t s t a t e m e n t

Example The following prompts the user for a number, and returns the natural logarithm for that number:

Function OnLButtonDblClick ( )On Error Goto ErrorHandlerDim UserNum, Msg As StringUserNum = InputBox("Please type a number.")Msg= "The log (base e), or Log(" & UserNum & ") is "Msg= Msg & Log(UserNum)MsgBox MsgExit Function

ErrorHandler: MsgBox "Actuate Basic error: " & Err & " -- " & Error$(Err)MsgBox "Sorry! An error occurred. Please try again."Resume Next

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Exp function

LSet statementLeft-aligns a string within the space of a string variable.

Syntax LSet <string variable> = <string exprs>

Parameters <string variable>Name of a string variable in which LSet stores the left-aligned <string exprs>.

<string exprs>String expression that you want LSet to left-align within <string variable>.

The behavior of LSet depends upon whether <string exprs> is shorter or longer than <string variable>.

<string exprs> Behavior of LSet

Shorter than <string variable>

Left-aligns <string exprs> within <string variable>. Replaces any leftover characters in <string variable> with spaces.

Longer than <string variable>

Places only the leftmost characters, up to the length of the <string variable>, in <string variable>. Truncates characters beyond the length of <string variable> from the right.

Page 267: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 243

L T r i m , L T r i m $ f u n c t i o n s

Description Used for left-aligning a string expression within a variable.

Example The code in the following example left-aligns text within a 20-character String variable:

Function OnLButtonDblClk ( )Dim Msg, NL, TmpStr As StringNL = Chr(10) ' Define newlineTmpStr = String(20, "*") ' Create 20-character stringMsg = "The following two strings that have been right"Msg = Msg & NL & "and left justified in a " & Len(TmpStr)Msg = Msg & "-character string." & NL & TmpStr & NLRSet TmpStr = "Right->" ' Right justifyMsg = Msg & TmpStr & NLLSet TmpStr = "<-Left" ' Left justifyMsg = Msg & TmpStr & NLMsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also RSet statement

LTrim, LTrim$ functionsReturns a copy of a string expression after removing leading spaces.

Syntax LTrim(<string exprs>)

LTrim$(<string exprs>)

Parameters <string exprs>String from which LTrim[$] strips leading spaces. Leading spaces are any spaces that occur before the first non-space character in a string. <string exprs> must be a variable string, a literal string, a string constant, the return value of any function that returns a string, or a Variant that can evaluate to a String.

Returns LTrim: VariantLTrim$: String

A copy of <string exprs> with leading spaces removed. If there are no leading spaces, LTrim$ returns <string exprs>.

Tips ■ To simultaneously strip both leading and trailing spaces in a string, use Trim$.

■ To find spaces in the middle of a string, use InStr.

Page 268: Actuate Basic Reference

244 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

L T r i m , L T r i m $ f u n c t i o n s

Example The following example uses LTrim$ to strip leading spaces from a string variable, while RTrim$ is used to strip trailing spaces:

Function OnLButtonDblClk ( )Dim Msg As String, NL As StringDim CustName As String, CustName1 As StringNL = Chr(10) ' Define newline

CustName = " Harold Pinter "CustName1 = LTrim$(RTrim$(CustName)) ' Strip spacesMsg = "The original customer name " & NL & "'" Msg = Msg & CustName & "'" & NL & " ...was "Msg = Msg & Len(CustName) & " characters long. There were two "Msg = Msg & "leading spaces and two trailing spaces." & NL & NLMsg = Msg & "The name returned after stripping the spaces "Msg = Msg & "is:" & NL & "'" & CustName1 Msg = Msg & "'" & NL & "...and it contains only "Msg = Msg & Len(CustName1) & " characters."MsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also InStr functionRTrim, RTrim$ functions

Page 269: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 245

M i d , M i d $ f u n c t i o n s

Mid, Mid$ functionsReturns the specified portion of a string expression.

Syntax Mid(<string exprs>, <start>[,<length>])

Mid$(<string exprs>, <start>[,<length>])

Parameters <string exprs>Source string from which you are copying a portion. It can be a variable string, a literal string, a string constant, the return value of any function that returns a string, or a Variant that can evaluate to a String.

<start>Integer that specifies the character position within a <string exprs> where copy begins.

Rule: Must be between 1 and 2,147,483,647, inclusive.

<length>Integer indicating how many characters to copy.

Rules for <length>:

■ If <length> is omitted, Actuate Basic uses all characters from <start> to the end of <string exprs>.

■ Must be between 0 and 2,147,483,647.

Examples:

■ The following examples are equivalent:

Mid$("Widget",4,3)Mid$("Widget",4)

■ The following example returns Widget:

Mid$("Widget",1,99)

Returns Mid: VariantMid$: String

■ If <start> is greater than length of <string exprs>, returns zero-length string.

■ If <length> = 0, returns zero-length string.

■ If <length> is greater than length of <string exprs>, returns only the characters up to the length of <string exprs>.

Tip Use Len to find the number of characters in <string exprs>.

Page 270: Actuate Basic Reference

246 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

M i d , M i d $ s t a t e m e n t s

Example In the following example, Mid[$] returns the middle word from a variable containing three words:

Function OnLButtonDblClk ( )Dim MiddleWord, Msg, TestStrDim SpacePos1, SpacePos2, WordLenTestStr = "Mid function Example" ' Create text stringSpacePos1 = InStr(1, TestStr, " ") ' Find first spaceSpacePos2 = InStr(SpacePos1 + 1, TestStr, " ") ' Find next spaceWordLen = (SpacePos2 - SpacePos1) - 1 ' Calc 2nd word length' Find the middle wordMiddleWord = Mid(TestStr, SpacePos1 + 1, WordLen)Msg = "The word in the middle of TestStr is """ & MiddleWord & """"MsgBox Msg, 0, TestStr

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Left, Left$ functionsLen functionRight, Right$ functions

Mid, Mid$ statementsReplaces a segment of a string with another string.

Syntax Mid(<string variable>,<start>[,<length>]) = <string exprs>

Mid$(<string variable>,<start>[,<length>]) = <string exprs>

Parameters <string variable>String expression or Variant variable to modify.

Rule for <string variable>: Cannot be a literal, function, or other expression.

<start>Position in <string variable> at which replacement text begins. The position of the first character is 1.

Rule for <start>: Must be between 1 and 2,147,483,647, inclusive.

<length>Number of characters from <string exprs> to use.

Default: Unchanged <string exprs>.

Page 271: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 247

M i d B , M i d B $ f u n c t i o n s

Rules for <length>:

■ Must be between 1 and 2,147,483,647, inclusive.

■ No matter how large you specify <length> to be, the resulting string is never longer than <string variable>.

<string exprs>String expression that replaces segment of <string variable>. It can be a variable-length string, a literal string, a string constant, the return value of any function that returns a string, or a Variant that can evaluate to a String.

Rule for <string exprs>: Cannot entirely replace <string variable> with a shorter <string exprs>.

Example The following example replaces part of the string FREUDIAN with all or part of Jung in the variable Hillman:

Function OnLButtonDblClk()Dim Hillman As StringHillman = "FREUDIAN"

Mid$(Hillman,1,5) = "Jung" ' now Hillman = "JungDIAN"MsgBox Hillman

Hillman = "FREUDIAN"Mid(Hillman,1,4) = "Jung" ' same result, "JungDIAN"MsgBox Hillman

Hillman = "FREUDIAN" Mid$(Hillman,1,3) = "Jung" ' now Hillman = "JunUDIAN"MsgBox Hillman

Hillman = "FREUDIAN"Mid(Hillman,5) = "Jung" ' now Hillman = "FREUJung"MsgBox Hillman

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Left, Left$ functionsMid, Mid$ functionsRight, Right$ functions

MidB, MidB$ functionsReturns the specified portion of a string expression.

These functions are provided for backward compatibility with previous Actuate releases. Actuate uses UCS-2 as internal encoding, therefore passing

Page 272: Actuate Basic Reference

248 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

M i d B , M i d B $ f u n c t i o n s

strings consisting of characters from different code pages might produce unexpected results. For this reason, Actuate recommends you use the Mid and Mid$ functions instead of the MidB and MidB$ functions.

Syntax MidB(<string exprs>, <start>[,<length>])

MidB$(<string exprs>, <start>[,<length>])

Parameters <string exprs>String expression from which you are copying a byte or a series of contiguous bytes. Can be a variable string, a literal string, a string constant, the return value of any function that returns a string, or a Variant that can evaluate to a String.

<start>Integer that specifies the byte position within a <string exprs> where copy begins.

Rule: Must be between 1 and 2,147,483,647, inclusive.

<length>Integer indicating how many bytes to copy.

Rules:

■ If <length> is omitted, Actuate Basic uses all characters from <start> to the end of <string exprs>.

■ <length> must be between 0 and 2,147,483,647.

Examples:The following statements are equivalent:

MidB$("Widget",4,3)MidB$("Widget",4)

The following statement returns "Widget":

MidB$("Widget",1,99)

Returns MidB: VariantMidB$: String

■ If <start> is greater than length of <string exprs>, the function returns zero-length string.

■ If <length> = 0, the function returns zero-length string.

■ If <length> is greater than length of <string exprs>, the function returns only the characters up to the length of <string exprs>.

Tips ■ Use LenB[$] to find the number of bytes in <string exprs>.

■ Use InStrB[$] to find the position of a specified byte in <string exprs>.

Page 273: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 249

M i d B , M i d B $ s t a t e m e n t s

Example In the following example, MidB returns the middle word from a variable containing three words:

Function OnLButtonDblClk ( )Dim MiddleWord, Msg, TestStrDim SpacePos1, SpacePos2, WordLenTestStr = "MidB function Example" ' Create text stringSpacePos1 = InStr(1, TestStr, " ") ' Find first spaceSpacePos2 = InStr(SpacePos1 + 1, TestStr, " ") ' Find next spaceWordLen = (SpacePos2 - SpacePos1) - 1 ' Calc 2nd word length' Find the middle wordMiddleWord = MidB(TestStr, SpacePos1 + 1, WordLen)Msg = "The word in the middle of TestStr is """ & MiddleWord & """"MsgBox Msg, 0, TestStr

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also InStrB functionLeftB, LeftB$ functionsLenB functionMid, Mid$ functionsRightB, RightB$ functions

MidB, MidB$ statementsReplaces a segment of a string with another string.

Syntax MidB(<string variable>,<start>[,<length>]) = <string exprs>

MidB$(<string variable>,<start>[,<length>]) = <string exprs>

Parameters <string variable>String expression or Variant to modify.

Rule for <string variable>: Must be a variable, not a literal, function, or other expression.

<start>Position in <string variable> at which replacement text begins. The position of the first byte is 1.

Rule for <start>: Must be between 1 and 2,147,483,647, inclusive.

<length>Number of bytes from <string exprs> to use.

Page 274: Actuate Basic Reference

250 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

M i n u t e f u n c t i o n

Default: Unchanged <string exprs>.

Rules for <length>:

■ Must be between 1 and2,147,483,647, inclusive.

■ No matter how large you specify <length> to be, the resulting string is never longer than <string variable>.

<string exprs>String expression that replaces segment of <string variable>. It can be a variable string, a literal string, a string constant, the return value of any function that returns a string, or a Variant that can evaluate to a String.

Rule for <string exprs>: Cannot entirely replace <string variable> with a shorter <string exprs>.

Example The following example replaces part of the string FREUDIAN with all or part of Jung in the variable Hillman:

Function OnLButtonDblClk()Dim Hillman As StringHillman = "FREUDIAN"

MidB(Hillman,1,5) = "Jung" ' now Hillman = "JungDIAN"MsgBox Hillman

Hillman = "FREUDIAN"MidB(Hillman,1,4) = "Jung" ' same result, "JungDIAN"MsgBox Hillman

Hillman = "FREUDIAN" MidB$(Hillman,1,3) = "Jung" ' now Hillman = "JunUDIAN"MsgBox Hillman

Hillman = "FREUDIAN"MidB$(Hillman,5) = "Jung" ' now Hillman = "FREUJung"MsgBox Hillman

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also LeftB, LeftB$ functionsMidB, MidB$ functionsRightB, RightB$ functions

Minute functionReturns an integer from 0 to 59, inclusive, that represents the minute of the hour specified by a date expression.

Page 275: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 251

M i n u t e f u n c t i o n

Syntax Minute(<date exprs>)

Parameters <date exprs>Date expression, or any numeric or string expression that can be interpreted as a date, a time, or both a date and a time:

■ Can be a string such as November 12, 1982 8:30 PM, Nov. 12, 1982 08:30 PM, 11/12/82 8:30pm, 08:30pm, or any other string that can be interpreted as a date, a time, or both a date and a time in the valid range.

■ Can be a date serial number such as 30267.854, which corresponds to November 12, 1982 at 8:30 P.M., or any other number that can be mapped to a date, a time, or both a date and a time in the valid range.

■ For date serial numbers, the integer component represents the date itself while the fractional component represents the time of day on that date, where January 1, 1900 at precisely noon has the date serial number 2.5, and negative numbers represent dates prior to December 30, 1899 (0).

Default: 0.

Rules:

■ If <date exprs> includes a date, it must be a valid date, even though Minute does not return a date. A valid date is any date in the range January 1, 100 through December 31, 9999, expressed in one of the standard date formats.

■ If <date exprs> includes a time, it must be in the range 00:00:00 (12:00:00 A.M.) through 23:59:59 (11:59:59P.M.), in either the 12- or 24-hour format.

■ If <date exprs> is a numeric expression, it must be in the range -657434.0 to +2958465.9999, inclusive.

■ If <date exprs> is a variable containing a date serial number, the variable must be explicitly declared as one of the numeric types.

■ <date exprs> is parsed according to the formatting rules of the current run time locale.

Example:The following statements are equivalent. Each assigns 35 to the variable UserMinute:

UserMinute = Minute("6/7/64 2:35pm")UserMinute = Minute("5:35 pm")UserMinute = Minute("June 7, 1964 2:35 PM")UserMinute = Minute("Jun 7, 1964") + 35UserMinute = Minute(23535.6077)UserMinute = Minute(0.6077)

Returns Integer

■ If <date exprs> cannot be evaluated to a date, Minute returns a Null.

Page 276: Actuate Basic Reference

252 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

M i n u t e f u n c t i o n

Example:

Minute(“This is not a date.“) returns Null

■ If <date exprs> fails to include all date components (day, month, and year), Minute returns a Null.

Examples:

Minute(“Nov 12, 1982 7:11 AM“) returns 11, butMinute(“Nov 1982 7:11 AM“) returns Null

■ If <date exprs> is Null, Minute returns a Null.

The following assumes that the AC_CENTURY_BREAK property is set to the default value of 30. For information about using AC_CENTURY_BREAK, please see Chapter 7, “Using a query data stream,” in Developing Advanced e.Reports.

■ For abridged date expressions ending in 00 through 29 that do not specify the century, relevant date functions estimate the unabridged year by adding 2000. For example, while Year(4/30/1910) returns 1910, the abridged expression Year(4/30/10) returns 2010 (10 + 2000).

■ For abridged date expressions ending in 30 through 99 that do not specify the century, relevant date functions estimate the unabridged year by adding 1900. For example, while Year(11/12/2082) returns 2082, the abridged expression Year(11/12/82) returns 1982 (82 + 1900).

Tip If you use a date expression in one locale, it might be misinterpreted in another locale. For instance, in the United States, 1/2/2005 means January 2nd, 2005, but in France, it means February 1st, 2005. To avoid such ambiguities, use DateSerial to specify all your dates.

Example The following example displays the number of hours, minutes, and seconds to midnight:

Function OnLButtonDblClk()Dim HrDiff As Integer, MinDiff As Integer, SecDiff As IntegerDim RightNow As Double, Midnight As Double, TotalDiff As DoubleDim TotalMinDiff As Double, TotalSecDiff As DoubleDim Msg As String'Midnight = TimeValue("23:59:59")RightNow = Now ' Get current timeHrDiff = Hour(Midnight) - Hour(RightNow) ' Get diffs re midnightMinDiff = Minute(Midnight) - Minute(RightNow)SecDiff = Second(Midnight) - Second(RightNow) + 1

' Restate seconds and minutes if necessaryIf SecDiff = 60 Then

Page 277: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 253

M I R R f u n c t i o n

MinDiff = MinDiff + 1 ' Add 1 to minuteSecDiff = 0 ' And set 0 seconds

End If

If MinDiff = 60 ThenHrDiff = HrDiff + 1 ' Add 1 to hourMinDiff = 0 ' And set 0 minutes

End If

' Now get totalsTotalMinDiff = (HrDiff * 60) + MinDiffTotalSecDiff = (TotalMinDiff * 60) + SecDiffTotalDiff = TimeSerial(HrDiff, MinDiff, SecDiff)

' Prepare msg for displayMsg = "There are a total of " & Format(TotalSecDiff, "#,##0")Msg = Msg & " seconds until midnight. That translates to "Msg = Msg & HrDiff & " hours, " Msg = Msg & MinDiff & " minutes, and "Msg = Msg & SecDiff & " seconds. "Msg = Msg & "Expressed in standard time notation, it becomes "

' Remember not to use "mm" for minutes! m is for month.Msg = Msg & Format(TotalDiff, "hh:nn:ss") & "."MsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Day functionHour functionMonth functionNow functionSecond functionTime, Time$ functionsWeekday functionYear function

MIRR functionReturns the modified internal rate of return for a series of periodic cash flows (payments and receipts) in an existing array.

Syntax MIRR(<casharray>( ),<finance rate>, <reinvestment rate>)

Page 278: Actuate Basic Reference

254 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

M I R R f u n c t i o n

Parameters <casharray>()Array of Doubles that specifies the name of an existing array of cash flow values.

Rule for <casharray>: Array must contain at least one positive value (receipt) and one negative value (payment).

<finance rate>Numeric expression that specifies the interest rate paid as the cost of financing.

Rule for <finance rate>: Must be a decimal value that represents a percentage.

<reinvestment rate>Numeric expression that specifies the interest rate received on gains from cash reinvestment.

Rule for <reinvestment rate>: Must be a decimal value that represents a percentage.

Example:The following example assumes you have filled the array MyArray() with a series of cash flow values. If the interest rate you pay for financing is 12%, and the rate your earn on income is 11.5%, what is the modified internal rate of return? The answer is assigned to the variable MIRRValue:

MIRRValue = MIRR(MyArray( ), 0.12, 0.115)

Returns Double

The modified internal rate of return is the internal rate of return (IRR) when payments and receipts are financed at different rates. MIRR takes into account both the cost of the investment (<finance rate>) and the interest rate received on the reinvestment of cash (<reinvestment rate>).

Rules ■ You must express cash paid out (such as deposits to savings) using negative numbers, and cash received (such as dividend checks) using positive numbers.

■ <casharray>() must contain at least one negative and one positive number.

■ In cases where you have both a positive cash flow (income) and a negative one (payment) for the same period, use the net flow for that period.

■ If no cash flow or net cash flow occurs for a particular period, you must type 0 (zero) as the value for that period.

Tip Because MIRR uses the order of values within the array to interpret the order of payments and receipts, be sure to type your payment and receipt values in the correct sequence.

Page 279: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 255

M k D i r s t a t e m e n t

Example The following example returns the modified internal rate of return for a series of cash flows contained in the array CashValues(). LoanAPR represents the financing interest, and InvAPR represents the interest rate received on reinvested cash. Option Base is assumed to be set to zero:

Function OnLButtonDblClk( )Static CashValues(5) As Double ' Set up arrayDim LoanAPR As Double, InvAPR As Double, NL As StringDim Fmt As String, ReturnRate As Double, Msg As StringNL = Chr$(10)LoanAPR = .1 ' Loan rateInvAPR = .12 ' Reinvestment rateFmt = "#0.00" ' Define money formatCashValues(0) = -80000 ' Business start-up costs

'Now type positive cash flows reflecting income for four successive years:CashValues(1) = 23000: CashValues(2) = 27000CashValues(3) = 31000: CashValues(4) = 35000ReturnRate = MIRR(CashValues, LoanAPR, InvAPR)' Calc internal rateMsg = "The modified internal rate of return for these five cash flows is: "Msg = Msg & Format(Abs(ReturnRate) * 100, Fmt) & "%."MsgBox MsgMsg = CashValues(1) & NL & CashValues(2) & NLMsg = Msg & CashValues(3) & NL & CashValues(4)MsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also IRR functionRate function

MkDir statementCreates a new directory or subdirectory on the specified or current drive.

Syntax MkDir <path name>

Parameters <path name>String expression that is the name of the directory to be created.

Rules for <path name>:

■ Must contain fewer than 259 characters.

■ Cannot be the name of a directory that already exists.

Page 280: Actuate Basic Reference

256 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

M k D i r s t a t e m e n t

<path name> has the following syntax:

[<drive:>] [ \ ]<directory>[\<directory>]...(Windows)

[ /]<directory>[/<directory>]...(UNIX)

<drive:>Character, followed by a colon, that is the name of the drive (Windows only).

<directory>String expression that is the name of the directory or subdirectory to create.

Examples:The following example creates the subdirectory Docs under the current directory on the default drive:

MkDir "Docs"

The following example creates the subdirectory Docs under the root directory of the current drive:

DirName$ = "\Docs"MkDir DirName$

On a Windows system, the following example creates the subdirectory Docs under the root directory of drive D:

MkDir "D:\Docs"

Description If you do not specify the full path name, MkDir creates the new subdirectory on the current drive under the current directory.

Tips ■ MkDir is similar to the operating system MkDir. Unlike the DOS command, however, it cannot be abbreviated.

■ If you use one or more embedded spaces in <path name> when you create a directory, use Actuate Basic’s RmDir to remove the directory.

■ To determine the current directory, use CurDir.

Example The following example determines whether or not a \Tmp subdirectory exists on the current drive. If it does not, it creates it, prompts the user to retain or remove it, and responds accordingly:

Function OnLButtonDblClk ( )Dim UserAns As Integer, ThisDrive As StringDim Msg As String, TempDir As StringOn Error Resume Next ' Set up error handlerThisDrive = Left$(CurDir, 2) ' Get current drive letterTempDir = UCase$(ThisDrive & "\Tmperase") ' Construct full path specMkDir TempDir ' Make the new directoryIf Err = 41Then ' Does it exist?

Msg = "Sorry, " & TempDir & " directory already exists."

Page 281: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 257

M o n t h f u n c t i o n

ElseMsg = TempDir & " directory was created. "

End IfMsg = Msg & "Would you like to remove it?"UserAns = MsgBox(Msg, MB_YESNOCANCEL)If UserAns = IDYES Then

RmDir TempDirEnd If

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also CurDir, CurDir$ functionsChDir statementRmDir statement

Month functionReturns an integer between 1 and 12, inclusive, that represents the month of the year for a specified date argument.

Syntax Month(<date exprs>)

Parameters <date exprs>Date expression, or any numeric or string expression that can evaluate to a date or a date and a time:

■ Can be a string such as November 12, 1982, Nov 12, 1982, 11/12/82, 11-12-82, or any other string that can be interpreted as a date in the valid range.

■ Can be a date serial number such as 30267.854, which corresponds to November 12, 1982 at 8:30 P.M., or any other number that can be mapped to a date in the valid range.

■ For date serial numbers, the integer component represents the date itself while the fractional component represents the time of day on that date, where January 1, 1900 at precisely noon has the date serial number 2.5, and negative numbers represent dates prior to December 30, 1899 (0).

Rules:

■ If <date exprs> a string expression, must specify a date in the range January 1, 100 through December 31, 9999, inclusive.

■ If <date exprs> is a numeric expression, must be in the range -657434 to +2958465, inclusive.

Page 282: Actuate Basic Reference

258 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

M o n t h f u n c t i o n

■ If <date exprs> is a variable containing a date serial number, the variable must be explicitly declared as one of the numeric types.

■ <date exprs> is parsed according to the formatting rules of the current run time locale.

Examples:The following statements are equivalent. Each assigns 6 to the variable UserMonth:

UserMonth = Month("6/7/64")UserMonth = Month("June 7, 1964 2:35 PM")UserMonth = Month("Jun 7, 1964")UserMonth = Month(23535)UserMonth = Month(4707*5)

Returns Integer

■ If <date exprs> cannot be evaluated to a date, Month returns a Null.

Example:

Month(“This is not a date.“) returns Null

■ If <date exprs> fails to include all date components (day, month, and year), Month returns a Null.

Examples:

Month(“Nov 12, 1982“) returns 11, but Month(“Nov 1982“) returns Null

■ If <date exprs> is Null, Month returns a Null.

The following assumes that the AC_CENTURY_BREAK property is set to the default value of 30. For information about using AC_CENTURY_BREAK, please see Chapter 7, “Using a query data stream,” in Developing Advanced e.Reports.

■ For abridged date expressions ending in 00 through 29 that do not specify the century, relevant date functions estimate the unabridged year by adding 2000. For example, while Year(4/30/1910) returns 1910, the abridged expression Year(4/30/10) returns 2010 (10 + 2000).

■ For abridged date expressions ending in 30 through 99 that do not specify the century, relevant date functions estimate the unabridged year by adding 1900. For example, while Year(11/12/2082) returns 2082, the abridged expression Year(11/12/82) returns 1982 (82 + 1900).

Tip If you use a date expression in one locale, it might be misinterpreted in another locale. For instance, in the United States, 1/2/2005 means January 2nd, 2005, but in France, it means February 1st, 2005. To avoid such ambiguities, use DateSerial to specify all your dates.

Page 283: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 259

M o n t h f u n c t i o n

Example The following example prompts the user to enter a date. Then it uses various interrelated date functions to display the year, the month, the day, and the weekday for the given date. Finally, it gives the date’s serial number.

To use this example, paste the function (Function Suffix) into your Actuate Basic source code (.bas) file. Then paste the subroutine code into a clickable control, compile, and run:

Function OnLButtonDblClk ( )Dim UserEntry, UserYear As Integer, UserMonth As IntegerDim UserDay As Integer, UserDOW As Integer, DOWName As StringDim Msg As String, NL As String, LeapYear As String

NL = Chr$(10) ' Define newlineUserEntry = InputBox("Please type a date.") ' Get user inputUserEntry = CDate(UserEntry)UserYear = Year(UserEntry) ' Calculate yearUserMonth = Month(UserEntry) ' Calculate monthUserDay = Day(UserEntry) ' Calculate dayUserDOW = Weekday(UserEntry) ' Calculate day of weekDOWName = Format$ (UserEntry, "dddd") ' Convert to name of day

' Determine if the year is a leap year or a centesimalIf UserYear Mod 4 = 0 And UserYear Mod 100 = 0 Then

If UserYear Mod 400 = 0 Then ' Evenly divisible by 400?LeapYear = "is a leap year."

Else ' Not evenly divisibleLeapYear = "is a centesimal but not a leap year."

End IfElseIf UserYear Mod 4 = 0 Then

LeapYear = "is a leap year."Else

LeapYear = "is not a leap year."End If

' Display results for the user after the pattern:' The given year 1982 is not a leap year. The weekday number for' the 12th day of the 11th month in 1982 is 3, which means that ' day was a Tuesday.'' The date serial number for 11/12/82 is: 30267'MsgBox "The given year, " & UserYear & ", " & LeapYearMsg = "The weekday number for the " Msg = Msg & UserDay & Suffix(UserDay) & " day "Msg = Msg & "of the " & UserMonth & Suffix(UserMonth) & " month "Msg = Msg & "in " & UserYear & " is " & UserDOWMsg = Msg & ", which means that day is a " & DOWName & "." & NL & NLMsg = Msg & "The date serial number for " & UserEntry & " is: "

Page 284: Actuate Basic Reference

260 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

M s g B o x f u n c t i o n

Msg = Msg & CDbl(DateSerial(UserYear, UserMonth, UserDay))MsgBox Msg

End Function

' The following function called in the previous procedure tells us what' suffix (1st, 2nd, 3rd) to use with a number. Paste this in your .bas file.Function Suffix (DateNum) As String

Select Case DateNumCase 1

Suffix = "st"Case 2

Suffix = "nd"Case 3

Suffix = "rd"Case Else

Suffix = "th"End Select

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Date, Date$ functionsDay functionHour functionMinute functionNow functionSecond functionWeekday functionYear function

MsgBox functionDisplays a user-defined message in a window with a specified set of response buttons, waits for the user to choose a button, and returns a value indicating which button the user selected.

Syntax MsgBox(<message text> [, [<configuration>][, <window title>] ])

Parameters <message text>String expression that is the message to be displayed in the dialog box. Lines break automatically at the right edge of the dialog box.

Rule for <messages text>: If the <message text> for an application modal message box is longer than 1024 characters, the message is truncated.

Page 285: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 261

M s g B o x f u n c t i o n

<configuration>Numeric expression that is the bitwise sum of up to four separate values:

■ Number and type of buttons

■ Icon style

■ Default button

■ Modality

The following table summarizes values for <configuration> and their corresponding meanings.

Symbolic constant Value Meaning

Button group

MB_OK 0 Display OK button.

MB_OKCANCEL 1 Display OK and Cancel buttons.

MB_ABORTRETRYIGNORE 2 Display Abort, Retry, and Ignore buttons.

MB_YESNOCANCEL 3 Display Yes, No, and Cancel buttons.

MB_YESNO 4 Display Yes and No buttons.

MB_RETRYCANCEL 5 Display Retry and Cancel buttons.

Icon style group

MB_ICONSTOP 16 Display Stop icon.

MB_ICONQUESTION 32 Display Question Mark icon.

MB_ICONEXCLAMATION 48 Display Exclamation Point icon.

MB_ICONINFORMATION 64 Display Information icon.

Default button group

MB_DEFBUTTON1 0 First button is default.

MB_DEFBUTTON2 256 Second button is default.

MB_DEFBUTTON3 516 Third button is default.

Page 286: Actuate Basic Reference

262 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

M s g B o x f u n c t i o n

Add these numbers or constants together to specify the corresponding attributes of the message box.

Default: 0

Rule: You can use only one number from each group.

Example:Each displays a message box with the Question Mark icon, the message: Are you sure you want to overwrite the file?, and the Yes, No and Cancel buttons. In each case, the No button is the default. The user’s response is assigned to the variable UserAns:

UserAns = MsgBox("Are you sure you want to overwrite the file? ", 3+32+256)UserAns = MsgBox("Are you sure you want to overwrite the file? ", 291)UserAns = MsgBox("Are you sure you want to overwrite the file? ",

MB_YESNOCANCEL + MB_ICONQUESTION + MB_DEFBUTTON2)

<window title>String expression that is the text displayed in the title bar of the dialog box.

Default: No title in the title bar.

Returns Integer

The value that MsgBox function returns tells you which button the user selected.

The following table summarizes the possible user selections and their corresponding return values.

Modality group

MB_APPLMODAL 0 Application modal. User must respond to message box before continuing in current application.

MB_SYSTEMMODAL 4096 System modal. User must respond to message box before continuing with any application.

Symbolic constant Value Meaning

Selection at run time MsgBox returns Symbolic Constant is

OK button 1 IDOK

Cancel button 2 IDCANCEL

Abort button 3 IDABORT

Page 287: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 263

M s g B o x s t a t e m e n t

Tip To set line breaks yourself, place a linefeed (ANSI character 10) before the first character of the text that is to begin each new line. This does not apply to Microsoft Windows 3.0.

Example The following example displays a different message box based on whether the user selected the Yes button or No button in a dialog box:

Function OnLButtonDblClk ( )Dim Title As String, MsgTxt As StringDim DialogDef As Integer, UserResponse As IntegerTitle = "Demonstration of MsgBox Function"MsgTxt = "This demonstrates the display of a critical-error message."MsgTxt = MsgTxt & " Do you want to continue?"DialogDef = MB_YESNO + MB_ICONSTOP + MB_DEFBUTTON2UserResponse = MsgBox(MsgTxt, DialogDef, Title)If UserResponse = IDYES Then

MsgTxt = "You selected Yes."Else

MsgTxt = "You selected No or pressed Enter."End IfMsgBox MsgTxt

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also InputBox, InputBox$ functionsMsgBox statement

MsgBox statementDisplays a user-defined message in a window with a specified set of response buttons, and waits for the user to choose a button. MsgBox statement does not return a value indicating which button the user has clicked.

Syntax MsgBox <message text> [, [<configuration>][, <window title>] ]

Retry button 4 IDRETRY

Ignore button 5 IDIGNORE

Yes button 6 IDYES

No button 7 IDNO

Selection at run time MsgBox returns Symbolic Constant is

Page 288: Actuate Basic Reference

264 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

M s g B o x s t a t e m e n t

Parameters <message text>String expression that is the message displayed in the dialog box. Lines break automatically at the right edge of the dialog box.

Rule for <message text>: For application modal message boxes, must not be longer than 1024 characters, or are truncated.

<configuration>Numeric expression that is the bit-wise sum of up to four separate values:

■ Number and type of buttons

■ Icon style

■ Default button

■ Modality

The following table summarizes values for <configuration> and their corresponding meanings.

Symbolic constant Value Meaning

Button group

MB_OK 0 Display OK button.

MB_OKCANCEL 1 Display OK and Cancel buttons.

MB_ABORTRETRYIGNORE 2 Display Abort, Retry, and Ignore buttons.

MB_YESNOCANCEL 3 Display Yes, No, and Cancel buttons.

MB_YESNO 4 Display Yes and No buttons.

MB_RETRYCANCEL 5 Display Retry and Cancel buttons.

Icon style group

MB_ICONSTOP 16 Display Stop icon.

MB_ICONQUESTION 32 Display Question Mark icon.

MB_ICONEXCLAMATION 48 Display Exclamation Point icon.

MB_ICONINFORMATION 64 Display Information icon.

Default button group

MB_DEFBUTTON1 0 First button is default.

Page 289: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 265

M s g B o x s t a t e m e n t

Add these numbers or constants together to specify the corresponding attributes of the message box.

Default: 0.

Rule: You may use only one number from each group.

Example:Each of the following displays a message box with the Exclamation Point icon, the message: Sorry, insufficient disk space, and the OK button. In each case, the No button is the default button.

MsgBox "Sorry, insufficient disk space", 0+48MsgBox "Sorry, insufficient disk space", 48MsgBox "Sorry, insufficient disk space", (MB_OK + MB_ICONEXCLAMATION)

<window title>String expression that specifies the words to appear in the title bar of the message window.

Default: No title in title bar.

Tip To set line breaks yourself, place a linefeed (ANSI character 10) before the first character of the text that is to begin each new line. This does not apply to Microsoft Windows 3.0.

Example The following example displays three message boxes consecutively:

Function OnLButtonDblClk ( )' Define the dialog boxMsgBox "The dialog box shows a Yes and a No button.", MB_YESNOMsgBox "The dialog box shows only an OK button."

MB_DEFBUTTON2 256 Second button is default.

MB_DEFBUTTON3 516 Third button is default.

Modality group

MB_APPLMODAL 0 Application modal. User must respond to message box before continuing in current application.

MB_SYSTEMMODAL 4096 System modal. User must respond to message box before continuing with any application.

Symbolic constant Value Meaning

Page 290: Actuate Basic Reference

266 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

N a m e s t a t e m e n t

MsgBox "The dialog box shows an OK button, a Cancel button, ?and an info icon.", MB_OKCANCEL + 64.

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also InputBox, InputBox$ functionsMsgBox function

Name statementRenames a file or directory. Also, moves a file from one directory to another.

Syntax Name <old name> As <new name or path>

Parameters AsKeyword that separates the name of the original file or directory from the name of the target file or directory.

<old name>String expression that specifies an existing file or directory to rename.

Default path: Current default drive and directory.

Rules for <old name>:

■ Indicated file or directory must exist.

■ Drive letter, if specified, must be the same as that specified in <new name or path>.

■ Indicated file must not currently be open by Actuate Basic.

<new name or path>String expression that specifies the new file or directory name.

Default path: Current drive and directory.

Rules for <new name>:

■ Indicated file must not already exist if its path is the same as the path in <old name>.

■ Indicated path must already exist if it is not the same as the path in <old name>.

■ Drive letter, if specified, must be the same as that specified in <old name>.

■ Indicated file must not currently be open by Actuate Basic.

Page 291: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 267

N a m e s t a t e m e n t

<old name> or <new name or path> can optionally specify a full path, in which case use the following syntax:

[<drive:>] [ \ ]<directory>[\<directory>][\<file name>] (Windows)

[ / ]<directory>[/<directory>][<file name>] (UNIX)

<drive:>Character, followed by a colon that specifies the drive on which the directory to be renamed, or file to be renamed/moved is located (Windows only).

Rule for <drive:>: Both <old name> and <new name or path> must refer to the same drive.

<directory>String expression that specifies the name of a directory or subdirectory in the full path specification of <old name> or of <new name or path>.

Rule: You can use Name to change the name of a directory, but you cannot move directories.

Examples:The following example changes the name of the file Test1.fil in the current directory to Test2.fil:

Name "Test1.fil " As "Test2.fil "

The following example moves the file Test1.fil from the C:\Temp subdirectory to the root directory:

Name "C:\Temp\Test1.fil " As "C:\Test1.fil "

Description Name is similar to the operating system’s Rename command. Name, however, can change the name of a directory as well as that of a file.

Example The following example moves a file from one directory to another and renames it at the same time:

Function OnLButtonDblClk ( )Dim FileName1 As String, FileName2 As StringDim Msg As String, NL As String, TestDir As StringNL = Chr$(10) ' Define newlineFileName1 = "Nameaaaa.dat" ' Define filenamesFileName2 = "Namebbbb.dat"TestDir = "\Test.dir" ' Test directory nameOpen FileName1 For Output As #1 ' Create test file

Print #1, "This is a test." ' Put sample data in fileClose #1MkDir TestDir ' Make test directoryName FileName1 As TestDir & "\" & FileName2 ' Move and renameMsg = "A new file, " & FileName1 & " was created "

Page 292: Actuate Basic Reference

268 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

N e w I n s t a n c e f u n c t i o n

Msg = Msg & "in " & CurDir$ & ". After being created, it was "Msg = Msg & "moved to " & TestDir & " and renamed "Msg = Msg & FileName2 & "." & NL & NLMsg = Msg & "Choose OK to delete the test data file and "Msg = Msg & "directory."MsgBox MsgKill TestDir & "\" & FileName2 ' Delete file from diskRmDir TestDir ' Delete test directory

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Kill statement

NewInstance functionDynamically creates an instance of a class given the name of that class as a String. Use NewInstance to choose at run time which class to instantiate.

Syntax NewInstance(<class name>)

Parameters <class name>String expression that specifies the fully qualified name of the class to instantiate.

Rule: The class name must be valid or a run-time error is sent.

Returns The reference to the new object instance.

Example In this example, two methods for instantiating an object are demonstrated:

Function OnLButtonDblClk ( )Dim Obj1 As AcLabelControlDim Obj2 As AcLabelControl, Msg As StringSet Obj1 = New AcLabelControl ' Standard instantiationSet Obj2 = NewInstance ("AcLabelControl") ' Dynamic instantiationObj2.BackgroundColor = RedMsg = "The numeric value for the background color "Msg = Msg & "of Obj2 is: " & Obj2.BackgroundColorMsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

Page 293: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 269

N e w P e r s i s t e n t I n s t a n c e f u n c t i o n

See also IsPersistent functionNewPersistentInstance functionSet statement

NewPersistentInstance functionDynamically creates a persistent instance of a class given the name of that class as a String. Use NewPersistentInstance to choose at run time which class to instantiate.

Syntax NewPersistentInstance(<class name>, <file number>)

Parameters <class name>String expression that specifies the name of the class to instantiate.

Rule: Must be valid or a run-time error is sent.

<file number>Numeric expression that specifies the number of the open .roi file.

Rules:

■ If no file number is specified, the object is persistent in the current default .roi file.

■ If two or more .roi files are open, you must specify the file number.

Returns String

The reference to the new object instance.

Example In this example, a persistent instance of an AcLabelControl object is created dynamically:

Function OnLButtonDblClk ( )Dim Obj As AcLabelControl, Msg As StringSet Obj = NewPersistentInstance ("AcLabelControl", 1)Obj.BackgroundColor = RedMsg = "The numeric value for the background color "Msg = Msg & "of Obj is: " & Obj.BackgroundColorMsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also IsPersistent functionNewInstance functionSet statement

Page 294: Actuate Basic Reference

270 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

N o w f u n c t i o n

Now functionReturns a date that represents the current date and time according to the user’s operating system.

Syntax Now

Examples:The following example assigns the current year to the variable ThisYear:

ThisYear = Year(Now)

The following example assigns the current date and time to the variable ThisInstant:

ThisInstant = Now

The following example assigns the full date serial number representing the present moment to the double-precision variable FreezeFrame:

FreezeFrame# = Now

Returns Date

The value that Now returns usually looks like a date and/or time but is stored internally as a Double-precision floating-point number—a date serial number—that represents a date between midnight January 1, 1980, and December 31, 2036, inclusive, and/or a time between 00:00:00 and 23:59:59, or 12:00:00 A.M. and 11:59:59 P.M., inclusive.

Example In the following example, Now returns the current date and Format displays it as a long date that includes the day and date:

Function OnLButtonDblClk()Dim Today As DoubleToday = NowMsgBox "Today is " & Format(Today, "dddd, mmmm dd, yyyy") & "."

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Date, Date$ functionsDay functionHour functionMinute functionMonth functionSecond functionTime, Time$ functionsWeekday functionYear function

Page 295: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 271

N P e r f u n c t i o n

NPer functionReturns the number of periods for an annuity based on periodic, constant payments, and on an unvarying interest rate.

Syntax NPer(<rate per period>, <each pmt>, <present value>, <future value>, <when due>)

Parameters <rate per period>Numeric expression that specifies the interest rate that accrues per period.

Rule for <rate per period>: Must be given in the same units of measure as <each pmt>. For instance, if <each pmt> is expressed as a monthly payment, then <rate per period> must be expressed as the monthly interest rate.

<each pmt>Numeric expression that specifies the amount of each payment.

Rule for <each pmt>: Must be given in the same units of measure as <rate per period>. For instance, if <rate per period> is expressed in months, then <each pmt> must be expressed as a monthly payment.

<present value>Numeric expression that specifies the value today of a future payment or of a stream of payments.

Example:If you put $23.94 in the bank today and leave it there for 15 years at an interest rate of 10% compounded annually, you will end up with about $100. In this case, the present value of $100 is approximately $23.94.

<future value>Numeric expression that specifies the cash balance you want after you have made your final payment.

Examples:

■ You set up a savings plan with a goal of having $75,000 in 18 years to pay for your child’s education. For this plan, the future value is $75,000.

■ You take out a loan for $11,000. The future value is $0.00, as it is for any typical loan.

<when due>Numeric expression that specifies whether each payment is made at the beginning (1), or at the end (0) of each period.

Default: 0.

Rule for <when due>: Must be 0 or 1.

Page 296: Actuate Basic Reference

272 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

N P e r f u n c t i o n

Example:The following example assumes you are making monthly payments at the first of each month on a loan of $20,000, at an APR of 11.5%. If each payment is $653.26, how many payments will you have to make to finish paying off the loan? The answer (36) is assigned to the variable NumPeriods.

NumPeriods = NPer(.115/12, -653.26, 20000, 0, 1)

Returns Double

An annuity is a series of cash payments, constant in value, made over a period of time. An annuity can be an investment, such as a monthly savings plan, or a loan, such as a home mortgage.

Rules ■ <rate per period> and <each pmt> must be expressed in terms of the same units (weekly/monthly/yearly, and so on).

■ You must express cash paid out (such as deposits to savings) using negative numbers, and cash received (such as dividend checks) using positive numbers.

Example The following example prompts the user to supply various particulars about a loan. It then returns the number of payments the user must make to pay it off. To use this example, paste the first section at or near the beginning of your Actuate Basic source code (.bas) file and copy the procedure into the code window for a clickable component like a label:

DeclareGlobal Const ENDPERIOD = 0Global Const BEGINPERIOD = 1 ' When payments are made

End Declare'Function OnLButtonDblClk()

Dim FutureVal As Double, PresVal As Double, APR As DoubleDim Payment As Double, PayWhen As Integer, TotalPmts As Integer'FutureVal = 0 ' Usually 0 for a loan' Get user inputPresVal = InputBox("How much will you borrow?")APR = InputBox("What is the annual percentage rate of this loan?")If APR > 1 Then

APR = APR / 100 ' Ensure proper formEnd IfPayment = InputBox("How much do you want to pay each month?")PayWhen = MsgBox("Do you make payments at month end?", MB_YESNO)If PayWhen = IDNO Then

PayWhen = BEGINPERIOD Else

PayWhen = ENDPERIOD

Page 297: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 273

N P V f u n c t i o n

End If' Do computationTotalPmts = NPer(APR / 12, -Payment, PresVal, FutureVal, PayWhen)If Int(TotalPmts) <> TotalPmts Then

TotalPmts = Int(TotalPmts) + 1End IfMsgBox "It will take " & TotalPmts & " months to pay off your loan."

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also FV functionIPmt functionPmt functionPPmt functionPV functionRate function

NPV functionReturns the net present value of a varying series of periodic cash flows, both positive and negative, at a given interest rate.

Syntax NPV(<rate>,<casharray>( ))

Parameters <rate>Numeric expression that specifies the discount rate over the length of the period.

Rule for <rate>: Must be expressed as a decimal.

<casharray>( )Array of Doubles that specifies the name of an existing array of cash flow values.

Rule for <casharray>: Array must contain at least one positive value (receipt) and one negative value (payment).

Example:The following example assumes you have filled the array MyArray with a series of cash flow values, and that the interest rate is 11%. What is the net present value? The answer is assigned to the variable NetPValue:

NetPValue = NPV(.11,MyArray( ))

Returns Double

Page 298: Actuate Basic Reference

274 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

N P V f u n c t i o n

While PV determines the present value of a series of constant payments, NPV does the same for a series of varying payments. Net present value is the value in today’s dollars of all future cash flows associated with an investment minus any initial cost. In other words, it is that lump sum of money that would return the same profit or loss as the series of cash flows in question, if the lump sum were deposited in a bank today and left untouched to accrue interest at the rate given by <rate> for the same period of time contemplated by the cash flow stream.

Rules ■ The NPV investment begins one period before the date of the first cash flow value and ends with the last cash flow value in the array.

■ If your first cash flow occurs at the beginning of the first period, its value must be added to the value returned by NPV and must not be included in the cash flow values of <casharray>( ).

■ You must express cash paid out (such as deposits to savings) using negative numbers, and cash received (such as dividend checks) using positive numbers.

■ <casharray>( ) must contain at least one negative and one positive number.

■ In cases where you have both a positive cash flow (income) and a negative one (payment) for the same period, use the net flow for that period.

■ If no cash flow or net cash flow occurs for a particular period, you must enter 0 (zero) as the value for that period.

Tip Because NPV uses the order of values within the array to interpret the order of payments and receipts, be sure to enter your payment and receipt values in the correct sequence.

Example The following example assumes Option Base is set to zero, and returns the net present value for a series of cash flows contained in an array. The variable ReturnRate represents the fixed internal rate of return:

Function OnLButtonDblClk()Static CashFlows(6) As Double ' Set up the arrayDim Fmt As String, ReturnRate As DoubleDim Msg As String, NetPVal As DoubleFmt = "$###,##0.00" ' Money display formatReturnRate = .12 ' Set fixed internal rateCashFlows(0) = -100000 ' Business start-up expense' Now enter positive cash flows reflecting income for four successive years:CashFlows(1) = 20000: CashFlows(2) = 40000CashFlows(3) = 80000: CashFlows(4) = 0: CashFlows(5) = 10000NetPVal = NPV(ReturnRate, CashFlows) ' Calc net present valueMsg = "The net present value of these cash flows is: "Msg = Msg & Format(NetPVal, Fmt) & ". "MsgBox Msg

End Function

Page 299: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 275

O c t , O c t $ f u n c t i o n s

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also FV functionIRR functionPV function

Oct, Oct$ functionsConverts a numeric expression from decimal to octal notation, and from numeric to string.

Syntax Oct(<numeric exprs>)

Oct$(<numeric exprs>)

Parameters <numeric exprs>Numeric expression to be converted from decimal to octal notation.

Rules:

■ Oct[$] rounds <numeric exprs> to the nearest whole number before evaluating it.

■ If <numeric exprs> is a String, it is parsed according to the formatting rules of the current run time locale.

Examples:

The following statements are equivalent. Each returns &O010, which is the full form of the octal notation equivalent of decimal number 8:

"&O" & Oct$(8)"&O" & Oct$(2*4)

In the following example, the first statement returns the decimal value 16, but the second statement generates an error because the return value of Oct[$] is not preceded by the octal prefix, &O:

("&O" & Oct$(8)) * 2Oct$(8) * 2

Returns Oct: VariantOct$: String

■ If <numeric exprs> evaluates to Null, Oct[$] returns a Null.

■ If <numeric exprs> is an Integer, Variant of type 2 (Integer), Variant of type 0 (Empty) or any other numeric or Variant data type, Oct[$] returns up to 11 octal characters.

Page 300: Actuate Basic Reference

276 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

O n E r r o r s t a t e m e n t

Tips ■ To represent an octal number directly, precede a number in the correct range with &O. An octal number’s correct range is from 0 to O7777777777. For example, you can use &O010 * 2 to return decimal value 16, because &O010 is octal notation for 8.

■ To generate the full octal representation of <numeric exprs>, supply the radical prefix &O, because Oct[$] does not return that component.

Example The following example prompts the user for a decimal number, then uses Oct[$] to convert that number to octal notation:

Function OnLButtonDblClk ( )Dim Msg, NumNum = InputBox("Please enter a number to convert.")' Get user inputMsg = Num & " in decimal notation is &O"Msg = Msg & Oct(Num) & " in octal notation."MsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Hex, Hex$ functionsVal function

On Error statementTells the program what to do if an error occurs at run time.

Syntax On Error { GoTo <line | line label> | Resume Next | GoTo 0 }

Parameters GoToClause that enables the error-handling routine that starts at <line >, or, more commonly, <line label>. Enabling the routine means that if a run-time error occurs, program control branches to <line>. The error-handler at <line> remains active until a Resume, Exit Sub, or Exit Function is executed.

<line> or <line label>The line number or line label to which the program branches when a run-time error occurs.

Rule for <line>: Must be in the same procedure as On Error.

Example:The following statement tells Actuate Basic to branch to the label ErrorTrap when an error occurs:

On Error GoTo ErrorTrap

Page 301: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 277

O n E r r o r s t a t e m e n t

Resume NextClause specifying that when a run-time error occurs, control passes to the statement immediately following that in which the error occurred. That is, directs Actuate Basic to continue executing code even though an error has occurred.

GoTo 0Clause that disables any enabled error handler in the current procedure.

Rule for <GoTo 0>: Cannot be used to specify line number 0 as the start of the error-handling code.

Description ■ Unless you use On Error, any run-time error that occurs is fatal. Actuate Basic generates an error message and stops executing the program.

■ If another error occurs while an error handler is active, Actuate Basic passes control back through any previous calling procedure or procedures until it finds an inactive error handler, which it then activates. If it cannot find such an inactive error handler, the error is fatal.

■ Each time control passes back to a calling procedure, that procedure becomes the current one. Once an error handler in any procedure succeeds in handling an error, program execution resumes in the current procedure at the point designated by its own error handler’s Resume statement—which may not be the error handler or the Resume you perhaps intended to execute a few levels down the calling hierarchy.

■ An error-handler is automatically disabled when you exit its procedure.

Rules ■ The error handler indicated by <line> or <line label> cannot be a sub or function procedure. It must be a block of code marked by a line label or line number.

■ To prevent error-handling code from becoming part of the normal program flow even when there is no error—that is, from inadvertently executing when it should not—place an Exit Sub or Exit Function immediately before the label of the error handler.

Tips ■ An error-handling routine should be exited only by using some form of Resume.

■ You can use Err to obtain the error number of a run-time error.

■ Your error-handling routine should test or save the value of Err before any other error can occur, or before it calls any procedure that could cause an error.

■ You can use Error[$] function to return the error message associated with any given run-time error returned by Err.

Page 302: Actuate Basic Reference

278 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

O p e n s t a t e m e n t

Example The following example generates an error, then it displays the error’s number and description:

Function OnLButtonDblClk ( )Dim Drive As String, Msg As StringOn Error GoTo ErrorHandler7 ' Set up error handler

Open Drive & ":\Test\X.dat" For Input As #1 ' Attempt to open fileClose #1' Exit before entering the error handlerExit Function

ErrorHandler7: ' Error handler line labelMsg = "Error " & Err & " occurred, which is: " & Error$(Err)MsgBox MsgResume Next ' Resume procedure

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Erl functionErr functionError, Error$ functionsResume statement

Open statementEnables reading and writing—input and output (I/O)—to a file.

Syntax Open <file name> [For <mode>[encoding_name]] [Access <permissions>] [<lock>] As [#]<file number> [Len = <record or buffer size>] <file name>

Parameters <file name>String expression, enclosed in double quotes, that is the name of the target file. If the file does not exist when it is opened for Append, Binary, Output, or Random modes, it is created and then opened.

Example:

Open "C:\Windows\Mynotes.file" As #1

For <mode>Clause that specifies the file mode. Indicates whether and how to read from or write to the file. <mode> might be Append, Binary, Input, Output, or Random.

Example:

Open "C:\Windows\Mynotes.fil" For Input As #1

Page 303: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 279

O p e n s t a t e m e n t

<encoding_name>String expression that specifies the encoding value.

Rules:

■ If <encoding_name> is not specified or is an invalid value, Open uses the value of the current run time encoding.

■ If <encoding_name> is "text", Open assumes the file uses the same code page as the current system.

Access <permissions>Clause that specifies what operations this process is permitted to perform on <file name>. Another process can be more or less restricted than this one is. The <permissions> keyword can consist of any one of the following: Read, Write, or Read Write.

Rules:

■ If another process already opened the file and made <permissions> unavailable to others, the Open operation fails and a Permission denied error occurs.

■ Windows 3.1 users: To enable locking operations and use this clause, you must first run Share.exe before running your Actuate Basic program.

Example:

Open "C:\Windows\Mynotes.fil" For Input Access Read As #1

<lock> Keyword or set of keywords that specifies what operations other processes are permitted to perform on <file name>. In a multiuser environment or multiprocessing environment, <lock> restricts access by other processes or users. The <lock> keyword can consist of any one of the following: Shared, Lock Read, Lock Write, or Lock Read Write.

Example:

Open "C:\Windows\Mynotes.fil" For Binary As #1 Shared

As <file number>Clause that assigns a number to the open file.

<file number>Integer that specifies the number that is associated with the file as long as it remains open. Other I/O statements can then use <file number> to refer to the file.

Rule: Must be between 1 and 255, inclusive.

Len = <record or buffer size>Clause specifying how much information to take from the file into the buffer.

Page 304: Actuate Basic Reference

280 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

O p e n s t a t e m e n t

The following table summarizes the behavior of the Len = <record or buffer size> clause, which depends on the setting of <mode>:

<record or buffer size>Integer expression that indicates either the record length or buffer size depending on <mode>.

Rules:

■ <record or buffer size> must be positive.

■ <record or buffer size> must be less than or equal to 32,767 bytes.

Example:

Open "C:\Windows\Mynotes.fil" For Input As #1 Len = 512

Default mode: Random.

Options for<mode>

RandomKeyword that specifies random-access file mode. Instructs Actuate Basic to make three attempts to open the file with these permissions, in the following order:

■ Read and write

■ Write-only

■ Read-only

BinaryKeyword that specifies binary file mode so you can read and write information to any byte position in the file. If you do not supply an Access clause, instructs Actuate Basic to make three attempts to open the file, following the same order as for Random files.

Rule: If <file name> does not exist, it is created, then opened.

Tip: Use Get and Put to write to any byte position in a Binary file.

InputKeyword that specifies sequential input mode.

Rule: <file name> must exist.

Mode Len = <record or buffer size>

Random Specifies the record length, the number of bytes in a record. Default for <record or buffer size> in bytes is 128.

InputOutputAppend

Specifies the number of bytes to be placed in the buffer. Default for <record or buffer size> in bytes is 512.

Binary Ignored.

Page 305: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 281

O p e n s t a t e m e n t

OutputKeyword that specifies sequential output mode.

Rule: If <file name> does not exist, it is created, then opened.

AppendKeyword that specifies sequential output mode, and sets the file pointer to the end of the file. If <file name> does not exist it is created, then opened.

Tip: Use Print # or Write# to append to the file.

Example:

Open "C:\Windows\Mynotes.fil" For APPEND As #1

Options forAccess

ReadKeyword instructing Actuate Basic to open the file for a reading process only.

WriteKeyword that instructs Actuate Basic to open the file for a writing process only.

Read WriteKeyword that instructs Actuate Basic to open the file for both reading and writing processes.

Rule: Valid only if <mode> is Random, Binary, or Append.

Options for<lock>

SharedKeyword indicating that any process on any machine has permission to read from or write to <file name> while this Open is in effect.

Lock ReadKeyword indicating that no other process has permission to read <file name> while this Open is in effect.

Rule for Lock Read: Applied only if no other process has a previous read access to the file.

Lock WriteKeyword indicating that no other process has permission to write to <file name> while this Open is in effect.

Rule: Applied effect only if no other process has a previous write access to the file.

Lock Read WriteKeyword indicating that no other process has permission to read from or write to <file name> while this Open is in effect.

Page 306: Actuate Basic Reference

282 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

O p e n s t a t e m e n t

Lock Read Write can only occur if:

■ No other process has already been granted read or write access.

■ A Lock Read or Lock Write is not already in effect.

Default for <lock>: Lock Read Write.

Description You must open a file before any I/O operation can be performed on it. Open allocates a buffer to the file for I/O, and determines the mode of access used with the buffer.

In Actuate Basic there are three types of file access, Random, Sequential and Binary. The type you use in Open causes Actuate Basic to assume that <file name> has certain characteristics. These assumptions are summarized in the following table.

Rules ■ In Binary, Input, and Random modes, you do not need to first close an open file before opening it with a different <file number>.

■ In Append and Output modes, you must first close an open file before opening it with a different <file number>.

Tips ■ Use Random access files when you want easy access to individual records. Do not use them when you want to conserve storage space.

■ Use Sequential access files when you want to process files consisting only of text. Do not use them for other types of information.

■ Use Binary access files when you want to save storage space by varying your record lengths, sizing them only as needed to fit the data they contain. Do not use them if you do not want to keep track of the differently sized records.

Example The following example opens six files for sequential output and puts some test data into them:

Function OnLButtonDblClk ( )Dim FileName As String, FileNum As Integer, I As IntegerDim UserMsg As String, SampleTxt As String

Access Mode Actuate Basic assumes <file name>

Random Random Consists of a series of records of identical length, and all of the same data type.

Sequential InputOutputAppend

Is a text file, or consists of a series of text characters and/or of text formatting characters such as newline.

Binary Binary Can consist of data of any type, with records of any length, or even of variable lengths.

Page 307: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 283

O p e n s t a t e m e n t

SampleTxt = "Here is some sample text." ' Create test string

For I = 1 To 6FileNum = FreeFile ' Determine file numberFileName = "TEST" & FileNum & ".DAT"' Open for sequential outputOpen FileName For Output As #FileNumPrint #FileNum, SampleTxt ' Write test data to file

Next I

Close ' Close all open filesUserMsg = "Six test files have been created on your disk. "UserMsg = UserMsg & "Choose OK to delete them."MsgBox UserMsgKill "TEST?.DAT" ' Delete the test files

End Function

The following example opens eight files specifying the encoding for each file:

Function Start( ) As BooleanStart = Super::Start( )

Open "Korean.txt" For Input "AC_WINDOWS_949" As #1Open "KoreanOut.txt" For Output "AC_WINDOWS_949" As #2

Open "Japanese.txt" For Input "AC_WINDOWS_932" As #3Open "JapaneseOut.txt" For Output "AC_WINDOWS_932" As #4

Open "Chinese.txt" For Input "AC_WINDOWS_936" As #5Open "ChineseOut.txt" For Output "AC_WINDOWS_936" As #6

Open "Unicode.txt" For Input "AC_UCS_2" As #7Open "UnicodeOut.txt" For Output "AC_UCS_2" As #8

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Close statementFreeFile functionGet statementPrint # statementPut statementWrite # statement

Page 308: Actuate Basic Reference

284 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

O p t i o n B a s e s t a t e m e n t

Option Base statementDeclares the default lower bound for array subscripts.

Syntax Option Base {0 | 1}

Parameters 0Specifies that the lowest subscript for arrays in the current module is 0.

1Specifies that the lowest subscript for arrays in the current module is 1.

Default: 0.

Rule: Must be 0 or 1.

Example:The following statement declares that the lowest subscript for any arrays you create is 1:

Option Base 1

Description ■ Affects only arrays in the same module.

■ Has no effect on arrays within user-defined types. The lower bound for all such arrays is always 0.

Rules ■ Can appear only once in a module.

■ Can occur only in the Declare... End Declare section.

■ Must be used before you declare the dimensions of any array.

Tips ■ The To clause in Dim, ReDim, and Static provides a more flexible way to control the range of an array’s subscripts.

■ If you do not explicitly set the lower bound with a To clause, you can use Option Base to change the default lower bound to 1.

Example The code in the following example uses Option Base to override the default base array subscript value of 0. The first portion of the example should be pasted at or near the beginning of your Actuate Basic source code (.bas) file:

DeclareOption Base 1 ' Module level statement

End Declare'Function OnLButtonDblClk ( )

Dim MyArray1(), Msg, NLNL = Chr(10) ' Define newlineReDim MyArray1(25) ' Create an arrayMsg = "The lower bound of MyArray1 array is " & LBound(MyArray1) & "."

Page 309: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 285

O p t i o n C o m p a r e s t a t e m e n t

Msg = Msg & NL & "The upper bound is " & UBound(MyArray1) & "."MsgBox Msg

End Function

After you compile and run this example once, delete the Option Basic statement lines from your Actuate Basic source code (.bas) file and compile and test the example again. The lower bound reverts to zero, the default.

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Dim statementLBound functionReDim statementStatic statement

Option Compare statementDeclares default comparison mode used when comparing string data.

Syntax Option Compare { Binary | Text }

Parameters BinaryString comparisons in the module are case-sensitive by default. For example, if you use Option Compare Binary, then by default McManus does not match MCMANUS or mcmanus.

TextString comparisons in the module are not case-sensitive by default. If you use Option Compare Text, then by default McManus matches MCMANUS or mcmanus.

Rules ■ Use Option Compare within a Declare... End Declare section.

■ If used, Option Compare must appear before any statements that declare variables or define constants.

Example The following example shows the difference between using Option Compare Text and Option Compare Binary. To use this example, paste the first portion at or near the beginning of your Actuate Basic source code (.bas) file, and paste the subroutine into the OnLButtonDblClk() method of a clickable control:

DeclareOption Compare Text

End Declare'Function OnLButtonDblClk ( )

Page 310: Actuate Basic Reference

286 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

O p t i o n C o m p a r e s t a t e m e n t

Dim NameStr As String, UName As String, LName As StringDim Msg As String

NameStr = InputBox ("Enter customer name.")UName = UCase(NameStr)LName = LCase(NameStr)If UName Like LName Then

Msg = UName & " matches " & LNameElse

Msg = UName & " does NOT match " & LNameEnd IfMsgBox Msg

End Function

When you compile your report and try the example, note that the uppercase and lowercase version of the customer’s name match. Now delete the Options Compare Text statement from your Actuate Basic source code and compile the example again. This time, the uppercase and lowercase versions of the customer’s name will not match because without any Option Compare statement, Option Compare Binary is in effect by default.

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also InStr functionStrComp function

Page 311: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 287

P a r s e D a t e f u n c t i o n

ParseDate functionControls how dates are converted. Use when your program must be locale-independent, or when the format of date strings in your database differs from the format of the current locale. You can also specify the locale to use for date conversion.

Syntax ParseDate(<strDateSource>, <strFormatSpec>)

ParseDate(<strDateSource>, <strFormatSpec>, <locale>)

Parameters <strDateSource>String expression. The date string to convert from. The source date string.

Rule: Must be, or evaluate to, a valid date string.

Examples:

"2/1/2010""1 Feb, 2010""February 1, 2010"Format$((DateSerial(2010, 2, 1)), "mm/dd/yyyy")

<strFormatSpec>String expression. The date string to convert from. The format in which the date string currently appears.

Rules:

■ <strFormatSpec> must be, or evaluate to, a valid format string.

■ You can use the format characters described in the following table to convert date expressions.

Format character Description

? Indicates an optional field.

d Specifies that the next field is a day. Must appear only once in a date expression. If you use the d format character, you must also use the m and y format characters.

l Specifies that the date format specified in the current locale should be used. If this character is used, it must be the only format specified.

Page 312: Actuate Basic Reference

288 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

P a r s e D a t e f u n c t i o n

Examples:To convert a date string from the French date format, use the following format string for <strFormatSpec>:

"dmy"

To convert a date from the U.S. date format, use the following format string for <strFormatSpec>:

"mdy"

To convert a date from the ISO date format, use the following format string for <strFormatSpec>:

"ymd"

The following table shows return values when converting date expressions containing a day of week and the format character w.

m Specifies that the next field is a month. Must appear only once in a date expression. If you use the m format character, you must also use the y and d format characters.

p The base year for the pivot.

t Specifies that the next field is the time. Must appear only once in a date expression.

w Specifies that the next field is a (noise) word, such as the name of the day of the week.

y Specifies that the next field is a year. Must appear only once in a date expression. If you use the y format character, you must also use the m and d format characters.

Format character Date expression Return value

w?mdy Friday, September 28, 2001

2001-9-28

w?mdy September 28, 2001 2001-9-28

wmdy Friday, September 28, 2001

2001-9-28

wmdy September 28, 2001 Null

Format character Description

Page 313: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 289

P a r s e D a t e f u n c t i o n

For more information about formatting data, see Format() function.

Rule: Range of valid dates is January 1, 100 through December 31, 9999, inclusive.

<locale>String expression specifying the locale to use for date conversion. Must be in the <language>_<location> format, for example fr_FR for French locale.

Rule: If <locale> is Null or invalid, ParseDate uses the current run time locale.

Returns Date

■ If the date string is invalid, ParseDate returns a Null.

Description Actuate Basic implicitly converts strings to dates and dates to strings. This conversion is patterned after Visual Basic. If you want your applications to be Y2K-compliant, to run in multiple locales, or to work with string date data imported from another application, be aware of the limitations of the implicit date conversions.

Implicit string-to-date conversions occur when you:

■ Pass a string to a function that takes a date argument

■ Assign a string to a date variable

■ Use the CDate or CVDate functions

In all these cases, Actuate converts dates using the date format of the current locale or the locale specified by the <locale> parameter and Actuate's default pivot year of 30. Actuate converts a date of 2/1/99 to a date of February 1, 1999 in the U.S., and to January 2, 1999 in the UK.

Implicit date-to-string conversion occurs when you:

■ Pass a date to a function that takes a string argument

■ Assign a date to a string

■ Use the CStr() function

■ Output the date using the Print statement

In all cases, Actuate performs implicit date-to-string conversion using the date format of the current locale or the locale specified by the <locale> parameter and Actuate’s default pivot year of 30. If you assign the date February 1, 1999 to a string in the U.S., the result will be 2/1/1999. In the UK, however, the string will be 1/2/1999.

wmdy on September 28, 2001 2001-9-28

mdy September 28, 2001 2001-9-28

Format character Date expression Return value

Page 314: Actuate Basic Reference

290 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

P a r s e D a t e f u n c t i o n

Like Visual Basic, Actuate Basic attempts to parse a date using a number of different formats in order, until one works or until there is nothing else to try. This means that a date that is invalid for the given locale might still be parsed using a different format. For example, in the U.S. locale, a date of 13/1/99 converts to January 1, 1999 using the European format.

The format rules, in order of use, are:

■ Current locale

■ U.S. format (m/d/y)

■ European format (d/m/y)

■ ISO format (y/m/d)

When you write data streams, ParseDate() allows you to precisely control how dates are converted. Hence, if Basic’s default rules do not work, you can use ParseDate() to perform the conversion correctly.

Tips ■ Use ParseDate() to convert type String date input to type DateTime as early in the program run as possible.

■ Convert dates to strings as late as possible before you display or output the dates to a file. To manage this conversion, use the Format() function.

■ Always explicitly declare your date variables to be of type DateTime, do not rely on using Variants.

■ To accurately convert dates of type Date or type DateTime to strings, use the Format() function.

■ To accurately convert dates of type String to dates of type DateTime, use the ParseDate() function.

■ To convert date expressions containing a day of week and/or a word, use ParseDate() with the format character 'w'. You can also use the optional field indicator format character '?'.

Example The following example prompts the user for a date in French format and returns that date in U.S. format:

Function OnLButtonDblClk ( )Dim dtSafeDate As DateDim strFr_Date As String, strUS_Date As String, strMsg As String

strFr_Date = InputBox("Please type a date in French format.")dtSafeDate = ParseDate(strFr_Date, "dmy")

strMsg = "In US format, that date is shown as: "strMsg = strMsg & CStr(dtSafeDate)MsgBox strMsg

End Function

Page 315: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 291

P a r s e N u m e r i c f u n c t i o n

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also CVDate functionFormat functionVarType function

ParseNumeric functionParses the numeric expression using the specified radix and thousand separator characters.

Syntax ParseNumeric(<numeric expression>, <radix character>, <thousand separator>)

ParseNumeric(<numeric expression>, <radix character>, <thousand separator>, <currency symbol>)

Parameters <numeric expression>Numeric expression of type String to be converted to a Double data type.

<radix character>String expression that specifies the radix character used in the numeric expression.

Rule: If <radix character> is Null or an empty string, ParseNumeric uses the currency symbol of the current run time locale.

<thousand separator>String expression that specifies the thousand separator character used in the numeric expression.

Rules:

■ If <thousand separator> contains more that one character, ParseNumeric uses only the first character.

■ If <thousand separator> is Null or an empty string, ParseNumeric uses the thousands separator character of the current run time locale.

<currency symbol>String expression that specifies the currency symbol used in the numeric expression.

Rules:

■ If <currency symbol> contains more that one character, ParseNumeric uses only the first character.

Page 316: Actuate Basic Reference

292 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

P m t f u n c t i o n

■ If <currency symbol> is Null or an empty string, ParseNumeric uses the currency symbol of the current run time locale.

Returns Variant

■ If <numeric expression> is Null, ParseNumeric returns a Null.

■ If the expression is not valid or cannot be parsed using the specified decimal or thousand separator character, ParseNumeric returns a Null.

Example Each of the following statements returns 123456.78:

ParseNumeric(“123,456.78”, ”.”, ”,”, NULL)ParseNumeric(“123.456,78”, ”,”, ”.”, NULL)ParseNumeric(“123!456*78”, ”*”, ”!”, NULL)

The following statement returns 1500.00:

ParseNumeric(“$1,500.00”, ”.”, ”,”, “$”)

Pmt functionReturns the payment for an annuity, based on periodic, constant payments, and on an unvarying interest rate.

Syntax Pmt(<rate per period>, <number pay periods>, <present value>, <future value>, <when due>)

Parameters <rate per period>Numeric expression that specifies the interest rate that accrues per period.

Rule for <rate per period>: Must be given in the same units of measure as <number pay periods>. For instance, if <number pay periods> is expressed in months, then <rate per period> must be expressed as a monthly rate.

<number pay periods>Numeric expression that specifies the total number of payment periods in the annuity.

Rule for <number pay periods>: Must be given in the same units of measure as <rate per period>. For instance, if <rate per period> is expressed as a monthly rate, then <number pay periods> must be expressed in months.

<present value>Numeric expression that specifies the value in today’s dollars of a future payment, or stream of payments.

Page 317: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 293

P m t f u n c t i o n

Example: If you put $23.94 in the bank today and leave it there for 15 years at an interest rate of 10% compounded annually, you end up with about $100. In this case, the present value of $100 is approximately $23.94.

<future value>Numeric expression that specifies the cash balance you want after you have made your final payment.

Examples:

■ You set up a savings plan with a goal of having $75,000 in 18 years to pay for your child’s education. For this plan, the future value is $75,000.

■ You take out a loan for $11,000. The future value is $0.00, as it is for any typical loan.

<when due>Numeric expression that specifies whether each payment is made at the beginning (1), or at the end (0) of each period.

Default: The end of the period (0).

Rule for <when due>: Must be 0 or 1.

Example:The following example assumes you are making monthly payments the first of each month on a loan of $20,000, over 36 months, at an APR of 11.5%. How much will each of your payments be? The answer ($653.26) is assigned to PaymentAmt.

PaymentAmt = Pmt(.115/12, 36, -20000, 0, 1)

Returns Double

An annuity is a series of cash payments, constant in value, made over a period of time. An annuity can be an investment, such as a monthly savings plan, or a loan, such as a home mortgage.

Rules ■ <rate per period> and <number pay periods> must be expressed in terms of the same units (weekly/weeks, monthly/months, yearly/years).

■ You must express cash paid out (such as deposits to savings) using negative numbers, and cash received (such as dividend checks) using positive numbers.

Example The following example prompts the user to supply various particulars about a loan. It then returns the amount of the payments.

To use this example, paste the first portion at or near the beginning of your Actuate Basic source code (.bas) file.

Page 318: Actuate Basic Reference

294 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

P P m t f u n c t i o n

DeclareGlobal Const ENDPERIOD = 0Global Const BEGINPERIOD = 1 ' When payments are made

End DeclareFunction OnLButtonDblClk ( )

Dim Fmt As String, FutureVal As Double, PresVal As DoubleDim APR As Double, TotPmts As Integer, PayWhen As IntegerDim Period As Integer, InterestPmt As Double, PrincipPmt As DoubleDim Payment As Double, Msg As StringFmt = "$###,###,##0.00" ' Specify money formatFutureVal = 0 ' Normally 0 for a loanPresVal = InputBox("How much do you want to borrow?")APR = InputBox("What is the annual percentage rate (APR) for your loan?")If APR > 1 Then ' Ensure proper form as %

APR = APR / 100End IfTotPmts = InputBox("How many monthly payments will you make?")PayWhen = MsgBox("Payments at the end of month?", MB_YESNO)If PayWhen = IDNO Then

PayWhen = BEGINPERIODElse

PayWhen = ENDPERIODEnd If

Payment = Pmt(APR / 12, TotPmts, -PresVal, FutureVal, PayWhen)Msg = "Your payments are " & Format(Payment, Fmt) & "."MsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also FV functionIPmt functionNPer functionPPmt functionPV functionRate function

PPmt functionReturns the principal payment for a given period of an annuity, based on periodic, constant payments, and on an unvarying interest rate.

Syntax PPmt(<rate per period>,<single period>, <number pay periods>, <present value>, <future value>, <when due>)

Page 319: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 295

P P m t f u n c t i o n

Parameters <rate per period>Numeric expression that specifies the interest rate that accrues per period.

Rule for <rate per period>: Must be given in the same units of measure as <number pay periods>. For instance, if <number pay periods> is expressed in months, then <rate per period> must be expressed as a monthly rate.

<single period>Numeric expression that specifies the particular period for which you want to determine how much of the payment for that period represents interest.

Rule for <single period>: Must be in the range 1 through <number pay periods>.

<number pay periods>Numeric expression that specifies the total number of payment periods in the annuity.

Rule for <number pay periods>: Must be given in the same units of measure as <rate per period>. For instance, if <rate per period> is expressed as a monthly rate, then <number pay periods> must be expressed in months.

<present value>Numeric expression that specifies the value today of a future payment, or stream of payments.

Example:If you put $23.94 in the bank today and leave it there for 15 years at an interest rate of 10% compounded annually, you end up with about $100. In this case, the present value of $100 is approximately $23.94.

<future value>Numeric expression that specifies the cash balance you want after you have made your final payment.

Examples:

■ You set up a savings plan with a goal of having $75,000 in 18 years to pay for your child’s education. For this plan, the future value is $75,000.

■ You take out a loan for $11,000. The future value is $0.00, as it is for any typical loan.

<when due>Numeric expression that specifies whether each payment is made at the beginning (1), or at the end (0) of each period.

Default: 0.

Rule for <when due>: Must be 0 or 1.

Page 320: Actuate Basic Reference

296 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

P P m t f u n c t i o n

Example:The following example assumes you are making monthly payments at the first of each month on a loan of $20,000, over 36 months, at an APR of 11.5%. How much of your 5th payment represents principal? The answer ($481.43) is assigned to Principal5:

Principal5 = PPmt(.115/12, 5, 36, -20000, 0, 1)

Returns Double

An annuity is a series of cash payments, constant in value, made over a period of time. An annuity can be an investment, such as a monthly savings plan, or a loan, such as a home mortgage.

Each payment in an annuity consists of two components: principal and interest. PPmt returns the principal component of the payment.

Rules ■ <rate per period> and <number pay periods> must be expressed in terms of the same units such as weeks, months or years.

■ You must express cash paid out (such as deposits to savings) using negative numbers, and cash received (such as dividend checks) using positive numbers.

Example The following example prompts the user to supply various particulars about a loan. It then returns, for a single payment period the user specifies, the portion of that payment that represents principal, and the portion that represents interest.

To use this example, paste the first portion at or near the beginning of your Actuate Basic source code (.bas) file:

DeclareGlobal Const ENDPERIOD = 0Global Const BEGINPERIOD = 1 ' When payments are made

End Declare'Function OnLButtonDblClk ( )

Dim Fmt As String, FutureVal As Double, PresVal As DoubleDim APR As Double, TotPmts As Integer, PayWhen As IntegerDim Period As Integer, IntPmt As Double, PrinPmt As DoubleDim Payment As Double, Msg As String'Fmt = "$###,###,##0.00" ' Specify money formatFutureVal = 0 ' Normally 0 for a loanPresVal = InputBox("How much do you want to borrow?")APR = InputBox("What is the annual percentage rate (APR) for your loan?")If APR > 1 Then ' Ensure proper form as %

APR = APR / 100End If

Page 321: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 297

P r i n t # s t a t e m e n t

TotPmts = InputBox("How many monthly payments will you make?")PayWhen = MsgBox("Payments at month end?", MB_YESNO)If PayWhen = IDNO Then

PayWhen = BEGINPERIODElse

PayWhen = ENDPERIODEnd If

Msg = "Which payment period are you interested in? "Msg = Msg & "Please type a number from 1 to " & TotPmts

Period = InputBox(Msg)IntPmt = IPmt(APR / 12, Period, TotPmts, -PresVal, FutureVal, PayWhen)PrinPmt = PPmt(APR / 12, Period, TotPmts, -PresVal, FutureVal, PayWhen)Payment = Pmt(APR / 12, TotPmts, -PresVal, FutureVal, PayWhen)Msg = "At period " & Period & " you will pay a total "Msg = Msg & " of " & Format(Payment, Fmt) & ", representing "Msg = Msg & Format(PrinPmt, Fmt) & " principal and "Msg = Msg & Format(IntPmt, Fmt) & " interest. "MsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also FV functionIPmt functionNPer functionPmt functionPV functionRate function

Print # statementWrites unformatted data to a sequential file.

Syntax Print #<file number>, [ [{ Spc(<number of blanks>) | Tab(<tab column>) } ] [ <expression list> ] [ { ; | , } ]... ]

Parameters <file number>Numeric expression that is the file number used to Open a sequential file to which Print # writes data.

Page 322: Actuate Basic Reference

298 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

P r i n t # s t a t e m e n t

Example:The following example writes Hello, world! to the file opened under file number 1, and appends a carriage-return-linefeed character-pair (CRLF) to the file, so that whatever is next written to the file appears on the next line:

Print #1, "Hello, world!"

The following example shows three statements that work together, although they can be separated from one another by any number of lines of code. The first statement opens a file called Mynotes.fil, the second one writes to that file, and the third, by closing it, turns the file over to the operating system to complete the process of writing it to the disk:

Open "C:\Myfiles\Mynotes.fil" For Output As #2Print #2, "This datum.", "This datum, too. "Close #2

Spc(<number of blanks>)Clause that inserts spaces into the output. May be repeated; separated by commas or semicolons.

<number of blanks>Numeric expression that specifies the number of spaces Spc inserts.

Example:

Print #2, "This datum.", Spc(10), "This datum, too.", Spc(5), "And this."

Tab(<tab column>)Clause that tabs to the specified column before the program prints <expression list>. May be repeated; separated by commas or semicolons.

<tab column>Numeric expression that specifies the column to which the program jumps before it prints the <expression list>.

Example:

Print #2, "This datum."; Tab(5); "This datum, too."; Tab(7); "And this."

<expression list>Numeric or string expressions that specify the data that Print # writes to the file. There can be any number of these.

Default: Blank line, if comma is used.

; (semicolon)Character (semicolon) that determines the position of the next character printed. Instructs Actuate Basic to print the next character immediately after the last one.

Page 323: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 299

P r i n t # s t a t e m e n t

, (comma)Character (comma) that determines the position of the next character printed. Instructs Actuate Basic to print the next character at the start of the next print zone. Print zones begin every 14 columns.

Default position for next character: Next line.

Example:The following example writes the number 250, and the content of P$ to the file. The comma after the number 250 causes P$ to be written at the next print zone. The semicolon after P$ causes Actuate Basic to suppress the printing of the carriage-return-linefeed character-pair, so that whatever is next written to the file occurs immediately after the text in P$:

Print #1, 250, P$;

Description Print # usually writes Variant data to a file the same way it writes any other Actuate Basic data type. However, there are some exceptions.

Rules ■ <file number> must match the number of a currently open file.

■ The file corresponding to <file number> must be open under either the Output or Append mode.

■ You must have write access to the open file. That is, the file must not have been opened using a Lock Write or Lock Read Write clause.

■ The data cannot be an object variable, user-defined data type structure, handle to a class, CPointer, or OLE object.

Tips ■ To ensure integrity of separate data fields, use Write # instead of Print #. Write # delimits data properly and ensures that the data can be read correctly in any locale.

■ Use Print # with ASCII text files.

■ Spacing of data displayed on a text screen with monospaced characters may not work well when the data is redisplayed in a graphical environment using proportionally spaced characters.

Data type Print # writes this to the file

Variant of VarType 0 (Empty) Nothing at all

Variant of VarType 1 (Null) The literal value Null

Variant of VarType 7 (Date) The date, using whatever Short Date format is defined in the Control Panel

Variant of VarType 7 (Date), but with either the date or time component missing or zero

Only the part of the date provided

Page 324: Actuate Basic Reference

300 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

P u t s t a t e m e n t

Example The following example creates a file called Testifle.txt, writes some data in it, then closes it. It then reopens the file to read the data just written. Finally, after displaying a message, it closes the file and deletes it:

Function OnLButtonDblClk ( )Dim TestData As String, UserMsg As String, NL As StringNL = Chr$(10) ' Define newline

Open "Testifle.txt" For Output As #1 ' Open to write filePrint #1, "Test of the Print # statement."Print #1, ' Print extra blank line to filePrint #1, "Zone 1", "Zone 2" ' Print in two print zonesPrint #1, "With no space between"; "these" ' Print two strings togetherClose #1Open "Testifle.txt" For Input As #1 ' Open to read fileDo While Not EOF(1) ' Read entire file

Line Input #1, TestData ' Read a lineUserMsg = UserMsg & TestData & NL ' Construct message

LoopClose #1MsgBox UserMsgKill "Testifle.txt" ' Delete file from disk

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Open statementWrite # statement

Put statementWrites data from a variable to a disk file.

Syntax Put [#] <open file number>, [<record number>], <variable to write>

Parameters <open file number>Numeric expression that specifies the number you used in the previously issued Open that opened the file to which you now want to write using Put.

<record number>Numeric expression:

■ For files opened in Random mode, <record number> is the number of the record to be written.

Page 325: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 301

P u t s t a t e m e n t

■ For files opened in Binary mode, it is the byte position at which writing starts, where the first byte in a file is at position 1, the second byte at position 2, and so on.

Default: The next record or byte—that is, the one following the last Get or Put statement, or the one pointed to by the last Seek2 function.

Rules for <record number>:

■ If you omit <record number> you must still include the delimiting commas that would have been on either side of it had you included it. For example:

Put #1, , HoldingVar1

■ Must be between 1 and 2,147,483,647.

<variable to write>String expression that specifies the variable to write to the open file.

Rules for <variable to write>:

■ Cannot be an object variable, user-defined data type structure, handle to a class, CPointer, or OLE object.

■ Cannot be an array variable that refers to an entire array, although you can use one that describes a single element of an array.

Description For Files opened in Random mode:

■ If the length of the data you write is less than the length specified in the Len clause of the Open statement, Put still writes subsequent records on record-length boundaries. The space between the end of one record and the beginning of the next is padded with the existing contents of the file buffer.

Example:In the following example, the first Put writes the 4 bytes of the variable HoldingVar1 to the disk file Myfile.txt at byte positions 1-4. Any data that was there is overwritten. The second Put, however, does not pick up where the last one left off but instead skips to the record-length boundary (20) and starts counting from there, which means it writes the 5 bytes of HoldingVar2 to byte positions 21-25. The intervening bytes (5-20) remain what they were, but now represent padding between records:

Dim HoldingVar1 As String * 4Dim HoldingVar2 As String * 5Open "Myfile.txt" For Random As #1 Len = 20HoldingVar1 = "1234"HoldingVar2 = "12345"Put #1, , HoldingVar1Put #1, , HoldingVar2

Page 326: Actuate Basic Reference

302 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

P u t s t a t e m e n t

■ The following table summarizes how Put behaves depending on the data type of <variable to write>. Open refers to the particular statement that opened the file in question.

For Files opened in Binary mode:

All the Random descriptions and rules above apply except that the Len clause in Open has no effect. Put writes all variables to disk contiguously, that is, with no padding between records.

Example:In the following example, the first Put writes the 4 bytes of the variable HoldingVar1 to the disk file Myfile.txt at byte positions 1-4. The second Put writes the 5 bytes of HoldingVar2 to byte positions 5-10. No data shows between them as padding:

Dim HoldingVar1 As String * 4Dim HoldingVar2 As String * 5Open "Myfile.txt" For Binary As #1 Len = 20

<variable to write> Put writes, in order Rules

Variable-length string

1 2-byte descriptor containing string length

2 Data in the variable

Record length specified in the Len clause of Open must be at least 2 bytes greater than the actual length of the string.

Numeric Variant (Variant Types 0-7)

1 2-byte descriptor that identifies the type of the Variant

2 Data in the variable

Len clause length must be at least 2 bytes greater than the actual number of bytes required to store the variable.

String Variant(Variant Type 8)

1 2-byte Variant Type descriptor

2 2 bytes indicating the string length

3 Data in the variable

Len clause length must be at least 4 bytes greater than the actual length of the string.

Any other type of variable

1 Data in the variable

Len clause length must be greater than or equal to the length of the data.

Page 327: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 303

P u t s t a t e m e n t

HoldingVar1 = "1234"HoldingVar2 = "12345"Put #1, , HoldingVar1Put #1, , HoldingVar2

For variable-length strings, Put does not write a 2-byte descriptor; it writes the number of bytes equal to the number of characters already in the string.

Example:The following example writes 12 bytes to file number 1:

VariLen$ = String$(12, "*")Put #1, , VariLen$

Tip To avoid corrupting or misreading data, be sure your record lengths and/or variable lengths match the lengths of the data you want to read or write.

Example The following example prompts the user to type three customer names. It write each name in turn to a test file and then reads the names back:

Function OnLButtonDblClk ( )Dim CustName As StringDim Indx As Integer, Max As Integer, Msg As String, NL As StringNL = Chr$(10)CustName = String(20, " ")'Generate sample random-access file using PUT:Msg = "Please type a name." & NL & NLMsg = Msg & "When finished, press 'Enter' with no name."Open "testfil3.txt" For Random As #1 Len = Len(CustName)CustName = InputBox(Msg) ' Get user inputDo While CustName <> " " And CustName <> ""

Put #1, , CustName ' Write to fileCustName = InputBox(Msg) ' Get user input

Loop'Read the sample random-access file using GET:Max = Loc(1)If Max = 0 Then ' Check if records exist

Msg = "Sorry, your file contains no names." & NLElse

Msg = "Your file contains the following names:" & NL & NLEnd IfFor Indx = 1 To Max

Get #1, Indx, CustName ' Read from test fileMsg = Msg & CustName & NL

Next IndxClose #1 ' Close fileMsg = Msg & NL & "Please press OK to delete the test file."MsgBox MsgKill "testfil3.txt" ' Delete test file

End Function

Page 328: Actuate Basic Reference

304 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

P V f u n c t i o n

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Get statementOpen statementType...End Type statement

PV functionReturns the present value of an annuity based on periodic, constant payments to be paid in the future, and on an unvarying interest rate.

Syntax PV(<rate per period>,<number pay periods>,<each pmt>, <future value>, <when due>)

Parameters <rate per period>Numeric expression that specifies the interest rate that accrues per period.

Rule for <rate per period>: Must be given in the same units of measure as <number pay periods>. For instance, if <number pay periods> is expressed in months, then <rate per period> must be expressed as a monthly rate.

<number pay periods>Numeric expression that specifies the total number of payment periods in the annuity.

Rule for <number pay periods>: Must be given in the same units of measure as <rate per period>. For instance, if <rate per period> is expressed as a monthly rate, then <number pay periods> must be expressed in months.

<each pmt>Numeric expression that specifies the amount of each payment.

Rule for <each pmt>: Must be given in the same units of measure as <rate per period>. For instance, if <rate per period> is expressed in months, then <each pmt> must be expressed as a monthly payment.

<future value>Numeric expression. Specifies the cash balance you want after you have made your final payment.

Examples:

■ You set up a savings plan with a goal of having $75,000 in 18 years to pay for your child’s education. For this plan, the future value is $75,000.

■ You take out a loan for $11,000. The future value is $0.00, as it is for any typical loan.

Page 329: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 305

P V f u n c t i o n

<when due>Numeric expression that specifies whether each payment is made at the beginning (1), or at the end (0) of each period.

Default: 0.

Rule: Must be 0 or 1.

Examples:The following example assumes you are considering the purchase of a corporate bond with a $1000 face value. The bond pays an annual coupon of $100, matures in 15 years, and the next coupon is paid at the end of one year. The yield to maturity on similar bonds is 12.5%. What is a fair price for this bond (its present value)? The answer, $834.18, is assigned to the variable PresentValue:

PresentValue = PV(.125, 15, 100, 1000, 0)

The following examples assumes you have won the lottery. The jackpot is $10 million, which you receive in yearly installments of $500,000 per year for 20 years, beginning one year from today. If the interest rate is 9.5% compounded annually, how much is the lottery worth today? The answer, $4,406,191.06, is assigned to PresentValue:

PresentValue = PV(.095, 20, 50000,10000000, 0)

The following example assumes you want to save $11,000 over the course of 3 years. If the APR is 10.5% and you plan to save $325 monthly, and if you make your payments at the beginning of each month, how much would you need to start off with in your account to achieve your goal? The answer, $2,048.06, is assigned to StartValue. Note that <each pmt> is expressed as a negative number because it represents cash paid out:

StartValue = PV(.105/12, 3*12, -325, 11000, 1)

Returns Double

An annuity is a series of cash payments, constant in value, made over a period of time. An annuity can be an investment, such as a monthly savings plan, or a loan, such as a home mortgage. The present value is the value today of a future payment, or of a stream of payments structured as an annuity.

Example:If you put $23.94 in the bank today and leave it there for 15 years at an interest rate of 10% compounded annually, you end up with about $100. So, the present value of $100 is approximately $23.94.

Rules ■ <rate per period> and <number pay periods> must be expressed in terms of the same units (if weekly/then weeks, monthly/months, yearly/years, and so on).

Page 330: Actuate Basic Reference

306 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

P V f u n c t i o n

■ You must express cash paid out (such as deposits to savings) using negative numbers, and cash received (such as dividend checks) using positive numbers.

Example The following example prompts the user to supply the amount to save or invest each month, the annual percentage rate (APR) of the interest, the total number of payments, a target amount, and when during the month payments are made. Then it interprets the present value as the amount the user would have to start with in order to achieve the goal.

To use this example, copy the first portion at or near the beginning of your Actuate Basic source code (.bas) file:

DeclareGlobal Const ENDPERIOD = 0Global Const BEGINPERIOD = 1

End Declare'Function OnLButtonDblClk ( )

Dim EachPmt As Double, APR As Double, Fmt As String, Msg As StringDim TotalPmts As Single, PayWhen As IntegerDim PresentVal As Double, FutureVal As DoubleFmt = "$###,###,##0.00" ' Specify money formatEachPmt = InputBox("How much do you save each month?")APR = InputBox("What is the annual percentage rate for the interest?")If APR > 1 Then ' Ensure proper form as %

APR = APR / 100End IfTotalPmts = InputBox("For how many months are you saving?")PayWhen = MsgBox("Payments at month’s end?", MB_YESNO)If PayWhen = IDNO Then

PayWhen = BEGINPERIODElse

PayWhen = ENDPERIODEnd If

FutureVal = InputBox("What amount is your goal?")PresentVal = PV(APR / 12, TotalPmts, -EachPmt, FutureVal, PayWhen)Msg = "Starting with " & Format(-PresentVal, Fmt) & " "Msg = Msg & " and saving " & Format(EachPmt, Fmt) & " every month at "Msg = Msg & "an interest rate of " & Format(APR, "##.0%") & " for a period "Msg = Msg & "of " & TotalPmts & " months brings you to your goal of "Msg = Msg & Format(FutureVal, Fmt) & "."MsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

Page 331: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 307

Q B C o l o r f u n c t i o n

See also FV functionIPmt functionNPer functionPmt functionPPmt functionRate function

QBColor functionTranslates the numeric representations for colors from older BASIC languages such as Quick Basic to those used by Actuate Basic.

Syntax QBColor(<number to translate>)

Parameters <number to translate>Integer that specifies the number of a color, specifically one of the 16 standard Windows colors.

Rules:

■ Must be between 00 and 15, inclusive.

■ If <number to translate> evaluates to a Null, QBColor returns a Null.

Returns Long

The following table shows the 16 color codes QBColor accepts, their names, and their equivalents in Actuate Basic—that is, the values returned by QBColor.

Older BASIC Code Number Color Name

Actuate Code Number

00 Black 00

01 Blue 8388608

02 Green 32768

03 Cyan 8421376

04 Red 128

05 Magenta 8388736

06 Yellow 32896

07 White 12632256

08 Gray 8421504

09 Bright Blue 16711680

Page 332: Actuate Basic Reference

308 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

R a n d o m i z e s t a t e m e n t

Tips There are at least four ways to represent a color in Actuate Basic:

■ Specify the relative mix of red, green, and blue in a color by using RGB with decimal numbers.

■ Directly specify, without using RGB or any function, the relative mix using hexadecimal numbers in a certain format.

■ Use one of the 16 standard Windows colors by supplying the appropriate integer to QBColor.

■ Use one of the appropriate color name constants from Header.bas.

Example The following example displays a variety of color shades on a component:

Function OnLButtonDblClk( )Dim UserAns, MsgMsg = "The 16 standard Windows colors are specified by "Msg = Msg & "integers from 0 to 15. Please type an integer "Msg = Msg & "from 0 to 15 to see its equivalent in "Msg = Msg & "Actuate Basic."UserAns = InputBox(Msg)MsgBox "The Actuate Basic code for that color is: " & QBColor(UserAns)

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also RGB function

Randomize statementInitializes the random number generator so it can generate a new sequence of apparently random numbers.

Syntax Randomize [<seed number>]

10 Bright Green 65280

11 Bright Cyan 16776960

12 Bright Red 255

13 Bright Magenta 16711935

14 Bright Yellow 65535

15 Bright White 16777215

Older BASIC Code Number Color Name

Actuate Code Number

Page 333: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 309

R a n d o m i z e s t a t e m e n t

Parameters <seed number>Numeric expression that specifies the number that initializes the random number generator by supplying it with a new seed value.

Rule: Must be between -2,147,483,648 and 2,147,483,647.

Examples:

RandomizeRandomize 34

Description Actuate Basic supplies you with Randomize and Rnd as tools for generating random numbers.

Randomize generates a sequence of pseudo-random numbers by starting with a seed value. The randomizing function then takes that initial seed value and uses it to generate the first number in the pseudo-random sequence. Then it uses that number in turn to produce the second one, and so on. The result is a series of numbers that vary well enough to seem to have no pattern, or in other words, to be random.

Rules ■ If you do not use Randomize, Rnd returns the same sequence of numbers every time the program is run.

■ Use Randomize before Rnd, or it has no effect.

Tips ■ To generate numbers that seem truly random, use Randomize—with no argument—at the beginning of your program. In that case, Actuate Basic uses a randomizing seed based on the current running system time, which is almost certain to vary randomly whenever you run the program.

■ Although, you can use Randomize several times throughout a program, it works best if you use it only once, at the beginning.

■ To help you debug certain programs, use Randomize with a specific <seed number>. That way, the same random numbers repeat every time you run the program.

Example The following example simulates rolling a die twice by generating random values between 1 and 6 for each roll:

Function OnLButtonDblClk ( )Dim DieRoll1, DieRoll2, UserMsgRandomize ' Seed random num generatorDieRoll1 = Int(6 * Rnd + 1) ' First rollDieRoll2 = Int(6 * Rnd + 1) ' Second roll

UserMsg = "You rolled a " & DieRoll1UserMsg = UserMsg & " and a " & DieRoll2UserMsg = UserMsg & " giving a total of "UserMsg = UserMsg & (DieRoll1 + DieRoll2) & "."MsgBox UserMsg

End Function

Page 334: Actuate Basic Reference

310 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

R a t e f u n c t i o n

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Rnd function

Rate functionReturns the interest rate per period for an annuity.

Syntax Rate(<number pay periods>,<each pmt>, <present value>, <future value>, <when due>, <starting guess>)

Parameters <number pay periods>Numeric expression that specifies the total number of payment periods in the annuity.

Rule for <number pay periods>: Must be given in the same units of measure as <each pmt>. For instance, if <each pmt> is expressed as a monthly payment, then <number pay periods> must be expressed in months.

<each pmt>Numeric expression that specifies the amount of each payment.

Rule for <each pmt>: Must be given in the same units of measure as <number pay periods>. For instance, if <number pay periods> is expressed in months, then <each pmt> must be expressed as a monthly payment.

<present value>Numeric expression that specifies the value today of a future payment, or of a stream of payments.

Example:If you put $23.94 in the bank today and leave it there for 15 years at an interest rate of 10% compounded annually, you will end up with about $100. So in this case, the present value of $100 is approximately $23.94.

<future value>Numeric expression that specifies the cash balance you want after you have made your final payment.

Examples:

■ You set up a savings plan with a goal of having $75,000 in 18 years to pay for your child’s education. For this plan, the future value is $75,000.

■ You take out a loan for $11,000. The future value is $0.00, as it is for any typical loan.

Page 335: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 311

R a t e f u n c t i o n

<when due>Numeric expression that specifies whether each payment is made at the beginning (1), or at the end (0) of each period.

Default: 0.

Rule: Must be 0 or 1.

<starting guess>Numeric expression that specifies the value you estimate Rate will return. In most cases, this is 0.1 (10 percent).

Example:The following example assumes you have taken out a loan for $20,000, that you are paying off over the course of 3 years. If your payments are $653.26 per month, and you make them at the beginning of each month, what interest rate (APR) are you paying? The answer, .115 or 11.5%, is assigned to the variable InterestRate. Note that the return value of Rate must be multiplied by 12 to yield an annual rate:

InterestRate = Rate(3*12, -653.26, 20000, 0, 1, .1) * 12

Returns Double

An annuity is a series of cash payments, constant in value, made over a period of time. An annuity can be an investment, such as a monthly savings plan, or a loan, such as a home mortgage.

Rate calculates the interest rate on an annuity iteratively. Starting with the value of <starting guess>, it repeats the calculation until the result is accurate to within 0.00001 percent. If it cannot determine a result after 20 iterations, the function fails.

Rules ■ <number pay periods>, and <each pmt> must be expressed in terms of the same units (weekly/weeks, monthly/months, yearly/years, and so on).

■ You must express cash paid out (such as deposits to savings) using negative numbers, and cash received (such as dividend checks) using positive numbers.

Tips ■ Because Rate uses the order of values within the array to interpret the order of payments and receipts, be sure to enter your payment and receipt values in the correct sequence.

■ If Rate fails, try a different value for <starting guess>.

Example The following example prompts the user for particulars about a loan, then returns the interest rate. To use this example, paste the first portion at or near the beginning of your Actuate Basic source code (.bas) file. Then copy the procedure into the Method Window for a clickable component:

Page 336: Actuate Basic Reference

312 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

R e D i m s t a t e m e n t

DeclareGlobal Const ENDPERIOD = 0Global Const BEGINPERIOD = 1 ' When payments are made

End Declare'Function OnLButtonDblClk ( )

Dim Fmt As String, FutVal As Double, Guess As DoubleDim PresVal As Double, Pymt As Double, TotalPmts As IntegerDim PayWhen As Integer, APR As DoubleFmt = "##0.00" ' Define percentage formatFutVal = 0 ' Usually 0 for a loanGuess = .1 ' Guess of 10 percentPresVal = InputBox("What is the loan amount?")Pymt = InputBox("What is the monthly payment?")TotalPmts = InputBox("How many monthly payments are needed?")PayWhen = MsgBox("Payments at month end?", MB_YESNO)If PayWhen = IDNO Then

PayWhen = BEGINPERIODElse

PayWhen = ENDPERIODEnd If

APR = (Rate(TotalPmts, -Pymt, PresVal, FutVal, PayWhen, Guess) * 12)* 100MsgBox "Your interest rate is " & Format(APR, Fmt) & " percent."

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also FV functionIPmt functionNPer functionPmt functionPPmt functionPV function

ReDim statementDeclares a new dynamic array variable or changes the size of an existing dynamic array variable, and reallocates memory if needed.

Syntax ReDim [Preserve] <array variable name>(<subscripts>) [As <type>], <array variable name>(<subscripts>) [As <type>]. . .

Page 337: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 313

R e D i m s t a t e m e n t

Parameters PreserveRetains the data in an existing array when you resize the last dimension. With Preserve, if you decrease the size of any dimension, you will lose some of the data in that dimension although the data in the others will be retained.

<array variable name>Name you create for the array.

<subscripts>Each <subscripts> argument specifies the number of elements in a dimension. The number of <subscripts> arguments specifies the number of dimensions in the array.

Array dimensions using the following syntax:

[<lower> To]<upper>[,[<lower> To]<upper>]...

Rules for <subscripts>:

■ <lower> and <upper> can range from -2,147,483,647 to 2,147,483,647 inclusive.

■ <lower> must always be less than <upper>.

■ Each ReDim can specify up to 60 dimensions.

■ When working with an existing array, you cannot add dimensions. That is, the number of <subscripts> arguments must not exceed the number given when the array was originally declared.

■ When working with an existing array, you cannot add dimensions. The number of [<lower>To] <upper> pairs must not exceed the number given when the array was originally declared.

In the following example, the statements are equivalent if you do not use Option Base:

ReDim P(7,5)ReDim P(0 TO 7, 0 TO 5)ReDim P(7, 0 TO 5)

As <type>Specifies a data type or class for the variable. If you specify a class, the variable can hold a reference to an instance of that class or descendant classes. You must use As <type> to declare the variable that you use to specify the dimensions of an array. If you do not specify a data type in Actuate Basic, the data type for a variable defaults to the Variant data type, which cannot be used as a parameter for sizing an array with the ReDim statement.

Rules ■ Use ReDim only at the procedure level.

■ Use ReDim to change the number of elements in an array, not the number of dimensions.

Page 338: Actuate Basic Reference

314 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

R e D i m s t a t e m e n t

■ You cannot use ReDim to resize a fixed-size array.

■ You cannot change the data type of an existing array.

Tips ■ To work with large arrays, use ReDim, which dynamically allocates memory as needed.

■ To create a dynamic array with more than eight dimensions, declare it with ReDim, not Dim.

■ To clear the values in an array, use ReDim without Preserve.

To avoid debugging problems, note that variables declared with Dim are automatically initialized as follows.

Example The following example dynamically resizes an array while a procedure is running:

Function OnLButtonDblClk ( )Dim Customer1 As Integer, Customer2 As Integer, Msg As StringDim NL As String, I As Integer

NL = Chr$(10)Customer1 = 5Customer2 = 10

ReDim MyArray(Customer1)

For I = 1 To Customer1MyArray(I) = I ^ 2Msg = Msg & I & ": " & MyArray(I) & NL

Next IMsgBox Msg

ReDim MyArray(Customer2)

For I = 1 To Customer2MyArray(I) = I ^ 2Msg = Msg & I & ": " & MyArray(I) & NL

Type Initialized As

Numeric 0

Variant Empty

Variable-length strings Empty string("")

User-defined type Separate variables

Object or class Nothing (before Set)

CPointer Null

Page 339: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 315

R e m s t a t e m e n t

Next IMsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Dim statement

Rem statementInserts comments or explanatory remarks in a program.

Syntax {Rem | :Rem | ‘ }<comment>

Parameters <comment>Any characters or numbers, including spaces or punctuation. <comment> is a remark that explains what is happening in the program.

Description ■ All text to the right of Rem is ignored by the compiler.

■ <comment> appears exactly as you entered it when the program is listed.

■ If you branch from a GoTo statement to a line that contains Rem, program execution continues with the first executable statement that follows Rem.

To place a comment on the same line as a code instruction, precede the comment either with the apostrophe identifier or with :Rem:

For A = 1 To 20 'This code steps through the 20 itemsFor A = 1 To 20 : REM This code steps through the 20 items

To place a comment on a line by itself, precede the comment with any one of the three identifiers:

Rem The third line after this steps through the 20 items of the array.: Rem The second line after this steps through the 20 items of the array.' The next line steps through the 20 items of the array.For A = 1 To 20

Tips ■ Use comments liberally throughout your program to explain how the code works.

■ To disable a line of code when debugging, precede it with one of the three Rem identifiers. Temporarily commenting out the line, lets you see what happens when that line is left out of the program.

Example The following example shows various ways in which you can use Rem:

Page 340: Actuate Basic Reference

316 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

R e p o r t C u s t o m F a i l u r e f u n c t i o n

Function OnLButtonDblClk ( )Dim Message1, Message2, Message3, NL, AllMessages

NL = Chr(10) ' Define newlineRem The compiler will ignore this entire line. ' This line will also be ignored.Message1 = "First message line." :Rem Colon needed before REM hereMessage2 = "Second message line."' But this one needs no colon: Rem This line has a colon, but really does not need it.Message3 = "This example shows different ways to use REM."AllMessages = Message1 & NL & Message2 & NL & Message3MsgBox AllMessages

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Format, Format$ functionsStr, Str$ functions

ReportCustomFailure functionSee also

Reports an error.

Syntax Sub ReportCustomFailure(errorString As String)

Parameters errorStringThe error message.

Description This function sends an error message if an error occurs.

Either the ReportCustomFailure or ReturnCustomFormat function, but not both, is the last function you should call in your program to return control to the View process.

If you call ReportCustomFailure from the View process, the function displays the message in the browser. If you call ReportCustomFailure from e.Report Designer Professional, the function displays the message in a message box.

See also ReturnCustomFormat function

Page 341: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 317

R e s e t s t a t e m e n t

Reset statementWrites all data in open file buffers to the appropriate disk files, then closes all open disk files.

Syntax Reset

Description Performs the same task as Close with no parameters.

Example The following example creates and opens two test files, closes them using Reset, then reopens them and reads back the data. Finally, it deletes the test files:

Function OnLButtonDblClk ( )Dim FirstVar, SecondVarOpen "testalpha.fil" for Output As #1Open "testbeta.fil" for Output As #2Print #1, "This line is in the first test file."Print #2, "This line is in the second test file."Reset

Open "testalpha.fil" for Input As #1Open "testbeta.fil" for Input As #2Line Input #1, FirstVarLine Input #2, SecondVarReset

MsgBox FirstVar & " " & SecondVarResetMsgBox "Press okay to delete the test files."Kill "testalpha.fil"Kill "testbeta.fil"

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Close statementEnd statement

Resume statementReleases control from an error-handling routine and resumes program execution at a specified place.

Page 342: Actuate Basic Reference

318 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

R e s u m e s t a t e m e n t

Syntax Resume { [0] | Next | <line> | <line label> }

Parameters [0]Keyword (an optional zero) indicating that Actuate Basic is to resume program execution with the statement that caused the error, or with the statement that last called out of the procedure containing the error handler.

Examples:The following two statements are equivalent:

ResumeResume 0

NextKeyword indicating that Actuate Basic is to resume program execution with the statement following the one that caused the error, or with the statement following the one that last called out of the procedure containing the error handler.

Example:

Resume Next

<line> or <line label>Keyword indicating the line number or line label at which Actuate Basic is to resume execution.

Rule: Must be in the same procedure as the error handler.

Example:The following example instructs Actuate Basic to continue execution at the label Continuation:

Resume Continuation

Description Where Actuate Basic resumes execution depends on the location of the error handler in the which the error is trapped, not necessarily on the location of the error itself. The following table summarizes where a program resumes execution when either the Resume [0] or Resume Next statement is used.

Error occurred Resume [0] Resume Next

In the same procedure as the error handler.

The statement that caused the error.

The statement after the one that caused the error.

In a different procedure from the error handler.

The statement that last called out of the procedure containing the error handler.

The statement after the one that last called out of the procedure containing the error handler.

Page 343: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 319

R e t u r n C u s t o m F o r m a t f u n c t i o n

Rules ■ You can only use Resume in an error-handling routine.

■ You can only exit an error-handling routine by using Resume, not by using End Sub or End Function.

Example The code in the following example generates two errors in succession and does something different in each case. In the first case, the error routine displays the error number and description and then uses Resume to resume execution of the code at the line following the line that caused the error. In the second case, the error routine displays a simple message and uses Resume to branch to a specified routine. This branch causes the flow of program execution to skip the line following the one that caused the error:

Function OnLButtonDblClk()On Error GoTo ErrorHandlerDim Zilch, Zero, DivisionByZero, NadaZilch = 0Zero = 0DivisionByZero = Zilch/NadaMsgBox "This is the next line after the divide-by-zero error."Open "z:\zzzzzz.zzz" for Input As #1MsgBox "This is the next line after the file error. It is skipped."

Badfile: MsgBox "This line is in the Badfile routine."

Exit FunctionErrorHandler:

If Err = 8 ThenMsgBox "Sorry! Error number: " & Err & " occurred: " & Error$(Err)Resume Next

ElseMsgBox "A file error! Rerouting to the Badfile label."Resume Badfile

End IfEnd Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also On Error statement

ReturnCustomFormat functionOpens the specified file.

Page 344: Actuate Basic Reference

320 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

R e v I n S t r f u n c t i o n

Syntax Sub ReturnCustomFormat(fName As String, mimeType As String,needDelete As Boolean)

Parameters fName The name and extension of the file to open.

mimeTypeThe Multipurpose Internet Mail Extensions (MIME) type of the file.

needDeleteTrue deletes the file after it is sent. False keeps the file after it is sent.

Description Either the ReturnCustomFormat or the ReportCustomFailure function, but not both, is the last function you should call in your program to return control to the View process.

If you call ReturnCustomFormat from the View process, the function:

■ opens the specified file if it exists

■ sets the MIME type as specified

■ if the file exists, sends the file to the browser

■ if the file does not exist, displays an error

■ if needDelete is true, deletes the file after it is sent

If you call ReturnCustomFormat from the e.Report Designer Professional, the function:

■ checks whether the specified file exists

■ if the file exists, displays a message that the method ran successfully and the output file can be viewed as <fName>

■ if the file does not exist, displays an error

See also ReportCustomFailure function

RevInStr functionReturns the starting position of the last, rightmost, occurrence of one string within another. RevInStr is used to extract a filename like Myhouse.txt from a long or fully qualified string like C:/Country/State/City/Street/Myhouse.txt.

Syntax RevInStr(<end>, <string being searched>, <string to find>)

Page 345: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 321

R e v I n S t r f u n c t i o n

Parameters <string being searched>String you are inspecting in order to locate the last, rightmost, occurrence of <string to find>.

<string being searched> must be a variable string, a literal string, a string constant, the return value of any function that returns a string, or a variant that can evaluate to a string.

<string to find>String in which last occurrence you are seeking is within <string being searched>.

<string to find> must be a variable string, a literal string, a string constant, the return value of any function that returns a string, or a variant that can evaluate to a string.

<end> (optional)The position within <string being searched> at which to end searching. The first, leftmost, character occupies position 1.

Rules for <end>:

■ If you supply <end>, Actuate Basic searches for the last occurrence of <string to find> that appears before the character at position <end>.

■ If you do not supply <end>, Actuate Basic searches to the last character of <string being searched>.

■ Must be a number or numeric expression.

■ Must be between 1 and 2,147,483,647, inclusive.

Returns Integer

■ If <string to find> is found within <string being searched>, RevInStr returns the position of the first character at which the last, rightmost, match was found.

■ If <string to find> is not found within <string being searched>, RevInStr returns 0.

■ If <string being searched> is zero-length, RevInStr returns 0.

■ If <end> is greater than the length of <string being searched>, RevInStr returns 0.

Description RevInStr is like InStr, except that where InStr returns the position of the first character of the first, leftmost, occurrence of a string, RevInStr returns the position of the first character of the last, rightmost, occurrence of a string.

In cases where <string to find> occurs only once within <string being searched>, first and last occurrences coincide, and both InStr and RevInstr return the same value.

Page 346: Actuate Basic Reference

322 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

R e v I n S t r f u n c t i o n

Examples:

In the following examples, InStr and RevInStr return different values:

RevInStr("C:/Country/State/City/Myfile.txt", "/") = 22RevInStr(21, "C:/Country/State/City/Myfile.txt", "/") = 17RevInStr("C:/Country/State/State2/City/Myfile.txt", "/State") = 17

In the following examples, both InStr and RevInStr return the same value:

RevInStr("C:/Country/State/City/Myfile.txt", "/State") = 11RevInStr("C:/Country/State/State2/City/Myfile.txt", "Etats/") = 0

Example This example shows how to use RevInStr to find the filename portion of a fully qualified filename that contains slashes.

Because in this example RevInStr returns the position of the last occurrence of a slash, the following code displays Johnsmith.fil regardless of the number of slashes in the file’s full name or path:

Function OnLButtonDblClk( )

Dim baseName, fileName As StringDim posn As Integer

fileName = "C:/USA/Massachusetts/Springfield/Zip01109/Johnsmith.fil"posn = RevInStr( fileName, "/" )

If posn = 0 ThenbaseName = fileName

ElsebaseName = Mid$( fileName, posn + 1 )

End If

MsgBox baseName

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also InStr functionLeft, Left$ functionsLen functionMid, Mid$ functionsRight, Right$ functions

Page 347: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 323

R G B f u n c t i o n

RGB functionReturns a number representing the RGB color value for a given mix of red, green and blue values.

Syntax RGB(<red>, <green>, <blue>)

Parameters <red>Integer indicating the red value of the color.

Rules for <red>:

■ If <red> is greater than 255, <red> defaults to 255.

■ If <red> is empty, <red> defaults to 0.

■ <red> must be greater than 0.

■ <red> must not be Null.

<green>Integer indicating the green value of the color.

Rules for <green>:

■ If <green> is greater than 255, <green> defaults to 255.

■ If <green> is empty, <green> defaults to 0.

■ <green> must be greater than 0.

■ <green> must not be Null.

<blue>Integer indicating the blue value of the color.

Rules for <blue>:

■ If <blue> is greater than 255, <blue> defaults to 255.

■ If <blue> is empty, <blue> defaults to 0.

■ <blue> must be greater than 0.

■ <blue> must not be Null.

Returns Long

■ Returns a number between 0 and 16,777,215, inclusive. This single number represents the relative intensities of red, green, and blue that make up a particular color.

■ The following table shows some standard colors. For each color, you see the decimal values returned by RGB, the hexadecimal equivalent, the

Page 348: Actuate Basic Reference

324 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

R G B f u n c t i o n

corresponding QBColor number, and the mix of red, green and blue decimal values that make up the color.

Tips There are four ways in which you can precisely represent a color in Actuate Basic:

■ Specify the relative mix of red, green and blue in a color by using RGB with decimal numbers, as described here.

■ Directly specify, without using RGB or any function, the relative mix using hexadecimal numbers in a certain format.

■ Use one of the 16 standard Windows colors by supplying the appropriate integer to QBColor.

■ Use one of the built-in color constant names, such as BLUE.

Example The following example returns the RGB value for a mix of red, green, and blue values specified by the user:

Function OnLButtonDblClk ( )Dim NL As String, RedPart As Integer, GreenPart As IntegerDim BluePart As IntegerDim HexVersion, Msg As String, RGBNumber

NL = Chr$(10)RedPart = InputBox("How much red?")GreenPart = InputBox("How much green?")BluePart = InputBox("How much blue?")RGBNumber = RGB(RedPart, GreenPart, BluePart)HexVersion = Hex(RGBNumber)Msg = "Red component: " & RedPart & NLMsg = Msg & "Green component: " & GreenPart & NL

Color

RGB Value (Dec)

RGB Value (Hex) QBColor

Red Value

Green Value

Blue Value

Black 0 &H00 0 0 0 0

Blue 16711680 &HFF0000 1 0 0 255

Green 65280 &HFF00 2 0 255 0

Cyan 16776960 &HFFFF00 3 0 255 255

Red 255 &HFF 4 255 0 0

Magenta 16711935 &HFF00FF 5 255 0 255

Yellow 65535 &HFFFF 6 255 255 0

White 16777215 &HFFFFFF 15 255 255 255

Gray 8421504 &H808080 8 128 128 128

Page 349: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 325

R i g h t , R i g h t $ f u n c t i o n s

Msg = Msg & "Blue component: " & BluePart & NLMsg = Msg & "The decimal representation of that mix of "Msg = Msg & "red, green, and blue is: "Msg = Msg & RGBNumber & "." & NLMsg = Msg & "The hex representation of it is: "Msg = Msg & HexVersionMsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also QBColor function

Right, Right$ functionsReturns a segment of a Variant or String, starting at the rightmost character and working to the left.

Syntax Right(<string exprs>, <length>)

Right$(<string exprs>, <length>)

Parameters <string exprs>Source string from which you are copying a rightmost portion. Can be a variable string, a literal string, a string constant, the return value of any function that returns a string, or a Variant that can evaluate to a String.

<length>Long that specifies how many characters to copy from the right of <string exprs>.

■ <length> must be an Integer or expression between 0 and 2,147,483,647.

■ In the following example, the statements are equivalent. Both return Widget:

Right$("Widget",6)Right$("Widget",99)

Returns Right: VariantRight$: String

■ If <length> = 0, returns zero-length string.

■ If <length> is greater than or equal to the length of <string exprs>, returns an exact copy of <string exprs>.

Tip ■ Use Len to find the number of characters in <string exprs>.

■ Use InStr to find the position of a specified character in <string exprs>.

Page 350: Actuate Basic Reference

326 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

R i g h t B , R i g h t B $ f u n c t i o n s

Example The following example asks the user to input a customer’s first and last names, then returns the last name:

Function OnLButtonDblClk ( )Dim FName As String, Msg As String, Message As StringDim LName As String, SpacePos As Integer, UserInput As String

Msg = "Please enter a customer’s first and last names, "Msg = Msg & " separated by a space."UserInput = InputBox(Msg) ' Get user's inputSpacePos = InStr(1, UserInput, " ") ' Find the spaceIf SpacePos Then

FName = Left$(UserInput, SpacePos - 1) ' Get first & last namesLName = Right$(UserInput, Len(UserInput) - SpacePos)Message = "The first name is """ & FNameMessage = Message & "." & """" & " The last name is """Message = Message & LName & "." & """"

ElseMessage = "You did not enter a first and last name."

End IfMsgBox Message ' Display the message

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also InStr functionLeft, Left$ functionsLen functionMid, Mid$ functions

RightB, RightB$ functionsReturns a segment of a Variant or String, starting at the rightmost byte and working to the left.

These functions are provided for backward compatibility with previous Actuate releases. Actuate uses UCS-2 as internal encoding, therefore passing strings consisting of characters from different code pages might produce unexpected results. For this reason, Actuate recommends you use the Right and Right$ functions instead of the RightB and RightB$ functions.

Syntax RightB(<string exprs>, <length>)

RightB$(<string exprs>, <length>)

Page 351: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 327

R i g h t B , R i g h t B $ f u n c t i o n s

Parameters <string exprs>Source string from which you are copying a rightmost portion. It can be a variable string, a literal string, a string constant, the return value of any function that returns a string, or a Variant that can evaluate to a String.

<length>Long that specifies how many bytes to copy from the right of <string exprs>.

Rule: Must be an Integer or expression between 0 and 2,147,483,647.

Example:The following statements are equivalent. Both return Widget:

RightB$("Widget",6)RightB$("Widget",99)

Returns RightB: VariantRightB$: String

■ If <length> = 0, the function returns zero-length string.

■ If <length> is greater than or equal to the length of <string exprs>, the function returns an exact copy of <string exprs>.

Tips ■ Use LenB to find the number of bytes in <string exprs>.

■ Use InStrB to find the position of a specified bytes in <string exprs>.

Example The following example prompts the user for a string and a number of bytes to show from the left or right side of the string:

Function OnLButtonDblClk( )

Dim UserString As String, BytesToShow As IntegerDim Msg As StringMsg = "Please type a string of characters."UserString = InputBox(Msg)Msg = "How many bytes from the left of <" & UserString & "> do you want

to see?"BytesToShow = InputBox(Msg)'Show that many bytes.Msg = LeftB$(UserString, BytesToShow)MsgBox MsgMsg = "How many bytes from the right of <" & UserString & "> do you

want to see?"BytesToShow = InputBox(Msg)Msg = RightB$(UserString, BytesToShow)MsgBox Msg

End Function

Page 352: Actuate Basic Reference

328 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

R m D i r s t a t e m e n t

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also InStrB functionLeftB, LeftB$ functionsLenB functionMidB, MidB$ functionsRight, Right$ functions

RmDir statementRemoves a subdirectory from a disk.

Syntax RmDir <directory name>

Parameters <directory name>String expression that is the name of the directory or subdirectory to be deleted.

Default: Current drive and directory.

Rules:

■ Must specify a valid directory.

■ Target directory must contain no child subdirectories.

■ Target directory must be empty.

<directory name> has the following syntax.

[<drive:>] [ \ ]<directory>[\<directory>]...(Windows)

[ / ]<directory>[/<directory>]...(UNIX)

<drive:>Character, followed by a colon, that specifies the drive (Windows only).

<directory>String expression that is the name of the directory or subdirectory to remove.

Examples:The following statement removes the subdirectory Test under the current directory on the current drive:

RmDir "Test"

The following removes the subdirectory Test under the root directory of the current drive:

RmDir "\Test"

Page 353: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 329

R m D i r s t a t e m e n t

The following removes the subdirectory Test under the root directory ofdrive D:

RmDir "D:\Test"

Description RmDir works like the DOS command of the same name. Unlike the DOS command it cannot be abbreviated.

Tips ■ If a directory name contains embedded spaces, you cannot use the DOS RmDir command to remove it. Instead, use RmDir.

■ To determine the current directory, use CurDir.

Example The following example determines whether a \Tmpzzz subdirectory exists on the current drive. If the subdirectory does not exists, the example creates the subdirectory, prompts the user to retain or remove the subdirectory, and responds accordingly:

Function OnLButtonDblClk ( )Dim UserAns As Integer, ThisDrive As StringDim Msg As String, TempDir As StringOn Error Resume Next ' Set up error handlerThisDrive = Left$(CurDir, 2) ' Get current drive letterTempDir = UCase$(ThisDrive + "\Tmpzzz") ' Construct full path specMkDir TempDir ' Make the new directory

If Err = 41 Then ' Does it exist?Msg = "Sorry, " & TempDir & " directory already exists. "

ElseMsg = TempDir & " directory was just created. "

End If

Msg = Msg & "Would you like to remove it?"UserAns = MsgBox(Msg, MB_YESNOCANCEL)

If UserAns = IDYES ThenRmDir TempDir

End IfEnd Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also CurDir, CurDir$ functionsMkDir statement

Page 354: Actuate Basic Reference

330 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

R n d f u n c t i o n

Rnd functionReturns a random number.

Syntax Rnd[(<sequencing code>)]

Parameters <sequencing code>Numeric expression for the code number that identifies the value to return from the pseudo-random sequence. The pseudo-random sequence is the fixed sequence of numbers you generate if you have not used Randomize and you call Rnd repeatedly without any argument.

Rule: If <sequencing code> is omitted, Actuate Basic moves to the next number in the pseudo-random sequence.

The following table shows the possible values of <sequencing code>, and the corresponding values Rnd returns from the pseudo-random sequence.

Example:The following expressions are all true, but only if (A) you evaluate them in the order shown, and (B) you do not use a Randomize statement before them. If you do use a Randomize statement, the last of these expressions will always be different.

Rnd(-5) = 0.298564536496997Rnd(0) = .298564536496997Rnd(1) = .223996873013675Rnd = .0928899832069874

Returns Single

■ Rnd returns a value less than 1 but greater than or equal to 0.

■ Unless you use Randomize beforehand, Rnd generates the same random-number sequence every time the program is run.

■ As long as <sequencing code> is omitted or is greater than zero, each successive call to Rnd uses the previous random number as the seed for the next one.

<sequencing code> Rnd returns

Less than 0 The same number every time. The specific value varies as a function of <sequencing code>.

Greater than 0 The next random number in the pseudo-random sequence.

Equal to 0 The number most recently generated.

Page 355: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 331

R S e t s t a t e m e n t

Tips ■ To generate a more apparently random sequence every time the program is run, use Randomize without an argument before you use Rnd.

■ To produce random integers in a given range, use the following formula:

Int((<high number> - <low number> + 1) * Rnd + <low number>)

In this formula, <high number> represents the highest number in the range, and <low number> the lowest.

Example The following example simulates rolling a die twice by generating random values between 1 and 6 for each roll:

Function OnLButtonDblClk( )Dim DieRoll1, DieRoll2, UserMsgRandomize ' Seed random num generatorDieRoll1 = Int(6 * Rnd + 1) ' First rollDieRoll2 = Int(6 * Rnd + 1) ' Second rollUserMsg = "You rolled a " & DieRoll1UserMsg = UserMsg & " and a " & DieRoll2UserMsg = UserMsg & " giving a total of "UserMsg = UserMsg & (DieRoll1 + DieRoll2) & "."MsgBox UserMsg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Randomize statementTime, Time$ functions

RSet statementRight-aligns a string within the space of a string variable.

Syntax RSet <string variable> = <string exprs>

Parameters <string variable>Name of a string variable in which RSet stores the right-aligned <string exprs>.

Page 356: Actuate Basic Reference

332 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

R T r i m , R T r i m $ f u n c t i o n s

<string exprs>String expression that you want RSet to right-align within <string variable>.

Description RSet right-aligns a string expression within a variable.

Example The code in the following example right-aligns text within a 20-character String variable:

Function OnLButtonDblClk ( )Dim Msg, NL, TmpStrNL = Chr(10) ' Define newlineTmpStr = String(20, "*") ' Create 20-character stringMsg = "The following two strings that have been right"Msg = Msg & NL & "and left justified in a " & Len(TmpStr)Msg = Msg & "-character string." & NL & TmpStr & NLRSet TmpStr = "Right->" ' Right justifyMsg = Msg & TmpStr & NLLSet TmpStr = "<-Left" ' Left justifyMsg = Msg & TmpStr & NLMsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also LSet statement

RTrim, RTrim$ functionsReturns a copy of a string after removing the trailing spaces.

Syntax RTrim(<string exprs>)

RTrim$(<string exprs>)

<string exprs> Behavior of RSet

Shorter than <string variable>

Right-aligns <string exprs> within <string variable>. Replaces any leftover characters in <string variable> with spaces.

Longer than <string variable>

Places only the right most characters, up to the length of the <string variable>, in <string variable>. Truncates characters beyond the length of <string variable> from the left.

Page 357: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 333

R T r i m , R T r i m $ f u n c t i o n s

Parameters <string exprs>String expression from which RTrim$ strips trailing spaces. Trailing spaces are any spaces that occur after the last non-space character in a string. The <string exprs> must be a variable string, a literal string, a string constant, the return value of any function that returns a string, or a Variant that can evaluate to a String.

Returns RTrim: VariantRTrim$: String

If there are no trailing spaces, RTrim[$] returns the original <string exprs>.

Tips ■ To simultaneously strip both leading and trailing spaces in a string, use Trim[$].

■ To find other spaces in the middle of a string, use InStr.

Example The following example strips trailing spaces from a string variable, while LTrim[$] strips leading spaces:

Function OnLButtonDblClk( )Dim Msg As String, NL As StringDim CustName As String, CustName1 As String

NL = Chr$(10) ' Define newlineCustName = " Harold Pinter "CustName1 = LTRIM$(RTRIM$(CustName)) ' Strip left and right spacesMsg = "The original client name " & NL & "'" & CustName & "'" & " was "Msg = Msg & Len(CustName) & " characters long. There were two "Msg = Msg & "leading spaces and two trailing spaces." & NL & NLMsg = Msg & "The name returned after stripping the spaces "Msg = Msg & "is:" & NL & "'" & CustName1 & "'" Msg = Msg & NL & "...and it contains only "Msg = Msg & Len(CustName1) & " characters."MsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also InStr functionLTrim, LTrim$ functionsTrim, Trim$ functions

Page 358: Actuate Basic Reference

334 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

S a f e D i v i d e f u n c t i o n

SafeDivide functionDivides two given numbers, but prevents division by zero. Returns a specified value if division by zero might otherwise have occurred.

Syntax SafeDivide(<num> As Variant, <denom> As Variant, <ifZero> As Variant) As Variant

Parameters <num>Any number, or valid numeric expression. The numerator of a fraction or ratio.

<denom>Any number, or valid numeric expression. The denominator of a fraction or ratio.

<ifZero>Value to return when <denom> is zero.

Returns Variant

If <denom> = 0, SafeDivide returns <ifZero>. Otherwise, SafeDivide returns <num>/<denom>.

Example The following statement averages amounts in a number of records. But if there are no records at all, the statement does not generate a division-by-zero error. Instead, it simply returns zero.

AverageAmtVar = SafeDivide(Sum(Amount)), Count(), 0)

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Err functionError, Error$ functionsOn Error statement

Second functionReturns an Integer from 0 to 59, inclusive, that represents the second of the minute specified by a date expression.

Syntax Second(<date expression>)

Parameters <date expression>Date expression, or any numeric or string expression that can be interpreted as a date, a time, or both a date and a time:

Page 359: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 335

S e c o n d f u n c t i o n

■ Can be a string such as November 12, 1982 8:30 PM, Nov 12, 1982 08:30 PM, 11/12/82 8:30pm, or 08:30pm, or any other string that can be interpreted as a date, a time, or both a date and a time in the valid range.

■ Can be a date serial number such as 30267.854, which corresponds to November 12, 1982 at 8:30 P.M., or any other number that can be mapped to a date, a time, or both a date and a time in the valid range.

■ For date serial numbers, the integer component represents the date itself while the decimal component represents the time of day on that date, where January 1, 1900, at noon has the date serial number 2.5, and negative numbers represent dates prior to December 30, 1899 (0).

Default if no time specified: 0

Rules:

■ If <date expression> includes a date, it must be a valid date, even though Second does not return a date. A valid date is any date in the range January 1, 100, through December 31, 9999, expressed in one of the standard date formats.

■ If <date expression> includes a time, it must be in the range 00:00:00 (12:00:00 A.M.) through 23:59:59 (11:59:59 P.M.), in either 12- or 24-hour format.

■ If <date expression> is a numeric expression, it must be in the range -657434.0 to +2958465.9999, inclusive.

■ If <date expression> is a variable containing a date serial number, the variable must have been explicitly declared as one of the numeric types.

■ <date expression> is parsed according to the formatting rules of the current run time locale.

Examples:The following statements are equivalent. Each assigns 22 to the variable UserSecond:

UserSecond = Second("6/7/64 2:35:22pm")UserSecond = Second("5:35:22 pm")UserSecond = Second("June 7, 1964 2:35:22 PM")UserSecond = Second("Jun 7, 1964") + 22UserSecond = Second(23535.60789)UserSecond = Second(0.60789)

Returns Integer

■ If <date expression> cannot be evaluated to a date, Second returns a Null.

Example:

Second(“This is not a date.“) returns Null

Page 360: Actuate Basic Reference

336 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

S e c o n d f u n c t i o n

■ If <date expression> fails to include all date components (day, month, and year), Second returns a Null.

Examples:

Second(“Nov 12, 1982 7:11:22 AM“) returns 22, butSecond(“Nov, 1982 7:11:22 AM“) returns Null

■ If <date expression> is Null, Second returns a Null.

The following assumes that the AC_CENTURY_BREAK property is set to the default value of 30. For information about using AC_CENTURY_BREAK, please see Chapter 7, “Using a query data stream,” in Developing Advanced e.Reports:

■ For abridged date expressions ending in 00 through 29 that do not specify the century, relevant date functions estimate the unabridged year by adding 2000. For example, while Year(4/30/1910) returns 1910, the abridged expression Year(4/30/10) returns 2010 (10 + 2000).

■ For abridged date expressions ending in 30 through 99 that do not specify the century, relevant date functions estimate the unabridged year by adding 1900. For example, while Year(11/12/2082) returns 2082, the abridged expression Year(11/12/82) returns 1982 (82 + 1900).

Tip If you use a date expression in one locale, it might be misinterpreted in another locale. For instance, in the United States, “1/2/2005“ means January 2nd, 2005; but in France, it means February 1st, 2005. To avoid such ambiguities, use DateSerial to specify all your dates.

Example The following example displays the number of hours, minutes, and seconds to midnight:

Function OnLButtonDblClk()Dim HrDiff As Integer, MinDiff As Integer, SecDiff As IntegerDim RightNow As Double, Midnight As Double, TotalDiff As DoubleDim TotalMinDiff As Double, TotalSecDiff As DoubleDim Msg As String

Midnight = TimeValue("23:59:59")RightNow = Now ' Get current timeHrDiff = Hour(Midnight) - Hour(RightNow) ' Get diffs re midnightMinDiff = Minute(Midnight) - Minute(RightNow)SecDiff = Second(Midnight) - Second(RightNow) + 1

' Restate seconds and minutes if necessaryIf SecDiff = 60 Then

MinDiff = MinDiff + 1 ' Add 1 to minuteSecDiff = 0 ' And set 0 seconds

End IfIf MinDiff = 60 Then

Page 361: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 337

S e e k s t a t e m e n t

HrDiff = HrDiff + 1 ' Add 1 to hourMinDiff = 0 ' And set 0 minutes

End If

' Now get totalsTotalMinDiff = (HrDiff * 60) + MinDiffTotalSecDiff = (TotalMinDiff * 60) + SecDiffTotalDiff = TimeSerial(HrDiff, MinDiff, SecDiff)

' Prepare msg for displayMsg = "There are a total of " & Format(TotalSecDiff, "#,##0")Msg = Msg & " seconds until midnight. That translates to "Msg = Msg & HrDiff & " hours, " Msg = Msg & MinDiff & " minutes, and "Msg = Msg & SecDiff & " seconds. "Msg = Msg & "Expressed in standard time notation, it becomes "' Remember to use "nn" for minutes! m is for month.Msg = Msg & Format(TotalDiff, "hh:nn:ss") & "."MsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Day functionHour functionMinute functionMonth functionNow functionTime, Time$ functionsWeekday functionYear function

Seek statementSets the position in a file for the next read or write. The Seek statement should not be confused with the Seek2 function.

Syntax Seek #<open file number>, <next position>

Parameters <open file number>Numeric expression is the file number for a file that is Open.

Rules for <open file number>:

■ Must be the number of a currently open file.

■ The pound sign (#) preceding the file number is required.

Page 362: Actuate Basic Reference

338 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

S e e k s t a t e m e n t

<next position>Numeric expression that specifies the number that indicates where in <open file number> the next read or write should occur.

Rule: Must be in the range 1 to 2,147,483,647, inclusive.

<next position> means or refers to different things depending on the mode under which the file corresponding to <open file number> is open. The following table summarizes these different meanings.

Examples:In the following code fragment, we open a file called Test.dat for random access and use Get to read record number 52 from it; this action positions the pointer at record 53. Then we use the Seek2 function to save this new position to the variable CurrentRec. Finally, we use the Seek statement to reposition the file pointer to record number 100:

Open "Test.dat" For Random As #1 Len = 32Get #1, 52, TestRecordCurrentRec = Seek2(1)Seek #1, 100

Rule ■ If <next position> is beyond the end of a file, Seek extends the file.

■ Record numbers in Get and Put override Seek file positioning.

Example The following example prompts the user to type three customer names. After writing the names to a test file, the Seek statement repositions the pointer three times successively and then displays the names in reverse order; then the Seek2 function identifies the record numbers:

Function OnLButtonDblClk ( )Dim CustName As StringDim I As Integer, Max As Integer, Msg As String' Create a sample data file:Open "Testfile.dat" For Random As #1 Len =50' Ask user to type a few records:For I = 1 To 3

CustName = InputBox("Please type a customer name: ")Put #1, I, CustName ' Put record into file

Next I

Mode <next position> refers to

Random The number of a record in the open file. The first record is record 1.

BinaryInputOutputAppend

The byte position relative to the beginning of the file. The first byte is byte 1.

Page 363: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 339

S e e k 2 f u n c t i o n

Close #1 ' Close data file' Open data fileOpen "Testfile.dat" For Random As #1 Len = 50Max = LOF(1) \ 50 ' Calc total # of recordsMax = Max+ 1For I = Max To 1 Step -1 ' Read file backwards

Seek #1, I ' Seek STATEMENTGet #1, , CustName ' Get record at that positionMsg = "Record #" & (Seek2(1) - 1) & " contains: "' Seek2 FUNCTIONMsg = Msg & CustNameMsgBox Msg

Next IClose #1 ' Close test fileMsg = "Choose OK to remove the test file."MsgBox MsgKill "Testfile.dat" ' Delete file from disk

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Get statementOpen statementPut statementSeek2 function

Seek2 functionReturns the current position in an open file. This function should not be confused with the Seek statement.

Syntax Seek2(<open file number>)

Parameters <open file number>Numeric expression that represents the file number of a file that is Open.

Rule: Must be the number of a currently open file.

Examples:In the following code fragments, we open a file called Test.dat for random access and use Get to read record number 52 from it; this action positions the pointer at record 53. Then we use the Seek2 function to save this new position to the variable CurrentRec. Finally, we use the Seek statement to reposition the file pointer to record number 100:

Open "Test.dat" For Random As #1 Len = 32Get #1, 52, TestRecordCurrentRec = Seek2(1)Seek #1, 100

Page 364: Actuate Basic Reference

340 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

S e e k 2 f u n c t i o n

Returns Integer

■ Returns a value between 1 and 2,147,483,647.

■ The value Seek2 returns means, or refers to, different things depending on the mode under which the file corresponding to <open file number> is open. The following table summarizes these different meanings.

Example The following example prompts the user to type three customer names. After writing the names to a test file, the Seek statement repositions the pointer three times successively and then displays the names in reverse order; then thee Seek2 function to identifies the record numbers:

Function OnLButtonDblClk ( )Dim CustName As StringDim I As Integer, Max As Integer, Msg As String' Create a sample data file:Open "Testfile.dat" For Random As #1 Len =50' Ask user to type a few records:For I = 1 To 3

CustName = InputBox("Please type a customer name: ")Put #1, I, CustName ' Put record into file

Next IClose #1 ' Close data file' Open data fileOpen "Testfile.dat" For Random As #1 Len = 50Max = LOF(1) \ 50 ' Calc total # of recordsMax = Max + 1For I = Max To 1 Step - 1 ' Read file backwards

Seek #1, I ' Seek STATEMENTGet #1, , CustName ' Get record at that positionMsg = "Record #" & (Seek2(1) - 1) & " contains: "' Seek2 FUNCTIONMsg = Msg & CustNameMsgBox Msg

Next IClose #1 ' Close test fileMsg = "Choose OK to remove the test file."MsgBox MsgKill "Testfile.dat" ' Delete file from disk

End Function

Mode Seek2 refers to:

Random The number of the next record to be read or written to.

BinaryInputOutputAppend

The byte position at which the next operation is to take place.

Page 365: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 341

S e l e c t C a s e s t a t e m e n t

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Get statementOpen statementPut statementSeek statement

Select Case statementExecutes the first of several blocks of instructions for which an associated expression matches a given one.

Syntax Select Case <compare to this>

[Case <value to compare> [, <value to compare>]...

[<statement block 1>]]

[Case <value to compare> [, <value to compare>]...

[<statement block 2>]]

...

[Case Else

[<statement block n>]]

End Select

Parameters <compare to this>Any valid numeric or string expression.

CaseKeyword that begins a statement block of a Select Case statement. Case is always followed by a value to compare, and a statement to execute if <value to compare> is the same as <compare to this>. Case may be repeated.

<value to compare>Any valid numeric or string expression. In addition to the form previously shown in the Syntax section, <value to compare> can also take either of the following forms, or it can take any combination of all three forms.

Range Form

<lower value > To <higher value >

Page 366: Actuate Basic Reference

342 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

S e l e c t C a s e s t a t e m e n t

For <value to compare>, specifies a range of values between <lower value> and <higher value>, inclusively. If <compare to this> falls within the range, the case evaluates as True.

ToKeyword used to specify a range of values.

<lower value>, <higher value>Numeric or string expressions.

Rule: The lower value must always precede the higher one.

Example:

Case 65, 19 To 25, 34 To 49Case "ZACHARY", "ADAMS" To "JEFFERSON"

Comparison Operator Form

[Is] <comparison operator> <value to compare>

IsAn optional keyword preceding <comparison operator> <value to compare>.

<comparison operator>Any valid comparison operator except Like.

Example:

Case Is <= 25 , 34 To 49, Is = 65

Case ElseKeyword indicating the statement block Actuate Basic executes if it finds no match between <compare to this> and any of the <value to compare> expressions. If there is more than one Case Else clause, only the first is executed.

Description For the purposes of this discussion, one expression is said to match a second expression when they are equivalent, or when the first falls within a range specified by the second.

Actuate Basic compares <compare to this> against each <value to compare> until it finds a match. For the first—and only the first—of these matches, if there is one, Actuate Basic:

■ Executes the instructions in the <statement block> that immediately follows the matching <value to compare>.

■ Skips any other intervening lines.

■ Passes control to the statement that follows End Select.

Page 367: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 343

S e l e c t C a s e s t a t e m e n t

If no <value to compare> at all matches <compare to this>, Actuate Basic looks for a Case Else clause. If it finds one, it:

■ Executes any statements that immediately follow it.

■ Passes control to the statement immediately following End Select.

If it does not find a Case Else clause, it passes control to the statement immediately following End Select.

Rules The data type of <value to compare> must be compatible with the data type of <compare to this>. The following table summarizes data type compatibilities in Actuate Basic.

Tips ■ To handle any unforeseen <compare to this> values, always use a Case Else clause in your Select Case statements.

■ The Is comparison operator is different from the Is keyword in this statement.

■ To be sure that string data the user supplies always matches <value to compare> strings consistently, use UCase$ on the user data before you use Select Case.

■ To specify whether string comparisons are or are not case sensitive, use Option Compare.

■ It is good programming practice to evaluate Boolean variables by using the keywords True or False instead of by inspecting their content for a nonzero (True) or zero (False) numeric value.

Example The following example shows one way to use logical operators with a Select Case statement:

Function OnLButtonDblClk( )Dim UTyp As String, Insect As Integer, Light As IntegerDim Tester As Integer, Msg As StringUTyp = InputBox("Please type 'BUG', 'LIGHTNING BUG', or a number.")UTyp = UCase$(UTyp)'If the user types either 'lightning bug' or 'bug' then the 'variable Insect will have a value of 1 (True)Insect = (InStr(UTyp, "LIGHTNING BUG") <> 0) Or (InStr(UTyp, "BUG") <> 0)'If the user types 'lightning' but NOT 'bug' then the

<compare to this> <value to compare>

Numeric expression NumericVariant that converts to Numeric

String expression String non-Null Variant

Page 368: Actuate Basic Reference

344 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

S e t s t a t e m e n t

'variable Light will have a value of 1 (True)Light = (InStr(UTyp, "LIGHTNING") <> 0) And Not (InStr(UTyp, "BUG") <> 0)'Set Tester to True, just to get startedTester = 1Select Case Tester

Case InsectMsg = "That is an insect, or refers to one."

Case LightMsg = "That is definitely not an insect."

Case Else'The following nested Select Case structure helps sort out'numeric input in cases where the user typed a numberSelect Case Val(UTyp)

Case 1 To 9Msg = "That is, or starts with, a number from 1 to 9."

Case Is > 9Msg = "That is, or starts with, a number greater than 9."

Case ElseMsg = "I don't know anything about that."

End SelectEnd SelectMsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also GoTo statementIf...Then...Else statementOption Compare statement

Set statementAssigns an object reference to a variable.

Syntax Set <object variable> = {<object reference> | New <class> | Nothing}

Parameters <object variable>Expression that specifies the name of the variable to which you are assigning an object reference.

Rules:

■ Must be of a class consistent with that of <object reference>.

■ Must have been explicitly declared unless declared for you by Actuate Basic.

Page 369: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 345

S e t s t a t e m e n t

<object reference>Expression that specifies the name of an object, of another declared variable of the same class, or of a function or method that returns an object.

NewReserved word used to create a new instance of a specific class.

Rule: Cannot be used to create new variables of any of the fundamental data types.

<class>The name of a specific class.

NothingReserved word that discontinues association of <object variable> with any specific object. Assigning Nothing to <object variable> releases all resources associated with the previously referenced object, as long as no other variable refers to it.

Description When you use Set to assign an object reference to a variable, Actuate Basic generally creates not a copy of the object but a reference to it. More than one object variable can refer to the same object. Because these variables are references and not copies, as the object changes, so do they.

When you use the New reserved word with Set, you create a new instance of the referenced type.

Example The following example uses the Set statement with New to create a new instance of AcLabelControl:

Function OnLButtonDblClk ( )Dim MyLabel As AcLabelControl, Msg As StringSet MyLabel = New AcLabelControlIf IsKindOf(MyLabel, "AcLabelControl") Then

Msg = "Yes, MyLabel is an AcLabelControl. "Msg = Msg & "We will now set its background color to red."MsgBox MsgMyLabel.BackgroundColor = Red

End IfEnd Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Dim statementNewInstance functionNewPersistentInstance functionReDim statementStatic statement

Page 370: Actuate Basic Reference

346 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

S e t A t t r s t a t e m e n t

SetAttr statementSets attribute information for files.

Syntax SetAttr(<file name>, <attributes>)

Parameters <file name>String expression that specifies the file for which to set one or more attributes.

Default path: Current drive and current directory.

Rules:

■ Cannot include wildcard characters.

■ Must refer to a valid file.

<attributes>Numeric expression that specifies the sum of one or more of the values in the following table, which shows what attribute each value indicates along with its Header.bas constant name. The return values not supported under UNIX are 0.

<file name> can optionally specify a full path, in which case it has the following syntax:

[[<drive:>] [ \ ]<directory>[\<directory>]...<file name> (Windows)

[ /]<directory>[/<directory>]...<file name> (UNIX)

<drive:>Character, followed by a colon, that specifies the drive (Windows only).

<directory>String expression that specifies the name of a directory or subdirectory.

Return value Constant name File type Operating system

0 ATTR_NORMAL Normal Windows, UNIX

1 ATTR_READONLY Read-only Windows, UNIX

2 or 0 ATTR_HIDDEN Hidden Windows

4 or 0 ATTR_SYSTEM System file Windows

32 or 0 ATTR_ARCHIVE Changed since last backup

Windows

Page 371: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 347

S e t A t t r s t a t e m e n t

Example:The following statement sets the System and Read-only (4 + 1) attributes for a file in the current directory called Testfile.dat:

SetAttr("Testfile.dat", 5)

Description The operating system assigns one or more attributes to each file. These attributes indicate whether the file is a normal, read-only, hidden, or system file; whether it has been modified since the last backup; or whether some combination of these is the case. SetAttr lets you modify these attributes.

Rule <file name> can be open for read-only access, but must not be opened for write access.

Tips ■ To determine whether, or in what mode, a file is open, use FileAttr.

■ To determine what attributes of a file, directory, or volume have already been set, use GetAttr.

Example The following example prompts the user for the name of a file. If the Archive attribute for that file is already set, it displays a message; if not, it sets the attribute:

Function OnLButtonDblClk( )Dim FileName As String, Msg As StringOn Error GoTo ErrorHandler

FileName = InputBox("Please type a file name.")If GetAttr(FileName) BAnd ATTR_ARCHIVE Then'Check for Archive attribute

MsgBox "Sorry, " & FileName & " already has the Archive attribute."Else

SetAttr FileName, ATTR_ARCHIVE ' Set Archive attributeMsgBox FileName & " now has the Archive attribute."

End IfExit FunctionErrorHandler:

Msg = "Sorry! An error occurred. Please "Msg = Msg & "check the file name or path and "Msg = Msg & "try again."MsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also FileAttr functionGetAttr function

Page 372: Actuate Basic Reference

348 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

S e t B i n d i n g f u n c t i o n

SetBinding functionEstablishes an alias for an instance variable of a class. SetBinding is used primarily to set up a mapping from database column names to the names of variables in a data row class.

Syntax SetBinding(<instance handle>, <column name>, <variable name>)

Parameters <instance handle>The instance handle to one instance of the class for which to set up the binding.

<column name>The name, usually a column name, to map to a variable.

<variable name>The name of the variable or constant to associate with the column name.

Tip The column name mapped to the column name within a class lets you access variables through their column aliases using GetValue. SetBinding is called automatically for data rows created through the Actuate Query Builder, and you can call SetBinding through custom code for data rows you create manually. When you call SetBinding for a manually created data row, you can insert the calls to SetBinding in the data row’s BuildBinding method. For any other class for which you want to set up bindings, you must call SetBinding at the beginning of your code.

Example The following example assumes you have a database column called Customer.Name. Note the declaration for SetBinding:

Declare Sub SetBinding Lib "Factory" (handle As AnyClass, rname As String, vname As String)

'Using string variables SetBinding(me, myStr1, myStr2 )'Using string constants SetBinding(me, "Customer.Name", "Customer_Name")

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also GetValue function

Page 373: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 349

S e t C l i p b o a r d T e x t f u n c t i o n

SetClipboardText functionPlaces a string expression in the operating environment Clipboard using the specified Clipboard format.

Syntax SetClipboardText(<data>[, <format>])

Parameters <data>String data to be placed on the Clipboard.

<format>One of the following Clipboard formats. If <format> is omitted, CF_TEXT is assumed.

The symbolic constants and their values should be declared in your Actuate Basic code module (.bas file).

Returns Integer

■ Returns 1 (True) if Clipboard text is successfully set.

■ Returns 0 (False) if Clipboard text cannot be set.

Example The following example places the current date on the Clipboard and then displays the contents of the Clipboard:

Function OnLButtonDblClk ( )Dim Msg As String, UserContent, DoMore, Success As IntegerOn Error Resume NextMsg = "The Clipboard currently contains: " & GetClipboardText()MsgBox MsgMsg = "Choose OK to load today's date onto the Clipboard."MsgBox Msg

ClearClipboard()SetClipboardText(Format$(Date, "dddd, mm/dd/yyyy"))Msg = "Today's date is on the Clipboard. Choose OK to get the "Msg = Msg & "date back from the Clipboard and put it in a message."MsgBox Msg

Msg = GetClipboardText()MsgBox "The Clipboard currently contains: " & Msg

Symbolic constant Value Clipboard format

CF_LINK &HBF00 DDE conversation information

CF_TEXT 1 Text

Page 374: Actuate Basic Reference

350 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

S e t D e f a u l t P O S M F i l e f u n c t i o n

DoMore = MsgBox("Put something else on the clipboard?", MB_YESNO)If DoMore = IDNO Then

MsgBox "The date is still on the Clipboard."Else

UserContent = InputBox("Put what?")SetClipboardText(UserContent)

End IfMsgBox "The Clipboard currently contains: " & GetClipboardText( )

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also ClearClipboard functionGetClipboardText function

SetDefaultPOSMFile functionDetermines which open .roi file is used as the default when you call New Persistent() to instantiate an object.

Syntax SetDefaultPOSMFile(<intFileID>)

Parameters <intFileID>Integer. Specifies an open .roi file.

Returns Boolean

■ True, if all arguments are correct.

■ False, if any of the arguments are invalid.

Description Use SetDefaultPOSMFile() in connection with advanced report bursting. For example, you are creating two .roi files simultaneously. Your report scans a set of rows and, depending on the values in a given row, adds the row to one or the other .roi. Use SetDefaultPOSMFile() to switch the default back and forth between the two .roi files.

Rule This function must be called on open report files.

Example The first line of the following code sets the default POSM file to the currently open .roi with the file ID 1. The second line instantiates an object named abc in ROI #1:

SetDefaultPOSMFile(1)Set abc = New Persistent className

See also SetStructuredFileExpiration function

Page 375: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 351

S e t H e a d l i n e s t a t e m e n t

SetHeadline statementSets to a given value the headline associated with the completed request for a report.

Syntax SetHeadline(<newHeadline> [As String])

Parameters <newHeadline>String expression. The text you want the headline to display.

Description Headlines are associated with the completed request for a report, and are visible only in the ReportCast when viewing channels.

By default, the headline is set to the value of the Headline parameter that appears in the Output Options section of the Requester. Use SetHeadline to programmatically change the headline to contain some other text.

Rules ■ GetHeadline and SetHeadline do not work in the Viewer.

■ To change the headline, do not change the Headline parameter itself. Instead, use SetHeadline.

Tip To determine the current headline setting, use GetHeadline.

See also GetHeadline function

SetMessageArguments functionSets the arguments to the GetMessageArgument function.

Syntax Sub SetMessageArguments(aString As String)

Parameters aStringThe string to pass.

Description When you call SetMessageArguments from e.Report Designer Professional, the function sets the arguments to the GetMessageArgument function. When you call SetMessageArguments from the View process, the function does nothing.

SetStructuredFileExpiration functionSets the object aging rules on an .row file.

Syntax SetStructuredFileExpiration(<intFileID>, <intAgingOptions>, <intMaxVers>,

| [ { [Null, <intExpAge>] | [<datExpDate>, Null] } ] )

Page 376: Actuate Basic Reference

352 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

S e t S t r u c t u r e d F i l e E x p i r a t i o n f u n c t i o n

Parameters <intFileID>Integer. Specifies an open .row file.

<intAgingOptions>Integer. Specifies the aging policy. The aging policy is expressed by using the constants from the following table together with a BOR operator.

Example:To create a policy that deletes dependencies and archives before deletion, use code such as the following:

Dim policy As Integerpolicy = Age_ DeleteDependencies BOR Age_ArchiveBeforeDelete

<intMaxVers>Specifies the maximum number of versions to keep. Set this to Null or 0 if no version limit is to be set.

<intExpAge>Integer. Specifies the age, in minutes, after which to expire the object. Set this to Null or 0 if no expiration age is to be set.

<datExpDate>Date. Specifies the date after which to expire the object. Set this to Null if no expiration date is to be set.

Rules:

■ <datExpDate> and <intExpAge> are optional, but if <intExpAge> is provided, <datExpDate> must also be provided, even though it is Null.

■ Only one of <datExpDate> or <intExpAge> should be non-Null. If both are non-Null, only <intExpAge> is used.

Global constant name Value Meaning

Age_NoOptions &H00 No object aging options are to be used.

Age_ArchiveBeforeDelete &H01 Archives the file before deletion. Combine this constant with either a version, date, or age-based expiration.

Age_DeleteDependencies &H02 Deletes dependents for the file. Note that .row files usually do not have dependents. Combine this constant with either a version, date, or age-based expiration.

Page 377: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 353

S e t V a l u e f u n c t i o n

■ It is legal for <intMaxVers>, <datExpDate>, and <intExpAge> to be Null. If all three are Null, no aging policy is set for the file.

Example:

SetStructuredFileExpiration( fileID, Age_NoOptions, Null, Null, Null )

Returns Boolean

■ True, if all arguments are correct.

■ False, if any of the arguments are invalid.

Description You customize object aging settings for a file as follows:

■ Set the values of the object’s aging properties. For example, if you want a report to never archive more than ten versions, set <intMaxVers> to 10.

■ To ensure that a report expires no later than a week after creation, set the age variable, <intExpAge>, or the date expiration variable, <datExpDate>, accordingly.

Rule This function must be called on the open report file.

Example The following code specifies that an .row is to be archived and deleted after thirty minutes.

SetStructuredFileExpiration(fileID, Age_ArchiveBeforeDelete, Null, Null, 30)

See also SetDefaultPOSMFile function

SetValue functionSets the value of a variable in an object dynamically at run-time.

Syntax SetValue(<object reference>, <variable name>|<index>, <value>)

Parameters <object reference>AnyClass expression that specifies an object which has a variable whose value you want to set.

<variable name>String expression that specifies the name of the variable whose value you want to set.

<index>Integer expression that specifies the index of the variable whose value you want to set.

Indexing starts at 1. The index order puts all superclass variables before those defined in a subclass.

Page 378: Actuate Basic Reference

354 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

S e t V a l u e f u n c t i o n

Within a given class, the index order of variables is the order in which the variables are defined in the Actuate Basic source. If e.Report Designer Professional generates the Basic source for a class, it lists the variables in alphabetical order.

<value>Variant. The value to assign.

Description You typically use SetValue in conjunction with GetVariableCount, GetVariableName, GetValue, and GetValueType to work with variables in objects whose types you do not know in advance.

Returns True if the specified variable exists.

False if the specified variable does not exist. It is not an error if the variable does not exist.

Example The following example shows how to use GetVariableCount, GetVariableName, GetValueType, GetValue, and SetValue together.

' Simulate the behavior of the CopyInstance statement,' but only copy integers > 0 whose names begin "Z_"Dim vCount As IntegerDim vName As StringDim vType As IntegerDim vValue As VariantDim i As IntegervCount = GetVariableCount( fromObject )For i = 1 To vCount vName = GetVariableName( fromObject, i ) vType = GetValueType( fromObject, vName ) If (Left( vName, 2 ) = "Z_") And (vType = V_INTEGER) Then vValue = GetValue( fromObject, vName ) If (vValue > 0) Then SetValue( toObject, vName, vValue ) End If End IfNext i

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also GetValue functionGetValueType functionGetVariableCount functionGetVariableName function

Page 379: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 355

S e t V S T e m p F i l e f u n c t i o n

SetVSTempFile functionSets the name of the temporary file to which the Excel file is to be written.

Syntax Sub SetVSTempFileName()

Description When called from e.Report Designer Professional, SetVSTempFileName sets the name of the temporary file to which the Excel file is to be written. When called from the View process, SetVSTempFileName does nothing.

Sgn functionIndicates whether a number is positive, negative, or zero.

Syntax Sgn(<number>)

Parameters <number>Number, numeric expression, or Variant of VarType 8 (String) that specifies the number for which you want to determine the sign.

Returns Same data type as <number>. If <number> is a Variant of type 8 (String), returns Variant of type 5 (Double). Returns one of the following numbers indicating whether <number> is positive, negative, or zero.

Example The following example tells whether a given number is positive, negative, or zero:

Function OnLButtonDblClk( )Dim Number As Double, Msg As StringNumber = InputBox("Please type a number.")Select Case Sgn(Number)

Case 0Msg = "That is zero."

Case 1Msg = "That is a positive number."

Case -1Msg = "That is a negative number."

End SelectMsgBox Msg

End Function

Return value Description

1 Positive number

-1 Negative number

0 Zero

Page 380: Actuate Basic Reference

356 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

S h e l l f u n c t i o n

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Abs function

Shell functionRuns a specified executable program.

Syntax Shell(<program name and parameters> [, <window style>] )

Parameters <program name and parameters>String expression containing a valid executable name. Name of the program to execute, with its required arguments or command line switches, if there are any.

Default file extension under Windows: .exe.

Rules:

■ Must have an extension of .exe, .com, .bat, or .pif (Windows).

■ Must have execute permission set (UNIX).

■ Must be enclosed within quotes.

■ If the executable is not located in the default directory:■ Program name must include the full path.■ Program must be located in a directory specified in the PATH

environment variable.

Example:Each of the following examples runs the Windows calculator and then immediately executes the next statement in the program, whether or not Calc.exe has terminated:

DummyVar = Shell("Calc.exe")

X = Shell("C:\Windows\Calc.exe")

The following example opens Excel and the file Extract.csv at the same time:

Shell( "D:\Program Files\Microsoft Office\Office\Excel.exe C:\Temp\Extract.csv" )

Page 381: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 357

S h e l l f u n c t i o n

<window style> ignored on UNIX systemsInteger that specifies the number for the style of the window to use for the new program, and whether or not to give it the focus. The following table identifies each possible value for <window style> and the resulting style and focus of the window.

Default if omitted: 2.

Example:The following example calls Word for Windows, maximizes its window, and gives it focus:

Z = Shell("C:\Word\Winword.exe", 3)

Returns Integer

■ Shell loads an executable file into the Windows environment, and returns the unique task ID number that Windows assigns to each running program as its identifier (Windows).

■ Shell runs programs asynchronously. You cannot be certain whether or not a program you start with Shell will finish executing before the code following the Shell function in your Actuate Basic application is executed.

■ If Shell cannot start the named program, it generates an error.

Rule You cannot use Shell on Windows NT Server to run a Windows application unless:

■ Your program has been allowed to interact with the desktop, and

■ Your program invokes Shell from the System account.

Tips ■ To shell to DOS—in other words, to run the DOS command processor—specify the program name Command.com with Shell (Windows).

■ To enjoy greater flexibility and exercise better control over the behavior of external programs, use an OLE technique rather than Shell (Windows).

Example In the following Windows example, Shell runs the Windows Calculator. The next statement in the program is then executed immediately, whether or not Calc.exe has terminated.

Value Window style Focus

1, 5, 9 Normal New program receives

2 Minimized New program receives

3 Maximized New program receives

4, 8 Normal Current program retains

6, 7 Minimized Current program retains

Page 382: Actuate Basic Reference

358 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

S h o w F a c t o r y S t a t u s s t a t e m e n t

Function OnLButtonDblClk( )Dim DummyVarDummyVar = Shell("C:\Windows\Calc.exe", 6)MsgBox "Calculator opened and minimized, without focus."

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

ShowFactoryStatus statementInstructs e.Report Designer Professional to display a comment in the status line of the Factory dialog box when you generate a report. Excessive use of ShowFactoryStatus causes request server memory growth.

Syntax ShowFactoryStatus(<StatusMsg>)

Parameters <StatusMsg>String you want to display in the status line of the Factory dialog box.

Example:

ShowFactoryStatus("Preparing the statement.")

Example The following code shows how you might use ShowFactoryStatus.

To try this example, override the DataStream’s OpenCursor() method, and paste the following code in the Method Editor window:

Sub OpenCursor( stmtText As String )

Dim stmtAs AcDBStatement

Assert( Cursor Is Nothing )' Prepare the statementSet stmt = New AcDBStatement( GetDBConnection( ) )ShowFactoryStatus("Got a handle for the statement.")

If Not stmt.Prepare( stmtText ) ThenGetDBConnection( ).RaiseError( )

End IfShowFactoryStatus("Preparing the statement.")

' Create a cursor for the statement.Set Cursor = New AcDBCursor( stmt )ShowFactoryStatus("Got a handle for the cursor.")

' Now we must bind any static parameters which may be presentBindStaticParameters( Cursor )

Page 383: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 359

S i n f u n c t i o n

ShowFactoryStatus("Binding static parameters")

' Open the CursorIf Not Cursor.OpenCursor( )Then

GetDBConnection( ).RaiseError( )Set Cursor = Nothing

End IfShowFactoryStatus("opening the cursor")

' Bind the data row class variables to the output row of the cursorBindDataRow( Cursor )ShowFactoryStatus("Binding datarow.")

End Sub

For information about using the code examples, see “Using the code examples” earlier in this chapter.

Sin functionGives the sine of an angle.

Syntax Sin(<angle>)

Parameters <angle>Number, numeric expression, or Variant of type 8 (String) that specifies, in radians, the angle for which you want to find the sine.

Rule: If <angle> is a String, it is parsed according to the formatting rules of the current run time locale.

Returns Double

■ If <number> evaluates to Null, Sin returns a Null.

Example The following example prompts the user for an angle expressed in radians and returns the sine of the angle:

Function OnLButtonDblClk( )Dim UserTypedUserTyped = InputBox("Type a number representing an angle in radians.")MsgBox "The sine of " & UserTyped & " is: " & Sin(UserTyped)

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Atn functionCos functionTan function

Page 384: Actuate Basic Reference

360 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

S l e e p s t a t e m e n t

Sleep statementTemporarily suspends report execution.

Syntax Sleep(<seconds>)

Parameters <seconds>Double expression that specifies the number of seconds to suspend report execution. The value must be in the range 0 – 600. The value can be a fraction, for example 0.5.

Description You can use Sleep to suspend execution while waiting for an external event, for example a file being created. The timing accuracy of Sleep is dependent on the underlying operating system.

Tip Shell commands run asynchronously. This means that a report continues to execute as soon as a Shell command is started. To wait for the result of a Shell command, make the Shell command create a file when it is done, then looparound checking whether that file exists. Use Sleep inside the loop to avoid extra processor cycles.

Example ' Run a script and wait for it to create a file' Remove previous file, if any If FileExists( "myfile.txt" ) Then

Kill "myfile.txt"End If

' Run the script Shell("myscript.bat")

' Wait for the file to appear Dim startTime As Date startTime = Now( )

Do ' Check for file If FileExists( "myfile.txt" ) Then Exit Do End If

' Timeout after 60 seconds If (DateDiff( "s", startTime, Now( ) ) > 60) Then Error 9999, "Time out!" End If

' Wait a while and try again

Page 385: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 361

S L N f u n c t i o n

Sleep( 2.5 ) Loop

' Now we can use the file

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Shell function

SLN functionReturns the straight-line depreciation of an asset for a single period.

Syntax SLN(<initial cost>, <salvage value>, <asset lifespan>)

Parameters <initial cost>Numeric expression that specifies the initial cost of the asset.

<salvage value>Numeric expression that specifies the value of the asset at the end of its useful life. You can type a salvage value to view the straight line depreciation offset by the salvage value, or return straight line depreciation without salvage value by entering 0 in salvage value.

<asset lifespan>Numeric expression that specifies the length of the useful life of the asset.

Rule for <asset lifespan>: Must be given in the same units of measure you want the function to return. For example, if you want SLN to determine the annual depreciation of the asset, <asset lifespan> must be given in years.

Examples:The following example calculates the depreciation under the straight-line method for a new machine purchased at $1400, with a salvage value of $200, and a useful life estimated at 10 years. The result ($120 annually) is assigned to AnnualDeprec:

AnnualDeprec = SLN(1400, 200, 10)

Returns Double

Straight-line depreciation is the oldest and simplest method of depreciating a fixed asset. It uses the book value of the asset less its estimated residual value, and allocates the difference equally to each period of the asset's life. Such procedures are used to arrive at a uniform annual depreciation expense that is charged against income before calculating income taxes.

Page 386: Actuate Basic Reference

362 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

S p a c e , S p a c e $ f u n c t i o n s

Rule All arguments must be positive numbers.

Example The following example prompts the user for various particulars about an asset, then returns the asset’s straight-line depreciation for any single period. To use this example, paste the first portion at or near the beginning of your Actuate Basic source code (.bas) file; then paste the procedure into the OnLButtonDblClk( ) method for a clickable component such as a label.

DeclareGlobal Const YEARMONTHS = 12 ' Number of months in a year

End Declare' Function OnLButtonDblClk ( )

Dim Fmt As String, InitCost As Double, SalvageVal As DoubleDim MonthLife As Double, LifeSpan As Double, PerDepr As Double

Fmt = "$###,##0.00" ' Define money formatInitCost = InputBox("What is the initial cost of the asset?")SalvageVal = InputBox("What is the asset's value at useful life end?")MonthLife = InputBox("What is the asset's useful life in months?")

Do While MonthLife < YEARMONTHS ' Ensure period is >= 1 yearMsgBox "Sorry, asset life must be a year or more."MonthLife = InputBox("What is the asset's useful life in months?")

Loop

LifeSpan = MonthLife / YEARMONTHS ' Convert months to yearsIf LifeSpan <> Int(MonthLife / YEARMONTHS) Then

LifeSpan = Int(LifeSpan + 1) ' Round up to nearest yearEnd IfPerDepr = SLN(InitCost, SalvageVal, LifeSpan)MsgBox "The depreciation is " & Format(PerDepr, Fmt) & " per year."

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also DDB functionSYD function

Space, Space$ functionsReturns a string consisting of the specified number of spaces.

Syntax Space(<number of spaces>)

Space$(<number of spaces>)

Page 387: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 363

S q r f u n c t i o n

Parameters <number of spaces>Numeric expression indicating the length of the returned string of spaces.

Rules:

■ Must be between 0 and 2,147,483,647 or memory limit.

■ The <number of spaces> is rounded to Long regardless of its numeric data type.

Returns Space: VariantSpace$: String

Tip To generate a string of characters other than spaces, use String[$].

Example The following example creates a variable containing 10 spaces:

Function OnLButtonDblClk ( )Dim NL, Msg, Pad, UserFname, UserLnameNL = Chr(10)

UserFname = InputBox("Please type your first name.")UserLname = InputBox("Please type your last name.")' Create 10-space padPad = Space(10)Msg = "Notice the 10-space pad between your first "Msg = Msg & "and last names. " & NL & NLMsg = Msg & UserFname & Pad & UserLnameMsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also String, String$ functions

Sqr functionGives the square root of a number.

Syntax Sqr(<number>)

Parameters <number>Number, numeric expression, or Variant of type 8 (String) indicating the number for which you want to determine the square root.

Rule: If a String, it is parsed according to the formatting rules of the current run time locale.

Page 388: Actuate Basic Reference

364 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

S t a t i c s t a t e m e n t

Returns Double

■ If <number> evaluates to Null, Sqr returns a Null.

Example The following example prompts the user for a number and returns the square root of that number:

Function OnLButtonDblClk( )On Error GoTo ErrorHandlerDim UserTyped, MsgUserTyped = InputBox("Please type a number.")MsgBox "The square root of " & UserTyped & " is: " & Sqr(UserTyped)Exit FunctionErrorHandler:

Msg = "Sorry! An error occurred. Please try again."MsgBox MsgResume Next

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

Static statementDeclares a static variable or static procedure.

Syntax Static <variable name> [([<subscripts>])] [As <type>] [, <variable name> [([<subscripts>])] [As <type>]]...

- or -

Static <procedure name>

Parameters <variable name>Name you create for the new variable.

<procedure name>Name you create for the new procedure. When you use the syntax Static <procedure name>, all the variables in <procedure name> are declared to be static.

<subscripts>The dimensions of an array variable.

Subscript syntax

[<lower> To] <upper>[,[<lower> To] <upper>]...

Page 389: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 365

S t a t i c s t a t e m e n t

Rule: <lower> and <upper> can range from -2,147,483,648 to 2,147,483,647, inclusive.

Examples:The following two statements have the same effect. Both declare a two-dimensional array that contains 11 elements in its first dimension, and 6 elements in its second:

Static MEM(10, 5)Static MEM(0 TO 10, 0 TO 5)

As <type>Clause in which you specify a data type for the new variable.

Default: Variant or the data type specified by the type declaration character appended to <variable name>, if there is one.

Description Static variables retain their values as long as the program is running, unlike local variables, which are cleared when the procedure ends. This does not mean, however, that you can access them from outside the procedure. Every time you execute the procedure in which the static variables are declared, the procedure can make use of and update the most recent values of those variables. Whatever changes it makes are preserved until the next time you call the procedure.

Rules ■ To declare a fixed-size array in a nonstatic procedure, you must use Static.

■ Use Static at the procedure level.

Tip To retain the values of all the variables in a procedure, you do not have to declare each one individually as Static, or list each one on a Static declaration line. Instead, use Static <procedure name> to declare the procedure itself.

Example:

Static Sub MyProcedure

Example In the following example, the value of the variable Accumulate is preserved between calls to the Sub procedure. Each time the procedure is called, it prompts the user to add to the Accumulate variable. Then it displays the accumulated value:

Function OnLButtonDblClk ( )Static Accumulate As DoubleAccumulate = Accumulate + InputBox("Add what number? ")MsgBox "The static variable now has the following value: " & Accumulate

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

Page 390: Actuate Basic Reference

366 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

S t o p s t a t e m e n t

See also Dim statementFunction...End Function statementSub...End Sub statement

Stop statementSuspends execution of the running Actuate Basic code.

Syntax Stop

Description ■ Unlike End, Stop does not close files or clear variables.

■ To continue a program suspended by Stop, choose Debug➛Continue, or press F5.

Tip You can place Stop anywhere in procedures to suspend program execution. It is useful as a debugging aid.

Example In the following example, for each step through the For...Next loop, Stop suspends execution. To resume program execution, choose Debug➛Continue:

Function OnLButtonDblClk ( )Dim I As IntegerFor I = 1 To 10 ' Begin For...Next loop

MsgBox I ' Show I Stop ' Stop each time through loop

Next IEnd Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also End statement

Str, Str$ functionsConverts a numeric expression to a String.

Syntax Str(<numeric expression>)

Str$(<numeric expression>)

Parameters <numeric expression>Numeric expression to be converted to a String.

Page 391: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 367

S t r , S t r $ f u n c t i o n s

Rule: If a String, it is parsed according to the formatting rules of the current run time locale.

Examples:The following statements are equivalent. Each returns Customer 55:

"Customer" & Str$(55)"Customer" & Str$(110/2)

The following statement returns 123.456 on a French run time locale and 123456.00 on an English run time locale:

Str("123,456")

Returns Str: VariantStr$: String

■ If <numeric expression> is positive, Str[$] precedes the string representation of the number with a leading space.

■ If < numeric expression> is negative, Str[$] precedes the string representation of the number with a minus sign instead of a leading space.

Tips ■ To put the results of a calculation into a message for the user and avoid generating a Data Type Mismatch error, use Str[$].

■ To convert numeric values you want rendered in currency, date, time, or user-defined formats, use Format[$] instead of Str[$].

■ To convert a String to a number, use Val.

Example The following example returns a string representation of the values contained in two variables. A space precedes the first string character in each case because the numbers are positive:

Function OnLButtonDblClk ( )Dim Dice1, Dice2, MsgRandomize ' Seed random num generatorDice1 = Int(6 * Rnd + 1) ' Generate first valueDice2 = Int(6 * Rnd + 1) ' Generate second valueMsg = "You first rolled a " & Str$(Dice1)Msg = Msg & " and then a " & Str$(Dice2)Msg = Msg & " for a total of "Msg = Msg & Str$(Dice1 + Dice2) & "."MsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Format, Format$ functionsVal function

Page 392: Actuate Basic Reference

368 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

S t r C o m p f u n c t i o n

StrComp functionCompares two strings and returns a Variant indicating the result.

Syntax StrComp(<string exprs 1>, <string exprs 2>[,<compare method>])

Parameters <string exprs 1>, <string exprs 2>Any string expression. Whether the underlying data type is Variant or String, each expression is first converted to a Variant before the arguments are compared.

<compare method>Numeric expression that indicates whether <compare method> is case sensitive or insensitive.

Default: 0, unless you used Option Compare Text in the module.

Rule: Must be 0 or 1.

Example:

■ When <compare method> is case-sensitive (0), McManus does not match MCMANUS or McMANUS.

■ When <compare method> is case-insensitive (1) McManus matches MCMANUS or McMANUS.

Returns Variant

StrComp returns a Variant that reports the relationship between the two string expressions. The following table illustrates each possible return value and the relationship or condition it signifies.

Value String comparison Similar to

0 Case-sensitive Option Compare Binary

1 Case-insensitive Option Compare Text

Return value Relationship or condition

-1 <string exprs 1> is less than <string exprs 2>

0 <string exprs 1> = <string exprs 2>

1 <string exprs 1> is greater than <string exprs 2>

Null <string exprs 1> = Null or <string exprs 2> = Null

Page 393: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 369

S t r C o m p f u n c t i o n

Example The following example prompts for two strings and for the comparison method to use when comparing them. Then it returns the result of the comparison along with a short explanation:

Function OnLButtonDblClk()Dim Comp, CompMethod, Msg As StringDim String1 As String, String2 As String, Desc As String

String1 = InputBox("Type a customer’s name.")String2 = InputBox("Type the same name, or a different one if you like.")CompMethod = InputBox("Use which comparison method? Type 0 or 1.")

If CompMethod <> 0 And CompMethod <> 1 ThenMsgBox "You did not type 0 or 1 so CompMethod is case sensitive."CompMethod = 0

End IfSelect Case CompMethod

Case 0Desc = "case sensitive."

Case 1Desc = "NOT case sensitive."

End SelectComp = StrComp(String1, String2, CompMethod)Select Case Comp

Case -1Msg = String1 & " is less than " & String2Msg = Msg & " for compare method " & CompMethodMsg = Msg & ", which is " & Desc

Case 0Msg = String1 & " is equal to " & String2Msg = Msg & " for compare method " & CompMethodMsg = Msg & ", which is " & Desc

Case 1Msg = String1 & " is greater than " & String2Msg = Msg & " for compare method " & CompMethodMsg = Msg & ", which is " & Desc

End SelectMsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Option Compare statement

Page 394: Actuate Basic Reference

370 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

S t r i n g , S t r i n g $ f u n c t i o n s

String, String$ functionsReturns a string consisting of a specified character repeated a specified number of times.

Syntax String(<number of characters>,<char to repeat>)

String$(<number of characters>,<character code number>)

Parameters <number of characters>Numeric expression that specifies the number of times the character is to be repeated.

Rule: Must be between 0 and 2,147,483,647.

<char to repeat>String expression that specifies the character to repeat.

Rules:

■ If <char to repeat> is longer than one character, only the first character is repeated.

■ If <char to repeat> is a Variant of any numeric type, String[$] interprets the numeric value as the ANSI code for the repeated character.

Default: If longer than one character, only the first character is used.

<character code number>Numeric expression that specifies the ANSI code for the repeated character.

Rules:

■ <character code number> must not be Null.

■ <character code number> must be between 0 and 65535.

■ <character code number> is interpreted as a value in the code page corresponding to the current run time encoding.

■ If < character code number> is a Variant of any numeric type, String[$] interprets the numeric value as the ANSI code for the repeated character.

Examples:

String$(5, 64) returns AAAAA String$(5,227) returns γγγγγ on a Greek localeString$(5, 227) returns äääää on an English locale

Returns String: VariantString$: String

Page 395: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 371

S t r i n g W , S t r i n g W $ f u n c t i o n s

Tips ■ To generate a string of spaces, use Space[$].

■ If the run time encoding is UCS-2, String behaves in the same way as StringW.

Example The following example returns a string consisting of 12 number signs (#) followed by a sample check amount. The ANSI code of the number sign character is 35:

Function OnLButtonDblClk ( )Dim Msg As String, NL As StringNL = Chr(10) ' Define newline

Msg = "This generates two strings of 12 number signs, " & NLMsg = Msg & "followed by a sample check amount. " & NL & NLMsg = Msg & "Both forms of String$ syntax are illustrated. " & NLMsg = Msg & NL & "First Form: " & String$(12, "#") & "$100.00" & NLMsg = Msg & "Second Form: " & String$(12, 35) & "$100.00" & NL & NLMsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Space, Space$ functionsStringW, StringW$ functions

StringW, StringW$ functionsReturns a string consisting of a specified character in UCS-2 character set repeated a specified number of times.

Syntax StringW(<number of characters>,<char to repeat>)

StringW$(<number of characters>,<character code number>)

Parameters <number of characters>Numeric expression that specifies the number of times the character is to be repeated.

Rule: Must be between 0 and 2,147,483,647.

<char to repeat>String expression that specifies the character to repeat.

Rules:

■ If <char to repeat> is longer than one character, only the first character is repeated.

Page 396: Actuate Basic Reference

372 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

S t r L o a d , S t r L o a d $ f u n c t i o n s

■ If <char to repeat> is a Variant of any numeric type, String[$] interprets the numeric value as the ANSI code for the repeated character.

<character code number>Numeric expression that specifies the UCS-2 code for the repeated character.

Rules:

■ <character code number> must not be Null.

■ <character code number> must be between 0 and 65535.

■ If <character code number> is a Variant of any numeric type, String[$] interprets the numeric value as the UCS-2 code for the repeated character.

Examples:The following statement returns ##########.

StringW$(10,"#")

The following statement returns γγγγγγγγγγ

StringW$(10,947)

Returns String

Example The following example returns a string consisting of 12 number signs (#) followed by a sample check amount. The ANSI code of the number sign character is 35:

Function OnLButtonDblClk ( )Dim Msg As String, NL As StringNL = ChrW(10) ' Define newline

Msg = "This generates two strings of 12 number signs, " & NLMsg = Msg & "followed by a sample check amount. " & NL & NLMsg = Msg & "Both forms of StringW$ syntax are illustrated. " & NLMsg = Msg & NL & "First Form: " & StringW$(12, "#") & "$100.00" & NLMsg = Msg & "Second Form: " & StringW$(12, 35) & "$100.00" & NL & NLMsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

StrLoad, StrLoad$ functionsRetrieves the string specified by the <id>.

Syntax StrLoad(<id>)

StrLoad$(<id>)

Page 397: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 373

S t r S u b s t f u n c t i o n

Parameters <id>Numeric expression to associated with a string. The string is in a resource file attached to the executable file.

Returns StrLoad: VariantStrLoad$: String

Rule: If <id> evaluates to Null, StrLoad[$] returns a Null.

StrSubst functionReplaces part of a string with a different substring and returns the result.

Syntax StrSubst(<strTarget>, <strToFind>, <strNew>)

Parameters <strTarget>String expression. The string within which you want to locate <strToFind>.

<strToFind>String expression. The string you want to locate within <strTarget> so you can replace it with <strNew>.

<strNew>String expression. The new substring within <strTarget> that you want in place of <strToFind>.

Returns String

<strTarget>, but with substring <strNew> in place of <strToFind>.

If <strToFind> does not exist within <strTarget>, Actuate returns <strTarget> unchanged.

See also InStr functionMid, Mid$ statements

Sub...End Sub statementDeclares and defines the name, code, and any arguments that constitute an Actuate Basic Sub procedure.

Syntax [Static] Sub <name of procedure> [(<list of arguments>)]

[<statements>]

[Exit Sub]

Page 398: Actuate Basic Reference

374 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

S u b . . . E n d S u b s t a t e m e n t

[<statements>]

End Sub

Parameters StaticKeyword that instructs Actuate Basic to preserve the values of the procedure's local variables between calls.

Rules:

■ Cannot use Static to affect variables declared outside the procedure.

■ Avoid using Static in recursive Sub procedures.

<name of procedure>The name you assign to the procedure.

Rules for <name of procedure>:

■ Subject to the same constraints as variable names, as well as to the following additional constraints:■ Cannot include a type declaration character.■ Cannot be the same as any other globally recognized name like that of:

- Procedure in a declared dynamic-link library (DLL).- Any Global variable.- Any Global constant.

■ Can be overloaded. That is, you can define another function and/or procedure that has the same name, as long as the respective arguments are unique. For example, the following are both permissible in the same program:

Sub Potato(intTomato As Integer)..End SubSub Potato(intTomato As Double)..End Sub

<list of arguments>The list of variables that Actuate Basic passes as arguments from the calling procedure to the Sub procedure.

<statements>One or more valid Actuate Basic statements. These statements constitute the body of the Sub procedure.

Exit SubStatement that signals Actuate Basic to terminate the Sub procedure and transfer control to the statement following the one that called the procedure.

Page 399: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 375

S u b . . . E n d S u b s t a t e m e n t

You may use as many Exit Sub statements as you wish, anywhere in a Sub procedure.

<list of arguments> has the following syntax:

[ByVal] <variable name>[( )] [As <data type>] [,[ByVal] <variable name>[( )] [As <data type>]...

ByValKeyword that instructs Actuate Basic to pass the argument to the procedure by value rather than by reference. This means that the changes the Sub makes to the argument variable have no effect on its value in the calling procedure.

Rule: Cannot be used with a variable of user-defined type, class, or with an array variable.

<variable name>Name of the variable to pass as an argument.

If the Sub procedure changes the value of <variable name> internally, then it also changes its value externally—that is, in the procedure that called the Sub.

Rules:

■ You must use the ByVal keyword if you do not want the Sub’s changes to an argument variable to affect the variable's value in the calling procedure.

■ For array variables, use the parentheses but omit the number of dimensions.

Example:The following statement calls a Sub procedure named SalesTax and passes to it as its argument an array variable previously declared as MyArray(50,72):

SalesTax MyArray( )

As <data type>Clause that declares the data type of <variable name>.

Rule: <data type> can specify any valid Actuate Basic or user-defined data type except a fixed-length string:

Example:

SalesTax Customer As String, Amount As Currency

Description Like a Function procedure, a Sub procedure can take arguments, execute a series of statements, and change the values of its arguments. However, unlike a Function procedure, a Sub procedure does not return a value directly and cannot be used in an expression.

You can use the same name for two or more different procedures, as long as you make sure the procedures take a different number of arguments, or that the arguments are of different data types. For example, you can write two

Page 400: Actuate Basic Reference

376 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

S u b . . . E n d S u b s t a t e m e n t

different square root functions - one that operates on integers, and another that operates on doubles. Their respective first lines might look like the following:

Function SquareRoot(intParam As Integer) As Integer

Function SquareRoot(dblParam As Double) As Double

Actuate Basic knows which procedure you mean by the type of value you pass when you call the procedure. For instance, if you write a call to SquareRoot(5), the compiler chooses the first SquareRoot function. But if you call SquareRoot(5.1234567), or SquareRoot(5.000), it executes the second one.

Rules ■ You cannot define a Sub procedure from within another Sub procedure.

■ You cannot use a Sub procedure in an expression, as you can a Function procedure.

■ You cannot use GoTo to enter or exit a Sub procedure.

Tips ■ Sub procedures can be recursive. Actuate Basic sets a run-time stack limit of 200. A report using recursion with a large number of iterations might exceed this limit.

■ To evaluate a certain condition and then determine whether or not the Sub procedure should continue, use Exit Sub within a conditional structure such as If Then.

■ See Call for further information on how to call Sub procedures.

Example The following example declares two Sub procedures. The first one calls the second. In this example OnLButtonDblClk( ) is overridden to prompt the user to enter the data. The procedure SalesTax( ) should be typed after the End Function of the OnLButtonDblClk( ) procedure or saved in an Actuate Basic source code (.bas) file:

Function OnLButtonDblClk ( )Dim PassThisArg1 As Double, PassThisArg2 As DoublePassThisArg1 = InputBox("What is the amount of the sale?")PassThisArg2 = InputBox("What is the tax rate,expressed as a decimal?")SalesTax(PassThisArg1, PassThisArg2)

End Function

Sub SalesTax (Arg1, Arg2)Dim LocalVarLocalVar = Arg1 * Arg2MsgBox "The sales tax is: " & Format$(LocalVar, "$#,###.00")

End Sub

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Call statementDim statement

Page 401: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 377

S Y D f u n c t i o n

Function...End Function statementStatic statement

SYD functionReturns sum-of-years’-digits depreciation of an asset for a specified period.

Syntax SYD(<initial cost>, <salvage value>, <asset lifespan>, <single period>)

Parameters <initial cost>Numeric expression that specifies the initial cost of the asset.

<salvage value>Numeric expression that specifies the value of the asset at the end of its useful life.

<asset lifespan>Numeric expression that specifies the length of the useful life of the asset.

Rule for <asset lifespan>: Must be given in the same units of measure as <single period>. For example, if <single period> represents a month, then <asset lifespan> must be expressed in months.

<single period>Numeric expression that specifies the period for which you want SYD to calculate the depreciation.

Rule for <single period>: Must be given in the same units of measure as <asset lifespan>. For example, if <asset lifespan> is expressed in months, then <single period> must represent a period of one month.

Examples:The following example calculates the depreciation for the first year under the sum-of-years’-digits method for a new machine purchased at $1400, with a salvage value of $200, and a useful life estimated at 10 years. The result, $218.18, is assigned to Year1Deprec. You may wish to note (a) that this result is equivalent to 10/55 * $1,200; (b) that 55 = 10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1; and (c) that 10 is the 1st (Year 1) term in this series of digits:

Year1Deprec = SYD(1400, 200, 10, 1)

The following example calculates the depreciation of the same asset for the second year of its useful life. The result, $196.36, is assigned to Year2Deprec. You may wish to note (a) that this result is equivalent to 9/55 * $1,200; (b) that 55 = 10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1; and (c) that 9 is the 2nd (Year 2) term in this series of digits:

Year2Deprec = SYD(1400, 200, 10, 2)

Returns Double

Page 402: Actuate Basic Reference

378 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

S Y D f u n c t i o n

Sum-of-years’-digits is an accelerated method of depreciation that results in higher depreciation charges and greater tax savings in the earlier years of the useful life of a fixed asset than are given by the straight-line depreciation method (SLN), where charges are uniform throughout.

The method bases depreciation on an inverted scale of the total of digits for the years of useful life. For instance, if the asset’s useful life is 4 years, the digits 4, 3, 2, and 1 are added together to produce 10. SYD for the first year then becomes 4/10ths of the depreciable cost of the asset (cost less salvage value). The rate for the second year becomes 3/10ths, and so on.

Rules ■ <asset lifespan> and <single period> must both be expressed in terms of the same units of time.

■ All arguments must be positive numbers.

Example The following example prompts the user for various particulars about an asset, then returns the asset’s sum-of-years’-digits depreciation for any single period. To use this example, paste the first portion at or near the beginning of your Actuate Basic source code (.bas) file. Then paste the procedure into the OnLButtonDblClk( ) method for a clickable component such as a label:

DeclareGlobal Const YEARMONTHS = 12 ' Number of months in a year

End Declare'Function OnLButtonDblClk ( )

Dim Fmt As String, InitCost As Double, SalvageVal As DoubleDim MonthLife As Double, LifeSpan As Double, DepYear As DoubleDim PeriodDepr As Double, Msg As String

Fmt = "###,##0.00" ' Define money formatInitCost = InputBox("What is the initial cost of the asset?")SalvageVal = InputBox("What is the asset's value at the end of its life?")MonthLife = InputBox("What is the asset's useful life in months?")

Do While MonthLife < YEARMONTHS ' Ensure period is >= 1 yearMsgBox "Asset life must be a year or more."MonthLife = InputBox("What is the asset's useful life in months?")

Loop

LifeSpan = MonthLife / YEARMONTHS ' Convert months to yearsIf LifeSpan <> Int(MonthLife / YEARMONTHS) Then

LifeSpan = Int(LifeSpan + 1) ' Round up to nearest yearEnd IfDepYear = CInt(InputBox("For which year do you want depreciation?"))Do While DepYear < 1 Or DepYear > LifeSpan

MsgBox "You must enter at least one but not more than " & LifeSpan

Page 403: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 379

T a b f u n c t i o n

DepYear = CInt(InputBox("For what year do you want depreciation?"))LoopPeriodDepr = SYD(InitCost, SalvageVal, LifeSpan, DepYear)Msg = "The depreciation for year " & DepYear & " is "Msg = Msg & Format(PeriodDepr, Fmt) & "."MsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also DDB functionSLN function

Tab functionSpecifies the columnar position at which the next character is to print.

Syntax Tab(<column>)

Parameters <column>Integer expression. Specifies the column at which printing is to continue.

Example:The following statements open a file and use Tab to move the print position to column 40 in an output data file:

Open "Test.fil" For Output As #1Print #1, "Here is a test of the "; Tab(40); "Tab function."Close #1

Description■ The leftmost print position on an output line is always 1.

■ When you use Print # to print to files, the rightmost print position is the current width of the output file, which you can set using Width #.

■ When you use Tabs without separators, the semicolon (;) separator is assumed by default.

■ There is no simple correlation between the number of characters printed and the number of fixed-width columns they occupy. For example, the uppercase letter W occupies more than one fixed-width column.

Page 404: Actuate Basic Reference

380 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

T a b f u n c t i o n

■ The following table describes Tab behavior.

Rule You can use Tab only with the Print # statement.

Tips ■ To accommodate wider letters, make sure your tabular columns are wide enough.

■ To set the width of the output file, use Width #.

Example The following example uses the Tab function to move the print position to column 40 in an output data file:

Function OnLButtonDblClk ( )Dim Msg'Create sample fileOpen "Test.fil" For Output As #1Print #1, "This is a test of the "; Tab(40); "Tab function."'Close fileClose #1'Reopen test file for inputOpen "Test.fil" For Input As #1'Read test dataInput #1, Msg'Close fileClose #1MsgBox Msg'Delete test fileKill "Test.fil"

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

If: Then Tab:

The current print position on the current line is greater than <column>.

Skips to <column> on the next output line and continues printing there.

<column> is greater than the output-line width (set by Width #).

Calculates <print position> = <column> Mod <width>.

<column> is less than the current print position.

Continues printing on the next line at the calculated print position.

<column> is less than 1. Moves the print position to column 1.

The calculated print position is greater than the current printposition.

Continues printing at the calculated print position on the same line, as expected.

Page 405: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 381

T a n f u n c t i o n

See also Print # statement

Tan functionReturns the tangent of an angle.

Syntax Tan(<angle>)

Parameters <angle>Number, numeric expression, or Variant of type 8 (String) that specifies, in radians, the angle for which you want to find the tangent.

Rule: If a String, it is parsed according to the formatting rules of the current run time locale.

Returns Double

■ If <angle> evaluates to Null, Tan returns a Null.

Tips ■ To find the cotangent of an angle, use: Cotangent = 1/Tan.

■ To convert between radians and degrees, use: radians = degrees * Pi/180.

Example The following example prompts the user for an angle expressed in radians and returns the tangent of the angle:

Function OnLButtonDblClk( )Dim UserTypedUserTyped = InputBox ("Type a number representing an angle in radians.")MsgBox "The tangent of " & UserTyped & " is: " & Tan(UserTyped)

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Atn functionCos functionSin function

Time, Time$ functionsReturns the current system time.

Syntax Time[()]

Time$[()]

Page 406: Actuate Basic Reference

382 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

T i m e r f u n c t i o n

Example:The following statement assigns the current system time to a variable:

CurrTime = Time

Returns Time: VariantTime$: String

■ Time returns a Variant of type 7 (Date) that contains a time stored internally as the fractional part of a double-precision number.

■ Time$ returns an 8-character string of the form hh:nn:ss, where hh represents the hour (00-23), nn the minute (00-59), and ss the second (00-59). The function uses a 24-hour clock, so 8:00 P.M. appears as 20:00:00.

■ The return value of Time$ is equivalent to that of the following statement:

Format$(Now, "hh:nn:ss")

Example The following example selects a lucky number for the user that is based on the exact time the user calls the routine. This number ranges from 1 to 48:

Function OnLButtonDblClk( )Dim CurrTime, Msg, UserUniv, PowerUp, ChoiceCurrTime = TimeUserUniv = 48

PowerUp = CurrTime * 10000000Choice = (PowerUp Mod UserUniv) + 1Msg = "Your lucky number, based on the "Msg = Msg & "exact time of day is: " & ChoiceMsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also CVDate functionDate, Date$ functionsFormat, Format$ functionsNow function

Timer functionReturns the number of seconds that have elapsed since midnight of the current day.

Syntax Timer

Page 407: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 383

T i m e S e r i a l f u n c t i o n

Example:The following statements use the Timer function to determine how long it takes the procedure TestRoutine to execute:

StartTime = TimerCall TestRoutineEndTime = TimerTimeElapsed = EndTime - StartTime

Returns Double

Tips ■ Timer is automatically used with Randomize to generate a seed for the Rnd (random-number) function.

■ You can also use Timer to time programs or parts of programs.

Example The code in the following example prompts the user to type a number (500000 is suggested as the default). The computer then counts up to that number using a simple FOR NEXT loop. Actuate Basic times this counting process and reports the total number of seconds elapsed to the user:

Function OnLButtonDblClk( )Dim UserNum, StartTime, I, EndTime, TimeElapsed, MsgUserNum = InputBox("Please type a number to count up to.", , "500000")StartTime = Timer

For I = 1 To UserNumNext I

EndTime = TimerTimeElapsed = EndTime - StartTimeMsg = "The time it took your computer to count to "Msg = Msg & UserNum & " was: " & TimeElapsedMsg = Msg & " seconds."MsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Randomize statement

TimeSerial functionReturns a date variant based on supplied integer hour, minute, and second arguments.

Syntax TimeSerial(<hour>, <minute>, <second>)

Page 408: Actuate Basic Reference

384 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

T i m e S e r i a l f u n c t i o n

Parameters <hour>Numeric expression that specifies a particular hour of the day.

Rule for <hour>: Must be in the range 0 (12:00 A.M.) through 23 (11:00 P.M.), inclusive.

<minute>Numeric expression that specifies a particular minute after <hour>.

Rule for <minute>: Must be in the range 0 through 59, inclusive.

<second>Numeric expression that specifies a particular second.

Rule for <second>: Must be in the range 0 through 59, inclusive.

Examples:The following statements are equivalent. Each stores 05:03:46 to the variable TimeVar:

TimeVar = TimeSerial(05, 03, 46)TimeVar = TimeSerial(5, 3, 46)

Each of the following statements stores the underlying serial number for 05:03:46, which is about .210949, to the double-precision variable TimeVar#:

TimeVar# = CDbl(TimeSerial(5, 3, 46))TimeVar# = TimeSerial(5, 3, 46) * 1

Returns Date

The value TimeSerial returns usually looks like a time but is stored internally as a double-precision fractional number between 0 and .99999. This number represents a time between 00:00:00 and 23:59:59, or 12:00:00 A.M. and 11:59:59 P.M., inclusive.

In other contexts, this fractional number becomes part of what is known as a date serial number—a number that represents a date and/or time from midnight January 1, 100, through December 31, 9999, inclusive.

The integer component of any date serial number represents the date (day, month, and year) while the decimal or fractional component represents the time of day on that date as a proportion of a whole day—where January 1, 1900, at noon has the date serial number 2.5, and where negative numbers represent dates prior to December 30, 1899 (0).

Tip TimeSerial can return a new time based on calculations done on a given time. In the following example, TimeSerial returns a time that is thirty minutes before 11:45:00 A.M. and assigns it to the variable T:

T = TimeSerial(11, 45, 00) -((30/60)/24)

Page 409: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 385

T i m e S e r i a l f u n c t i o n

Example The following example displays the number of hours, minutes, and seconds to midnight:

Function OnLButtonDblClk()Dim HrDiff As Integer, MinDiff As Integer, SecDiff As IntegerDim RightNow As Double, Midnight As Double, TotalDiff As DoubleDim TotalMinDiff As Double, TotalSecDiff As DoubleDim Msg As String'Midnight = TimeValue("23:59:59")RightNow = Now ' Get current timeHrDiff = Hour(Midnight) - Hour(RightNow) ' Get diffs re midnightMinDiff = Minute(Midnight) - Minute(RightNow)SecDiff = Second(Midnight) - Second(RightNow) + 1

' Restate seconds and minutes if necessaryIf SecDiff = 60 Then

MinDiff = MinDiff + 1 ' Add 1 to minuteSecDiff = 0 ' And set 0 seconds

End IfIf MinDiff = 60 Then

HrDiff = HrDiff + 1 ' Add 1 to hourMinDiff = 0 ' And set 0 minutes

End If

' Now get totalsTotalMinDiff = (HrDiff * 60) + MinDiffTotalSecDiff = (TotalMinDiff * 60) + SecDiffTotalDiff = TimeSerial(HrDiff, MinDiff, SecDiff)

' Prepare msg for displayMsg = "There are a total of " & Format(TotalSecDiff, "#,##0")Msg = Msg & " seconds until midnight. That translates to "Msg = Msg & HrDiff & " hours, " Msg = Msg & MinDiff & " minutes, and "Msg = Msg & SecDiff & " seconds. "Msg = Msg & "Expressed in standard time notation, it becomes "' Remember to use "nn" for minutes! m is for month.Msg = Msg & Format(TotalDiff, "hh:nn:ss") & "."MsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also DateSerial functionDateValue functionHour functionNow functionSecond functionTimeValue function

Page 410: Actuate Basic Reference

386 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

T i m e V a l u e f u n c t i o n

TimeValue functionReturns a Date variant representing a time of day based on a specified string.

Syntax TimeValue(<time string>)

Parameters <time string>String expression that specifies a time. Can be any string that can be interpreted as a time of day. You can enter valid times using a 12- or 24-hour clock.

Rules:

■ <time string> must be in the range 00:00:00 (12:00:00 A.M.) through 23:59:59 (11:59:59 P.M.).

■ If <time string> includes a date , it must be a valid one, even though TimeValue does not return a date.

■ <time string> is parsed according to the formatting rules of the current run time locale.

Examples:The following statements are equivalent. Each stores 1:25:00 P.M. to the variable TimeVar:

TimeVar = TimeValue("1:25PM")TimeVar = TimeValue("1:25 PM")TimeVar = TimeValue("01:25 pm")TimeVar = TimeValue("13:25")

Each of the following statements stores the underlying serial number for 1:25:00 P.M., which is about .559028, to the double-precision variable TimeVar#:

TimeVar# = CDbl(TimeValue("1:25PM"))TimeVar# = TimeValue("1:25PM") * 1

Returns Date

■ TimeValue return value looks like a time but is stored internally as a double-precision fractional number between 0 and .99999. This number represents a time between 00:00:00 and 23:59:59, or 12:00:00 A.M. and 11:59:59 P.M., inclusive. In other contexts, this fractional number becomes part of what is known as a date serial number—a number that represents a date and/or time from midnight January 1, 100, through December 31, 9999, inclusive.

■ The integer component of any date serial number represents the date (day, month, and year) while the decimal or fractional component represents the time of day on that date as a proportion of a whole day—where January 1, 1900, at noon has the date serial number 2.5, and where negative numbers represent dates prior to December 30, 1899 (0).

Page 411: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 387

T i m e V a l u e f u n c t i o n

Example The following example displays the number of hours, minutes, and seconds to midnight:

Function OnLButtonDblClk()Dim HrDiff As Integer, MinDiff As Integer, SecDiff As IntegerDim RightNow As Double, Midnight As Double, TotalDiff As DoubleDim TotalMinDiff As Double, TotalSecDiff As DoubleDim Msg As String'Midnight = TimeValue("23:59:59")RightNow = Now ' Get current timeHrDiff = Hour(Midnight) - Hour(RightNow) ' Get diffs re midnightMinDiff = Minute(Midnight) - Minute(RightNow)SecDiff = Second(Midnight) - Second(RightNow) + 1

' Restate seconds and minutes if necessaryIf SecDiff = 60 Then

MinDiff = MinDiff + 1 ' Add 1 to minuteSecDiff = 0 ' And set 0 seconds

End IfIf MinDiff = 60 Then

HrDiff = HrDiff + 1 ' Add 1 to hourMinDiff = 0 ' And set 0 minutes

End If

' Now get totalsTotalMinDiff = (HrDiff * 60) + MinDiffTotalSecDiff = (TotalMinDiff * 60) + SecDiffTotalDiff = TimeSerial(HrDiff, MinDiff, SecDiff)

' Prepare msg for displayMsg = "There are a total of " & Format(TotalSecDiff, "#,##0")Msg = Msg & " seconds until midnight. That translates to "Msg = Msg & HrDiff & " hours, " Msg = Msg & MinDiff & " minutes, and "Msg = Msg & SecDiff & " seconds. "Msg = Msg & "Expressed in standard time notation, it becomes "' Remember to use "nn" for minutes! m is for month.Msg = Msg & Format(TotalDiff, "hh:nn:ss") & "."MsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also DateSerial functionDateValue functionHour function

Page 412: Actuate Basic Reference

388 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

T r i m , T r i m $ f u n c t i o n s

Minute functionNow functionSecond functionTimeSerial function

Trim, Trim$ functionsReturns a copy of a string after removing leading and trailing spaces.

Syntax Trim(<string expression>)

Trim$(<string expression>)

Parameters <string expression>String expression from which Trim[$] strips leading and trailing spaces. Leading spaces are any spaces that occur before the first non-space character in a string (leftmost spaces). Trailing spaces are any spaces that occur after the last non-space character in a string (rightmost spaces).

Returns Trim: VariantTrim$: String

■ If there are no leading or trailing spaces, Trim[$] returns the original <string expression>.

■ Trim[$] has no effect on spaces in the middle of a string.

Tips ■ To strip extraneous spaces a user added in response to a prompt, use Trim[$].

■ To find other spaces in the middle of a string, use InStr.

Example The following example strips leading and trailing spaces from a string variable. It shows a typical situation in which you would use Trim[$] to remove extraneous spaces a user might have entered in response to a prompt:

Function OnLButtonDblClk()Dim Msg, NL, CustName, CustName1, LeftSpcs, RightSpcs, InstructNL = Chr(10) ' Define newline

Instruct = "Type a customer name. Put "Instruct = Instruct & "a few extra spaces before and "Instruct = Instruct & "after it, to simulate something "Instruct = Instruct & "a user might do unintentionally."CustName = InputBox(Instruct)

' Number of leading spacesLeftSpcs = Len(CustName) - Len(LTrim$(CustName))

Page 413: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 389

T y p e . . . E n d T y p e s t a t e m e n t

' Number of trailing spacesRightSpcs = Len(CustName) - Len(RTrim$(CustName))CustName1 = Trim$(CustName) ' Strip left and right spaces

Msg = "The original name " & NL & "'" & CustName & "'" & NL & " was "Msg = Msg & Len(CustName) & " characters long. There were " & LeftSpcsMsg = Msg & " leading spaces and " & RightSpcs & " trailing spaces." & NLMsg = Msg & "The name returned after stripping the spaces "Msg = Msg & "is:" & NL & "'" & CustName1 & "'" & NL & " which is only "Msg = Msg & Len(CustName1) & " characters."MsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also InStr functionLTrim, LTrim$ functionsRTrim, RTrim$ functions

Type...End Type statementDeclares a user-defined variable or record structure.

Syntax Type <user-defined variable type>

<component variable> [(<subscripts>)] As <data type>

[ <component variable> [(<subscripts>)] As <data type>]

. . .

End Type

Parameters <user-defined variable type>The name of a user-defined data type.

Rule for <user-defined variable type>: Must follow standard variable-naming conventions.

<component variable>The name of an element of the user-defined data type.

Rule for <component variable>: Must follow standard variable-naming conventions.

Page 414: Actuate Basic Reference

390 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

T y p e . . . E n d T y p e s t a t e m e n t

<subscripts>The dimensions of an array element. Each <subscripts> argument specifies the number of elements in a single dimension. The number of <subscripts> arguments for an array variable specifies the number of dimensions in the array.

The syntax of <subscripts> is as follows:

[<lower> To]<upper>[,[<lower> To]<upper>]...

Rules for <subscripts>:

■ <lower> and <upper> can range from -2,147,483,648 to +2,147,483,647 inclusive.

■ <lower> must always be less than <upper>.

■ <lower> and <upper> cannot be the names of variables. They must be literal numeric constants.

■ Each <subscripts> clause can specify up to 60 dimensions.

You cannot use Type to declare dynamic arrays. However, you can declare the dimensions for an existing dynamic array within Type.

<data type>

The name of a valid data type.

Rules for <data type>:

■ Can be any valid Actuate Basic data type except an object type, including String, for variable-length strings.

■ Can be another user-defined type.

Examples:The following three arrays are equivalent if you do not use Option Base:

MyArray(7,5)MyArray(0 TO 7, 0 TO 5)MyArray(7, 0 TO 5)

The following shows the use of array variables in the context of Type:

DeclareType CustomerData

CustName As String CustAddress As StringArrayPhones(5) As StringArrayOther(5 To 10, 31) As Double

End TypeEnd Declare

Page 415: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 391

T y p e . . . E n d T y p e s t a t e m e n t

Rules ■ You cannot use line numbers or line labels in Type.

■ When declaring a static array within Type, you must use literal numeric constants rather than variables to declare its dimensions.

Tip To more easily manipulate data records that consist of a number of related elements of different data types, use Type to define your own custom data types.

Example The following example creates a user-defined type with three elements. Then it declares a new variable of the user-defined type, and prompts the user to assign data to each element. To use this example, first create a user-defined type and call it SampleRec. Paste the code for SampleRec in your Actuate Basic source code (.bas) file. Paste the rest of the code into the OnLButtonDblClk( ) method of a clickable component such as a label:

DeclareType SampleRec

ClientNum As LongClientName As StringClientPurchase As String

End TypeEnd Declare'Function OnLButtonDblClk ( )

Dim UserAns, FileNum, IDTracker, Msg, NL, TB' Declare new variable to be of user-defined type SampleRecStatic ClientEntry As SampleRecNL = Chr$(10): TB = Chr$(9) ' Define newline and tabFileNum = FreeFile ' Get an unused file numberOpen "SAMPLE.FIL" For Random As FileNumIDTracker = 1 ' Track record numbers

' Now get data from user to fill the elements of data records:Do

ClientEntry.ClientNum = IDTrackerMsg = "Please type client name. Type 'END' when finished."ClientEntry.ClientName = InputBox(Msg)If UCase$(Trim(ClientEntry.ClientName)) = "END" Then Exit Do

Msg = "Please type the amount of the purchase:"ClientEntry.ClientPurchase = InputBox(Msg)Msg = "Client #"Msg = Msg & ClientEntry.ClientNum & NLMsg = Msg & ClientEntry.ClientName & NLMsg = Msg & ClientEntry.ClientPurchase & NLMsg = Msg & NL & "Is this data correct?"' Display current rec, confirm

Page 416: Actuate Basic Reference

392 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

T y p e . . . A s s t a t e m e n t

UserAns = MsgBox(Msg, MB_YESNOCANCEL)If UserAns = IDYES Then ' If Yes

Put FileNum, IDTracker, ClientEntryIDTracker = IDTracker + 1 ' Increment record counter

End IfLoopClose FileNum

Msg = "The records you typed were written to a test file. "Msg = Msg & "Choose OK to delete the test file from your disk."MsgBox MsgKill "SAMPLE.FIL" ' Delete test file

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Class statementDeclare statementType...As statement

Type...As statementDeclares an alias for an existing data type.

Syntax Type <alias data type name> As <existing data type name>

Parameters <alias data type name>The name you assign as an alias for an existing data type.

Rule for <alias data type name>: Must follow standard naming conventions.

<existing data type name>The name of an existing, valid data type.

Rule for <existing data type name>: Must follow standard naming conventions.

Example The following example illustrates the use of Type As. To use this example, paste the first portion at or near the beginning of your Actuate Basic source code (.bas) file. Then copy the second portion into the OnLButtonDblClk() method of a clickable component such as a label:

DeclareType SampleRec

ClientNum As LongClientName As String

Page 417: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 393

T y p e . . . A s s t a t e m e n t

ClientPurchase As CurrencyEnd TypeType OtherName As SampleRecType LogicalVar As Boolean

End Declare

Function OnLButtonDblClk( )Dim UserVar1 As OtherName, IsValid As LogicalVarDim Msg As String, UserAns, NLNL = Chr$(10)UserVar1.ClientName = InputBox("Please type a client's name.")

Msg = "You typed: " & UserVar1.ClientName & NL & NLMsg = Msg & "Is this correct?"UserAns = MsgBox(Msg, 4) ' Display current name, confirmIf UserAns = 6 Then ' If Yes

IsValid = 1 ' Set Boolean to TrueElse

IsValid = 0 ' If No, set to FalseEnd If

MsgBox "The value of the IsValid variable is: " & IsValidIf IsValid Then

Msg = "In other words, IsValid is True."Else

Msg = "In other words, IsValid is False."End IfMsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Class statementDeclare statementType...End Type statement

Page 418: Actuate Basic Reference

394 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

U B o u n d f u n c t i o n

UBound functionReturns the largest available subscript for the given dimension of an array.

Syntax UBound(<array name>[,<dimension>])

Parameters <array name>Name of an array variable.

<dimension>Numeric expression that specifies the array dimension for which you want to determine the upper bound.

Default: 1.

Rules:

■ Use 1 for the first dimension, 2 for the second, and so on.

■ Must not be larger than the total number of dimensions in <array name>.

■ Must not be zero, negative, or Null.

Examples:The following example shows the values UBound returns for an array with these dimensions:

Dim MyArray(1 To 55, 0 To 27, -3 To 42)UBound(MyArray, 1) = 55UBound(MyArray, 2) = 27UBound(MyArray, 3) = 42

Returns Integer

Rule: If <dimension> is not an Integer, UBound rounds it to the nearest Integer before evaluating it.

Tips ■ To determine the lower bound of an array, use LBound.

■ To determine the total number of elements in a given dynamic array dimension, take the value returned from UBound, subtract the value returned from LBound, then add 1.

Example The following example uses UBound to determine the upper bounds of an array of 3 dimensions. The use of Rnd simulates changes in upper bounds that may have been made by the user at run time in response to your program:

Function OnLButtonDblClk( )Dim First As Integer, Sec As Integer, Third As IntegerDim Msg As String, NL As String, TabChar As StringDim MyArray() ' Declare array variable

Page 419: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 395

U C a s e , U C a s e $ f u n c t i o n s

NL = Chr(10): TabChar = Chr(9) ' Define newline, tabRandomize ' Seed rnd generator

First = Int(14 * Rnd + 3) ' First dimensionSec = Int(14 * Rnd + 3) ' Second dimensionThird = Int(14 * Rnd + 3) ' Third dimension

ReDim MyArray(First, Sec, Third) ' Set dimensions

Msg = "MyArray has the following upper bounds: " & NLMsg = Msg & TabChar & "Dimension 1 ---> " & UBound(MyArray, 1) & NLMsg = Msg & TabChar & "Dimension 2 ---> " & UBound(MyArray, 2) & NLMsg = Msg & TabChar & "Dimension 3 ---> " & UBound(MyArray, 3)MsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Dim statementLBound functionRnd function

UCase, UCase$ functionsConverts all lowercase alphabetic characters in a string to uppercase.

Syntax UCase(<string exprs>)

UCase$(<string exprs>)

Parameters <string exprs>String expression that contains the characters to convert to uppercase.

Examples:The following statements are equivalent. Each returns 6 JANE STREET, 2ND FL:

UCase$("6 jane street, 2nd fl")UCase$("6 Jane Street, 2nd Fl")UCase$("6 jAn" & "E sTreeT, 2nD fL")

Returns UCase: VariantUCase$: String

■ If <string exprs> contains no lowercase alphabetic characters, UCase[$] returns the original <string exprs>.

■ UCase[$] has no effect on non-alphabetic characters in <string exprs>.

Page 420: Actuate Basic Reference

396 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

V a l f u n c t i o n

Tips ■ To ensure uniformity in the data you get from the user so that, for example, strings like MacManus, Macmanus, and macMaNus are always sorted, compared, or otherwise treated in the same way, use UCase[$] to convert the data before using it.

■ To convert alphabetic characters in <string exprs> to all lowercase characters, use LCase[$].

Example The following example uses UCase[$] to render the all uppercase version of a customer’s name:

Function OnLButtonDblClk( )Dim AnyCase, Uppercase, MsgAnyCase = InputBox("Please type a customer's name.")Uppercase = UCase$(AnyCase) ' Convert to uppercaseMsg = "UCase$ converts """ & AnyCase & """ to """Msg = Msg & Uppercase & """."MsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also LCase, LCase$ functions

Val functionReturns the numeric value of a string expression.

Syntax Val(<string exprs>)

Parameters <string exprs>String expression from which to extract a numeric value.

Examples:

The following are equivalent. They both return the value 118:

Val("118 36th Street")Val("118 36th Street, #55")

The following returns the value 11836:

Val("&H2E3C")

Because the first character is non-numeric, the following returns 0:

Val("$1,275,332.52")

Page 421: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 397

V a r T y p e f u n c t i o n

Returns Double

■ Starts translating a string into a number by starting at the left of the string and proceeding toward the right.

■ Stops translating the string as soon as it encounters a non-numeric character or the end of the string, whichever comes first.

■ Interprets the prefixes &O and &H as numeric characters representing octal and hexadecimal numbers, respectively.

■ Interprets dollar sign as non-numeric.

■ Ignores spaces, tabs, commas, and line feeds.

■ Interprets the first period or dot it encounters as a decimal point, but stops translating at the appearance of the second period or dot.

■ Returns zero if it stopped before it encounters a numeric character.

Tip ■ To convert a number to a String use Str$.

■ To avoid having to use Val, use the Variant data type for variables when it is necessary to convert between strings and numbers.

Example The following example returns the value of a string you enter:

Function OnLButtonDblClk ( )Dim Msg, NumberNumber = Val(InputBox$("Type a string containing some numbers."))Msg = "VAL extracted this value from your input: " & NumberMsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Format, Format$ functionsStr, Str$ functions

VarType functionReturns a value that indicates how Actuate Basic stores a Variant internally.

Syntax VarType(<variant variable>)

Parameters <variant variable>String expression that specifies a variant of the Variant data type.

Returns Integer

Page 422: Actuate Basic Reference

398 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

V a r T y p e f u n c t i o n

The following table shows the values VarType returns, the Variant data types they indicate, and the names of the corresponding symbolic constants stored in Header.bas.

Example The following example prompts the user to type a date, number, or string. It then displays the Variant data type for the user’s response. Numeric data in this example always returns Variant type 5 (Double). Date and string data return Variant types 7 and 8, respectively. If the user types nothing, the sample code returns a zero-length string (Variant type 8):

Function OnLButtonDblClk( )Dim UserTypedUserTyped = InputBox("Please type a date, number, or string.")If IsNumeric(UserTyped) Then

MsgBox "That’s numeric."UserTyped = CDbl(UserTyped)

End IfIf IsDate(UserTyped) Then

MsgBox "That’s a date."UserTyped = CVDate(UserTyped)

End IfMsgBox "That is of VarType: " & VarType(UserTyped)

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also IsDate functionIsEmpty functionIsNull functionIsNumeric function

VarType returns

Data type of <variant variable> Symbolic constant

0 Empty V_EMPTY

1 Null V_NULL

2 Integer V_INTEGER

3 Long V_LONG

4 Single V_SINGLE

5 Double V_DOUBLE

6 Currency V_CURRENCY

7 Date V_DATE

8 String V_STRING

Page 423: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 399

W e e k d a y f u n c t i o n

Weekday functionReturns an integer between 1 (for Sunday) and 7 (for Saturday) that represents the day of the week for a specified date argument.

Syntax Weekday(<date exprs>)

Parameters <date exprs>Date expression, or any numeric or string expression that can be interpreted as a date, or both a date and a time:

■ Can be a string such as November 12, 1982 8:30 PM, Nov. 12, 1982 08:30 PM, 11/12/82 8:30pm, or any other string that can be interpreted as a date or both a date and a time in the valid range.

■ Can be a date serial number such as 30267.854, which corresponds to November 12, 1982 at 8:30 P.M., or any other number that can be mapped to a date or both a date and a time in the valid range.

■ For date serial numbers, the integer component represents the date itself while the fractional component represents the time of day on that date, where January 1, 1900, at noon has the date serial number 2.5, and negative numbers represent dates prior to December 30, 1899 (0).

Rules:

■ If <date exprs> includes a time, it must be a valid time, even though Weekday does not return a time. A valid time is one that is in the range 00:00:00 (12:00:00 A.M.) through 23:59:59 (11:59:59 P.M.), in either 12- or 24-hour format.

■ If <date exprs> is a numeric expression, it must be in the range -657434 to +2958465, inclusive.

■ If <date exprs> is a variable containing a date serial number, the variable must be explicitly declared as one of the numeric types.

■ <date exprs> is parsed according to the formatting rules of the current run time locale.

The following assumes that the AC_CENTURY_BREAK property is set to the default value of 30. For details on how to set AC_CENTURY_BREAK to some other value, please see Chapter 7, “Using a query data stream,” in Developing Advanced e.Reports.

■ For abridged date expressions ending in 00 through 29 that do not specify the century, relevant date functions estimate the unabridged year by adding 2000. For example, while Year(4/30/1910) returns 1910, the abridged expression Year(4/30/10) returns 2010 (10 + 2000).

Page 424: Actuate Basic Reference

400 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

W e e k d a y f u n c t i o n

■ For abridged date expressions ending in 30 through 99 that do not specify the century, relevant date functions estimate the unabridged year by adding 1900. For example, while Year(11/12/2082) returns 2082, the abridged expression Year(11/12/82) returns 1982 (82 + 1900).

Note that there are arguably abridged dates like Nov. 12, 1982, versus November 12, 1982, that do specify the century. Note also that both abridged and unabridged dates are dates ending in 00 through 99.

Examples:The following statements are equivalent. Each assigns 1 (which maps to Sunday) to the variable DayOfWeek:

DayOfWeek = Weekday("6/7/64 2:35pm")DayOfWeek = Weekday("June 7, 1964 2:35 PM")DayOfWeek = Weekday("Jun " & 5+2 & ", 1964")DayOfWeek = Weekday(23535.6076)DayOfWeek = Weekday(0.6076) - 6

Returns Integer

■ If <date exprs> is Null, Weekday returns a Null.

■ If Weekday returns 1, the day of the week is Sunday. If Weekday returns 2, the day if the week is Monday, and so on.

■ If <date exprs> cannot be evaluated to a date, Weekday returns a Null.

Example:

Weekday(“This is not a date.“) returns Null

■ If <date exprs> fails to include all date components (day, month, and year), Weekday returns a Null.

Examples:

Weekday(“Nov 12, 1982“) returns 6, but Weekday(“Nov 1982“) returns Null

Tip If you use a date expression in one locale, it might be misinterpreted in another locale. For instance, in the United States, 1/2/2005 means January 2nd, 2005, but in France, it means February 1st, 2005. To avoid such ambiguities, use DateSerial to specify all your dates.

Example The following example displays a message indicating whether today is a weekend day or a weekday:

Function OnLButtonDblClk( )Dim DayNum As Integer, Msg As String, FullDesc as StringDayNum = Weekday(Now) ' Get current day of weekFullDesc = Format(Now, "dddd, mmmm dd, yyyy")If DayNum = 1 Or DayNum = 7 Then ' Is it a weekend day?

Page 425: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 401

W h i l e . . . W e n d s t a t e m e n t

Msg = "Today is " & FullDesc & ". It is a weekend day."Else '... or is it a weekday?

Msg = "Today is " & FullDesc & ". It is a weekday."End IfMsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Day functionHour functionMinute functionMonth functionNow functionSecond functionYear function

While...Wend statementRepeats a block of instructions each time a specified condition is True.

Syntax While <expression to reevaluate>

<statements to repeat>

Wend

Parameters <expression to reevaluate>Any valid numeric or string expression that evaluates to True (1) or False (0 or Null).

<statements to repeat>One or more valid Actuate Basic statements; the statements that, collectively taken, are referred to as the loop.

Example:Assuming the variable Counter starts at 1 and is incremented by 1 each time through the loop, the following statement causes its associated loop to be executed nine times:

While Counter < 10

Description First, <expression to reevaluate> is tested. If it is True, the <statements to repeat> in the body of the loop are executed. Then <expression to reevaluate> is tested again. If it is still True, <statements to repeat> are executed again. This process repeats until <expression to reevaluate> is False. In that case, Actuate

Page 426: Actuate Basic Reference

402 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

W h i l e . . . W e n d s t a t e m e n t

Basic skips all intervening <statements to repeat> and passes control to the statement immediately following Wend.

Rule Do not branch into the middle of a While...Wend statement. Execute the entire statement instead, starting at the line with the While keyword.

Tips ■ To take advantage of its greater flexibility, use Do...Loop instead of While Wend.

■ To be sure the loop executes at least once, explicitly set <expression to reevaluate> to True in a statement that closely or immediately precedes the While...Wend statement.

■ It is good programming practice to evaluate Boolean variables by using the keywords True or False instead of by inspecting their content for a nonzero (True) or zero (False) numeric value.

Example The following example sorts an array:

Function OnLButtonDblClk()Dim SwapThese, Position As Integer, Msg, NL, TempVarStatic Cities(5) ' Declare an arrayNL = Chr$(10) ' Define newline'Now assign array data out of alphabetical order'so we can see sort illustrated.Cities(1) = "New York"Cities(2) = "San Francisco"Cities(3) = "Paris"Cities(4) = "Boston"Cities(5) = "Seattle"SwapThese = True ' Make sure we loop at least once' Sort while there still are elements we need to swapWhile SwapThese' Now compare array elements by pairs. When two are swapped,' ensure another pass thru loop by setting SwapThese to TRUE:

SwapThese = FalseFor Position = 2 To 5

If Cities(Position - 1) > Cities(Position) ThenSwapThese = True' Now do the swap:TempVar = Cities(Position)Cities(Position) = Cities(Position - 1)Cities(Position - 1) = TempVar

End IfNext Position

Wend

Msg = "New, sorted order: " & NL & NLFor Position = 1 To 5

Msg = Msg & Cities(Position) & NL

Page 427: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 403

W i d t h # s t a t e m e n t

Next PositionMsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Do...Loop statementIf...Then...Else statement

Width # statementDefines the width of the output line of a sequential file.

Syntax Width #<open file number>, <new line width>

Parameters <open file number>

Numeric expression that is the file number for a file opened with the Open statement.

Rule: The file number must refer to a file that is currently open.

<new line width>

Numeric expression that is the new width for the line. Width is measured as the number of characters Actuate Basic prints on a line before it begins a new line. If <new line width> is specified as 0, there is no limit to the length of the line.

Default: 0

Rule: Must be in the range of 0-255, inclusive.

Example:

The following statement sets the output line width to 75 columns for open file #1:

Width #1, 75

Description When you print to an ASCII text file, you might need to define a maximum output length for each line. Use the Width # statement for this operation.

Example In the following example, the code first creates a test file and writes some ASCII characters to it using the default output width (unlimited). Then the width is changed, and the same ASCII characters are appended to the file. Finally, the entire file is read back and displayed with both sets of ASCII characters, then deleted:

Page 428: Actuate Basic Reference

404 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

W r i t e # s t a t e m e n t

Function OnLButtonDblClk( )Dim I As Integer, Msg As String, NL As String, TextLines As StringNL = Chr$(10) ' Define newlineOpen "Testfile.txt" For Output As #1 ' Create a sample text file' Print ASCII characters . . . 0-9 all on same lineWidth #1, 10Print #1, "Width 10:"For I = 0 To 9

Print #1, Chr$(48 + I)Next IPrint #1, ' Start a new lineWidth #1, 4 ' Change the line width to 4' Print ASCII characters . . . 4 characters to a lineFor I = 0 To 9

Print #1, Chr$(48 + I)Next IClose #1Msg = "The effect of WIDTH # is as displayed: " & NLOpen "Testfile.txt" For Input As #1 ' Reopen test file for inputDo While Not EOF(1)

Input #1, TextLines ' Get contents of each lineMsg = Msg & NL & TextLines

LoopClose #1Msg = Msg & NL & "Please select OK to delete the text file."MsgBox Msg ' Display resultsKill "Testfile.txt"

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Open statementPrint # statementSpace, Space$ functionsTab function

Write # statementFormats and writes data to a sequential file.

Syntax Write #<file number> [, <exprs 1>] [, <exprs 2>] [, <exprs 3>]...

Page 429: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 405

W r i t e # s t a t e m e n t

Parameters <file number>Numeric expression that is the file number of a sequential file that is Open for Output or Append.

Example:The following statements work together, although they can be separated from one another by lines of code. The first statement opens a file called Mynotes.fil, the second one writes the contents of four variables to that file, and the third, by closing it, turns the file over to the operating system to complete the process of writing it to the disk:

Open "C:\Myfiles\Mynotes.fil" FOR OUTPUT AS #2Write #2, A$, B%, C!, D#Close #2

The following statement writes the specified variables to the file opened by a previous Open statement under number 1. Actuate Basic places double quotes around the value in StringVar$, and it inserts commas between all the variables to delimit them. Finally, after the value in DoubleVar#, it writes a newline character:

Write #1, StringVar$, IntVar%, SingleVar!, DoubleVar#

<exprs n>Numeric and/or string expression that specifies the data that Write # places in the file. There can be any number of these.

Default: Newline character.

Description When Write # writes to the file it inserts commas between items and places quotation marks around strings. You do not need to put explicit delimiters in the list. Write # also inserts a newline character after it writes the final <exprs> to the file.

Write # usually writes Variant data to a file the same way it writes data of any other Actuate Basic data type. The following table, however, notes certain exceptions.

Data Write # writes to the file

One Variant of type 0 (Empty) Nothing at all

More than one Variant of type 0 (Empty)

Delimiting commas

Variant of type 1 (Null) Literal #NULL#

Page 430: Actuate Basic Reference

406 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

W r i t e # s t a t e m e n t

Rules ■ <file number> must match the number of a currently open file.

■ The file corresponding to <file number> must be open under either the Output or Append mode.

■ You must have write access to the open file. That is, the file must not have been opened using a Lock Write or Lock Read Write clause.

■ The data cannot be an object variable, user-defined data type structure, handle to a class, CPointer, or OLE object.

Tip Many database programs let you import data when the data is structured in the way that Write # structures it. Such programs interpret each newline character as delimiting the end of a complete record, and treat each comma on a line as delimiting the end of a field within that record. This means you can use Write # to export information from Actuate Basic to almost any database program.

Example The following example prompts the user for their name and age. It then writes this information to a test file, reads the file back, places the data in a message, and finally, displays the message to the user. After the user responds, it deletes the file from the disk:

Function OnLButtonDblClk( )Dim Msg, NL, UsersAge, UsersNameNL = Chr$(10) ' Define newline

' Now create a sample data file:Open "Test.fil" For Output As #1 ' Open the file for outputMsg = "Please enter your name."UsersName = InputBox(Msg)Msg = "Enter your age."UsersAge = InputBox(Msg)

Write #1, UsersName, UsersAge ' Write data to test fileClose #1 ' Close file

' Now read back the sample data file:Open "Test.fil" For Input As #1 ' Open test file for input

Variant of type 7 (Date) The date, using the fixed date format: #yyyy-mm-dd hh:nn:ss#

Variant of type 7 (Date), but with either the date or time component missing or zero

Only the part of the date provided

Data Write # writes to the file

Page 431: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 407

Y e a r f u n c t i o n

Input #1, UsersName, UsersAge ' Read the data in itClose #1 ' Close file

Msg = "The name '" & UsersName & "' was read from the test file. "Msg = Msg & "'" & UsersAge & "' is your age."Msg = Msg & NL & NL & "Choose OK to delete the test file."MsgBox MsgKill "Test.fil" ' Delete file from disk

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Open statementPrint # statement

Year functionReturns an integer between 100 and 9999, inclusive, that represents the year of a specified date argument.

Syntax Year(<date exprs>)

Parameters <date exprs>Date expression, or any numeric or string expression that can evaluate to a date. Specifies a date and/or time.

■ Can be a string such as November 12, 1982, Nov. 12, 1982, 11/12/82, 11-12-82, or any other string that can be interpreted as a date in the valid range.

■ Can be a date serial number such as 30267.854, which corresponds to November 12, 1982 at 8:30 P.M., or any other number that can be mapped to a date in the valid range.

■ For date serial numbers, the integer component represents the date itself while the fractional component represents the time of day on that date, where January 1, 1900 at noon has the date serial number 2.5, and negative numbers represent dates prior to December 30, 1899 (0).

Rules:

■ If <date exprs> is a string expression, must specify a date in the range January 1, 100 through December 31, 9999, inclusive.

■ If <date exprs> is a numeric expression, must be in the range -657434 to +2958465, inclusive.

Page 432: Actuate Basic Reference

408 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

Y e a r f u n c t i o n

■ If <date exprs> is a variable containing a date serial number, the variable must be explicitly declared as one of the numeric types.

■ <date exprs> is parsed according to the run time locale formatting rules.

The following assumes that the AC_CENTURY_BREAK property is set to the default value of 30. For information about using AC_CENTURY_BREAK, please see Chapter 7, “Using a query data stream,” in Developing Advanced e.Reports.

■ For abridged date expressions ending in 00 through 29 that do not specify the century, relevant date functions estimate the unabridged year by adding 2000. For example, while Year(4/30/1910) returns 1910, the abridged expression Year(4/30/10) returns 2010 (10 + 2000).

■ For abridged date expressions ending in 30 through 99 that do not specify the century, relevant date functions estimate the unabridged year by adding 1900. For example, while Year(11/12/2082) returns 2082, the abridged expression Year(11/12/82) returns 1982 (82 + 1900).

Note that there are arguably abridged dates like Nov. 12, 1982 versus November 12, 1982, that do specify the century. Note also that both abridged and unabridged dates are dates ending in 00 through 99.

Examples:The following statements are equivalent. Each assigns 1964 to the variable UserYear:

UserYear = Year("6/7/64")UserYear = Year("June 7, 1964 2:35 PM")UserYear = Year("Jun 7, 1964")UserYear = Year(23535)UserYear = Year(4707*5)

Returns Integer

■ If <date exprs> is Null, Year returns a Null.

■ If <date exprs> cannot be evaluated to a date, Year returns a Null.

Example:

Year(“This is not a date.“) returns Null

■ If <date exprs> fails to include all date components (day, month, and year), Year returns a Null.

Examples:

Year(“Nov 12, 1982“) returns 1982, butYear(“Nov 1982“) returns Null

Tip If you use a date expression in one locale, it might be misinterpreted in another locale. For instance, in the United States, 1/2/2005 means January 2nd, 2005, but in France, it means February 1st, 2005. To avoid such ambiguities, use DateSerial to specify all your dates.

Page 433: Actuate Basic Reference

C h a p t e r 2 , S t a t e m e n t s a n d f u n c t i o n s 409

Y e a r f u n c t i o n

Example The following example prompts the user to enter a date. Then it uses various interrelated date functions to display the year, the month, the day, and the weekday for the given date. Finally, it gives the date’s serial number. To use this example, paste the first portion into your Actuate Basic source code (.bas) file. Then paste the second portion into the OnLButtonDblClk( ) method of a clickable component like a label:

' This function tells us what suffix (1st, 2nd, 3rd) to use with a numberFunction Suffix (DateNum) As String

Select Case DateNumCase 1

Suffix = "st"Case 2

Suffix = "nd"Case 3

Suffix = "rd"Case Else

Suffix = "th"End Select

End Function'Function OnLButtonDblClk( )

Dim UserEntry As String, UserYear As Integer, UserMonth As IntegerDim UserDay As Integer, UserDOW As Integer, DOWName As StringDim Msg As String, NL As String, LeapYear' Define newlineNL = Chr$(10)

' Get user inputUserEntry = InputBox("Please type a date.")' Calculate yearUserYear = Year(UserEntry)' Calculate monthUserMonth = Month(UserEntry)' Calculate dayUserDay = Day(UserEntry)' Calculate day of weekUserDOW = Weekday(UserEntry)' Convert to name of dayDOWName = Format$ (UserEntry, "dddd")

' Determine if the year is a leap year or a centesimalIf UserYear Mod 4 = 0 And UserYear Mod 100 = 0 Then' Evenly divisible by 400?If UserYear Mod 400 = 0 Then

LeapYear = "is a leap year."' Not evenly divisible

Page 434: Actuate Basic Reference

410 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

Y e a r f u n c t i o n

ElseLeapYear = "is a centesimal but not a leap year."

End IfElseIf UserYear Mod 4 = 0 ThenLeapYear = "is a leap year."ElseLeapYear = "is not a leap year."End If

' Display results for the user after the pattern:' The given year 1982 is not a leap year. The weekday number for' the 12th day of the 11th month in 1982 is 6, which means that ' day was a Friday.'' The date serial number for 11/12/82 is: 30267'MsgBox "The given year, " & UserYear & ", " & LeapYearMsg = "The weekday number for the " Msg = Msg & UserDay & Suffix(UserDay) & " day "Msg = Msg & "of the " & UserMonth & Suffix(UserMonth) & " month "Msg = Msg & "in " & UserYear & " is " & UserDOWMsg = Msg & ", which means that day is a " & DOWName & "." & NL & NLMsg = Msg & "The date serial number for " & UserEntry & " is: "Msg = Msg & CDbl(DateSerial(UserYear, UserMonth, UserDay))MsgBox Msg

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

See also Date, Date$ functionsDay functionHour functionMinute functionMonth functionNow functionSecond functionWeekday function

Page 435: Actuate Basic Reference

A p p e n d i x A , A c t u a t e B a s i c d a t a t y p e s 411

A p p e n d i x

AAppendix AActuate Basic data types

Actuate Basic supports the following elementary data types:

Data type Suffix Data size Range

Integer % 4 bytes32 bits

-2,147,483,648 to +2,147,483,647

Long integer & 4 bytes32 bits

-2,147,483,648 to +2,147,483,647

Single-precisionfloating-point

! 8 bytes64 bits

-1.797693134862315E308 to -2.23E-308 for negative values; 2.23E-308 to 1.797693134862315E308 for positive values.

Date-precisionfloating-point

None 8 bytes64 bits

1 January 100 to 31 December 9999

Double-precisionfloating-point

# 8 bytes64 bits

-1.797693134862315E308 to -2.23E-308 for negative values; 2.23E-308 to 1.797693134862315E308 for positive values.

Currency(scaled integer)

@ 12 bytes96 bits

-39,614,081,257,132,168,796.771975167 to +39,614,081,257,132,168,796.771975168

String $ 1 byte percharacter

0 to approximately 2,147,483,648 bytes or memory limit.

CPointer None 4 bytes32 bits

Page 436: Actuate Basic Reference

412 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

Any data typeThe Any data type is used only to suppress type checking of arguments passed to dynamic-link library (DLL) procedures.

CPointer data typeThe CPointer data type is used to hold a pointer to data allocated in a C function you have created.

Currency data typeCurrency variables are stored as 96-bit numbers (12 bytes) in a two’s complement integer format, and are scaled by 1,000,000,000 to give a fixed point number with 20 digits to the left of the decimal point and 9 digits to the right. This representation provides a range of-39,614,081,257,132,168,796.771975167 to +39,614,081,257,132,168,796.771975168. The type-declaration character for a Currency variable is @ (ANSI character 64).

The Currency data type is useful for calculations involving money and for fixed-point calculations in which accuracy is particularly important.

Date data typeDate variables are stored as 64-bit (8 byte) floating-point numbers that represent dates ranging from 1 January 100 to 31 December 9999 and times from 0:00:00 to 23:59:59. Date variables display dates and times based on the formats specified by your computer.

User-defined(using Type)

None Numberof bytes defined by elements

The range of each element depends on its fundamental type.

Any None Used to suppress type-checking of arguments passed to DLL procedures.

Data type Suffix Data size Range

Page 437: Actuate Basic Reference

A p p e n d i x A , A c t u a t e B a s i c d a t a t y p e s 413

The Date data type is useful for performing calculations on date/time values. Adding and subtracting Integers operates on the date. Adding or subtracting fractions operates on the time.

Double data typeDouble (double-precision floating-point) variables are stored as 64-bit numbers (8 bytes) ranging in value from

-1.797693134862315E308 to -2.23E-308 for negative values and from 2.23E-308 to 1.797693134862315E308 for positive values. The type-declaration character for a Double is # (ANSI character 35).

Note: Double-precision floating-point numbers are stored in memory using IEEE 64-bit floating-point format. Each floating-point value consists of three parts: the sign, the exponent, and the mantissa. In a double-precision number, the sign takes I bit, the exponent takes 11 bits, and the mantissa uses the remaining 52 bits plus an additional implied bit.

Integer data typeInteger variables are stored as signed 32-bit numbers (4 bytes) ranging in value from -2,147,483,648 to 2,147,483,647. The type-declaration character for an Integer is % (ANSI character 37).

In addition to representing numbers in this range, Integers can represent Boolean values (values that can have only one of two states). For Boolean values, 1 represents true and 0 represents false. You can also use the Actuate Basic reserved words True and False, which return 1 and 0, respectively.

You can also use Integers to represent enumerated values. An enumerated value can contain a finite set of unique whole numbers, each of which has special meaning in the context in which it is used. Enumerated values provide a convenient way to select among a known number of choices.

Long data typeLong (long integer) variables are stored as signed 32-bit numbers (4 bytes) ranging in value from -2,147,483,648 to 2,147,483,647. The type-declaration character for a Long is & (ANSI character 38).

Page 438: Actuate Basic Reference

414 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

Single data typeSingle (single-precision floating-point) has the same precision and range as Double in Actuate Basic.

String data typeVariable-length strings can contain up to approximately 2,147,283,647 characters or up to your computer’s memory limit. Because some storage overhead is required, a string can’t actually be 2,147,283,647 characters long.

The type-declaration character for a String is $ (ANSI character 36). The codes for String characters range from 0 to 255. String characters that all applications designed for Microsoft Windows use consist of ANSI characters. The first 128 characters (0-127) correspond to the letters and symbols on a standard U.S. keyboard. These first 128 characters are the same as defined by the ASCII character set. The second 128 characters (128-255) represent special characters, such as letters in international alphabets, accents, currency symbols, and fractions.

Unlike Visual Basic, Actuate Basic’s InputBox function treats numbers the user supplies as string data by default. When you assign a Variant variable to the value InputBox returns, you will not be able to use this value in an arithmetic expression. For example:

Dim Alpha, Beta, GammaAlpha = InputBox("What is Alpha?")Beta = InputBox("What is Beta?")‘The following expression will cause a run time errorGamma = Alpha * BetaMsgBox Gamma

Some functions, like PV, treat a string from the InputBox, with a Variant variable assigned to it, as zero. This zero does not cause an error but returns an incorrect value.

User-defined data typeAny data type that you define using the Type reserved word. User-defined data types can contain one or more elements of any fundamental Actuate Basic data type.

Page 439: Actuate Basic Reference

A p p e n d i x A , A c t u a t e B a s i c d a t a t y p e s 415

Variant data typeThe Variant data type is the default for Actuate Basic—the data type that all variables become if they are not explicitly declared to be of some other type (using Dim, Global, or Static). The Variant data type has no type-declaration character.

The Variant is a special data type that can contain numeric, string, or date data as well as the special values empty and Null. You can determine how the data in a Variant is treated by using the VarType function. The following table illustrates the return value of the VarType function and the corresponding interpretation of the contents of the Variant.

Numeric data can be any Integer or real number value ranging from -1.797693134862315E308 to -4.94066E-324 for negative values and from 4.94066E-324 to 1.797693134862315E308 for positive values. Generally, numeric Variant data is maintained in its original fundamental data type within the Variant. For example, if you assign an Integer to a Variant, subsequent operations treat the Variant as if it were an Integer. However, if an arithmetic operation is performed on a Variant containing an Integer, a Long, or a Single, and the result exceeds the normal range for the original data type, the result is promoted within the Variant to the next larger data type. An overflow error occurs when Variant variables containing Currency and Double values exceed their respective ranges.

Always use the Variant data type when the data could contain date information, Empty, or a Null. You can also use the Variant data type in place of any fundamental data type to work with data in a more flexible way. If the contents of a Variant variable are digits, they may either be the string

Return value Interpretation of Variant

0 Empty (uninitialized)

1 Null (no valid data)

2 Integer

3 Long (long integer)

4 Single (single-precision floating-point)

5 Double (double-precision floating-point)

6 Currency (scaled integer)

7 Date

8 String

9 CPointer

Page 440: Actuate Basic Reference

416 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

representation of the digits or the actual value, depending on the context. For example:

Dim MyVar As VariantMyVar = 98052

In the preceding example, Myvar contains a numeric representation of the actual value 98052. Arithmetic operators work as expected on Variant variables that contain numeric values or string data that can be interpreted as numbers. If you use the + operator to add MyVar to another Variant containing a number or to a variable of a numeric data type, the result is an arithmetic sum.

The value Empty denotes a Variant variable that has not been initialized. A Variant containing Empty is 0 if it is used in a numeric context and a zero-length string if it is used in a string context. Do not confuse Empty with Null. Null indicates that the Variant variable intentionally contains no valid data.

Page 441: Actuate Basic Reference

A p p e n d i x B , K e y w o r d s 417

A p p e n d i x

BAppendix BKeywords

The words in the following list are keywords in Actuate Basic: data types, operators, statements, and certain other words that are recognized by the Actuate compiler. Although Actuate Basic allows using names that are the same as function names, avoid using these names.

Alias And Any

AnyClass Append As

Assert BAnd Base

Beep Binary BNot

BOr ByVal Call

Case ChDir ChDrive

Class Clipboard Close

Compare Const CPointer

Currency Date Debug

Declare DefCur DefDbl

DefInt DefLng DefSng

DefStr Dim Do

Double Else ElseIf

End Eqv Err

Error Exit Explicit

False FileCopy For

Page 442: Actuate Basic Reference

418 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

FreeLocks Function Get

Global GoTo If

Imp Input Integer

Internal Is Kill

Let Lib Like

Line Line Input Load

Local Lock Long

Loop LSet Me

Mid MidB MkDir

Mod MsgBox Name

New Next Not

Nothing Null Object

Of On On Error

Open Option Option Base

Option Compare Option Explicit Or

Output Persistent Preserve

Print Put Random

Randomize Read ReDim

Rem Reset Resume

Return RmDir RSet

Seek Select Select Case

Set SetAttr Shared

Single Static Step

Stop String Sub

Subclass Text Then

Time To True Transient

Type Unload Unlock

Until Variant VarType

Verify Volatile Wend

While Write XOr

Page 443: Actuate Basic Reference

A p p e n d i x C , O p e r a t o r s 419

A p p e n d i x

CAppendix COperators

This appendix contains information about operators Actuate Basic supports.

When several operations occur in an expression, each part is evaluated and resolved in a predetermined order, known as operator precedence. Parentheses can be used to override the order of precedence and force parts of an expression to be evaluated before others. Operations within parentheses are always performed before those outside. Within parentheses, normal operator precedence is maintained.

When expressions contain operators from more than one category, arithmetic operators are evaluated first, comparison operators are evaluated next, and logical operators are evaluated last. Within individual categories, operators are evaluated in the following order.

Arithmetic Comparison Logical Bitwise

Exponentiation(^) Equality(=) Not BNot

Negation(-) Inequality(<>) And BAnd

Multiplication andDivision(* and /)

Less than(<) Or BOr

Integer division(\) Greater than(>) XOr

Modulo arithmetic(Mod)

Less than or Equal to(<=)

Eqv

Addition and Subtraction (+and -)

Greater than or Equal to(>=)

Imp

String concatenation(&) Like Is

Page 444: Actuate Basic Reference

420 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

* o p e r a t o r

All comparison operators have equal precedence, that is, they are evaluated in the left-to-right order in which they appear.

When multiplication and division or addition and subtraction occur together in an expression, each operation is evaluated as it occurs from left to right.

In precedence, the string concatenation operator (&) falls after all arithmetic operators and before all comparison operators. The Like operator, while equal in precedence to all comparison operators, is actually a pattern-matching operator.

* operatorMultiplies two numbers.

Syntax <result> = <operand1> * <operand2>

Description The operands can be any numeric expression.

The data type of <result> is usually the same as that of the most precise operand. The order of precision, from least to most precise, is Integer, Long, Single, Double, Currency. The following are exceptions to this order:

■ When multiplication involves a Single and a Long, the data type of <result> is converted to a Double.

■ When the data type of <result> is a Variant of type 3 (Long), type 4 (Single), or type 7 (Date) that overflows its legal range, <result> is converted to a Variant of type 5 (Double).

■ When the data type of <result> is a Variant of type 2 (Integer) that overflows its legal range, <result> is converted to a Variant of type 3 (Long).

If one or both operands are Null expressions, <result> is a Null. Any operand that is empty (VarType0) is treated as 0.

Example The following example determines tax on a user-supplied value using the * operator to multiply the user-supplied value by the tax rate of 15%:

Function OnLButtonDblClick ( )Dim N As Double, Tax As Double ' Declare variablesN = InputBox("Enter a number.") ' Get tax rateTax = .15 * N ' Calculate taxMsgBox "Tax is" & Tax ' Display results

End Function

For information about using the code examples, see “Using the code examples” in Chapter 2, “Statements and functions”.

See also VarType function

Page 445: Actuate Basic Reference

A p p e n d i x C , O p e r a t o r s 421

+ o p e r a t o r

+ operatorSums two numbers.

Syntax <result> = <operand1> + <operand 2>

Description Use the & operator for concatenation to eliminate ambiguity and provide self-documenting code.

When you use the + operator, you may not be able to determine whether addition or string concatenation is to occur. If at least one operand is not a Variant, the following rules apply.

If either operand is a Null (Variant type 1), <result> is a Null.

If both operands are Variant expressions, the VarType of the operands determines the behavior of the + operator in the following way.

Condition Result

Both expressions are numeric data types (Integer, Long, Single, Double,or Currency).

Add

Both expressions are strings. Concatenate

One expression is a numeric data type and the other is a Variant (other than a Null).

Add

One expression is a String and the other is a Variant (other than a Null).

Concatenate

One expression is a Variant containing Empty.

Return the remaining operand unchanged as <result>

One expression is a numeric data type and the other is a String.

A Type Mismatch error occurs

Condition Result

Both Variant expressions are of type 2-7 (numeric data types).

Add

Both Variant expressions are of type8 (String).

Concatenate

One Variant expression is of type 2-7(a numeric data type) and the other is of type 8 (String).

Add

Page 446: Actuate Basic Reference

422 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

- o p e r a t o r

For simple arithmetic addition involving only operands of numeric data types, the data type of <result> is usually the same as the most precise operand.

The order of precision, from least to most precise, is Integer, Long, Single, Double, Currency. The following exceptions are to this order:

■ When a Single and a Long are added together, the data type of <result> is converted to a Double.

■ When the data type of <result> is a Variant of type 3 (Long), type 4 (Single), or type 7 (Date) that overflows its legal range, <result> is converted to a Variant of type 5 (Double).

If one or both of the expressions are Null expressions, <result> is a Null. If both operands are Empty, <result> is an Integer. If only one operand is Empty, the other operand is returned unchanged as <result>.

Example 1 The following example adds a user-supplied number to itself and displays the result:

Function OnLButtonDblCLk( )Dim N As Double, Result As Double ' Declare variablesN = InputBox ("Enter a number.") ' Get a numberResult = N + N 'Add numbersMsgBox N & " plus " & N & " is " & (N+N) ' Display result

End Function

Example 2 The following example uses the + operator to concatenate strings:

Function OnLButtonDblClk( )MsgBox "Actuate " + "Developer " + "Workbench "'Display result

End Function

For information about using the code examples, see “Using the code examples” in Chapter 2, “Statements and functions”.

See also VarType function

- operatorFinds the difference between two numbers or indicates the negative value of an operand.

Syntax 1

<result> = <operand1> - <operand2>

Page 447: Actuate Basic Reference

A p p e n d i x C , O p e r a t o r s 423

- o p e r a t o r

Syntax 2

-number

Description In Syntax 1, the - operator is the arithmetic subtraction operator used to find the difference between two numbers. The operands can be any numeric expression.

The data type of <result> is usually the same as the most precise operand. The order of precision, from least to most precise, is Integer, Long, Single, Double, Currency. The following exceptions are to this order:

■ When subtraction involves a String and a Long, the data type of <result> is converted to a Double.

■ When the data type of <result> is a Variant of type 3 (Long), type 4 (Single), or type 7 (Date) that overflows its legal range, <result> is converted to a Variant of type 5 (Double).

If one or both operands are Null expressions, <result> is a Null. If an operand is Empty (VarType 0), it is treated as if it were 0.

Example 1 The following example subtracts a user-supplied number from 1000 and displays the result:

Function OnLButtonDblClk( )Dim N As Double, Result As Double ' Declare variablesN = InputBox ("Enter a number.") ' Get a numberResult = 1000 - NMsgBox "1000 minus " & N & " is " & Result ' Display result

End Function

Example 2 The following example uses the - operator to indicate a negative value of a number:

Function OnLButtonDblClk( )Dim N As Double, MinusN As Double ' Declare variablesN = InputBox("Enter a number") ' Get a numberMinusN = -N ' Use negation operatorMsgBox "Negative " & N & " is " & MinusN ' Display result

End Function

For information about using the code examples, see “Using the code examples” in Chapter 2, “Statements and functions”.

See also VarType function

Page 448: Actuate Basic Reference

424 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

/ o p e r a t o r

/ operatorDivides two numbers and returns a floating-point result.

Syntax <result> = <operand1> / <operand2>

Description The operands can be any numeric expression.

The data type of <result> is always a Double or a Variant of type 5 (Double).

If one or both operands are Null expressions, <result> is a Null. If an operand is Empty (Variant type 0), it is treated as if it were 0.

Example The following example divides 100,000 by 7 and returns 14,285.7142857143:

Function OnLButtonDblClk( )Dim Result As Double ' Declare variableResult = 100000 / 7 ' Divide numbersMsgBox "100000 divided by 7 is " & Result ' Display results

End Function

For information about using the code examples, see “Using the code examples” in Chapter 2, “Statements and functions”.

See also VarType function

\ operatorDivides two numbers and returns an integer result.

Syntax <result> = <operand1> \ <operand2>

Description The operands can be any numeric expression.

Before division is performed, the operands are rounded to Integer or Long expressions.

The data type <result> is an Integer. Any fractional portion is truncated. However, if any operand is a Null, <result> is also a Null. Any operand that is Empty (Variant type 0) is treated as 0.

Example The following example divides 100,000 by 7 using integer division and returns 14,285:

Function OnLButtonDblClk( )Dim Result As Double ' Declare variablesResult = 100000 \ 7 ' Divide numbersMsgBox "100000 divided by 7 is " & Result ' Display results

End Function

Page 449: Actuate Basic Reference

A p p e n d i x C , O p e r a t o r s 425

^ o p e r a t o r

For information about using the code examples, see “Using the code examples” in Chapter 2, “Statements and functions”.

^ operatorRaises a number to the power of an exponent.

Syntax <result> = <number> ^ <exponent>

Description The <number> and <exponent> operands can be any numeric expression. However, the <number> operand can be negative only if <exponent> is an integer value. When more than one exponentiation is performed in a single expression, the ^ operator is evaluated as it is encountered from left to right.

Usually, the data type of <result> is a Double or a Variant (type 5). However, if either <number> or <exponent> is a Null expression, <result> is also a Null.

Example The following example squares (n^2) a user-supplied number:

Function OnLButtonDblClk( )Dim N As Double, Result As Double ' Declare variablesN = InputBox("Enter a number.") ' Get numberResult = N ^ 2 ' Square numberMsgBox N & " squared is " & Result ' Display result

End Function

For information about using the code examples, see “Using the code examples” in Chapter 2, “Statements and functions”.

See also VarType function

Mod operatorDivides two numbers and returns only the remainder.

Syntax <result> = <operand1> Mod <operand2>

Description The modulus, or remainder, operator divides <operand1> by <operand2> (rounding floating-point numbers to integers) and returns only the remainder as the <result>. For example, in the expression A = 19 Mod 6.7, A (which is <result>) equals 5. The operands can be any numeric expression.

Usually the data type of <result> is an Integer. However, <result> is a Null (Variant type 1) if one or both operands are Null expressions. Any operand that is Empty (Variant type 0) is treated as 0.

Page 450: Actuate Basic Reference

426 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

C o m p a r i s o n o p e r a t o r s

Example The following example uses the Mod operator to determine if a 4-digit year is a leap year:

Sub Form Click ( )Dim TestYr, LeapStatus ' Declare variablesTestYr = InputBox("Enter a 4-digit year.")If TestYr Mod 4 = 0 And TestYr Mod 100 = 0 Then ' Divisible by 4?

If TestYr Mod 400 = 0 Then ' Divisible by 400?LeapStatus = " is a leap year."

ElseLeapStatus = " is a centesimal year, but not a leap year."

End IfElseIf TestYr Mod 4 = 0 Then

LeapStatus = " is a leap year."Else

LeapStatus = " is not a leap year."End IfMsgBox TestYr & LeapStatus ' Display results

End Sub

For information about using the code examples, see “Using the code examples” in Chapter 2, “Statements and functions”.

See also VarType function

Comparison operatorsCompares two expressions.

Syntax <result> = <expr1> <operator> <expr2>

Description Comparison operators, also known as relational operators, compare two expressions. The following table contains a list of the comparison operators and the conditions that determine whether <result> is True, False, or Null.

Meaning True if False if Null if

< Less than expr1 < expr2

expr1 >= expr2

expr1 or expr2= Null

<= Less than or equal to

expr1 <= expr2

expr1 > expr2 expr1 or expr2= Null

> Greater than expr1 > expr2

expr1 <= expr2

expr1 or expr2= Null

>= Greater than or equal to

expr1 >= expr2

expr1 < expr 2 expr1 or expr2= Null

Page 451: Actuate Basic Reference

A p p e n d i x C , O p e r a t o r s 427

C o m p a r i s o n o p e r a t o r s

When comparing two expressions, you may not be able to easily determine whether the expressions are being compared as numbers or as strings. The following table shows how the expressions are compared or what results when either expression is not a Variant.

If <expr1> and <expr2> are both Variant expressions, their type determines how they are compared. The following table shows how the expressions are

= Equal to expr1 = expr2

expr1 <> expr 2

expr1 or expr2= Null

<> Not equal to expr1 <> expr2

expr1 = expr2 expr1 or expr2= Null

Meaning True if False if Null if

If Then

Both expressions are numeric data types (Integer, Long, Single, Double, or Currency).

Perform a numeric comparison.

Both expressions are String. Perform a string comparison.

One expression is a numeric data type and the other is a Variant of type 2-7 (a numeric data type) or type 8 (String) that can be converted to a number.

Perform a numeric comparison.

One expression is a numeric data type and the other is a Variant of type 8 (String) that cannot be converted to a number.

A Type Mismatch error occurs.

One expression is a String and the other is a Variant of any type except Null.

Perform a string comparison.

One expression is Empty and the other is a numeric data type.

Perform a numeric comparison, using 0 as the Empty expression.

One expression is Empty and the other is a String.

Perform a string comparison, using a zero-length string as the Empty expression.

One expression is Empty and the other is a Variant of type 8 (String).

A Type Mismatch error occurs.

Page 452: Actuate Basic Reference

428 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

C o m p a r i s o n o p e r a t o r s

compared or what results from the comparison, depending on the type of the Variant.

If a Currency is compared with a Single or Double, the Single or Double is converted to a Currency. This causes any fractional part of the Single or Double value less than 0.000000001 to be lost and might cause two values to compare as equal when they are not. Such a conversion can also cause an Overflow error if the magnitude of the Single or Double is too large.

Example The following example shows a typical use of a comparison operator to evaluate the relationship between variables A and B. An appropriate massage is displayed depending on whether A < B, A = B, or A > B. The other comparison operators can be used in a similar way:

Function OnLButtonDblClk( )Dim A, B, Msg ' Declare variablesA = InputBox("Enter a value for A.") ' Get first variableB = InputBox("Enter a value for B.") ' Get second variableIf A < B Then ' Evaluate relationship

Msg = "A is less than B." ' Create correct messageElseIf A = B Then

Msg = "A is equal to B."Else

Msg = "A is greater than B."End IfMsgBox Msg ' Display results

End Function

If Then

Both Variant expressions are of type 2-7 (numeric data types).

Perform a numeric comparison.

Both Variant expressions are of type 8 (String).

Perform a string comparison.

One Variant expression is of type 2-7 (a numeric data type) and the other is of type 8 (String).

The numeric expression is less than the String expression.

One Variant expression is Empty and the other is of type 2-7 (a numeric data type).

Perform a numeric comparison, using 0 as the Empty expression.

One Variant expression is Empty and the other is of type 8 (String).

Perform a string comparison, using a zero-length string as the Empty expression.

Both Variant expressions are Empty. The expressions are equal.

Page 453: Actuate Basic Reference

A p p e n d i x C , O p e r a t o r s 429

& o p e r a t o r

For information about using the code examples, see “Using the code examples” in Chapter 2, “Statements and functions”.

See also VarType function

& operatorForces string concatenation of two operands.

Syntax <result> = <operand1> & <operand2>

Description Whenever an operand is a number, it is converted to a Variant of type 8 (String). The data type of <result> is String if both operands are String expressions; otherwise, <result> is a Variant of type 8 (String). If both operand are Null (type 1), <result> is also Null. However, if only one operand is Null, that operand is treated as a zero-length string when concatenated with the other operand. Any operand that is Empty (type 0) is also treated as a zero-length string.

Example The following example uses the & operator to concatenate a numeric variable (Var1), a string literal containing a space, and a string variable (Var2) that contains trombones:

Function OnLButtonDblClk( )Dim Var1, Var2 ' Declare variablesVar1 = 76Var2 = "trombones"MsgBox 76 & " " & Var2 ' Concatenate and display

End Function

For information about using the code examples, see “Using the code examples” earlier in this chapter.

And operatorPerforms logical conjunction on two expressions.

Syntax <result> = <expr1> And <expr2>

Page 454: Actuate Basic Reference

430 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

B A n d o p e r a t o r

Description If, and only if, both expressions evaluate True, <result> is True. If either expression evaluates False, <result> is False. The following table illustrates how <result> is determined.

Example The following example displays a message that depends on the value of variables A, B, and C, assuming that no variable is a Null. If A = 10, B = 8, and C = 6, both expressions evaluate True. Because both expressions are True, the And expression is also True:

Function OnLButtonDblClk( )Dim A, B, C, Msg ' Declare variablesA = 10: B = 8: C = 6 ' Assign valuesIf A > B And B > C Then ' Evaluate expressions

Msg = "Both expressions are True."Else

Msg = "One or both expressions are False."End IfMsgBox Msg ' Display results

End Function

For information about using the code examples, see “Using the code examples” in Chapter 2, “Statements and functions”.

BAnd operatorPerforms a bitwise comparison of identically positioned bits in two numeric expressions.

Syntax <result> = <expr1> BAnd <expr2>

<expr1> And <expr2> <result>

True True True

True False False

True Null Null

False True False

False False False

False Null False

Null True Null

Null False False

Null Null Null

Page 455: Actuate Basic Reference

A p p e n d i x C , O p e r a t o r s 431

E q v o p e r a t o r

Description If, and only if, both expressions evaluate True, <result> is True. If either expression evaluates False, <result> is False. The BAnd operator sets the corresponding bit in <result> according to the following truth table.

Example The following example displays a message that depends on the value of variables A, B, and C, assuming that no variable is a Null. If A = 10, B = 8, and C = 6, both expressions evaluate True. Because both expressions are True, the BAnd expression is also True:

Function OnLButtonDblClk( )Dim A, B, C, Msg ' Declare variablesA = 10: B = 8: C = 6 ' Assign valuesIf A > B BAnd B > C Then ' Evaluate expressions

Msg = "Both expressions are True."Else

Msg = "One or both expressions are False."End IfMsgBox Msg ' Display results

End Function

For information about using the code examples, see “Using the code examples” in Chapter 2, “Statements and functions”.

Eqv operatorPerforms a logical equivalence on both expressions.

Syntax <result> = <expr2> Eqv <expr2>

Description If either expression is a Null, <result> is also Null. When neither expression is a Null, result is determined according to the following table.

Bit in <expr1> is Bit in <expr2> is <result>

0 0 0

0 1 0

1 0 0

1 1 1

<expr1> <expr2> <result>

True True True

True False False

False True False

False False True

Page 456: Actuate Basic Reference

432 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

I m p o p e r a t o r

Example The following example displays a message that depends on the value of variables A, B, and C, assuming that no variable is a Null. If A = 10, B = 8, and C= 6, both expressions evaluate True. As a result, the Eqv expression also evaluates True:

Function OnLButtonDblClk( )Dim A, B, C, Msg ' Declare variablesA = 10: B = 8: C = 6 ' Assign valuesIf A > B Eqv B > C Then ' Evaluate expressions

Msg = "Both expressions are True or both are False."Else

Msg ="One expression is True and one is False."End IfMsgBox Msg ' Display results

End Function

For information about using the code examples, see “Using the code examples” in Chapter 2, “Statements and functions”.

Imp operatorPerforms a logical implication on two expressions.

Syntax <result> = <expr1> Imp <expr2>

Description The following table illustrates how <result> is determined.

Example The following example displays a message that depends on the value of variables A, B, and C, assuming that no variable is a Null. If A = 10, B = 8, and C= 6, both expressions evaluate True. Because both are True, the Imp expression is also True:

<expr1> <expr2> <result>

True True True

True False False

True Null Null

False True True

False False True

False Null True

Null True True

Null False Null

Null Null Null

Page 457: Actuate Basic Reference

A p p e n d i x C , O p e r a t o r s 433

N o t o p e r a t o r

Function OnLButtonDblClk( )Dim A, B, C, Msg ' Declare variablesA = 10: B = 8: C = 6 ' Assign valuesIf A > B Imp B > C Then

Msg = "The left expression implies the right expression."Else

Msg = "The left expression doesn’t imply the right expression."End IfMsgBox Msg ' Display results

End Function

For information about using the code examples, see “Using the code examples” in Chapter 2, “Statements and functions”.

Not operatorPerforms logical negation on an expression.

Syntax <result> = Not <expr>

Description The following table illustrates how <result> is determined.

In addition, the Not operator inverts the bit values of any variable and sets the corresponding bit in <result> according to the following truth table.

If an integer variable has the value 0 (False), the variable becomes 1 (True); if it has the value of 1 it becomes 0.

Example The following example displays a message that depends on the value of variables A, B, and C, assuming that no variable is a Null. If A = 10, B = 8, and C= 6, the Not expression evaluates True because A is not equal to B:

<expr> <result>

True False

False True

Null Null

Bit in <expr> Bit in <result>

0 1

1 0

Page 458: Actuate Basic Reference

434 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

B N o t o p e r a t o r

Function OnLButtonDblClk( )Dim A, B, Msg ' Declare variablesA = 10: B = 8 ' Assign valuesIf Not A = B Then ' Evaluate expression

Msg = "A and B aren’t equal."Else

Msg = "A and B are equal."End IfMsgBox Msg ' Display results

End Function

For information about using the code examples, see “Using the code examples” in Chapter 2, “Statements and functions”.

BNot operatorInverts the bit values of any variable.

Syntax <result> = BNot <expr>

Description The BNot operator sets the corresponding bit in <result> according to the following truth table.

If an integer variable has the value 0 (False), the variable becomes 1 (True); if it has the value of 1, it becomes 0.

Example The following example displays a message that depends on the value of variables A, B, and C, assuming that no variable is a Null. If A = 10, B = 8, and C= 6, the BNot expression evaluates True because A is not equal to B:

Function OnLButtonDblClk( )Dim A, B, Msg ' Declare variablesA = 10: B = 8 ' Assign valuesIf BNot A = B Then ' Evaluate expression

Msg = "A and B aren’t equal."Else

Msg = "A and B are equal."End IfMsgBox Msg ' Display results

End Function

For information about using the code examples, see “Using the code examples” in Chapter 2, “Statements and functions”.

Bit in <expr> Bit in <result>

0 1

1 0

Page 459: Actuate Basic Reference

A p p e n d i x C , O p e r a t o r s 435

O r o p e r a t o r

Or operatorPerforms a logical disjunction on two expressions.

Syntax <result> = <expr1> Or <expr2>

Description If either or both expressions evaluate True, <result> is True. The following table illustrates how <result> is determined.

The Or operator performs a bitwise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in <result> according to the following truth table.

Example The following example displays a message that depends on the value of variables A, B, and C, assuming that no variable is a Null. If A = 10, B = 8, and C= 6, the left expression is True and the right expression is False. Because at least one comparison expression is True, the Or expression evaluates True:

Function OnLButtonDblClk( )Dim A, B, C, Msg 'Declare variablesA = 10: B = 8: C = 11 ' Assign valuesIf A > B Or B > C Then ' Evaluate expression

Msg = "One or both comparison expressions are True."

<expr1> <expr2> <result>

True True True

True False True

True Null True

False True True

False False False

False Null Null

Null True True

Null False Null

Null Null Null

Bit in <expr1> Bit in <expr2> <result>

0 0 0

0 1 1

1 0 1

1 1 1

Page 460: Actuate Basic Reference

436 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

B O r o p e r a t o r

ElseMsg = "Both comparison expressions are False."

End IfMsgBox Msg ' Display results

End Function

For information about using the code examples, see “Using the code examples” in Chapter 2, “Statements and functions”.

BOr operatorPerforms a bitwise comparison of identically positioned bits in two numeric expressions.

Syntax <result> = <expr1> BOr <expr2>

Description The BOr operator sets the corresponding bit in <result> according to the following truth table.

Example The following example displays a message that depends on the value of variables A, B, and C, assuming that no variable is a Null. If A = 10, B = 8, and C= 6, the left expression is True and the right expression is False. Because at least one comparison expression is True, the BOr expression evaluates True:

Function OnLButtonDblClk( )Dim A, B, C, Msg ' Declare variablesA = 10: B = 8: C = 11 ' Assign valuesIf A > B BOr B > C Then ' Evaluate expression

Msg = "One or both comparison expressions are True."Else

Msg = "Both comparison expressions are False."End IfMsgBox Msg ' Display results

End Function

For information about using the code examples, see “Using the code examples” in Chapter 2, “Statements and functions”.

Bit in <expr1> Bit in <expr2> <result>

0 0 0

0 1 1

1 0 1

1 1 1

Page 461: Actuate Basic Reference

A p p e n d i x C , O p e r a t o r s 437

X O r o p e r a t o r

XOr operatorPerforms a logical exclusion on two expressions.

Syntax <result> = <expr1> Xor <expr2>

Description If only one of the expressions evaluates True, <result> is True. If either expression is a Null <result> is also a Null. When neither expression is a Null, <result> is determined according to the following table.

Example The following example displays a message that depends on the value of variables A, B, and C, assuming that no variable is a Null. If A = 6, B = 8, and C= 10, both expressions evaluate False. Because both are False, the Xor expression is also False:

Function OnLButtonDblClk( )Dim A, B, C, Msg ' Declare variablesA= 6: B = 8: C = 10 ' Assign valuesIf A > B Xor B = C Then ' Evaluate expression

Msg = "Only one comparison expression is True, not Both."Else

Msg = "Both comparison expressions are True or both are False."End IfMsgBox Msg ' Display results

End Function

For information about using the code examples, see “Using the code examples” in Chapter 2, “Statements and functions”.

Is operatorCompares two object reference variables.

Syntax <result> = <objref1> Is <objref2>

Description If <objref1> and <objref2> both refer to the same object, <result> is True; if they do not, <result> is False. Two variables can be made to refer to the same object in several ways.

<expr1> <expr2> <result>

True True False

True False True

False True True

False False False

Page 462: Actuate Basic Reference

438 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

L i k e o p e r a t o r

In the following example, A has been set to refer to the same object as B:

Set A = B

The following example makes A and B refer to the same object as C:

Set A = CSet B = C

Example The following example uses the Is operator to evaluate whether two object reference values refer to the same control:

Function OnLButtonDblClk( )

Dim MLabel1 As AcLabelControl Dim MLabel2 As AcLabelControlDim Msg As String, LoopCount As Integer

'Instantiate two new, separate objectsSet MLabel1 = New AcLabelControlSet MLabel2 = New AcLabelControl

'Loop twice through the Is evaluationFor LoopCount = 1 to 2

If MLabel1 Is MLabel2 ThenMsgBox "Now MLabel1 and MLabel2 DO refer to the same object."

ElseMsgBox "MLabel1 and MLabel2 do NOT yet refer to the same object." 'Before the next Is evaluation loop, force identity.Set MLabel1 = MLabel2

End IfNext LoopCount

End Function

For information about using the code examples, see “Using the code examples” in Chapter 2, “Statements and functions”.

See also Set statement

Like operatorCompares two string expressions.

Syntax <result> = <exprs> Like <pattern>

Description If <exprs> matches <pattern>, <result> is True; if there is no match, <result> is False; and if either <exprs> or <pattern> is a Null, <result> is also a Null. The

Page 463: Actuate Basic Reference

A p p e n d i x C , O p e r a t o r s 439

L i k e o p e r a t o r

case sensitivity and character sort order of the Like operator depend on the setting of the Option Compare statement.

Unless other wise specified, the default string-comparison method for each module is Option Compare Binary; that is, string comparisons are case sensitive.

Built-in pattern matching provides a versatile tool for string comparisons. The pattern-matching feature allows you to use wildcard characters, such as those recognized by the operating system, to match strings. The wildcard characters and what they match are shown in the following table.

A group of one or more characters <character list> enclosed in brackets ([ ]) can be used to match any single character in <exprs> and can include almost any characters in the ANSI character set, including digits.The special characters left bracket ([), question mark (?), number sign (#), and asterisk (*) can be used to match themselves directly only by enclosing them in brackets. The right bracket ( ]) cannot be used within a group to match itself, but it can be used outside a group as an individual character.

In addition to a simple list of characters enclosed in brackets, <character list> can specify a range of characters by using a hyphen (-) to separate the upper and lower bounds of the range. For example, [A-Z] in <pattern> results in a match if the corresponding character position in <exprs> contains any of the uppercase letters in the range A through Z. Multiple ranges are included within the brackets without any delimiting. For example, [a-zA-Z0-9] matches any alphanumeric character.

Other important rules for pattern matching include the following:

■ The hyphen (-) can appear either at the beginning (after an exclamation mark if one is used) or at the end of <character list> to match itself. In any other location, the hyphen is used to identify a range of ANSI characters.

■ When a range of characters is specified, they must appear in ascending order (low to high).

■ The character sequence [ ] is ignored; it is evaluated as a zero-length string.

■ The special character exclamation point (!) is ignored.

Character(s) in <pattern> Matches in <exprs>

? Any single character

* Zero or more characters

# Any single digit (0-9)

[character list] Any single character in <character list>

[^character list] Any single character not in <character list>

Page 464: Actuate Basic Reference

440 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

L i k e o p e r a t o r

Example The following example shows what happens when you mix and match various wildcard characters in conjunction with the Like operator:

Function OnLButtonDblClk( )

MsgBox "PB123" Like "P[A-F]###" 'Returns True (1)MsgBox "PG123" Like "P[A-F]###" 'Returns False (0)MsgBox "PG123" Like "P[^A-F]###" 'Returns FalseMsgBox "PB12x" Like "P[A-F]###" 'Returns FalseMsgBox "PB123" Like "?B???" 'Returns TrueMsgBox "PB123" Like "?B??" 'Returns FalseMsgBox "PB123" Like "P*" 'Returns TrueMsgBox "PB123" Like "*P" 'Returns FalseMsgBox "PB123" Like "*P*" 'Returns TrueMsgBox "F" Like "[^A-Z]*" 'Returns TrueMsgBox "F" Like "[A-Z]*" 'Returns TrueMsgBox "abracadabra12Z%$a" Like "a*a" 'Returns TrueMsgBox "CAT123khg" Like "B?T*" 'Returns False

End Function

For information about using the code examples, see “Using the code examples” in Chapter 2, “Statements and functions”.

See also InStr functionStrComp functionOption Compare statement

Page 465: Actuate Basic Reference

A p p e n d i x D , Tr i g o n o m e t r i c i d e n t i t i e s 441

A p p e n d i x

DAppendix DTrigonometric identities

This appendix contains information about trigonometric formulas supported by Actuate Basic. Actuate Basic supports only a few built-in trigonometric functions: Sin, Cos, Tan and Atn. To use trigonometric functions other than these, you need to derive and write the functions yourself. To do so, use the following table, which shows the most commonly used trigonometric identities.

Name of formula Formula

Secant Sec(X) = 1 / Cos(X)

Cosecant Cosec(X) = 1 / Sin(X)

Cotangent Cotan(X) = 1 / Tan(X)

Inverse Sine Arcsin(X) = Atn(X / Sqr(-X * X + 1))

Inverse Cosine Arccos(X) = Atn(-X / Sqr(-X * X + 1)) + 2 * Atn(1)

Inverse Cotangent Arccotan(X) = -Atn(X) + 2 * Atn(1)

Hyperbolic Sine HSin(X) = (Exp(X) - Exp(-X)) / 2

Hyperbolic Cosine HCos(X) = (Exp(X) + Exp(-X)) / 2

Hyperbolic Tangent HTan(X) = (Exp(X) - Exp(-X)) / (Exp(X) + Exp(-X))

Hyperbolic Secant HSec(X) = 2 / (Exp(X) + Exp(-X))

Hyperbolic Cosecant HCosec(X) = 2 / (Exp(X) - Exp(-X))

Hyperbolic Cotangent

HCotan(X) = (Exp(X) + Exp(-X)) / (Exp(X) - Exp(-X))

Inverse Hyperbolic Sine

HArcsin(X) = Log(X + Sqr(X * X + 1))

Page 466: Actuate Basic Reference

442 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

Inverse Hyperbolic Cosine

HArccos(X) = Log(X + Sqr(X * X - 1))

Inverse Hyperbolic Tangent

HArctan(X) = Log((1 + X) / (1 - X)) / 2

Inverse Hyperbolic Secant

HArcsec(X) = Log((Sqr(-X * X + 1) + 1) / X)

Inverse Hyperbolic Cosecant

HArccosec(X) = Log((Sgn(X) * Sqr(X * X + 1) +1) / X)

Inverse Hyperbolic Cotangent

HArccotan(X) = Log((X + 1) / (X - 1)) / 2

Logarithm to base N LogN(X) = Log(X) / Log(N)

Name of formula Formula

Page 467: Actuate Basic Reference

I n d e x 443

IndexSymbols! format character 137" (double quote) characters 35, 128, 132# (pound sign)

as format character 129as wildcard 439

$ format character 130% format character 129& (ampersand) characters

in format strings 136& operator 429&H prefix 188&O prefix 276( ) parentheses

as literals 130in expressions 419

* operator 420* wildcard 439+ (plus) character as literal 130+ operator 421, (comma)

as format character 133as printer code 299

, (comma) format character 129. (dot) format character 129/ operator 424: (colon) format character 135; (semicolon)

as format character 130as printer code 298

< charactersin format strings 136

< operator 426<= operator 426<> operator 427= operator 427> characters

in format strings 137> operator 426>= operator 426? (question mark)

as format character 287

as wildcard 439@ format character 136[ ] (brackets) as wildcard delimiter 439\ (backslash) characters 128, 132\ operator 424^ operator 425– (hyphen)

as literal 130as wildcard 439

– operator 422’ (apostrophe) in code 315

Numerics0 format character 1290 keyword 318

AA/P format characters 136a/p format characters 136Abort buttons 261, 262, 264abridged date expressions 27Abs function 7, 14absolute paths 120absolute values 14AC_LOCALE_ CURRENCY_RADIX

constant 164AC_LOCALE_ MONTHS_LONG

constant 165AC_LOCALE_ MONTHS_SHORT

constant 165AC_LOCALE_ WEEKDAYS_LONG

constant 165AC_LOCALE_ WEEKDAYS_SHORT

constant 165AC_LOCALE_CURRENCY constant 164AC_LOCALE_CURRENCY_FORMAT

constant 164AC_LOCALE_CURRENCY_THOUSAND_

SEPARATOR constant 164AC_LOCALE_DATE_LONG constant 164AC_LOCALE_DATE_SEPARATOR

constant 165

Page 468: Actuate Basic Reference

444 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

AC_LOCALE_DATE_SHORT constant 165AC_LOCALE_NUM_RADIX constant 165AC_LOCALE_NUM_THOUSAND_

SEPARATOR constant 165AC_LOCALE_TIME_AM_STRING

constant 165AC_LOCALE_TIME_FORMAT constant 165AC_LOCALE_TIME_PM_STRING

constant 165AC_LOCALE_TIME_SEPARATOR

constant 165accelerated depreciation 378accented characters 414access permissions 279access restrictions 236, 281accessing

data xiJava objects xvonline documentation xviii

accessing files 282accessing online help xixaccounts receivable 65accumulated values 365Active Portal xiiiActiveX controls xiiiActuate Basic xiii

defining pointers to C functions 412function and statement reference 11fundamental data types for 411launching from command prompt 45programming tasks categorized 1types of file access for 282

Actuate Foundation Class Library xiiiActuate Foundation Class library

getting version 152Actuate home page xvActuate LRX

calling hyperlinks from 124Actuate product suite xiiActuate product updates xvActuate technology ixad hoc queries xivaddition 421

See also mathematical operationsAddValueIndex function 9, 15ADTContext constant 153Age_ArchiveBeforeDelete constant 352

Age_DeleteDependencies constant 352Age_NoOptions constant 352agent 171aging policy 352aging properties 353aging rules 351alarms 22Alias keyword 84, 86aliases

assigning to data types 392assigning to variables 348defining for external procedures 84, 86

alignment 242, 331allocating memory 89, 182alphanumeric characters 439alternate names. See aliasesAM/PM format characters 135am/pm format characters 135ampersand (&) characters

in format strings 136AMPM format characters 136ANALYSIS format 169, 219analysis tools xiiianalyzing data xivAnd operator 429angles 441

calculating hyperbolic sin for 110getting arctangents 20getting cosine 50getting sine 359getting tangent 381

annuitiesdefined 208getting future value 146getting interest payments 207getting interest rates 310getting number of periods 271getting present value 304getting principal 294getting total payments 292programming functions listed 6

ANSI charactersgetting 18, 34, 36matching 439programming tasks for 3, 8string types and 414

ANSI conversions 3

Page 469: Actuate Basic Reference

I n d e x 445

Any data typedescribed 412

apostrophe (’) in code 315Append mode 43, 112, 281application programming interfaces (APIs)

developing with xivapplication servers xiapplications

customizing xiiie.reporting solutions for x, xigetting currently running 153getting run-time errors for 101, 102, 104importing data 289, 406OLE object support for 53programming tasks for 4running from command prompt 45, 357sample xvi

archive driver xivarchives 155, 346

creating 351archiving tools xivarctangents 20ARDContext constant 153area 47argument lists. See parameter listsarguments

See also command-line argumentsadding to functions 142adding to subprocedures 374checking for invalid 17converting for DLLs 23disabling type checking for 412overloaded procedures and 141, 374passing by value 85, 143, 375programming tasks for 3

arithmetic expressions 414, 415arithmetic functions and statements. See math

functions and statementsarithmetic operators

listed 419order of evaluation for 419, 420

array functions and statements 2array variables 184, 390arrays

adding to procedures 143, 375assigning to user-defined variables 390changing at run time 223

deallocating memory for 100declaring as dynamic 89, 90, 312declaring as fixed-size 365defining dimensions 89, 182, 313, 390determining contents 139determining number of elements in 394getting elements in dynamic 223getting lower bounds 222getting upper bounds 394initializing 312literal values in 391naming 313passing to procedures 23programming tasks for 2reinitializing fixed 100resizing 312, 314setting lower bounds 284sorting 402variables referencing 195

As keywordin Class statements 39in Declare statements 85in Dim statements 90in Function statements 143in Global statements 183in Name statements 266in Open statements 279in ReDim statements 313in Static statements 365in Sub statements 375

Asc function 3, 8, 18ASCII characters

getting 35programming tasks for 8reading 233string types and 414

ASCII text files. See text filesAscW function 19Assert statement 5, 20assets

See also annuitiesgetting depreciation of 81, 361, 377getting net present values 273getting rate of return 210, 253programming tasks for 6

assigning classesto variables 90, 183, 313

Page 470: Actuate Basic Reference

446 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

assigning data typesto constants 46to functions 84, 86, 143, 145to subprocedures 375to variables 85, 90, 183, 313, 390to variants 197

assigning valuesas nulls 196, 231to data types 231, 415to variables 188, 214, 230, 391

assigning variablesto classes 39to object references 344to variant data 59, 196, 397

Atn function 7, 20ATTR_ARCHIVE constant 155, 346ATTR_DIRECTORY constant 155ATTR_HIDDEN constant 155, 346ATTR_NORMAL constant 155, 346ATTR_READONLY constant 155, 346ATTR_SYSTEM constant 155, 346ATTR_VOLUME constant 155attributes

getting current 154getting file type 112getting locale-specific 164setting file type 346

audible signals 22

Bbacking up files 346backslashes (\) 128, 132backspace characters 35BAnd operator 156, 430.bas files. See source filesBasic. See Actuate BasicBeep statement 4, 22binary files

accessing 282decoding from strings 48encoding as strings 47getting bytes from 199getting current position 235, 340locking 237opening 280programming tasks for 3, 6

reading from 149, 151, 198setting position 338testing input position 99writing to 301

Binary keyword 285Binary mode 112, 280binding column names to data rows 348bitwise And operator 156, 430bitwise comparisons 156, 430, 435, 436bitwise Not operator 434bitwise Or operator 436blank lines 196BNot operator 434Boolean operators

conjunction 429disjunction 435equivalence 431exclusion 437implication 432negation 433

Boolean valuescomparing 343data types supporting 413evaluating 117getting 128

Boolean variables 117BOr operator 436brackets ([ ]) as wildcard delimiter 439branching 276, 402

program comments and 315programming functions listed 2to specified line 185

browser codedisplaying output 168

browser scripting controlsadjusting bounding rectangle for 168

buffersflushing 43reading 317setting size 280writing to 279

bursting 350button style constants 261, 264buttons

adding to dialog boxes 201, 260, 263defining as default 261, 264selecting at run time 262

Page 471: Actuate Basic Reference

I n d e x 447

byte copy operations 226, 248, 327byte functions 8byte locks 236bytes 411ByVal keyword 23

in Declare statements 85in Function statements 143in Sub statements 375

Cc format character 134C functions

defining pointers to 412calculations

on date/time values 413programming tasks for 7returning depreciation 82

Call keyword 22Call statement 7, 22Cancel buttons 261, 262, 264carriage return characters 35, 198, 200cascading style sheets 181case comparisons 285case conversions 136, 224, 395Case Else keyword 342Case keyword 341case sensitivity 285, 343, 368, 439case statements 2, 341cash flow. See annuities; assetscatalogs xiCCur function 3, 24CDate function 3, 26CDbl function 3, 29CF_LINK constant 160, 349CF_TEXT constant 160, 349changing

case 136, 137, 224, 395current drive and directory 31, 32disk files 115, 119file names 266headlines 351strings 246, 249, 373

channels 164, 351character codes

getting ANSI 18

getting UCS-2 encoding 19string types and 414translating 34, 36

character conversions 18, 19, 34, 36character lists 439character placeholders 136, 137character strings. See stringsChDir statement 6, 31ChDrive statement 6, 32Chr function 3, 8, 34Chr$ function 3, 8, 34ChrW function 36ChrW$ function 36CInt function 3, 37

compared with Fix and Int 122circumference 47class functions and statements 2class names

assigning to classes 39determining fully qualified 16getting 158

Class statement 2, 39ending 95

class variablesaccessing 2copying 2initialization values for 183

classesaliasing instance variables for 348assigning to variables 90, 183, 313assigning variables to 39creating handles to Java 50creating Java 51declaring 39defining 94getting IDs 157instantiating 51, 268, 269, 345nesting 40programming tasks for 2referencing 183, 313testing for specific 159testing object status within 215

ClearClipboard function 4, 40Client Integration Technology xiiiclient/server applications

getting currently running 153

Page 472: Actuate Basic Reference

448 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

Clipboardclearing 40copying to 349getting contents 160programming tasks for 4, 8

Clipboard formats 349CLng function 3, 41clock 27, 71

time formats for 132, 135Close statement 5, 43closing disk files 43, 317clusters xiiicode

adding comments 315disabling while debugging 315examples for 12

Code Example window 12color codes

getting 323returned by QBColor 307

color constants 308color translations 307column names

binding to records 348columns

mapping to records 348comma separated values 169, 219Command function 4, 45command prompt

running files from 356Command$ function 4, 45command-line arguments

getting 45programming tasks for 4

comments xxi, 315comparison operators

described 426Is keyword and 342listed 419order of evaluation for 419, 420

comparisonsagainst a range of values 342bitwise 430, 435, 436Booleans 343currency 428expressions 341, 426numeric values 206, 343

object reference variables 437strings 285, 343, 368, 438variants 427

compilers 45completed requests

creating headlines for 351getting headlines for 163

Component Editordisplaying sample code in 12

componentsgetting class information for 157, 159

concatenationdescribed 429operator precedence and 420

concatenation operators 7conditional statements

programming tasks for 5conditions

applying to function calls 145applying to return values 194comparisons as 341running programs with 20setting for control structures 91, 192, 401testing 192

conjunction 429Const statement 9, 46constants

adding to arrays 391assigning data types to 46associating with database columns 348declaring as global 86declaring as symbolic 46, 349getting characters in string 225, 226, 325,

327naming 46programming tasks for 9report aging 352variant types 398

container objectsdynamically adjusting height 161

content management systems xiContents command 12context menus

adding hyperlinks 124context-sensitive help xviii, xixcontext-sensitive strings 105control codes 35

Page 473: Actuate Basic Reference

I n d e x 449

control functions and statements 2control structures

branching 185, 402executing indefinitely 91executing with conditions 192, 401exiting 107nesting 92, 192repeating statement blocks 137, 401stepping through 366

controlling program execution 366controlling program flow 2controls

adding to frames 40displaying login names in 171getting references to 438scaling 168

conversion functions and statements 3conversions

binary images to strings 47, 48case 136, 224, 395character strings 18, 19, 34, 36dates to strings 289dates to variants 60decimal to hexadecimal 187decimal to octal 275expressions to dates 26expressions to strings 55numbers to currency 24numbers to dates 213numbers to doubles 29numbers to integers 37numbers to longs 41numbers to singles 53numbers to strings 126, 187, 275, 366numbers to variants 58programming tasks for 3, 8radians to degrees 21strings to dates 289strings to numbers 53, 122, 206, 291testing status 212, 217

ConvertBFileToString function 3, 6, 47ConvertStringToBFile function 3, 6, 48Copy command (DOS) 113copying

bytes 226, 248, 327code examples 12, 13data 40, 160, 349disk files 113

strings 225, 243, 245, 325, 388text 243, 349, 388variables 49

CopyInstance statement 2, 49copyright symbols 35corrupting data 151, 303Cos function 7, 50cosecant 441cosine 50cotangent 441counter variables 139counters

debugging with 139incrementing 92, 138, 401setting 137, 139

CPointer data typeas variant 415assigning values 231described 412initialization values for 183

CreateJavaClassHandle function 2, 50CreateJavaObject function 2, 51CreateObject function 4, 52creating

database records 348instance variables 39Java classes 51OLE objects 52report archives 351report files 350report-specific online help xxistatic variables 39temporary files 44, 99, 112

cross-platform reporting xiiCSng function 3, 53CSS formats 181CStr function 3, 55CSV formats 169, 219CurDir function 6, 57CurDir$ function 6, 57currency

as variant 415formatting 127valid ranges 412

currency controlscomparing values in 428programming tasks for 6type declarations for 412, 415

Page 474: Actuate Basic Reference

450 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

Currency data typeconverting to 24described 412

Currency format 127Currency keyword 127currency symbols 130, 414currency variables 412current drive/directory 58current release ixcustom browser code

displaying output 168customer profiles xCustomer Support xvicustomizing

applications xiiireports xiii

customizing reports 177CVar function 3, 58CVDate function 3, 60

Dd format character 287data

accessing xianalyzing xivassigning to variables 195, 391case conversions and 396copying 40, 160, 349corrupting 151, 303exporting/importing 289, 406formatting 125, 404misreading 151, 303printing unformatted 297reading from disk 149reading from sequential files 195, 198reading from variables 300

data integrity xiidata rows. See recordsdata streams

creating complex 50writing date data to 290

data typesaliasing 392assigning to constants 46assigning to functions 84, 86, 143, 145assigning to subprocedures 375assigning to variables 85, 90, 183, 313, 390

assigning to variants 197assigning values 231, 415conversion functions for 3, 8creating user-defined 391, 414declaring as variant 415declaring in external procedures 84default assignment 313, 415defining 94listed 411mismatching 228passing to procedures and DLLs 25storing 229suppressing type checking for 412

databasesaccessing data 406binding columns to records 348e.reporting solutions for x, xi

Date data typeconverting to 26described 412

date expressions 65, 70, 399creating user-defined formats 132entering locale-specific format

characters 287entering time values in 27, 64, 66, 70, 73evaluating 212getting number of weeks 69negative numbers in 26not specifying century in 27returning time values 188, 251, 334

Date function 3, 63date literals 197date separators 133date serial numbers

as time 188, 251, 335assigning to variables 270described 26formatting 131getting 72time values in 384, 386

date stampsfile creation 115, 119file modification 115, 119

date variables 412Date$ function 3, 63date/time functions and statements 3DateAdd function 3, 64

Page 475: Actuate Basic Reference

I n d e x 451

DateDiff function 3, 66DatePart function 3, 69dates 74

adding specified time intervals to 64as variant 65, 68, 72, 290, 415assigning to variables 63checking conversion status 212converting expressions to 213, 289converting to strings 289converting to variants 60displaying 69, 74, 77, 80formatting 63, 125, 131getting day of month 78getting difference between specified 66getting for specified string 75getting month 257getting number of weeks 68getting system 63, 270getting weekday 95, 165, 399getting year 407importing from other applications 289parsing 69, 290programming tasks for 3redefining formats for 132specifying for report archiving 352specifying locale specific 28, 287type declarations for 412valid ranges for 212

DateSerial function 3, 72DateValue function 3, 75day format characters 133Day function 3, 78day. See weekday; datesDDB function 6, 81deallocating memory 100debugging 309, 314, 366

branching and 186disabling source code while 315error handlers 106invalid arguments and 17programs with counter variables 139programs with global variables 183

decimal numbersconverting to hexadecimal 187converting to octal 275defining colors with 308, 323formatting 127

programming tasks for 3decimal placeholder 129, 291declarations 87

arrays 89, 182, 312class 39external procedures 83functions 141indefinite loops 91procedures 364subprocedures 373symbolic constants 46variables 89, 182, 364, 389

Declare statement 7, 83ending 95

Declare...End Declare statement 86Decode function 8, 88Decode$ function 8, 88decoding

binary images 48disk files 88

default dates/time 26default directories 57

for copy operations 113for delete operations 220, 328in renaming operations 266

degrees 21DEL command (DOS) 221deleting

directories 328disk files 220, 352leading spaces 126

delimiters 405deployment xi, xvdepreciation 81, 361, 377derived classes 39design tools xiiDesigner. See e.Report Designerdesigning e.Spreadsheet reports xiii, xvdesigning reports xiidesigns

embedding images in 48developing reports xiii, xxidevelopment languages xiiidevelopment tools xiii, xivDHTML converter

scaling controls 168DHTML formats 181, 220

Page 476: Actuate Basic Reference

452 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

DHTML reportsdisplaying xigetting supported viewing formats for 180programming tasks for 5searching 169, 218

DHTMLLong formats 181DHTMLRaw formats 181dialog boxes

adding buttons 260, 263adding icons 261, 264adding title bars 201, 262, 265displaying dynamically 263displaying prompts in 201displaying user-defined messages 260, 263

Dim keyword 39Dim statement 2, 9, 89

ReDim statement vs. 314directories

adding to search paths 111, 121changing 31creating 255deleting 328getting attributes 154getting default 57moving 267moving files between 266removing files from 221renaming 266testing existence of 116

directory labels 155directory paths

default for copy operations 113default for delete operations 220default for search operations 58getting absolute 120setting system specific 57, 115specifying current drive 32specifying default drive 32specifying partial 32

disablingerror handlers 277type checking 412

disjunction 435display formats 181, 219display layouts 161

monospaced characters and 299, 380displaying

Clipboard content 349code examples 12custom browser output 168dates 69, 74, 77, 80DHTML reports xierror messages 20, 316headlines 351messages 22, 260, 263, 406online documentation xviiiprompts 201reports xv, 181

divide by zero errors 102, 103displaying messages for 106preventing 334

division 334, 424, 425DLLs

calling subprocedures from 22declaring procedures for 23, 83, 412disabling type checking for 412passing incorrect types to 25specifying 84

Do...Loop statement 2, 91nesting 92terminating 108

document filesgetting IDs for 15opening in web browsers 123searching for 121specifying as default 350

documentation xviiaccessing xviiioverview xvsyntax conventions for xxiitypographical conventions for xxi

DOS command processor 357DOS command prompt. See command-line

argumentsDOS file handles 112DOS shell 356Double data type

converting to 29described 413

double precision real 29, 74, 413double quote (") characters 35, 128, 132double-declining depreciation 82download formats 169, 219

Page 477: Actuate Basic Reference

I n d e x 453

drivechanging 31, 32entering in string expressions 57getting default directory 57specifying default 32

DWBContext constant 153dynamic arrays 89, 90

clearing 100declaring 182, 312determining number of elements in 394getting number of elements 223resizing 312, 314

dynamic-link libraries. See DLLs

EE– or e– format characters 130E+ or e+ format characters 130e.Analysis Option xive.Business applications xie.Report Designer xii

getting command-line arguments for 45e.Report Designer Professional xiii, 320

copying code examples 12error reporting for 316getting temporary Excel file names 182

e.Report Engine xve.Report Option xive.reporting solutions ix, xie.Spreadsheet Designer xiii, xive.Spreadsheet Engine xve.Spreadsheet Option xive.Spreadsheet reports

designing xiii, xvgenerating xiv

electronic catalogs xiElse keyword 193ElseIf keyword 193embedding image controls 48empty values 216, 415, 416

testing for 214Encode function 8, 94Encode$ function 8, 94encoding

binary images 47UCS-2 code point for 19

encoding formats 88, 94encryption 88, 94

Encyclopedia volumesgenerating documents for xiii

End If keyword 193End keyword 95End statement 2, 94

Exit statement vs. 108End User Desktop xiiend-of-file indicator 98enterprise reporting x, xienumerated values 413Environ function 4, 96Environ$ function 4, 96environment functions and statements 4environment variables

getting specific settings 96programming tasks for 4

EOF function 6, 98equality 427equivalence 431Eqv operator 431ERASE command (DOS) 221Erase statement 2, 100Erl function 5, 101Err function 5, 102Err statement 103error codes

creating user-defined 104getting 102returning messages for specific 105setting 103

Error function 5, 105error messages 277

creating user-defined 104, 106displaying 20, 316getting 105

Error statement 5, 106error trapping functions and statements 5Error$ function 5, 105errors

accessing run-time 101, 102, 103creating routines for 106, 107, 319disabling handlers for 277generating user-defined 104, 106getting for Java classes 51, 52handling run-time 276preventing divide by zero 334programming tasks for 5

Page 478: Actuate Basic Reference

454 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

errors (continued)recovering from 318reporting 316simulating 106trapping 20variants and overflow 415

EUDTContext constant 153Example folder xviExcel files

writing to temporary files 182, 355Excel spreadsheets

developing for xiii, xvgenerating xiv

exceptionsgetting Java 164programming tasks for 5

Exclamation Point icon 261, 264exclusion 437executable files

creating 45getting version 152, 163, 168running from DOS 356

executing applications 45, 357executing programs

at specified place 317from DOS shell 357

Exit Do keyword 92Exit For keyword 138Exit Function keyword 143Exit statement 8, 107Exit Sub keyword 374Exp function 7, 110expiration age 352exponentiation 110, 425exponentiation operator 425exponents 413exporting data 406expressions

aligning in variables 243assigning to constants 46bitwise comparisons in 430, 435, 436checking for null values in 216comparing 341, 426converting to currency 25converting to dates 26, 212converting to numbers 30, 37, 41, 53converting to strings 55

converting to variants 58, 60creating numeric formats 130creating user-defined formats 128, 132entering current drive 57entering locale-specific format

characters 287entering specific days/dates 28entering time values in 27, 64, 66, 70, 73entering variant data in 414, 415evaluating 194getting absolute values 14inserting functions in 84mixing type formats in 126not specifying century in date 27operator precedence in 419performing logical operations on 429, 432,

433, 435, 437returning time values 188, 251, 334setting line widths 403testing equality 431translating character codes 18, 19, 34, 36trigonometric functions in 441

ExtendSearchPath function 5, 111external applications xii

running from DOS shell 357external procedures

calling from DLLs 83disabling type checking for 412

FF1 key xixFactory dialog 4, 358Factory service

getting status 358getting version 163

FactoryReportContext constant 167False keyword 128fatal errors 277fields

mapping to records 348file buffers

flushing 43reading 317setting size 280writing to 279

file descriptors 98file I/O functions and statements 5

Page 479: Actuate Basic Reference

I n d e x 455

file I/O operations 228, 229, 278file IDs 15file mode. See file type attributesfile names

changing 266extracting 320getting for temporary files 182resolving relative 120

file numbersgetting unused 140reusing 44setting 279

file type attributesgetting 112, 154setting 280, 346

FileAttr function 6, 112FileCopy statement 5, 113FileDateTime function 6, 115FileExists function 6, 116FileLen function 6, 117files

accessing 282archiving report 351assigning access permissions 279, 281backing up 346caution for deleting 221changing 115, 119checking input position 98closing 43, 317copying 113creating multiple report 350creating temporary 44, 99, 112deleting 220, 352encoding binary graphics 47, 48encoding disk 88, 94error handling 104getting bytes from 199getting current position 234, 339getting date/time information 115, 119getting DOS handles 112getting end-of-file indicator 98getting report version 168getting size 117, 240locking/unlocking 236, 279, 281moving 266opening 104, 140, 235, 278, 319printing to disk 297, 379, 403

programming tasks for 5, 6reading 149, 195, 198, 232renaming 266running from DOS 356searching for 111, 120setting default report 350setting position 337testing existence of 116writing to 297, 299, 300, 317, 404

FileTimeStamp function 119filters

creating multiple input 50financial functions and statements 6FindFile function 6, 120fiscal quarters

getting difference between 66getting for user-defined formats 134getting specified 70

Fix function 3, 7, 122compared to Int 206

Fixed format 127Fixed keyword 127fixed-size arrays

declaring 365reinitializing 100

fixed-width fonts 299, 379floating-point numbers

as variant 415data types for 413, 414getting double-precision 29storing 413storing dates as 74storing time as 384, 386

FollowHyperlink statement 2, 123fonts 162

onscreen displays and 299, 380For...Next statement 2, 137

terminating 108format characters

creating user-defined formats with 129, 133, 135, 136

entering in expressions 126locale-specific date conversions 287

Format function 3, 7, 8, 125format patterns 126

See also format charactersFormat$ function 3, 7, 8, 125

Page 480: Actuate Basic Reference

456 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

formats 164creating user-defined 128, 132, 136described 132getting DHTML search 169getting supported DHTML viewing 180program-specific described 127testing search 218

formattingdates 63, 125, 131numbers 125, 127output 404strings 125, 136time 27, 132, 134

Formula One product suite xvfractions

as special characters 414removing 37, 122

frames 40FreeFile function 6, 140freeing resources 345Function keyword 84Function...End Function statement 8, 141functions

alphabetical reference for 11assigning data types to 84, 86, 143, 145declaring 141declaring constants in 46declaring external procedures as 84ending declarations for 94naming 141nesting 144overloading 141running from reports 13terminating execution 108, 143variant data and 414, 415with no parameters 144

fundamental data types. See data typesfuture dates 64future values 146, 208FV function 6, 146

GGeneral date format 132General number format 127general purpose libraries 177generating

reports xiii

generating reports 358Get statement 6, 149GetAFCROXVersion function 4, 152GetAppContext function 4, 153GetAttr function 6, 154GetClassID function 2, 157GetClassName function 2, 158GetClipboardText function 4, 8, 160GetDisplayHeight function 6, 161GetFactoryVersion function 4, 163GetHeadline function 163GetJavaException function 5, 164GetLocaleAttribute function 164GetMessageArgument function 166GetMLocaleName function 165GetOSUserName function 4, 166GetReportContext function 4, 167GetReportScalingFactor function 4, 168GetROXVersion function 4, 168GetSearchPageFormats function 5, 169GetServerName function 4, 170GetServerUserName function 4, 171GetUserAgentString function 4, 171GetValue function 2, 172GetValueType function 2, 174GetVariableCount function 2, 176GetVariableName function 2, 178GetViewContext function 180GetViewPageFormats function 5, 180GetVSTempFileName function 182Global keyword 46Global statement 2, 9, 182global variables 90

caution for declaring 183declaring 86, 182initializing 184

GoTo keyword 276GoTo statement 2, 185graphics files

converting binary 47, 48searching 111

graphics functions and statements 6

Hh or hh format characters 135Header.bas 155Headline parameter 164

Page 481: Actuate Basic Reference

I n d e x 457

headlinescreating at run time 351getting 163

help xviii–xxiopening code examples in 12

Help menu xixhelp topics xixHex function 3, 187Hex$ function 3, 187hexadecimal notation 188hexadecimal numbers

converting to decimal 187defining colors with 308, 323getting values 396

hidden files 155, 346home page (Actuate) xvhour

counting 67formatting 135getting increments 250, 334returning 188

Hour function 3, 188HTTP requests 171hyperbolic cosecant 441hyperbolic cosine 441hyperbolic cotangent 441hyperbolic secant 441hyperbolic sin 110hyperbolic sine 441hyperbolic tangent 441hyperlinks

adding to context menus 124adding value indexes to 16, 17building at run time 124defining URLs for 123searching with 16

hyphen (–)as literal 130as wildcard 439

Iicon style constants 261, 264icons

adding to dialog boxes 261, 264IDABORT constant 262IDCANCEL constant 262IDIGNORE constant 263

IDNO constant 263IDOK constant 262IDRETRY constant 263IDYES constant 263If keyword 192If...Then...Else statement 2, 192

ending 95Ignore buttons 261, 263, 264IIf function 2, 194images

embedding 48encoding binary 47, 48programming tasks for 3, 6searching 111

Imp operator 432implication 432implicit date conversions 289importing data 289, 406incorrect values 414index (online documentation) xviiiindexes 15, 172inequality 427Information Delivery API xivinformation delivery solutions ix, xiInformation icon 261, 264information objects xiiiinformational functions and statements 9initializing

arrays 312global variables 182, 183Java objects 52variables 89, 90, 214, 314

inputassigning to variables 232concluding 43defining error messages for 105getting record size for 228, 229opening files for 278programming tasks for 5prompting for 201reading from sequential files 232testing end-of-file position 98validating 195

Input # statement 6, 195input boxes

displaying 201entering variant data 414

Page 482: Actuate Basic Reference

458 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

input filterscreating multiple 50

Input function 6, 198input functions and statements. See file I/O

functions and statementsInput mode 112, 280Input$ function 6, 198InputB function 6, 199InputB$ function 6, 199InputBox function 5, 201, 414InputBox$ function 5, 201installing online documentation xviiiinstance variables

aliasing 348counting 176, 178creating 39getting values 172

instantiatingclasses 51, 268, 269, 345objects 268, 269, 350

instantiation 2, 268, 269InStr function 8, 202

RevInStr compared with 321InStrB function 8, 204Int function 3, 7, 206

Fix function vs. 122Integer data type

converting to 37described 413

integer variables 413integers

See also numbersas dates 74, 134as strings 414as variant 415checking conversion status 217comparing 427converting to dates 27, 28, 60converting to doubles 29converting to longs 41converting to singles 53converting to variants 58expressing as exponents 110, 425getting 122getting character codes for 34, 36getting largest 206getting square root 363

initialization values for 183inputting as error code 103, 105storing 413testing 355valid ranges for 413

integrated content xiiinterest rates 207, 310internal rate of return 253international alphabets 414invalid arguments 17invalid data types 196inverse cosine 441inverse cotangent 441inverse hyperbolic cosecant 442inverse hyperbolic cosine 442inverse hyperbolic cotangent 442inverse hyperbolic secant 442inverse hyperbolic sine 441inverse hyperbolic tangent 442inverse sine 441investments

See also annuitiesgetting depreciation for 81, 361, 377getting interest rates 310getting net present values 273getting principal payments 294getting rate of return 210, 253

IPmt function 6, 207IRR function 6, 210Is keyword 342Is operator 437IsDate function 3, 9, 212IsEmpty function 9, 214iServer

managing multiple xiiioverview xprogramming tasks for 4running multiple xiii

iServer Systemoverview xiii

IsKindOf function 2, 215IsNull function 9, 216IsNumeric function 9, 217ISO date format 288IsPersistent function 2, 218IsSearchFormatSupported function 5, 218IsViewPageFormatSupported function 5, 219

Page 483: Actuate Basic Reference

I n d e x 459

JJava classes

creating 51defining handles for 50

Java exceptions 164Java objects xv

initializing 52Java programs

developing for xv

Kkeywords

formatting functions 127, 132listed 417

Kill statement 6, 220

Ll format character 287launching report applications 45, 357LBound function 2, 222LCase function 8, 224LCase$ function 8, 224leading spaces 126

defined 243reading 198, 200removing 243, 388

leap years 426Left function 8, 225Left$ function 8, 225LeftB function 8, 226LeftB$ function 8, 226Len function 8, 228Len keyword 279LenB function 8, 229Let keyword 231Let statement 8, 230Lib keyword 84libraries

creating general purpose 177designing with xii

Library Organizercreating source files 12

Like operatordescribed 438precedence 420

line breaks 35, 202, 263Line Input # statement 6, 232line numbers

getting 102setting 186

line widths 403linefeed characters

character code for 35reading 198, 200

LinkExp property 124links (online documentation) xviiiliteral characters

adding to date expressions 132adding to numeric expressions 128as format specifiers 130

literal stringsadding to expressions 128, 132copying portions of 245getting characters in 225, 226, 325, 327replacing portions of 247, 250trimming 333variant dates as 197

literal valuesnull as 405static arrays and 391symbolic constants as 46

Live Report Extension (LRX)calling hyperlinks from 124

loading code examples 12Loc function 6, 234local variables 365

preserving 141, 374locales

e.reporting solutions for multiple xformatting data for specific 126getting attributes for 164getting current run time 165international character set for 414specifying dates for 28, 287

Lock Read keyword 281Lock Read Write keyword 281Lock Write keyword 281Lock...Unlock statement 6, 236locks 236, 279, 281LOF function 6, 240Log function 7, 241

Page 484: Actuate Basic Reference

460 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

logarithms 241, 442logical operators

conjunction 429disjunction 435equivalence 431exclusion 437implication 432negation 433order of evaluation for 419

logical valuescomparing 343data types supporting 413evaluating 117getting 128

loginsgetting system 166, 170, 171

Long data typeconverting to 41described 413

long date formatsapplying 132, 133converting 28, 61

long integers 413Long time format 132loops

branching 185, 402closing nested 139defined 401defining indefinite 91ending immediately 138executing with conditions 192, 401exiting 107interrupting 92nesting 92programming constructs for 2repeating specified number of times 137repeating statement blocks 401stepping through 366variables and 177

lowercase conversions 136, 224, 395LRX (Live Report Extension) xv

calling hyperlinks from 124LRXContext constant 153LSet statement 8, 242LTrim function 8, 243LTrim$ function 8, 243

Mm format character 288Management Console xiiimanaging clusters xiiimantissa 413Manuals directory xviiimapping column names to data rows 348math functions and statements 7mathematical operations

arithmetic operators for 419date/time values in 413entering variant data in 414, 415operator precedence in 419, 420preventing divide by zero errors 334

MB_ABORTRETRYIGNORE constant 261, 264

MB_APPLMODAL constant 262, 265MB_DEFBUTTON1 constant 261, 264MB_DEFBUTTON2 constant 261, 265MB_DEFBUTTON3 constant 261, 265MB_ICONEXCLAMATION constant 261,

264MB_ICONINFORMATION constant 261, 264MB_ICONQUESTION constant 261, 264MB_ICONSTOP constant 261, 264MB_OK constant 261, 264MB_OKCANCEL constant 261, 264MB_RETRYCANCEL constant 261, 264MB_SYSTEMMODAL constant 262, 265MB_YESNO constant 261, 264MB_YESNOCANCEL constant 261, 264Medium date format 132Medium time format 132memory

allocating 89, 182deallocating 100

menusadding hyperlinks to context 124

message boxesadding title bars 201, 262, 265displaying dynamically 263displaying prompts in 201displaying text in 199, 200, 260, 263entering variant data 414

Page 485: Actuate Basic Reference

I n d e x 461

messagesdisplaying 22, 260, 263, 406getting strings for 56inserting quotes in 35

Method Editorcopying code examples 12, 13

methodsprocedures as 40

Mid function 8, 245Mid statement 246Mid$ function 8, 245Mid$ statement 246MidB function 8, 247MidB statement 249MidB$ function 8, 247MidB$ statement 249military time 27, 71

getting 132, 135, 382MIME type 320Minute function 3, 250minutes

counting 67formatting 135getting second 334returning 250

MIRR function 6, 253mixing colors 308MkDir command (DOS) 256MkDir statement 6, 255Mod operator 425modal dialog boxes 262, 265modality constants 262, 265modified rate of return 253modules

declaring procedures in 86modulus 425monetary values 127monospaced characters 299, 379month

entering in expressions 73format characters for 134getting 70, 257getting day of 78getting difference in 66

Month function 3, 257moving files 266MsgBox function 260

MsgBox statement 5, 263Multi-Application Option xivmultibyte characters 18multidimensional arrays

changing at run time 223declaring 313defining dimensions 89, 182, 313, 390determining contents 139getting lower bounds 222getting upper bounds 394setting lower bounds 284

multi-line statements 94multilingual reporting xmultiplication operator 420Multipurpose Internet Mail Extensions

(MIME) 320

Nn or nn format characters 135name conflicts 144Name statement 6, 266names

caution for keywords as 417determining fully qualified 16

namingarrays 313constants 46functions 141procedures 144, 364, 375subprocedures 374temporary files 355variables 364

negation 433negative numbers

as monetary values 127as operands 422as variant 415comparing 206displaying 130financial transactions and 209in date expressions 26, 64rounding 122testing for 355valid ranges for 413

nested classes 40getting names 159

Page 486: Actuate Basic Reference

462 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

nestingcontrol structures 92, 192functions 144loops 92, 139statements 108subprocedures 376

net present value 6, 273New keyword 345New Library dialog 12new lines 202, 263, 405

setting line breaks for 35setting line widths for 403

NewInstance function 2, 268NewPersistentInstance function 2, 269Next keyword 138, 318No buttons 261, 263, 264No keyword 128nonprintable characters 35Not operator 433Nothing keyword 345Now function 3, 270NPer function 6, 271NPV function 6, 273NT servers 357null digit placeholder 129Null keyword 216null values

as literals 405assigning 196, 231empty values vs. 214, 216format specifier for 129testing for 216variant data returning 415

numbersas dates 74, 134as strings 414as variant 196, 415assigning to variables 194, 228, 229, 230checking conversion status 217comparing 206, 343, 427converting strings to 53, 122, 206, 291converting to currency 24converting to dates 27, 28, 60, 213converting to doubles 29converting to integers 37converting to long 41converting to singles 53

converting to strings 126, 187, 275, 366converting to variants 58expressing as exponents 110, 425extracting from strings 217, 396financial transactions and 209formatting 125, 127generating random 108, 308, 330getting absolute values 14getting character code for 34, 36getting from sequential files 196getting hexadecimal 187getting natural logarithms 241getting number of digits in 193getting octal 275getting square root 363getting values 396initialization values for 183inputting as error code 103, 105parsing 291programming tasks for 3redefining formats for 128removing fractional part 37, 122removing leading spaces 126representing time intervals 64testing 355valid ranges for 413

numeric data typesassigning values 231described 412, 413, 414reading 302

numeric expressions 187adding format characters to 130bitwise comparisons in 430, 435, 436creating user-defined formats 128evaluating 217setting line widths 403

OObject Linking and Embedding. See OLEobject reference variables

comparing 437getting 172initialization values for 183OLE Automation and 53

object referencesassigning to variables 344

Page 487: Actuate Basic Reference

I n d e x 463

objectschecking for given type 157copying variables between 49customizing aging settings for 353discontinuing associations 345free resources for 345getting class information 157, 158, 215getting number of variables 176, 178instantiating 268, 269, 350referencing 345, 437testing for type 218

Oct function 3, 275Oct$ function 3, 275octal notation 275octal numbers 397Off keyword 128OK buttons 261, 262, 264OLE applications 4OLE Automation objects 52On Error statement 2, 5, 276On keyword 128On/Off format 128online documentation

accessing xviiioverview xvsyntax conventions for xxiitypographical conventions for xxi

online help xviii–xxiopening code examples in 12

open server technology xiiOpen statement 5, 278opening

code examples 12disk files 104, 140, 235, 278, 319document files 123web pages 123

operating environmentsSee also specific environmentgetting system attributes for 155getting system dates/time 63, 270, 381getting variables for 96locking files and 238setting file type attributes 347setting system clock 384storing information for 97task-specific functions and statements 4

operators

categorized 7described 419order of evaluation for 419

Option Base statement 2, 284Option Compare statement 8, 285

Binary keyword in 439options

iServer System xivOr operator 435order of evaluation 419output

adding spaces to 298as unformatted data 297concluding 43controlling date conversions for 290defining line widths for 403determining system 161displaying browser 168e.reporting solutions for xiiformatting 404getting record size for 228, 229opening files for 278print zones for 299printing 379programming tasks for 5sending to disk files 300

output functions and statements. See file I/O functions and statements

Output mode 43, 112, 281overflow errors

currency conversions 25numeric conversions 29, 38, 42, 54variant types 59, 415

overloading functions 141overloading subprocedures 374overriding operator precedence 419

Pp format character 288Page Level Security Option xivpage-level security xivparameter lists

checking 86defining for functions 142defining for subprocedures 374procedure calls and 23

Page 488: Actuate Basic Reference

464 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

parametersconverting for DLLs 23disabling type checking for 412getting values 166overloaded procedures and 141, 374passing conventions 23, 85, 143, 375setting values 351

parentheses ( )as literals 130in expressions 419

ParseDate function 3, 287ParseNumeric function 291parsing

dates 69, 290numbers 291strings 164, 225, 245, 247, 320variant data 225, 226, 325, 326

passing by reference 23passing by value 23, 85, 143, 375passwords

obtaining customer xvpast dates 64path names 32PATH variable 97paths

adding directories to 121default for copy operations 113default for delete operations 220default for search operations 58getting absolute 120setting system specific 57, 115specifying current drive 32specifying default drive 32specifying partial 32specifying search 111

pattern matching 439pattern matching operators 7patterns 129, 133, 135, 136payment due 65PDF formats 181, 220Percent format 128Percent keyword 128percentage placeholder 129percentages 128, 129periodic cash flows 210, 253, 273permissions 279, 281

persistent classes 269Persistent keyword 89persistent objects

getting file IDs from 15testing for 218

persistent variables 89Pmt function 6, 292pointers

as variant 415defining for C functions 412repositioning file 338, 339

positive numbersas variant 415converting to strings 126displaying 130financial transactions and 209in date expressions 64removing leading spaces 126testing for 355valid ranges for 413

pound sign (#)as format character 129as wildcard 439

PPmt function 6, 294precedence 419present value 146, 208, 304Preserve keyword 313principal 294Print # statement 6, 7, 297print zones 299printed documentation xviiprinters

determining output to 161sending control codes to 35

printing functions and statements 6printing output 297, 379, 403printing reports 6printing unformatted data 297PrintReportContext constant 167procedural functions and statements 7procedures

as methods 40declaring as external 83declaring as static 364declaring constants in 46declaring data types in 84

Page 489: Actuate Basic Reference

I n d e x 465

procedures (continued)declaring variables in 90disabling type checking for 412error handling in 277exiting 108, 143, 374naming 144, 364, 375overloading 141, 374passing incorrect types to 25preserving variables in 141, 365, 374programming tasks for 7requiring arguments 23returning values 83suspending program execution from 366terminating execution 108unconditional branching in 185

product suite xiiproduct updates xvprogramming languages xiiiprogramming tasks 1programming tools xiii, xivprograms

adding comments 315control functions and statements 2ending 44getting available variables for 17global variables and 183handling run-time errors 276programming tasks for 2, 4running at specified place 317running from DOS shell 357running with conditions 20stopping execution 366subprocedures controlling 22terminating 94timing 383

Progress databases xivProgress Option xivprompts

creating default response to 201displaying 201

propertiescaution for variables with same names 17

proportionally spaced characters 299pseudo-random sequences 309, 330Put statement 6, 300PV function 6, 304

compared to NPV function 274

Qq format character 134QBColor function 7, 307quarter

getting difference in 66getting for user-defined formats 134getting specified 70

queriesrunning ad hoc xiv

Query Builder 348Query Option xivQuestion Mark icon 261, 264quotation marks 128, 132

including in messages 35reading 198, 200

Rradians 21radical prefixes 188, 276radix characters 291random files

accessing 282getting current position 235, 340getting record size 228, 229locking 237opening 280reading from 149, 280setting position 338testing input position 99writing to 300

Random mode 112, 280random number generator

initializing 308random numbers 99

defining seed values for 309, 383generating 108, 308, 330specifying range for 331

random-access file mode 280Randomize statement 7, 308

Rnd statement and 330Timer function and 383

range of valuesarray subscripts 313character lists 439color codes 323comparing against 342

Page 490: Actuate Basic Reference

466 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

range of values (continued)data types listed 411hexadecimal numbers 188octal numbers 276random numbers 331variant data 415

Rate function 6, 310rate of return 6, 210, 253Read keyword 281Read Write keyword 281read-only files 155, 346read-only permissions 281real

converting to double precision 29data types for 413, 414storing dates as 74

real types. See Double data type; Single data type

record structuresassigning data types to 390declaring 389

recordsavoiding data misreads 151, 303creating 348determining size 228, 229locking 236mapping to columns 348omitting numbers referencing 149padding 301reading from 149, 350specifying length 280with different data types 391writing data to 301

recursive statements 40, 144, 376ReDim statement 2, 312

Dim statement and 90Erase statement and 100

referencesassigning to variables 344defining multiple 437

referencingclasses 183, 313objects 345

relational operators 426relationships xivrelative file names 120release notes xv

Rem statement 5, 315remainder 425Rename command (DOS) 267renaming

directories 266files 266

repeating characters 370, 371report designs

embedding images in 48report examples xvireport files

archiving 351assigning access permissions 279, 281caution for deleting 221changing 115, 119checking input position 98closing 43, 317copying 113creating multiple 350deleting 220encoding 88, 94error handling 104getting current position 234, 339getting IDs for 15getting size 117, 240getting version 168locking/unlocking 236, 279, 281opening 104, 140, 235, 278, 319programming tasks for 5running from DOS 356searching for 111, 120setting default 350setting position 337testing existence of 116writing to 299, 300, 404

Report Server API xivReport Server Security Extension xivReportCast xiiiReportContext variable 167ReportCustomFailure function 316

ReturnCustomFormat and 320Reporting Engines suite xiireporting solutions ix, xiReportQuery technology xiireports

customizing xiii, 177designing xii

Page 491: Actuate Basic Reference

I n d e x 467

reports (continued)developing xiii, xxidisplaying xv, 181generating xiiigetting generation status for 358getting run time context 167opening in web browsers 123programming tasks for 4providing online help for xxirunning functions from 13

Requester API xiiirequests

creating headlines for 351getting headlines for 163

reserved charactersdate formats 133numeric formats 129string formats 136time formats 135

reserved wordsformatting functions 127, 132listed 417

Reset statement 5, 317resizing arrays 312, 314resources 345Resume Next keyword 277Resume Next statement 318Resume statement 5, 317resuming program execution 317retrieving data 406Retry buttons 261, 263, 264return (cash flow) 210, 253return values

declaring in procedures 83functions and 142setting conditions for 194variant values and 414, 415

ReturnCustomFormat function 319ReportCustomFailure and 316

RevInStr function 8, 320RGB color values 308, 323RGB function 7, 323Right function 8, 325Right$ function 8, 325RightB function 8, 326RightB$ function 8, 326RmDir command (DOS) 329

RmDir statement 6, 328Rnd function 7, 330.roi files. See report object files; document filesRoiimage example 48, 49rounding 37, 122, 206routines

converting arguments for 23creating user-defined errors in 104defining error handling 106, 107, 319

rows. See records.rox files. See executable filesRSet statement 8, 331RTrim function 8, 332RTrim$ function 8, 332running applications 45, 357running programs

at specified place 317from DOS shell 357with conditions 20

run-time errorsdisabling handlers for 277getting error codes for 102getting line numbers for 101getting messages for 105handling 276setting error codes for 103

Ss or ss format characters 135SafeDivide function 5, 334sample applications xvisample code 12sample reports xviscaling controls 168scaling factor 168Scientific format 128Scientific keyword 128scientific notation 128, 130scripting control. See browser scripting

controlsSearch Extension API xiiisearch formats 169, 218search indexes 15search paths

adding directories to 121default 58specifying 111

Page 492: Actuate Basic Reference

468 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

search results 169Searchable property 16searching

DHTML reports 169, 218for disk files 111, 120for special characters 439graphics files 111with hyperlinks 16

secant 441Second function 3, 334seconds

counting 67formatting 135returning 334

sections 40security 236

e.reporting solutions for xiienabling page-level xiv

security tools xivseed values 309, 383Seek statement 6, 337Seek2 function 6, 339Select Case statement 2, 341

ending 95semicolon (;)

as format character 130as printer code 298

separatorsdate values 133numeric values 291tab characters 379time values 135

sequential filesaccessing 282getting bytes from 199getting current position 235getting specified characters 198locking 237opening 280printing to 297, 379, 403reading 195, 198, 232testing input position 98writing to 297, 299, 404

sequential input mode 280sequential output mode 281serial numbers

assigning to variables 270

converting to dates 26described 26formatting 131getting 72, 383programming tasks for 3storing 386

Server Integration Technology xiiiserver-based reporting xiiServerContext constant 153servers

e.reporting solutions for xigetting currently running application 153managing clusters for xiiiprogramming tasks for 4

Set statement 9, 344SetAttr statement 6, 346SetBinding function 348SetBinding statement 2SetClipboardText function 4, 8, 349SetDefaultPOSMFile function 5, 350SetHeadline statement 351SetMessageArguments function 351SetStructuredFileExpiration function 6, 351SetValue function 353SetVSTempFile function 355Sgn function 7, 355share.exe 238shared files 281Shared keyword 281Shell function 4, 356shelling out to DOS 356short date formats

applying 132, 133Short time format 132ShowFactoryStatus statement 4, 358Sin function 7, 359sine 359Single data type

converting to 53described 414

single-precision real 414Sleep function 4Sleep statement 360SLN function 6, 361SOAP messaging protocol xivsorting arrays 402sounds 22

Page 493: Actuate Basic Reference

I n d e x 469

source codeadding comments 315disabling while debugging 315examples for 12

source filescreating 12

space charactersadding to output 298as literal 130returning in strings 362stripping extra 388

Space function 5, 8, 362Space$ function 5, 8, 362Spc keyword 298special characters

in strings 414returning 35searching for 439

spreadsheetsdesigning xiii, xvgenerating xiv

Sqr function 7, 363square root 145, 363Standard format 127Standard keyword 127statements

adding to functions 142alphabetical reference for 11branching to 185defining as recursive 40, 144, 376ending multiline 94nesting 108running blocks with conditions 341

static arrays 391Static keyword 39, 141, 374static procedures 364Static statement 2, 9, 364static variables

creating 39declaring 141, 364, 374

status informationgetting for factory 358

Step keyword 138Stop icon 261, 264Stop statement 2, 366stopping program execution 366Str function 3, 366

Str$ function 3, 366Format$ function vs. 126

straight-line depreciation 361double-declining vs. 82

StrComp function 8, 368string constants

copying portions of 245getting leftmost characters 225, 226getting rightmost characters 325, 327replacing portions 247trimming 333

String data typeassigning values 231converting to 55described 414

String function 8, 370string functions and statements 8String$ function 8, 370strings

alignment 242, 331as format patterns 126, 129, 133, 135, 136as variant 415assigning to variables 230binary reads to 151changing 246, 249, 373changing case 136, 137, 224, 395comparing 285, 343, 368, 427, 438concatenating 429converting dates to 289converting numbers to 126, 187, 275, 366converting to currency 24converting to dates 26, 28, 60, 289converting to doubles 29converting to integers 37converting to longs 41converting to numbers 53, 122, 206, 291copying 225, 243, 325, 388copying only portions 245counting characters 228displaying as prompts 201encoding binary images as 47, 48entering current drive 57extracting only numbers from 217, 396formatting 125, 136getting character codes for 18, 19, 34, 36getting dates for specified 75getting from IDs 372

Page 494: Actuate Basic Reference

470 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

strings (continued)getting from sequential files 196getting leftmost characters 225getting length 228getting number of bytes 229getting rightmost characters 320, 325getting specific byte 204, 226, 326getting specific characters 198getting with specified spaces 362initializing variable-length 183limits for variable-length 414locating substrings in 202, 204, 325numbers as 414numeric expressions and literal 128, 132parsing 164, 225, 245, 247, 320programming tasks for 3, 6, 8reading 302removing leading spaces 126, 243, 388removing trailing spaces 332, 388replacing portions 246, 249, 373representing dates 63returning from Clipboard 160returning repeating characters in 370, 371space characters replacing content 105trimming 243, 332, 388truncating 242, 332writing variant data to 150

StringW function 371StringW$ function 371StrLoad function 6, 372StrLoad$ function 6, 372StrSubst function 8, 373structured content technology xstyle sheets 181Sub keyword 83Sub...End Sub statement 8, 373subclasses

declaring 39testing for instances of 215

subdirectoriesSee also directories; directory pathsadding to search paths 121creating 255deleting 328getting attributes 155removing files from 221

subprocedures

assigning data types to 375declaring 83, 373declaring constants in 46ending declarations for 94exiting 374naming 374nesting 376overloading 374programming tasks for 8terminating execution 108transferring control to 22

subroutines 186subscripts. See arrays; multidimensional

arrayssubstrings

getting leftmost byte 226getting leftmost character 225getting rightmost byte 326getting rightmost character 325getting starting byte 204getting starting position 202, 320programming tasks for 8replacing in strings 246, 249, 373returning 164, 225, 245, 247, 320

subtraction 422summary operator 421sum-of-years’-digits depreciation 377superclasses 39suppressing type checking 412SYD function 6, 377symbolic constants 46, 349syntax conventions (documentation) xxiisystem attributes 155system clock

setting 384time formats for 135

system dates and time 63, 270, 381system files 155, 346system variables 97

See also environment variables

Tt format character 288tab characters

character code for 35setting position 298, 379

Page 495: Actuate Basic Reference

I n d e x 471

Tab function 5, 379Tab keyword 298tab separated values 169, 219Tan function 7, 381tangent 381technical assistance xvitemporary addresses 23temporary files

creating 44, 99, 112determining size 240displaying messages from 406getting current position 235getting names 182getting unused file numbers from 140locking 238naming 355reading from 151, 197, 233writing to 151, 300, 317, 403

textadding to headlines 351aligning 243, 332copying 243, 349, 388determining headline 164determining height 161displaying in dialog boxes 260, 264displaying in title bars 201, 262, 265

text boxes 201text files 282

reading 149, 198, 200reading one line at a time 232writing to 299, 403

Text keyword 285text strings. See stringsThen keyword 192third-party productivity tools xiiithird-party security tools xivthousands separator 129, 291time

as date interval 27, 64, 66, 70, 73converting to variants 60date serial numbers as 26entering in date expressions 71formatting 27, 132, 134getting current 386getting increments 188, 250, 334getting seconds past midnight 382

getting seconds to midnight 252, 336, 385, 387

programming tasks for 3returning system 270, 381setting 384

Time function 3, 381time separators 135time serial numbers

formatting 131getting 383storing 386

time stampsfile creation 115, 119file modification 115, 119

Time$ function 3, 381Timer function 3, 382TimeSerial function 3, 383TimeValue function 3, 386title bars 201, 262, 265To keyword 236, 342trailing spaces 332, 388

defined 388transactions xiTransient keyword 89transient objects

testing for 218transient variables 89trapping errors 20trends xivtrigonometric functions 7trigonometric operations 7, 441Trim function 8, 388Trim$ function 8, 388trimming strings 243, 332, 388True keyword 128True/False format 128truncating numbers 122truncating strings 242, 332TSV formats 169, 219ttttt format characters 136type checking 412Type keyword 414Type Mismatch error

getting 427preventing 228

Type...As statement 9, 392Type...End Type statement 9, 389

Page 496: Actuate Basic Reference

472 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

type-declaration charactersadding to procedures 84defining for variables 25listed 411

types. See data types; specific typetypographic conventions

(documentation) xxi

UUBound function 2, 394UCase function 8, 395UCase$ function 8, 395UCS-2 character sets 371UCS-2 encoding 19, 36unabridged dates 27unformatted data 297Unicode characters

converting to multibyte 18uniform annual depreciation 361uninitialized variables 214union filters 50UNIX environments

checking for disk files 117copying files 114creating directories 256deleting directories 328deleting files 221getting current default directory for 57getting date/time stamps for 115getting file size 118getting system attributes 155renaming files 267setting file type attributes 346

UnknownReportContext constant 167unlocking files 236unstructured content xiUntil keyword 91updates xvuppercase conversions 137, 224, 395URLs

adding to context menus 124building dynamically 181specifying 123

user names 224getting length 228

user-defined errorscreating messages for 106defining error codes for 104

generating 106user-defined formats 128, 132, 136user-defined messages 260, 263user-defined types

assigning to variables 40, 231, 389creating 391described 414random reads to 150

user-defined variablesassigning data types to 390assigning values to 391avoiding type mismatch for 228declaring 86, 389initializing 183

usersgetting login names for 166, 170, 171placing access restrictions for 236prompting for dates 259prompting for input 201

VV_CURRENCY constant 398V_DATE constant 398V_DOUBLE constant 398V_EMPTY constant 398V_INTEGER constant 398V_LONG constant 398V_NULL constant 398V_SINGLE constant 398V_STRING constant 398Val function 3, 396validating input 195values

assigning null 196, 231assigning to variables 188, 214, 230, 391comparing 341getting 367getting absolute 14getting incorrect 414getting numeric 396procedures returning 83setting conditions for 194static variables and 365supplying to random number

generator 309, 383symbolic constants as literal 46testing assignment 214

Page 497: Actuate Basic Reference

I n d e x 473

variable-length arraysresizing 312, 314

variable-length stringsbinary reads to 151copying portions of 245getting characters in 225, 226, 228, 325, 327getting length 228initializing 183limits for 414reading 302replacing portions of 247, 250trimming 333writing variant data to 150

variablesaccessing 2, 348adding value indexes 16aligning string expressions in 243assigning classes to 90, 183, 313assigning data types to 85, 90, 183, 313,

390assigning expressions to 25assigning numbers to 194, 228, 229assigning strings to 230assigning to classes 39assigning to object references 344assigning values to 188, 214, 230, 391assigning variant types to 59, 196, 397avoiding incorrect assignments 90avoiding name conflicts 144avoiding type mismatch for 228caution for declaring 89checking for uninitialized 214comparing 428, 437copying values 49creating user-defined 86, 389declaring 89declaring as global 86, 90, 182declaring as static 141, 364, 374evaluating boolean 117getting available 17getting number of 176, 178getting values in 172, 367index order for 172initializing 89, 90, 182, 183, 214, 314inverting bit values 433, 434mapping column names to 348naming 364

passing by reference 23passing by value 23, 85passing to functions 142passing to procedures 143, 375preserving values 141, 365, 374programming tasks for 9providing aliases for 348reading data from 300reading data to 149, 195referencing array elements 195values frequently changing 90writing to disk files 405

Variables windowgetting available variables 17

variant dataas date 65, 68, 72, 290as time 383, 386assigning to variables 59, 196, 397checking for null 216comparing 427converting to currency 24converting to doubles 29converting to integers 37converting to longs 41converting to singles 53defined 415formatting 125inputting in message boxes 414parsing 225, 226, 325, 326programming tasks for 9random reads to 150reading 196, 302return values for 415storing as strings 228, 229storing internally 397symbolic constants as 46writing to disk files 299, 405

Variant data typeassigning values 231converting to 58, 60copying as String 245described 415initialization values for 183symbolic constants for 398

Variant variables 90assigning data to 197getting information about 9

Page 498: Actuate Basic Reference

474 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e

VarType function 9, 397, 415varying payments 274Verify function 17version numbers 152versions

archiving report-specific 352view processes 320

error reporting for 316getting temporary file names for 182

Viewer xvcalling hyperlinks from 124getting command-line arguments for 45

ViewerContext constant 153ViewerReportContext constant 167viewing

Clipboard content 349code examples 12custom browser output 168dates 69, 74, 77, 80DHTML reports xierror messages 20, 316headlines 351messages 22, 260, 263, 406online documentation xviiiprompts 201reports xv, 181

viewing formats 180, 219ViewServer constant 153Volatile keyword 89volatile variables 90volume

getting attributes 154volume labels 155

Ww format character 288warning beeps 22web browsers

displaying online documentation in xviiidisplaying output for 168, 320displaying reports in xvgetting parameters for 166getting user agent 171opening targets 123setting parameters for 351

web pages

moving to specific 123web sites

e.reporting solutions for x, xiobtaining Actuate product updates xvsecuring xiii

weekdaycounting 67entering in expressions 68, 73format characters for 133getting 70, 95, 133, 165, 399locale-specific conversions for 288

Weekday function 3, 399While keyword 91While...Wend statement 2, 401whole numbers

as enumerated values 413getting 37, 122

Width # statement 5, 403wildcards 220, 439window style constants (Windows) 357Windows applications 357Windows environments

checking for disk files in 117copying files 114creating directories 256deleting files 221enabling DOS shell 356getting current default directory for 57getting date/time stamps for 115getting file size 118getting system attributes 155removing directories 328renaming files 267setting file type attributes 346

Windows predefined colors 308working directories

changing 31setting 32, 58specifying current drive 32

Write # statement 6, 7, 404Write keyword 281write-only permissions 281

XXML data sources xvXML development tool xiv

Page 499: Actuate Basic Reference

I n d e x 475

XMLCompressedDisplay formats 181XMLDisplay formats 169, 181, 219, 220XMLStyle formats 181XOr operator 437

Yy format characters 134, 288year

determining if leap 426entering in expressions 73estimating 27formatting 134, 288getting 70, 407getting difference in 66

getting month of 257Year function 3, 407Yes buttons 261, 263, 264Yes keyword 128Yes/No format 128

Zzero-digit placeholder 129zero-length strings 196zeros

as string 414testing for 355

zooming 168

Page 500: Actuate Basic Reference

476 A c t u a t e B a s i c L a n g u a g e R e f e r e n c e


Recommended