Professional Documents
Culture Documents
XCM Programming
XCM Programming
Destination ..........................................................................................................................202
Export .......................................................................................................................................202
FindDestinationInABL .............................................................................................................204
FindRecordInABL ....................................................................................................................205
FindSourceInABL ....................................................................................................................205
FirstCompletedTask ............................................................................................................206
FirstStartedTask .................................................................................................................206
FirstTask ..............................................................................................................................207
GetActiveCalendarName..........................................................................................................207
GetActiveScenarioName ..........................................................................................................208
GetActivityCount......................................................................................................................208
GetActivityName......................................................................................................................209
GetActivityNum .......................................................................................................................210
GetApil .....................................................................................................................................211
GetASLCount ...........................................................................................................................214
GetCalendarNameFromScenario ..............................................................................................214
GetClass....................................................................................................................................215
GetCurrentActivity ...................................................................................................................216
GetCurrentCalendarTime .........................................................................................................216
GetCurrentDirectory.................................................................................................................216
GetCurrentOutputStep ..............................................................................................................217
GetCurrentPeriod......................................................................................................................218
GetCurrentResource .................................................................................................................218
GetCurrentScheduleTime .........................................................................................................218
GetCurrentStepActivity ............................................................................................................218
GetCurrentStepDetails..............................................................................................................219
GetDatabaseName ....................................................................................................................219
GetDependencies ......................................................................................................................220
GetDestApil .........................................................................................................................220
GetDestinationABLCount ........................................................................................................220
GetEntity...................................................................................................................................221
GetEntityCount.........................................................................................................................224
GetFeatureCount.......................................................................................................................225
GetFeatureName.......................................................................................................................226
GetFeatureVertexCount............................................................................................................227
GetFeatureVertexXYZ .............................................................................................................227
GetFieldInfo .............................................................................................................................227
GetFirstABLItem......................................................................................................................231
GetFirstABLDestination...........................................................................................................232
GetFirstABLSource ..................................................................................................................233
GetFirstInRange .......................................................................................................................233
GetFirstOutputStep ...................................................................................................................235
GetFullModelName ..................................................................................................................235
GetGlobalArray ........................................................................................................................236
GetGlobalObject.......................................................................................................................238
GetInputPathName ...................................................................................................................238
GetInputPathNoOfSteps ...........................................................................................................239
GetInputStep.............................................................................................................................240
GetLastError .............................................................................................................................243
GetLastOutputStep ...................................................................................................................245
GetLastOutputStep ...................................................................................................................246
GetLayerCount .........................................................................................................................246
GetLayerName .........................................................................................................................247
GetLevelNum ...........................................................................................................................248
GetMax .....................................................................................................................................250
GetMin......................................................................................................................................250
GetMineStatus ..........................................................................................................................251
GetModelDirectory...................................................................................................................255
GetMOQItem............................................................................................................................255
GetMOQItemCount ..................................................................................................................258
GetNextABLItem .....................................................................................................................259
GetNextABLDestination ..........................................................................................................259
GetNextABLSource..................................................................................................................260
GetNextInRange .......................................................................................................................260
GetNextOutputStep ..................................................................................................................262
GetNote.....................................................................................................................................262
GetNumberOfPredecessors.......................................................................................................263
GetNumberOfSuccessors..........................................................................................................263
GetNumChildren ......................................................................................................................264
GetNumFields...........................................................................................................................265
GetNumRecords .......................................................................................................................266
GetOutputPathNoOfSteps.........................................................................................................268
GetOutputRange .......................................................................................................................270
GetOutputRangeForPeriod .......................................................................................................272
GetOutputRangeForRecord ......................................................................................................272
GetOutputStep ..........................................................................................................................272
GetParam ..................................................................................................................................274
GetParamFromPil .....................................................................................................................276
GetPctThroughPeriod ...............................................................................................................277
GetPeriodDuration Function.....................................................................................................277
GetPeriodFromRecNum ...........................................................................................................279
GetPeriodRangeForResource ...................................................................................................280
GetPeriodRangeForScenario ....................................................................................................280
GetPilFromPositionName.........................................................................................................280
GetPilFromPositionNameEx ....................................................................................................282
GetPolygonArea .......................................................................................................................284
GetPolygonAreaXY..................................................................................................................284
GetPolygonCentroid .................................................................................................................285
GetPolygonCentroidXY ...........................................................................................................285
GetPolygonCount .....................................................................................................................285
GetPolygonVertexCount ..........................................................................................................286
GetPolygonVertexXYZ ............................................................................................................286
GetPositionNameFromPil.........................................................................................................286
GetPositionNameFromPilEx ....................................................................................................288
GetPredecessor .........................................................................................................................290
GetPSItem.................................................................................................................................290
GetPSItemCount.......................................................................................................................294
GetRecFromName ....................................................................................................................295
GetRecFromNameDB ..............................................................................................................296
GetRecFromNameDBEx ..........................................................................................................297
GetRecFromNameEx................................................................................................................298
GetRecFromPil .........................................................................................................................299
GetRecFromPilDB....................................................................................................................300
GetRecFromPilEx.....................................................................................................................301
GetRecName.............................................................................................................................302
GetRecNameAtLevel................................................................................................................304
GetRecNameFromPeriod..........................................................................................................306
GetRecNum ..............................................................................................................................307
GetRecNumAtLevel .................................................................................................................309
GetRecNumFromPath ..............................................................................................................310
GetRecNumFromPeriod ...........................................................................................................312
GetResourceCount....................................................................................................................313
GetResourceLocation ...............................................................................................................314
GetResourceName ....................................................................................................................314
GetResourceRoster ...................................................................................................................315
GetRosterHrs ............................................................................................................................316
GetRowCodeFromNum............................................................................................................317
GetRowNumFromCode............................................................................................................317
GetScheduleStartPeriod............................................................................................................318
GetScriptExecutionRange.........................................................................................................318
GetScriptName .........................................................................................................................319
GetScriptsDirectory ..................................................................................................................320
GetSourceABLCount................................................................................................................320
GetSPCreationDate...................................................................................................................320
GetSuccessor ............................................................................................................................321
GetTrackingField......................................................................................................................321
GetValue...................................................................................................................................322
GetVertexEOS ..........................................................................................................................322
GetVertexEOSA .......................................................................................................................322
GoRec .......................................................................................................................................322
IIf ..............................................................................................................................................324
Import .......................................................................................................................................325
InitTrackingField ......................................................................................................................327
InPoly .......................................................................................................................................328
InPolyRec .................................................................................................................................330
InsertIntoInputPath ...................................................................................................................331
InsertResourceDelay.................................................................................................................334
IsCombinationConstrained .......................................................................................................336
IsFirst........................................................................................................................................336
IsFirstInRange ..........................................................................................................................338
IsInRange..................................................................................................................................339
IsLast ........................................................................................................................................339
IsLastInRange...........................................................................................................................340
IsTaskConstrained ....................................................................................................................341
IsTaskReserved.........................................................................................................................342
IsValidRecNum ........................................................................................................................343
LastCompletedTask .............................................................................................................344
LastStartedTask ..................................................................................................................344
LastTask ..............................................................................................................................345
LoadPolygon.............................................................................................................................345
M, C, P, R Accessors ................................................................................................................345
MakeRGB.................................................................................................................................346
OffsetPolygon...........................................................................................................................347
OpeningDumpCapacity .......................................................................................................348
OpeningInv ..........................................................................................................................348
OpeningInvSP .....................................................................................................................348
OperatingHrs .......................................................................................................................348
OriginalValue ......................................................................................................................348
PeriodEnd ............................................................................................................................348
PeriodStart ...........................................................................................................................348
Pil ........................................................................................................................................349
PointInPolygon .........................................................................................................................349
PolygonArithmetic....................................................................................................................349
QBColor ...................................................................................................................................352
RadToDeg.................................................................................................................................353
ReadBaseValue.........................................................................................................................354
ReadValue ................................................................................................................................355
RecalculateDatabase .................................................................................................................356
ReducePolygonComplexity ......................................................................................................356
Released ..............................................................................................................................357
RemoveAllDependencies .........................................................................................................357
RemoveDependency.................................................................................................................357
RemoveRecord .........................................................................................................................358
RemoveTask .............................................................................................................................359
ResetMaxCapacity....................................................................................................................360
Resource ..............................................................................................................................360
RNOEXDB...............................................................................................................................360
RosterHrs ............................................................................................................................362
RosterHrsResource .............................................................................................................362
RunActiveScenario ...................................................................................................................362
RunMacro .................................................................................................................................364
RunScheduleReport ..................................................................................................................365
RunScript..................................................................................................................................365
SafeDivide ................................................................................................................................367
SavePolygon .............................................................................................................................368
ScalePolygon ............................................................................................................................368
ScanCircleReference ................................................................................................................369
ScanCircleReferenceFrom........................................................................................................369
SetActivePolygonSet ................................................................................................................369
SetActiveScenario ....................................................................................................................369
SetClass ....................................................................................................................................370
SetDependency .........................................................................................................................371
SetDependencyEx.....................................................................................................................372
SetDependencyOnRange ..........................................................................................................372
SetFieldInfo ..............................................................................................................................372
SetGlobalArray.........................................................................................................................376
SetGlobalObject........................................................................................................................378
SetMOQItem ............................................................................................................................378
SetNote .....................................................................................................................................379
SetParam...................................................................................................................................380
SetParamFromPil......................................................................................................................381
SetProgressBar .........................................................................................................................383
SetPSItem .................................................................................................................................384
SetRecName .............................................................................................................................385
SetUserFlag ..............................................................................................................................387
SetVertex ..................................................................................................................................388
SetVertexA ...............................................................................................................................388
SetVertexEOS...........................................................................................................................389
SetVertexEOSA........................................................................................................................389
StartedTask .........................................................................................................................389
StepType .............................................................................................................................389
StockpileInventory ..............................................................................................................389
WorkHrs ..............................................................................................................................390
WriteABLToFile ......................................................................................................................390
WriteBaseValue........................................................................................................................390
WriteDestinationABLToFile ....................................................................................................392
WriteSourceABLToFile ...........................................................................................................392
WriteValue ...............................................................................................................................392
When you first access this window, the editor will be set to Use the built in script
editor. To select some other editor, click on the radio button below this option and
use the button too locate the executable file for your new editor (*.exe). Click on
to accept the changes. From now on the new editor will be used for
editing XCMs.
M - Main database
P - Parameters database
C - Calendar database
R - Results database
S - Schedule paths
UP - User Processing XCMs
• The letter is followed by a two digit number, ie. 01, 02, 03, etc, and a space. The
number will indicate the order in which the XCMs should be run. Where an XCM
is independent of all other XCMs, then the number should be 00 or 99, depending
on whether you want the XCM to appear at the start of the list or the end of the
list. User Processing XCMs do not require a number, as their order is defined in
the User Processing screen in XPAC.
• The final component of the XCM name is a brief meaningful description of what
the XCM does.
• As you are able to have multiple calendar and results databases in the one project,
the description for these XCMs should start with either the calendar or results
database name or an abbreviation of their name.
• If you need to insert an XCM in the middle of your list (either main, parameters,
calendar, results or schedule), then you should renumber (and hence rename) all of
the XCMs to keep their numbers sequential. Gaps should not be left in the
numbering system to allow for this, as it will not be obvious why numbers have
been missed out.
Some example XCM names are provided in the following table.
XCM Type Example XCM Name
Main Database XCM M03 Insitu Reserves.bas
Parameters Database XCM P04 Waste Dilution.bas
Calendar Database XCM C03 Long Term Calendar – Equip Prod.bas
C01 DetCal – Start Date.bas
Results Database XCM R02 Equipment Hours – Truck Hours.bas
R03 MajQnt – Drill Data.bas
Schedule Path XCM S01 Write Schedule Results to Excel.bas
User Processing XCM UP Update Remaining Loader Hours in Calendar.bas
• All XCMs that relate to your XPAC project should be stored in a sub-directory,
below where the project is stored, called XCMs.
• If you have stored different versions of the same project in a single directory, then
you may also have different versions of the XCMs. XCMs that relate to ALL
versions of the project will be stored in the XCMs sub-directory. XCMs that
relate to specific versions of the project will be stored in a sub-directory under the
XCMs directory. The sub-directory will be named according to the project
version or option.
• To the right of the edit XCM button is a button that is used for running
XCMs. Click on the down arrow and select the Run Range button from the
drop down list. If this button was the last selected, then it will already be
displayed on the toolbar and can be selected from there.
You will then be presented with a window from which you can select the XCM to run.
Note that the default directory for this window is the last directory that was accessed.
• To the right of the edit XCM button is a button that is used for running
XCMs. Click on the down arrow and select the Run Once button from the
drop down list. If this button was the last selected, then it will already be
displayed on the toolbar and can be selected from there.
You will then be presented with a window from which you can select the XCM to run.
Note that the default directory for this window is the last directory that was accessed.
• To the right of the edit XCM button is a button that is used for running
XCMs. Click on the down arrow and select the Run Immediate button
from the drop down list. If this button was the last selected, then it will already be
displayed on the toolbar and can be selected from there.
Immediate XCMs make use of the XCM Debug window for entry of the XCM code.
After selecting one of the options described above, this window will be displayed.
The Sub Main and End Sub commands have already been entered. Enter your own
XCM code in between these two commands.
When you have entered the required code, the XCM is run by clicking on the play
button on the toolbar. You will be asked to select a database range and then the
XCM will be run.
Note that if you access an Immediate XCM within the same XPAC session, then the
previously entered Immediate XCM will still be displayed. When you close XPAC,
the Immediate XCM will be cleared.
the database range for an XCM, highlight that XCM and click on the
button. Select the required database range or create a new range. The same database
range can be assigned to multiple XCMs in the list by highlighting the required XCMs
they will be run, click on the button. They will then start to run in the
specified order.
Note that the XCM Debug program cannot be used to resolve compile errors. If you
cannot determine where the error is in your XCM, then you may need to contact
Runge support for help.
XPAC forces you to declare all of your user-defined variables using the Dim
statement. If you attempt to use a variable without declaring it, then you will get an
error message saying “Variable not defined”. It could be due to the variable not being
defined, the variable may be defined in the wrong place or it could be a spelling
mistake.
This can be avoided by always using the SafeDivide function, which will return a
value of zero when dividing by zero.
The XCM will stop running when this error is encountered. The problem can be fixed
by:
• changing the status of the protection on the data field in data field design; or
• changing the data field reference in the XCM.
If you are getting error messages displayed while an XCM is running, if your XCM is
not calculating the correct values or if output data is not being generated correctly by
an XCM, then you may need to use the Debug program to locate the problem in your
XCM. XCM Debug runs from within XPAC and it is used to step through an XCM,
testing variable values and watching to see which code is processed within your
XCM.
To run an XCM in the Debug program, use either of the following:
• Select Tools from the application menu, select XCM and then select Debug; or
• To the right of the edit XCM button is a button that is used for running
XCMs. Click on the down arrow and select the Debug button from the
drop down list. If this button was the last selected, then it will already be
displayed on the toolbar and can be selected from there.
Locate the XCM that you want to debug and then click on to open the
XCM in the Debug program. The selected XCM will be displayed in the main part of
the window and the Debug Toolbar will be displayed.
Compile (F7)
This option is used to compile your XCM without running it. If there are any compile
errors, they will be displayed. If no compile errors are encountered, there will not be
any messages displayed.
Go/Run (F5)
This button should be selected to run your XCM in Debug. You will be asked for a
database range and the XCM will then be compiled. If no compile errors are found,
then the XCM will start running.
If this button is selected while an XCM is paused, then the XCM will resume running.
Restart (Ctrl+Shift+F5)
The Restart button is only available when the XCM is paused (ie. after break
execution, at a break point, during step into, etc). It is used to restart the XCM
running from the first record in the last database range that was selected.
Alternatively, the XCM can be stopped and then restarted using the Run button.
button can be used to start an XCM that is not running or it can be used to resume an
XCM that is a paused state.
4 Structure of an XCM
The structure of an XCM is controlled by:
• commands that must be in a certain order, so that XPAC can interpret the XCM;
• recommended comment lines, explaining how the XCM works; and
• recommended formatting, to make the XCM easier to read and to minimise errors.
The various components that contribute to the structure of an XCM are discussed in
detail in this section. They are dealt with in the order in which they will normally
appear. An example of a simple XCM has been provided on the following page to
illustrate the concept of these components.
'========================================================================='
'! !'
'! This XCM has been written for COMPANY NAME under Job Number ####. !'
'! !'
'========================================================================='
'==================
'DESCRIPTION OF XCM
'==================
'
'===========
'XCM HISTORY
'===========
'================================================================================================
'Declare Script Variables - use prefixes d:double l:long s:string b:boolean etc
'========================
'================================================================================================
'========
Sub Main
'========
'Declare Local Variables - use prefixes d:double l:long s:string b:boolean etc
'=======================
'The following logic is applied ONCE, BEFORE the first record in the range is processed
If IsFirstInRange() Then
End If
'---------------------------------------------------------------------------------------------
'MAIN PROCEDURE
'==============
'---------------------------------------------------------------------------------------------
'The following logic is applied ONCE, AFTER the last record in the range has been processed
If IsLastInRange() Then
End If
'---------------------------------------------------------------------------------------------
'=======
End Sub 'End of MAIN Subroutine
'=======
'================================================================================================
'==============
'OTHER ROUTINES
'==============
'================================================================================================
'End of XCM
If a block of code is within a subroutine and two control structures, it will end up
being indented by 9 spaces. An example of this is shown below, where dots have
been used to signify spaces. (Do not use dots in your code). Note how the start of
each control structure lines up with the end of that control structure. That is, the Do
While lines up with the Loop, the If Then lines up with the End If and the Sub lines
up with the End Sub.
Sub GetNextBench(lRecNum As Long)
…If (lRecNum > 0) Then
……Do While (GetRecNum(NXTSIB, lRecNum) > 0)
………Block of Code
……Loop
…End If
End Sub
The XCM initialisation logic is used to process a set of commands once, before any of
the records are processed. It makes use of the IsFirstInRange function at the start of
the Main subroutine. The initialisation logic is written as follows:
If IsFirstInRange() Then
…Commands to process once, before any records are processed.
End If
When an XCM is run once, each of the commands are only processed once. This
includes the initialisation logic.
sometimes there are commands that you only want to process once. Examples of such
commands include closing a file that has been written to, asking the user for input,
displaying the value of some variable, etc.
The XCM termination logic is used to process a set of commands once, after all of the
records have been processed. It makes use of the IsLastInRange function at the end of
the Main subroutine. The termination logic is written as follows:
If IsLastInRange() Then
…Commands to process once, after all records have been processed.
End If
When an XCM is run once, each of the commands are only processed once. This
includes the termination logic.
4.11 User-
User-Defined Functions and Subroutines
There are many functions and subroutines that are provided with XCM. Those that
you create and define are referred to as user-defined functions and subroutines. They
must be placed at the end of the XCM, after the “End Sub” statement. There are
many other rules regarding their use and these will be described in detail in a later
section.
If you find that you are repeating a set of commands in your XCM, with only slight
variations between each occurrence, then you should probably place that set of
commands in a subroutine or function. In your XCM, each time you “call” a function
or subroutine, the commands within it are processed and there is no limit to how many
times one can be called. It may take a little while to become comfortable with the use
of functions and subroutines, but there are significant advantages in using them. For
example:
• If the logic needs to be modified in such repetitious code, it will only need to be
done inside the function or subroutine, rather than in many places.
• Functions and subroutines can be used to break an XCM up into specific tasks.
The detail of the task may be stored in a function or subroutine and the instruction
of when to do that task may be stored in the Main subroutine, or even in some
other user-defined function or subroutine.
5.1 Comments
Comments are used to document your XCMs. Extensive use of comments in your
XCMs will mean that other XPAC users can quickly understand them, and they may
also provide information about why certain calculations have been carried out.
To distinguish between comments and XCM code, a comment must be preceded by a
single quote. When an XCM is compiled and run, the comments are ignored.
A comment may occupy a line by itself, or it may appear to the right of some code.
Comments cannot be placed to the left of XCM code. The general rule is that any
characters to the right of the comment character are considered to be comments. In
the following code, the comments are shown in blue/green and the code is shown in
red.
Sub Main
'Reserves with 10% Cut-Off
'==========================
'Ore Calculations
M(mOre_Ton) = M(mOre_Vol)*M(mPar_DefDen) 'Note use of default density
End Sub
Note that Rem (case insensitive) can be used in place of the single quote, to mark a
comment.
5.2 Statements
In every language, ideas are conveyed by grouping words together to form a
statement. Mathematics also uses statements to describe values. In an XCM, a
statement is a group of commands that instruct XPAC to perform a task. A statement
may be made up of any number of XCM language elements.
In XCM there is no statement terminator. More than one statement can be put on a
line, if they are separated by a colon. For example:
x = GetRecNum(UP)
y = GetNumChildren(x)
5.4 Numbers
XCM supports three representations of numbers, namely Decimal, Octal and
Hexadecimal. Most of the numbers used in this XCM guide are decimal or base 10
numbers. However, if you need to use Octal (base 8) or hexadecimal (base 16)
numbers, simply prefix the number with &O or &H respectively.
5.6 Operators
Operators are used to join together the variables, constants, functions, subroutines,
etc, that make up a statement. The different types of operators that are available in
XCM, are described in the following table.
XCM Operators
Type Operator Function Usage
Arithmetic ^ Exponentiation x = y^2
- Subtraction x=6-4
+ Addition x=2+3
* Multiplication x=2*3
/ Division x = 10 / 2
- Negation X = -2
Mod Modulo x = y Mod z
String +
& Concatenation
Logical Not Logical Negation If Not(x)
And Logical And If (x>y) And (x<z)
Or Logical Or If (x=y) Or (x=z)
Relational < Less Than X<y
<= Less Than or Equal To x <= y
= Equals X=y
>= Greater Than or Equal To x >= y
> Greater Than X>y
<> Not Equal To x <> y
5.9 Syntax
Syntax describes the rules controlling how code can be put together. It is analogous
to grammar in the English language.
6 XCM Variables
Variables and Constants
6.1 Introduction
Variables and constants are used to permanently and temporarily store values that can
be used in your XCM. As their names indicate, variables hold values that can change
as your XCM runs, whereas the value of constants cannot be changed.
6.1.1 User-
User-Defined Variables
User defined variables are used to store temporary values while your XCMs are
running. They should be used whenever your code must refer to a value multiple
times. You are able to give your user variables meaningful names, but these names
are subject to certain rules.
6.1.2 Arrays
Arrays are single or multi dimensional variables. They can be used to refer to a series
of variables by the same name, each with a separate index. Array names are subject
to the same rules as variables.
6.1.4 Constants
Constants are used to store a constant value that cannot be changed by any script.
Constants follow the naming convention for variables, except that their names (apart
from any prefixes) are all in upper case.
6.2 Variable
Variable Data Types
Variables and arrays must be declared as a certain data type and the data types
available are listed below. Each variable and array name should be prefixed with a
character, according to its data type. Note however, that the data type character will
follow the scope character (if there is one) in the variable or array name.
All of the elements in an array will have the same data type and they can be longs,
doubles, strings, booleans or variants.
Long
These data types are integers with a minimum value of –2,000,000,000 and a
maximum of +2,000,000,000. It has been decided to use these data types for all
integers in XCM. They should be prefixed with a lower case l.
Integer
These data types are integers with a minimum value of –32,000 and a maximum of
+32,000. It has been decided not to use these data types in XCMs unless there is a
particular need (eg. to speed up the XCM). All integers should be assigned as longs.
Double
These data types are real numbers with thirteen digits and a minimum value of
–1E+308 and a maximum of +1E+308. It has been decided to use these data types
for all real numbers in XCM. They should be prefixed with a lower case d.
Single
These data types are real numbers with six digits and a minimum value of
–1E+38 and a maximum of +1E+38. It has been decided not to use these data types
in XCMs unless there is a particular need (eg. to speed up the XCM). All real
numbers should be assigned as doubles.
String
These data types can store a mixture of alpha and numeric characters and can be up to
250 characters in length. Double quotation marks(“) should be placed around a string
value to indicate where it starts and finishes. String variables and arrays should be
prefixed with a lower case s.
If the double quotation character is a part of the string, then it must appear twice in the
string. For example, to store the expression “This block contains “Type 3” Ore” in a
string variable, it must be written as “This block contains ““Type 3”” Ore”.
Boolean
These data types can have a value of either True or False. Note that quotation marks
should not be placed around these values. They should be prefixed with a lower
case b.
Date/Time
These data types are used to store date and/or time data. They should be prefixed with
a lower case t.
Variant
A variant can be used to store any of the other data types, including numbers, strings,
dates, etc. They should be prefixed with a lower case v. Whilst these data types are
very flexible, they do not provide a check that a meaningful value is being assigned to
the variable.
Object
An object is used to store a discrete unit of data supplied by an application. Object
data types should begin with a lower case o and then follow the standard naming
convention.
You do not have to declare data field variables. XPAC does this automatically for
you.
6.6 User
User--Defined Variable and Constant
Names
There are a number of rules that you should follow when naming your user-defined
variables and constants. Some of these have already been discussed in relation to
variable scope and data types, while others are recommendations to make your XCMs
more clear. Note that array names must follow the same rules as variable names.
• All prefixes will be in lower case.
• Variables and constants should begin with a scope character as listed in the
following table.
Scope Prefix
Global g
Script none
Local none
• The data type character will follow the scope character (if it is required) and will
be one of those listed below.
Data Type Prefix
Long l
Double d
String s
Boolean b
Date/Time t
Variant v
Object o
• The remaining part of the variable and constant names may be made up of any
alpha/numeric characters. To avoid confusion with the data field full row codes,
the underscore character is prohibited from variable and constant names.
• Variable and constant names must commence with a letter.
• Reserved words, such as function or statement names, are prohibited as variable
or constant names.
• Variable names should be in lower case, except for the first letter of an
abbreviated word, which should be in upper case. Note that a variable name may
be made up of more than one abbreviated word, for example waste volume could
be written as dWstVol.
• Constant names should be all in upper case, except for any prefixes.
Some example names for variables and constants are listed in the following table.
are also quite meaningless and their use will make your XCM code difficult to
interpret. For example, the following line of XCM code does not tell us anything
about the calculation being carried out.
M(46) = M(42) * (M(18) + M(22))
For these reasons, it is better to use full row codes to reference your data fields. The
full row code is a unique set of characters for each data field. If your data field codes
and level numbers are set up correctly, when data fields are inserted the codes for
existing fields will not change. Also, they can provide a meaningful abbreviation for
the parameters they represent. For example, if the full row codes are used, the line of
code above may be written as follows.
M(mOre_Ton) = M(mOre_RD) * (M(mLG_Vol) + M(mHG_Vol))
The rules and suggestions for setting up row codes are provided in the XPAC On-line
Help.
• The position in level number for each database level is stored in a variable called
lLevelNameNum, where LevelName is the name of the database level as defined
by you. This variable is declared as a long data type.
Dim lLevelNameNum As Long
• The values of the position in level variables are assigned by XPAC using the
GetApil function. In this calculation, the LevelNumber is the number of the level
in your database (maximum of 10).
lLevelNameNum = GetApil(LevelNumber)
• The record name at each database level is stored in a variable called
sLevelNameName, where LevelName is the name of the database level as defined
by you. This variable is declared as a string data type.
Dim sLevelNameName As String
• These record name variables are assigned by XPAC using the
GetRecNameAtLevel function. In this calculation, the LevelNumber is the
number of the level in your database (maximum of 10).
lLevelNameName = GetRecNameAtLevel(LevelNumber)
Note that the level names are taken from the database over which the XCM is run, so
the variable names may be different for each database.
For example, consider a database with the following structure.
• Level 1 – Pit
• Level 2 – Block
• Level 3 – Bench
When an XCM is compiled within this database, the variables listed below are
automatically created and assigned, each time a new record is processed.
• lPitNum – stores the pil number for the Pit record.
• LBlockNum – stores the pil number for the Block record.
• LBenchNum – stores the pil number for the Bench record.
• SPitName – stores the Pit name.
• SBlockName – stores the Block name.
• SBenchName – stores the Bench name.
If data fields are inserted in your database and this field is moved to number 38, then
the next time that the XCM is compiled, the following line will be added to the
beginning of your XCM.
Const mROM_Ore_Grd = 38
These additions to your XCMs are not permanent, so you will not see any changes
when you edit them. They are carried out in the background by XPAC. It is useful to
understand what XPAC is doing with the full row codes, as it gives you greater
flexibility and power in your XCM coding.
For example, the following section of XCM code shows how eight different ore types,
that have a constant data field spacing, can be accumulated to obtain the total ore
tonnage.
'Accumulate the Ore Tonnage for all Ore Types
For lOreType = 1 to 8
lFldSpacing = mROM_OreType2_Ton - mROM_OreType1_Ton
lFldOffset = (lOreType – 1) * lFldSpacing
M(mROM_OreTot_Ton) = M(mROM_OreTot_Ton) + M(mROM_OreType1_Ton + lFldOffset)
Next lOreType
7 Control Structures
7.2 If Statements
There are four different ways in which an If statement can be used. The syntax for
each is described below and an example is provided.
7.2.1 If…Then
An If statement can be used in a single line of code if, when the condition is true, the
action consists of a single statement. The syntax for this application is:
If (Condition) Then Statement
Example:
'Allocate the Block to Waste if the Grade is less than the Cut-Off
If (M(mBlk_Grade) < dHighGrdCutOff) Then M(mWaste_Ton) = M(mBlk_Ton)
7.2.2 If…Then…End If
An If statement must be used in conjunction with an End If statement if, when the
condition is true, the action consists of multiple statements. Note that there is a space
in the End If statement. The syntax for this application is:
If (Condition) Then
Statements….
End If
Example:
'Allocate the Block to Waste if the Grade is less than the Cut-Off
If (M(mBlk_Grade) < dHighGrdCutOff) Then
M(mWaste_Ton) = M(mBlk_Ton)
M(mHighGrd_Ton) = 0
End If
7.2.3 If…Then…Else…End If
An If statement can also be used to execute one set of statements when the condition
is true and a different set of statements when the condition is false. The application is
the same as that above, except that an Else statement must also be used. The syntax
for this application is:
If (Condition) Then
Statements if Condition is True
Else
Statements if Condition is False
End If
Example:
'Allocate the Block to Waste or High Grade
If (M(mBlk_Grade) < dHighGrdCutOff) Then
M(mWaste_Ton) = M(mBlk_Ton)
M(mHighGrd_Ton) = 0
Else
M(mWaste_Ton) = 0
M(mHighGrd_Ton) = M(mBlk_Ton)
End If
7.2.4 If…Then…ElseIf…End If
The final application for the If test is to execute one set of statements when a
condition is true and when it is false, to test some other condition. The application is
similar to that described above, except that an ElseIf statement must be used. Note
that ElseIf is one word, without any spaces. The syntax for this application is:
If (Condition 1) Then
Statements if Condition 1 is True
ElseIf (Condition 2)
Statements if Condition 1 is False and Condition 2 is True
End If
Note that in this application, when a condition is found to be true, the statements that
follow it will be processed and then the End If statement will be processed. No further
ElseIf or Else statements will be processed.
Example:
'Allocate the Block to Waste, Low Grade or High Grade
If (M(mBlk_Grade) < dLowGrdCutOff) Then
M(mWaste_Ton) = M(mBlk_Ton)
M(mLowGrd_Ton) = 0
M(mHighGrd_Ton) = 0
ElseIf (M(mBlk_Grade) < dHighGrdCutOff) Then
M(mWaste_Ton) = 0
M(mLowGrd_Ton) = M(mBlk_Ton)
M(mHighGrd_Ton) = 0
Else
M(mWaste_Ton) = 0
M(mLowGrd_Ton) = 0
M(mHighGrd_Ton) = M(mBlk_Ton)
End If
7.4 Do Loops
Do Loops allow you to execute a block of statements an indefinite number of times.
There are a number of different forms of Do Loops, but in general the block of
statements are executed until or while some condition is met.
All of the Do Loop examples perform the same function in a slightly different way.
7.4.1 Do While…Loop
The Do While loop checks a condition before entering a loop. While the condition is
true, the statements inside the Do Loop will be processed repeatedly. Once the
condition is false the loop will be finished, and the next execution point will be after
the Loop statement. The syntax is:
Do While Condition
Statements
Loop
Example:
'Store the Bench Number where the Maximum Waste Depth is reached.
Do While (dCumWstThk < dMaxWstDpth)
dCumWstThk = dCumWstThk + M(mROM_Wst_Thk)
lBaseBenchNum = GetApil(3)
Call GoRec(NXT)
Loop
7.4.3 Do Until…Loop
The Do Until loop checks a condition before entering a loop. It is the opposite to the
Do While loop. Until the condition is true, the statements inside the Do Loop will be
processed repeatedly. Once the condition is true the loop will be finished, and the
next execution point will be after the Loop statement. The syntax is:
Do Until Condition
Statements
Loop
Example:
'Store the Bench Number where the Maximum Waste Depth is reached.
Do Until (dCumWstThk >= dMaxWstDpth)
dCumWstThk = dCumWstThk + M(mROM_Wst_Thk)
lBaseBenchNum = GetApil(3)
Call GoRec(NXT)
Loop
7.4.5 Exit Do
The Exit Do statement is optional and is used to exit from the Do Loop in the middle
of the statements. After this statement is encountered, the next execution point will be
after the Loop statement. The Exit Do statement can be used with any of the Do loops
described above. The syntax is:
Do While Condition
Statements
[Exit Do]
Loop
Example:
'Store the Bench Number where the Maximum Waste Depth is reached
'or the last Bench Number, whichever is higher.
Do While (dCumWstThk < dMaxWstDpth)
dCumWstThk = dCumWstThk + M(mROM_Wst_Thk)
lBaseBenchNum = GetApil(3)
If (IsLast()) Then Exit Do
Call GoRec(NXT)
Loop
Example:
'Store the Volume for each Bench in the current Pit in an Array.
For lBench = 20 To 95 Step 15
lBenchRec = GetRecFromPil(lPitNum, lBench)
If (lBenchRec > 0) Then
dBenchVol(lBench) = DbReadValue("Main", lBenchRec, mROM_Wst_Vol)
Else
dBenchVol(lBench) = 0
End If
Next lBench
Introduction
8.1 Introduction
Functions and subroutines consist of a set of statements and when the function or
subroutine is called, these statements are processed. Functions and subroutines can be
called from within the Main subroutine in your XCM, or from within user-defined
functions and subroutines in your XCM. There are two types of functions and
subroutines:
• XCM – these are predefined functions and subroutines and they are supplied to
you as part of the XCM language. Documentation is provided for each of these
functions and subroutines.
• User-defined – these functions and subroutines are written by you to perform
specific tasks. They are stored in your XCM, after the Main subroutine.
The main benefits in using functions and subroutines are:
• Code does not have to be repeated multiple times in your XCM. This will help to
reduce the length and complexity of your XCM, as well as making it easier to
update your XCM (changes will only be done in one place, rather than many
places).
• Code can be ordered logically into functions and subroutines, where each one
performs a specific task. The function and subroutine names can be used to
clearly indicate what that task consists of.
The key difference between a function and a subroutine is that a function will return a
value, whereas a subroutine will not return a value.
8.2 Functions
A function is a set of code that can be called and processed from within your XCM.
The following examples show how the function GoRec can be called in either way.
Function return value assigned to a variable:
'Display a Message when the Last Record in the Range is Reached
bOnNextRec = GoRec(NXT)
If (Not(bOnNextRec)) Then Print "Reached Last Record in Database Range"
8.3 Subroutines
A subroutine is a set of code that can be called and processed from within your XCM.
By reference is the default and it does not need to be used explicitly. An alternative
way of specifying an argument by value involves the use of parentheses. If
Argument1 is passed by reference and Argument2 is passed by value, then the syntax
is:
Sub Name(Argument1 As Type, (Argument2) As Type,….)
Statements
End Sub
'-------------------------------------------------------------------------
Sub CalcVol(ByVal dArea As Double, ByVal dThk As Double, ByRef dVol As Double)
'If the area is zero, use the default area stored in a global variable
If (dArea = 0) Then dArea = gdDEFAULTAREA
dVol = dArea * dThk
End Sub
In this example, the variable dWstVol starts off with a value of zero when it is
declared in the Main subroutine. This variable is then passed into the CalcVol
subroutine by reference. In this case it is passed to a new variable name in the
subroutine, called dVol, however the same variable name could have been used. In
the subroutine, the value of dVol is changed from zero to the product of the area and
the thickness. The value of dVol is then passed back to the Main subroutine into the
variable dWstVol. So, after this script has been executed, dWstVol will have a value
equal to the waste area times the waste thickness.
Since the area and the thickness are passed into the subroutine by value, they are not
returned by the subroutine. This does not affect the thickness since it’s value is not
modified in the subroutine, however it does affect the area. In the subroutine, the
value of the area may be changed from zero to a default value stored in the global
variables. This new value for the area is not passed back to the Main subroutine since
the argument is passed by value. So, after this script has been executed, the value of
M(mWst_Area) will not have changed.
In the previous example, only one value is returned from the subroutine, so a function
could have been used to calculate the volume. This would have been written as
follows.
Sub Main
'Waste Volume
M(mWst_Vol) = CalcVol(M(mWst_Area), M(mWst_Thk))
'Ore Volume
M(mOre_Vol) = CalcVol(M(mOre_Area), M(mOre_Thk))
End Sub
'-------------------------------------------------------------------------
Function CalcVol(ByVal dArea As Double, ByVal dThk As Double) As Double
'If the area is zero, use the default area stored in a global variable
If (dArea = 0) Then dArea = gdDEFAULTAREA
CalcVol = dArea * dThk
End Function
Sine of an angle, to getting information about the current database record, to getting
information about the resources in a scenario.
Each function and subroutine is described in detail, including examples, in the
following sections. They are listed alphabetically. XCM quick reference cards are
also available. These list all of the functions and subroutines, along with a brief
description of their application. Contact Runge for further information on these quick
reference cards.
8.6 User-
User-Defined Functions and Subroutines
User-defined functions and subroutines are created by you and are stored within an
XCM. They are only available for use within that XCM. They are located outside
and following the Main subroutine, at the end of an XCM.
Subroutines:
Sub SubroutineName(Argument1 As Type, Argument2 As Type,….)
Statements
End Sub
8.6.3 Arguments
The arguments are variables that are used by the function or subroutine. The starting
values for these variables are the values that are supplied when the function or
subroutine is called. The variable types are declared in the first line of the function or
subroutine. They do not have to be declared using the Dim statement. These
variables can be of any type, as described in the section on Variable Types. The
standard conventions for naming variables should be applied.
In the following example of a function there are two arguments. The imported
density, dImportRD, is declared as a double and the material type, sMatType, is
declared as a string. Note that in this example, the two arguments or variables are
passed into the function ByRef, since this is the default when it is not specified
otherwise.
'Determine the Insitu RD of the Material
Function InsituRD(dImportRD As Double, sMatType As String) As Double
If (dImportRD > 0) Then
InsituRD = dImportRD
Else
Select Case sMatType
Case "HighGrade"
InsituRD = 2.7
Case "Waste"
InsituRD = 2.4
End Select
End If
End Function
subroutine to the next, and they will retain their value from one record to the next,
however they will lose their value when the XCM finishes processing.
Global variables are declared within your project, but outside all XCMs. They are
available to any XCM that is run over the project and they will retain their value from
one XCM to the next.
The function (RecMethodA) and subroutine (Main) in the following example share
the script variable called sOreType. Note that both the function and the subroutine
change the value of sOreType, and read the current value of it.
'Determine the Plant Recovery from the Ore Type and Impurity Grade
Dim sOreType As String
'------------------------------------------------------------------------
Sub Main
sOreType = GetClass(mOre_Type)
If (sOreType="Type1" And M(mOre_Grd)>0.5) Then M(mRec) = RecMethodA()
If (sOreType="Type2" And M(mOre_Grd)>0.7) Then M(mRec) = RecMethodA()
Call SetClass(mOre_Type, sOreType)
End Sub
'------------------------------------------------------------------------
Function RecMethodA() As Double
If (M(mImpurity_Grd) > 0.09) Then sOreType = "Type2"
9 XCM Commands
9.1 Introduction
Commands are the building blocks for your XCMs. Some XCM Commands have
already been discussed, such as If…Then statements, but many are yet to be
described. The commands that are available for use in your XCMs can be divided
into three categories, as follows:
• Cypress EnableTM Commands;
• XPAC Database Functions and Subroutines; and
• XPAC Scheduling Functions and Subroutines.
All of the XCM commands are listed in the XPAC7 XCM Quick Reference Cards.
These cards can be used to prompt your memory on how to use a particular function
or they can be used to determine which function or subroutine is best suited to a
particular task. Once you have located a function or subroutine for use, detailed
information can be found in the alphabetical listings in the following three sections of
this manual.
10.1.1 Type/Functions/Statements
______________________________________________________
Flow of Control
GoSub, Goto, End, OnError, Stop, Do...Loop, Exit Loop,
For...Next, Exit For, If..Then..Else...End If, Return, Stop,
While...Wend, Select Case
______________________________________________________
Converting
Chr, Hex, Oct, Str, CDbl, CInt, Clng, CSng, CStr, CVar, CVDate,
Asc, Val, Date, DateSerial, DateValue, Format, Fix, Int, Day,
Weekday, Month, Year, Hour, Minute, Second, TimeSerial,
TimeValue
________________________________________________________________
Dialog
Text, TextBox, ListBox, DropList, ComboBox, CheckBox, OKButton,
BeginDialog, EndDialog, OptionGroup, OKButton, CancelButton,
PushButton, Picture, GroupBox, Multi-line TextBox,
______________________________________________________
File I/O
FileCopy, ChDir, ChDrive, CurDir, CurDir, MkDir,RmDir, Open,
Close, Print #, Kill, FreeFile, LOF, FileLen, Seek, EOF, Write #,
Input, Line Input, Dir, Name, GetAttr, SetAttr, Dir,
______________________________________________________
Math
Exp, Log, Sqr, Rnd, Abs, Sgn, Atn, Cos, Sin, Tan, Int, Fix
______________________________________________________
Procedures
Call, Declare, Function, End Function, Sub, End Sub, Exit, Global
______________________________________________________
Strings
Let, Len, InStr, Left, Mid, Asc, Chr, Right, LCase, Ucase, InStr,
LTrim, RTrim, Trim, Option Compare, Len, Space, String,
StrComp Format,
______________________________________________________
Variables and Constants
Dim, IsNull, IsNumeric,VarType, Const, IsDate, IsEmpty, IsNull,
Option Explicit, Global, Static,
______________________________________________________
Error Trapping
On Error, Resume
______________________________________________________
Date/Time
Date, Now, Time, Timer
______________________________________________________
DDE
DDEInitiate, DDEExecute, DDETerminate
______________________________________________________
Arrays
Option Base, Option Explicit, Static, Dim, Global, Lbound,
Ubound, Erase, ReDim
______________________________________________________
Miscellaneous
SendKeys, AppActivate, Shell, Beep, Rem, CreateObject,
GetObject
10.1.3 Operators
Arithmetic Operators
() parenthesis Highest
^ exponentiation
- unary minus
/,* division/multplication
mod modulo
+, -, & addition, subtraction, concatenation
=, <>, <, >,<=,>= is relational
not Logical negation
and Logical conjunction
or Logical disjunction
Xor Logical exclusion
Eqv Logical Equivalence
Imp Logical Implication Lowest
Seek, SendKeys, Set, SetAttr, Second, Select, Shell, Sin, Sqr, Stop,Str, Sng,
Single, Space, Static, Step, Stop, Str, String, Sub, StringComp
Tan,Text, TextBox, Time, Timer, TimeSerial, TimeVale, Then, Type, Trim, True, To,
Type
UBound, UCase, Ucase, Until
Val, Variant, VarType
Write #, While, Weekday, Wend, With
Xor
Year
The data type of the return value is the same as that of the number
argument. However, if the number argument is a Variant of VarType
(String) and can be converted to a number, the return value will be a
Variant of VarType (Double). If the numeric expression results in a Null,
_Abs returns a Null.
Example:
Sub Main ' Start Main routine
Dim vMsg As Variant ' Declare Message
Dim sXvalue As String ' Declare Input String
Dim dXvalue As Double ' Declare Value
Dim lYvalue As Long ' Declare absolute value
sXvalue = InputBox("Enter a Number:") ' Assign Keyboard value
dXValue = Val(sXvalue) ' Change string to number
lYvalue = Abs(lXvalue) ' Determine Absolute value
vMsg = "The number you entered is " & lXvalue
vMsg = vMsg + ". The Absolute value of " &lXvalue & " is " &lYvalue
MsgBox vMsg 'Display Message. ' Display message
End Sub ' end of routine
AppActivate “app”
Activates an application.
The parameter app is a string expression and is the name that appears in the
title bar of the application window to activate.
Example:
Sub Main ()
AppActivate "Microsoft Word"
SendKeys “%F,%N,Cypress Enable”,True
Msg = “Click OK to close Word”
MsgBox Msg
AppActivate “Microsoft Word” ‘ Focus back to Word
SendKeys “%F,%C,N”, True ‘Close Word
End Sub
Asc ( str)
Returns a numeric value that is the ASCII code for the first character in a
string. For example “A” = 65
Example:
Sub Main ' Start Subroutine
Dim lRepeat As Long ' Declare variables.
Dim vMsg ' Declare variables.
For lRepeat = Asc("A") To Asc("Z") ' From A through Z.
vMsg = vMsg & Chr(lRepeat) ' Create a string.
Next lRepeat ' Next until "Z
MsgBox vMsg ' Display results.
End Sub ' End Subroutine
Atn (rad )
The argument rad can be any numeric expression. The result is expressed
in radians
Example:
Sub Main ' Start Main routine
Dim vMsg, dPi ' Declare variables.
dPi = 4 * Atn(1) ' Calculate Pi.
vMsg = "Pi is equal to " & Str(dPi)
MsgBox vMsg ' Display results.
End Sub ' End Subroutine
Beep
Sounds a tone through the computer's speaker. The frequency and duration
of the beep depends on hardware, which may vary among computers.
Example:
Sub Main ' Start of routine
Dim lAnswer As Long ' Declare long Reply
Dim vMsg As Variant ' Declare variables.
Do ' Control structure
lAnswer = InputBox("Enter a value from 1 to 3.")
If (lAnswer >= 1 And lAnswer <= 3) Then ' Check range.
Exit Do ' Exit Do...Loop.
Else ' Error
Beep ' Beep error.
End If ' End Construct
Loop ' Loop
MsgBox "You entered a value in the proper range."
You are never required to use the Call statement when calling an Enable
subroutine or a DLL function. Parentheses must be used in the argument
list if the Call statement is being used.
Example:
Sub Main 'Start Sub Routine
Call Noise ' Call Beep
MsgBox "Returns a Beep" ' Message box
End Sub ' End subroutine
Sub Noise ' Start of routine
Dim lAnswer As Long ' Declare long Reply
Dim vMsg As Variant ' Declare variables.
Do ' Control structure
lAnswer = InputBox("Enter a value from 1 to 3.")
If (lAnswer >= 1 And lAnswer <= 3) Then ' Check range.
Exit Do ' Exit Do...Loop.
Else ' Error
Beep ' Beep eror.
End If ' End Construct
Loop ' Loop
MsgBox "You entered a value in the proper range."
End Sub ' End of Routine
' End of XCM
CBool (expression)
Example:
Sub Main ' Start main Routine
Dim lGoalgrade As Long ' Declare Grade
Dim lAchievedgrade As Long ' Achieved grade
Dim bResult As Boolean ' Resulting Boolean(True/False)
lGoalgrade = 5 ' Set Goal grade
lAchievedgrade = 5 ' Set grade
' Change to boolean expression
bResult = CBool(lGoalgrade = lAchievedgrade)
Print bResult ' Print True/false
lGoalgrade = 0 ' Change Grade
bResult = CBool(lGoalgrade) ' Change to boolean
Print bResult ' Print True/False
End Sub ' End subroutine
CVDate (expression)
Example:
Sub Main ' Start Routine
Dim sStartDate As String ' Dragline start date
Dim dStartDate As Date ' Dragline start date
Dim sStartTime As String ' Dragline start time
Dim dStartTime As Date ' Dragline start time
sStartDate = "May 29, 1969" ' Define date.
dStartDate = CDate(sStartDate) ' Convert to Date data type.
sStartTime = "10:32:27 PM" ' Define time.
CDbl (expression)
Example:
Sub Main ' Start Main Routine
Dim iROMTonnes As Integer ' ROM tonnage
Dim dROMTonnes As Double ' ROM tonnage
iROMTonnes = 25 ' Assign ROM tonnage
If VarType(iROMTonnes) = 2 Then ' Determine variable type
Print iROMTonnes ' Print as integer
dROMTonnes = CDbl(iROMTonnes) ' Converts integer to double
Print dROMTonnes ' Print as Double
End If ' End Construct
End Sub ' End of Routine
'End of XCM
ChDir pathname
Example:
Sub Main ' Start of Subroutine
Dim lAnswer As Long ' Declare answer
Dim vMsg As Variant ' Declare MSg
Dim sNL As String ' Declare Character
Dim sCurPath As String ' Declare variables.
ChDrive drivename
Example:
Sub Main ' Start of Subroutine
Dim vMsg As Variant ' Declare MSg
Dim sNL As String ' Declare Character
Dim sCurPath As String ' Declare variables.
sNL = Chr(10) ' Define new line.
sCurPath = CurDir() ' Get current path.
ChDir "\" ' Change to route directory
ChDrive "F:" ' Change to g drive
vMsg = "The current directory has been changed to "
vMsg = vMsg & CurDir() & sNL & sNL & "Press OK to change back "
vMsg = vMsg & "to your previous default directory."
MsgBox vMsg ' Get user response.
ChDir sCurPath ' Change back to user default.
vMsg = "Directory changed back to " & sCurPath & "."
MsgBox vMsg ' Display results.
End Sub ' End of Routine
'End of XCM
10.2.12 CheckBox
Example:
Sub Main ' Start of Subroutine
Begin Dialog DialogName1 60, 60, 160, 70, "ASc - Hello"
TEXT 10, 10, 28, 12, "Name:"
TEXTBOX 42, 10, 108, 12, .nameStr
TEXTBOX 42, 24, 108, 12, .descStr
CHECKBOX 42, 38, 48, 12, "&CHECKME", .checkInt
OKBUTTON 42, 54, 40, 12
End Dialog
Dim Dlg1 As DialogName1
Dialog Dlg1
MsgBox Dlg1.nameStr
MsgBox Dlg1.descStr
MsgBox Dlg1.checkInt
End Sub ' End of Routine
'End of XCM
Choose will return a null value if number is less than one or greater than the
number of choices in the list. If number is not an integer it will be rounded
tot he nearest integer.
Example:
Chr(int )
Example:
Sub Main ' Start Subroutine
Dim lRepeat As Long ' Declare variables.
Dim vMsg ' Declare variables.
For lRepeat = Asc("A") To Asc("Z") ' From A through Z.
vMsg = vMsg & Chr(lRepeat) ' Create a string.
Next lRepeat ' Next until "Z
MsgBox vMsg ' Display results.
End Sub ' End Subroutine
CInt (expression)
Example:
Sub Main ' Start Main Routine
Dim dDoubleVar As Double ' Double data type
Dim iIntegerVar As Integer ' Integer data type
dDoubleVar = 25.2 ' Assign value to double
CLng (expression)
Example:
' Converts integer to long
Sub Main ' Start Main routine
Dim iValue As Integer ' Declare as integer
Dim lValue As Long ' Declare As long
iValue = 25 ' Assign Value
If (VarType(iValue) = 2) Then ' Return variable type
Print iValue ' Print result
lValue = CLng(iValue) ' Integer value to long
Print lValue ' Print result
End If ' End Variable type construct
End Sub ' End of Subroutine
'End of XCM
Example:
Sub Main ' Start Main Routine
Dim sMyStr As String ' Declare string for raw data
Open "c:\rawdata.txt" For Input As #1
Do While Not EOF(1) ' Read file by line
sMyStr = Input(10, #1) ' Input file 10 bytes,from rawdata
MsgBox sMyStr ' Print in ten byte increments
The definition of a Const in Cypress Enable outside the procedure or at the module level is a global.
The syntax Global Const and Const are used below outside the module level are identical.
A type declaration character may be used however if none is used Enable will automatically assign
one of the following data types to the constant, long (if it is a long or integer), Double (if a decimal
place is present), or a String ( if it is a string). Constants can be defined and assigned within XPAC
and are called Global Variable. This permits the use of these global variables by a number of
XCM’s.
Example:
Global Const GloConst = 142 '
Const MyConst = 122 'Global to all procedures in a module
Sub Main ()
Dim Answer, Msg, NL ' Declare variables.
Const PI = 3.14159
NL = Chr(10) ' Define newline.
CurPath = CurDir() ' Get current path.
ChDir "\"
Msg = "The current directory has been changed to "
Msg = Msg & CurDir() & NL & NL & "Press OK to change back "
Msg = Msg & "to your previous default directory."
Answer = MsgBox(Msg) ' Get user response.
ChDir CurPath ' Change back to user default.
Msg = "Directory changed back to " & CurPath & "."
MsgBox Msg ' Display results.
myvar =myConst + PI + GloConst
Print MyVar
End Sub
Cos (rad)
The argument rad must be expressed in radians and must be a valid numeric expression. Cos will
by default return a double unless a single or integer is specified as the return value.
Example:
' Cos Function Example
Sub Main() ' Start Main Routine
Dim dValue As Double ' Double cos value
Dim lRepeat As Long ' Repeat integer
Dim iNumber As Integer ' Cos value integer
Dim vMsg As Variant ' Message box variant
For lRepeat =1 To 10 ' Repeat ten times
vMsg = vMsg & Cos(lRepeat) & ", " ' Cos function call
dValue=Cos(lRepeat) ' Return Cos value
Print dValue ' Report value
iNumber=Cos(lRepeat) ' Return Cos value
Print iNumber ' Report Value
Next lRepeat ' Loop statement
MsgBox vMsg ' Display results.
End Sub ' End routine
' End of XCM
CreateObject (class)
word6.Insert name
word6.Bold 0
word6.InsertPara
word6.Insert " Vender Address:"
word6.InsertPara
word6.Insert " Vender Product:"
word6.InsertPara
word6.InsertPara
word6.Insert " Dear Vender:"
word6.InsertPara
word6.InsertPara
word6.Insert " The letter you are reading was created with Cypress Enable."
word6.Insert " Using OLE Automation Cypress Enable can call any other OLE _ enabled "
word6.Insert " application. Enable is a Basic Scripting Language for _ applications"
word6.InsertPara
word6.InsertPara
word6.Insert " Product Name: Cypress Enable "
word6.InsertPara
word6.Insert " Company Name: Cypress Software Inc."
word6.InsertPara
word6.InsertPara
MsgBox "You have just called Word 6.0 using OLE"
End Sub
Dear Vender:
The letter you are reading was created with Cypress Enable. Using OLE
Automation Cypress Enable can call any other OLE enabled application. Enable is
a Basic Scripting Language for applications
Product Name: Cypress Enable
Company Name: Cypress Software Inc.
CSng (expression)
Example:
Sub Main ()
Dim y As Integer
y = 25
If VarType(y) = 2 Then
Print y
x = CSng(y) 'Converts the integer value of y to a single value in x
Print x
End If
End Sub
Converts any valid expression to a String. This function does not reserve
space for a leading sign character, as the Str function does. However the
CStr function does honour local numbering formatting unlike the Str
function.
Related topics: Space Function, Str
For Example
' Example for string conversion
Sub Main ' Start main Routine
CVar (expression)
CurDir (drive)
Example:
Sub Form () ' Start Form routine
Dim vMsg As Variant ' Declare message box
Dim sNL As String ' Declare variables.
sNL = Chr(10) ' Define newline.
vMsg = "The current directory is: "
vMsg = vMsg & sNL & CurDir() ' Return current directory
MsgBox vMsg ' Display message.
End Sub ' End of subroutine Form
Sub Main ' Start Main routine
Call Form ' Call routine
End Sub ' End of Routine
'End of XCM
Date, Date()
Example:
' MyTime and MyDate are displayed in the development environment using
' current system short time and short date settings.
Sub Main ' Start main Routine
Dim dValue As Date ' Declare Date value
Dim sMyTime As String ' Declare XCM time
Dim sMyDate As String ' Declare XCM date
Dim sSysDate As String ' Declare system date
dValue = Date() ' Assign date
Print Date ' Print date
Print dValue ' Print to screen
Print VarType(Date) ' Print variable type
sMyTime= "08:04:23 PM" ' Assign time
sMyDate = "03/03/04" ' Assign date
sSysDate = Date ' Assign system date
MsgBox sSysdate,0,"System Date" ' Display message system date
MsgBox Now,0,"Now" ' Display current date and time
MsgBox sMyTime,0,"MyTime" ' Display chosen time
MsgBox Second( sMyTime ) & " Seconds" ' Display seconds
MsgBox Minute( sMyTime ) & " Minutes" ' Display minutes
MsgBox Hour( sMyTime ) & " Hours" ' Display hours
MsgBox Day( sMyDate ) & " Days" ' Display days
MsgBox Month( sMyDate ) & " Months" ' Display Month
MsgBox Year( sMyDate ) & " Years" ' Display year
' Returns current system time in the system-defined long time format.
MsgBox Format(Time, "Short Time") & " Short Time"
Returns a variant (Date) corresponding to the year, month and day that
were passed in. All three parameters for the DateSerial Function are
required and must be valid.
Example:
Sub Main ' Start Main Routine
Dim vDate As Variant ' Declare date variable
vDate = DateSerial(1959, 5, 29) ' Assign date serial
Print vDate ' Print to screen
End Sub ' End Main Routine
'End of XCM
DateValue(dateexpression)
Example:
Sub Main() ' Start Main Routine
Dim vDateValue As Variant ' Declare date value variable
vDateValue = DateValue("2069/05/29") ' Calculate datevalue
MsgBox (VarType(vDateValue)) ' Display variable type
MsgBox (vDateValue) ' Display date value
End Sub ' End Main Routine
' End of XCM
Day(dateexpression)
Returns a variant date corresponding to the string date expression that was
passed in. dateexpression can be a string or any expression that can
represent a date.
Example:
Sub Main ' Start Main Routine
Dim vDate As Variant ' Declare date variable
Dim vDay As Variant ' Declare day variable
vDate = #May 29, 1959# ' Assign date
vDay = Day(vDate) ' Calculate day
Print vDay ' Display day on screen
End Sub ' End Main Routine
'End of XCM
The Libname parameter is the name of the DLL that contains the procedure.
The optional Alias aliasname clause is used to supply the procedure name in the
DLL if different from the name specified on the procedure parameter. When the
optional argument list needs to be passed the format is as follows:
Example:
Declare Function GetFocus Lib "User" () As Integer
Declare Function GetWindowText Lib "User" (ByVal hWnd%, ByVal Mess$, ByVal cbMax%) As _ Integer
Sub Main
Dim hWindow%
Dim str1 As String *51
Dim str2 As String * 25
hWindow% = GetFocus()
print "GetWindowText returned: ", GetWindowText( hWindow%, str1,51 )
print "GetWindowText2 returned: ", GetWindowText( hWindow%, str2, 25)
print str1
print str2
End Sub
Dialog(DialogRecord )
Example:
' This sample shows all of the dialog controls on one dialog and how to
' vary the response based on which Push-Button was pressed.
Sub Main () ' Start Main Routine
Dim sMyList$(2) As String ' Declare Array
Dim vButton As Variant ' Declare Button
sMyList(0) = "ANFO" ' Assign Text
sMyList(1) = "SLURRY" ' Assign Text
sMyList(2) = "EMULSION" ' Assign Text
Begin Dialog DialogName1 60, 60, 240, 184, "Test Dialog"
Text 10, 10, 28, 12, "Type:"
TextBox 40, 10,50, 12, .joe
ListBox 102, 10, 108, 16, sMyList$(), .sMyList1
ComboBox 42, 30, 108, 42, sMyList$(), .Combo1
DropListBox 42, 76, 108, 36, sMyList$(), .DropList1$
OptionGroup .grp1
OptionButton 42, 100, 48, 12, "Option &1"
OptionButton 42, 110, 48, 12, "Option &2"
OptionGroup .grp2
OptionButton 42, 136, 48, 12, "Option &3"
OptionButton 42, 146, 48, 12, "Option &4"
Allocates storage for and declares the data type of variables and arrays in a
module.
The types currently supported are integer, long, single, double and String
Example:
Sub Main
Dim lValue As Long
Dim iDay As Integer
Dim sz As single
Dim dNumber As double
Dim sName As String
Dim vVariant As Variant ' This is the same as Dim x or Dim x as any
Dir[(path,attributes)]
Returns a file/directory name that matches the given path and attributes.
Example:
'=========================================================
' Bitmap sample using the Dir Function
'=========================================================
Sub DrawBitmapSample
Dim MyList()
Begin Dialog BitmapDlg 60, 60, 290, 220, "Enable bitmap sample", .DlgFunc
ListBox 10, 10, 80, 180, MyList(), .List1, 2
Picture 100, 10, 180, 180, "Forest.bmp", 0, .Picture1
CancelButton 42, 198, 40, 12
OKButton 90, 198, 40, 12
End Dialog
The parameter ControlName is the name of the control on the dialog box.
The parameter Value is the value to set it to. 1 = Enable, 0 = Disable. On is
equal to 1 in the example below. If the second parameter is omitted the
status of the control toggles. The entire example below can be found in the
dialog section of this manual and in the example .bas files that ship with
Cypress Enable.
Example:
Function Enable( ControlID$, Action%, SuppValue%)
Begin Dialog UserDialog2 160,160, 260, 188, "3", .Enable
Text 8,10,73,13, "New dialog Label:"
TextBox 8, 26, 160, 18, .FText
CheckBox 8, 56, 203, 16, "New CheckBox",. ch1
CheckBox 18,100,189,16, "Additional CheckBox", .ch2
PushButton 18, 118, 159, 16, "Push Button", .but1
OKButton 177, 8, 58, 21
CancelButton 177, 32, 58, 21
End Dialog
Case 1
DlgEnable "Group", 0
DlgVisible "Chk2", 0
DlgVisible "History", 0
Case 2
If ControlID$ = "Chk1" Then
DlgEnable "Group", On
DlgVisible "Chk2"
DlgVisible "History"
End If
End If
Case Else
End Select
Enable =1
End Function
The parameter ControlName is the name of the control on the dialog box.
The parameter String is the value to set it to.
Example:
If ControlID$ = "Chk2" Then
DlgText "History", "Push to display nested dialog"
End If
The parameter ControlName is the name of the control on the dialog box.
The parameter Value is the value to set it to. 1 = Visible, 0 = Hidden. On is
equal to 1. If the second parameter is omitted the status of the control
toggles. The entire example below can be found in the dialog section of
this manual and in the example .bas files that ship with Cypress Enable.
Example:
If ControlID$ = "Chk1" Then
DlgEnable "Group", On
DlgVisible "Chk2"
DlgVisible "History"
End If
Do [{While|Until} condition]
[statements]
[Exit Do]
[statements]
Loop
Do
[statements]
[Exit Do]
[statements]
Loop [{While|Until} condition]
Example:
Sub Main ()
Dim Value, Msg ' Declare variables.
Do
Value = InputBox("Enter a value from 5 to 10.")
If Value >= 5 And Value <= 10 Then
Exit Do ' Exit Do...Loop.
Else
Beep ' Beep if not in range.
End If
Loop
End Sub
End[{Function | If | Sub}]
Example:
Sub Main()
Var1 = "hello"
MsgBox " Calling Test"
Test Var1
MsgBox Var1
End Sub
wvar1 = "goodbye"
MsgBox "Use of End Statement"
End
End Sub
Returns a value during file input that indicates whether the end of a file has
been reached.
Example:
' Input Function Example
' This example uses the Input function to read 10 characters at a time from a '
file and display them in a MsgBox. This example assumes that TESTFILE is a 'text
file with a few lines of 'sample data.
Sub Main
Open "TESTFILE" For Input As #1 ' Open file.
Do While Not EOF(1) ' Loop until end of file.
MyStr = Input(10, #1) ' Get ten characters.
MsgBox MyStr
Loop
Close #1 ' Close file.
End Sub
Erase arrayname[,arrayname ]
Example:
' This example demonstrates some of the features of arrays. The lower bound
' for an array is 0 unless it is specified or option base has set it as is
' done in this example.
Option Base 1
Sub Main
Dim a(10) As Double
MsgBox "LBound: " & LBound(a) & " UBound: " & UBound(a)
Dim i As Integer
For i = 0 to 3
a(i) = 2 + i * 3.1
Next i
Erase a ' If this line is uncommented then the values will all be 0
Print a(0),a(1),a(2), a(3)
End Sub
Example:
' This sample shows Do ... Loop with Exit Do to get out.
Sub Main ()
Dim Value, Msg ' Declare variables.
Do
Value = InputBox("Enter a value from 5 to 10.")
If Value >= 5 And Value <= 10 Then ' Check range.
Exit Do ' Exit Do...Loop.
Else
Beep ' Beep if not in range.
End If
Loop
End Sub
10.2.41 Exp
Exp(num)
Example:
Sub ExpExample ()
' Exp(x) is e ^x so Exp(1) is e ^1 or e.
Dim Msg, ValueOfE ' Declare variables.
ValueOfE = Exp(1) ' Calculate value of e.
Msg = "The value of e is " & ValueOfE
MsgBox Msg ' Display message.
End Sub
FileLen( filename )
Example:
Sub Main
Dim MySize
MySize = FileLen("TESTFILE") ' Returns file length (bytes).
Print MySize
End Sub
Fix(number )
Example:
Sub Main
dim z(1 to 4) as double
z(1) = 1.11
z(2) = 2.22
z(3) = 3.33
For Each v In z
Print v
Next v
End Sub
Example:
Sub main ()
Dim x,y,z
For x = 1 to 5
For y = 1 to 5
For z = 1 to 5
Print "Looping" ,z,y,x
Next z
Next y
Next x
End Sub
Part Description
expression Expression to be formatted.
fmt A string of characters that specify how the expression is to displayed. or the
name of a commonly-used format that has been predefined in Enable Basic. Do
not mix different type format expressions in a single fmt parameter.
if the fmt parameter is omitted or is zero-length and the expression parameter is a numeric,
Format[$] provides the same functionality as the Str[$] function by converting the numeric
value to the appropriate return data type, Positive numbers convert to strings using Format[$]
lack the leading space reserved for displaying the sign of the value, whereas those converted
using Str[$] retain the leading space.
To format numbers, you can use the commonly-used formats that have been predefined in
Enable Basic or you can create user-defined formats with standard characters that have special
meaning when used in a format expression.
Format
Name Description
General Display the number as is, with no thousand Separators
Number
Fixed Display at least one digit to the left and two digits to the right of the decimal
separator.
Standard Display number with thousand separator, if appropriate; display two digits to the
right of the decimal separator.
Percent Display number multiplied by 100 with a percent sign (%) appended to the right’
display two digits to the right of the decimal separator.
Format
Name Description
The following shows the characters you can use to create user-defined number formats.
Character Meaning
Null string Display the number with no formatting.
0 Digit placeholder.
Display a digit or a zero
If the number being formatted has fewer digits than there are zeros (on either side of the
decimal) in the format expression, leading or trailing zeros are displayed. If the number has
more digits to the right of the decimal separator than there are zeros to the right of the decimal
separator in the format expression, the number is rounded to as many decimal places as there
are zeros. If the number has more digits to left of the decimal separator than there are zeros to
the left of the decimal separator in the format expression, the extra digits are displayed without
modification.
# Digit placeholder.
Displays a digit or nothing. If there is a digit in the expression being formatted in the position
where the # appears in the format string, displays it; otherwise, nothing is displayed.
. Decimal placeholder.
The decimal placeholder determines how many digits are displayed to the left and right of the
decimal separator.
Character Meaning
% Percentage placeholder.
The percent character (%) is inserted in the position where it appears in the format string. The
expression is multiplied by 100.
, Thousand separator.
The thousand separator separates thousands from hundreds within a number that has four or
more places to the left of the decimal separator.
Use of this separator as specified in the format statement contains a comma surrounded by
digit placeholders(0 or #). Two adjacent commas or a comma immediately to the left of the
decimal separator (whether or not a decimal is specified) means “scale the number by dividing
it by 1000, rounding as needed.”
If the format expression contains at least one digit placeholder (0 or #) to the right of E-,E+,e-
or e+, the number is displayed in scientific formatted E or e inserted between the number and
its exponent. The number of digit placeholders to the right determines the number of digits in
the exponent. Use E- or e- to place a minus sign next to negative exponents. Use E+ or e+ to
place a plus sign next to positive exponents.
: Time separator.
The actual character used as the time separator depends on the Time Format specified in the
International section of the Control Panel.
/ Date separator.
The actual character used as the date separator in the formatted out depends on Date Format
specified in the International section of the Control Panel.
Character Meaning
To display a character other than one of those listed, precede it with a backslash (\).
The backslash itself isn’t displayed. To display a backslash, use two backslashes (\\).
Examples of characters that can’t be displayed as literal characters are the date- and time-
formatting characters (a,c,d,h,m,n,p,q,s,t,w,y, and /:), the numeric -formatting
characters(#,0,%,E,e,comma, and period), and the string- formatting characters (@,&,<,>, and
!).
To include a string in fmt from within Enable, you must use the ANSI code for a double
quotation mark Chr(34) to enclose the text.
Any empty space in a field is filled with the character following the asterisk.
Unless the fmt argument contains one of the predefined formats, a format expression for
numbers can have from one to four sections separated by semicolons.
Two The first section applies to positive values, the second to negative
sections values.
Three The first section applies to positive values, the second to negative
sections values, and the third to zeros.
Four The first section applies to positive values, the second to negative
section values, the third to zeros, and the fourth to Null values.
The following example has two sections: the first defines the format for positive values and
zeros; the second section defines the format for negative values.
“$#,##0; ($#,##0)”
Include semicolons with nothing between them, the missing section is printed using the format
of the positive value. For example, the following format displays positive and negative values
using the format in the first section and displays “Zero” if the value is zero.
“$#,##0;;\Z\e\r\o”
Some sample format expressions for numbers are shown below. (These examples all assume
the Country is set to United States in the International section of the Control Panel.) The first
column contains the format strings. The other columns contain the output the results if the
formatted data has the value given in the column headings
0 3 -3 1
#,##0 3 -3 1
$#,##0;($#,##0) $3 ($3) $1
Numbers can also be used to represent date and time information. You can format date and
time serial numbers using date and time formats or number formats because date/time serial
numbers are stored as floating-point values.
To format dates and times, you can use either the commonly used format that have been
predefined or create user-defined time formats using standard meaning of each:
The following table shows the predefined data format names you can use and the meaning of
each.
Format
Name Description
General Display a date and/or time. for real numbers, display a date and time.(e.g.
4/3/93 03:34 PM); If there is no fractional part, display only a date (e.g.
4/3/93); if there is no integer part, display time only (e.g. 03:34 PM).
Long Date Display a Long Date, as defined in the International section of the Control
Panel.
Medium Display a date in the same form as the Short Date, as defined in the
international section of the Control Panel, except spell out the month
abbreviation.
Short Date Display a Short Date, as defined in the International section of the Control
Panel.
Long Time Display a Long Time, as defined in the International section of the Control
panel. Long Time includes hours, minutes, seconds.
Medium Time Display time in 12-hour format using hours and minuets and the Time
AM/PM designator.
Short Time Display a time using the 24-hour format (e.g. 17:45)
This table shows the characters you can use to create user-defined date/time formats.
Character Meaning
c Display the date as dddd and display the time as ttttt. in the order.
ddddd Display a date serial number as a complete date (including day , month, and year).
Character Meaning
ttttt Display a time serial number as a complete time (including hour, minute, and
second) formatted using the time separator defined by the Time Format in the
International section of the Control Panel. A leading zero is displayed if the
Leading Zero option is selected and the time is before 10:00 A.M. or P.M. The
default time format is h:mm:ss.
Character Meaning
AMPM Use the 12-hour clock and display the contents of the 11:59 string (s1159)
in the WIN.INI file with any hour before noon; display the contents of the 2359 string (s2359)
with any hour between noon and 11:59 PM. AMPM can be either uppercase or lowercase, but
the case of the string displayed matches the string as it exists in the WIN.INI file. The default
format is AM/PM.
Format Display
m/d/yy 2/26/65
d-mmmm-yy 26-February-65
d-mmmm 26 February
mmmm-yy February 65
h:mm:ss 18:45:15
Strings can also be formatted with Format[$]. A format expression for strings can have one
section or two sections separated by a semicolon.
Two sections The first section applies to string data, the second to Null values and
zero-length strings.
The following characters can be used to create a format expression for strings:
Character Meaning
@ Character placeholder.
Displays a character or a space. Placeholders are filled from right to left unless there is
an ! character in the format string.
Example:
' This example shows various uses of the Format function to format values
' using both named and user-defined formats. For the date separator (/),
' time separator (:), and AM/ PM literal, the actual formatted output
' displayed by your system depends on the locale settings on which the code
' is running. When times and dates are displayed in the development
' environment, the short time and short date formats of the code locale
' are used. When displayed by running code, the short time and short date
' formats of the system locale are used, which may differ from the code
' locale. For this example, English/United States is assumed.
' MyTime and MyDate are displayed in the development environment using
' current system short time and short date settings.
Sub Main
MsgBox Now
MsgBox MyTime
' Returns current system time in the system-defined long time format.
MsgBox Format(Time, "Short Time")
MyStr = Format(Time, "Long Time")
' Returns current system date in the system-defined long date format.
MsgBox Format(Date, "Short Date")
MsgBox Format(Date, "Long Date")
FreeFile
Returns an integer that is the next available file handle to be used by the
Open Statement.
Example:
Sub Main
Dim Mx, FileNumber
For Mx = 1 To 3
FileNumber = FreeFile
Open "c:\e1\TEST" & Mx For Output As #FileNumber
Write #FileNumber, "This is a sample."
Close #FileNumber
Next Mx
Declares and defines a procedure that can receive arguments and return a
value of a specified data type.
When the optional argument list needs to be passed the format is as follows:
Example:
Sub Main
For I = 1 to 10
Print GetColor2(I)
Next I
End Sub
Function GetColor2( c% ) As Long
GetColor2 = c% * 25
If c% > 2 Then
GetColor2 = 255 ' 0x0000FF - Red
End If
If c% > 5 Then
GetColor2 = 65280 ' 0x00FF00 - Green
End If
If c% > 8 Then
GetColor2 = 16711680 ' 0xFF0000 - Blue
End If
End Function
GetObject(filename[,class])
The GetObject Function has two parameters a filename and a class. The filename is the name of
the file containing the object to retrieve. If filename is an empty string then class is reuqired. Class
is a string containing the class of the object to retrieve.
The Global Statement must be outside the procedure section of the script. Global variables are
available to all functions and subroutines in your program
Example:
Global Const GloConst = 142 '
Const MyConst = 122 'Global to all procedures is a module
Sub Main ()
Dim Answer, Msg, NL ' Declare variables.
Const PI = 3.14159
NL = Chr(10) ' Define newline.
CurPath = CurDir() ' Get current path.
ChDir "\"
Msg = "The current directory has been changed to "
Msg = Msg & CurDir() & NL & NL & "Press OK to change back "
Msg = Msg & "to your previous default directory."
Answer = MsgBox(Msg) ' Get user response.
ChDir CurPath ' Change back to user default.
Msg = "Directory changed back to " & CurPath & "."
MsgBox Msg ' Display results.
myvar =myConst + PI + GloConst
Print MyVar
End Sub
GoTo label
Example:
Sub main ()
Dim x,y,z
For x = 1 to 5
For y = 1 to 5
For z = 1 to 5
Print "Looping" ,z,y,x
If y > 3 Then
GoTo Label1
End If
Next z
Next y
Next x
Label1:
End Sub
10.2.53 Hex
Hex (num)
Example:
Sub Main ()
Hour(string )
The Hour Function returns an integer between 0 and 23 that is the hour of the day indicated in the
parameter number.
The parameter string is any numeric expressed as a string that can represent a date and time from
January 1, 1980 through December 31, 9999.
Example:
' This example shows various uses of the Format function to format values
' using both named and user-defined formats. For the date separator (/),
' time separator (:), and AM/ PM literal, the actual formatted output
' displayed by your system depends on the locale settings on which the code
' is running. When times and dates are displayed in the development
' environment, the short time and short date formats of the code locale
' are used. When displayed by running code, the short time and short date
' formats of the system locale are used, which may differ from the code
' locale. For this example, English/United States is assumed.
' MyTime and MyDate are displayed in the development environment using
' current system short time and short date settings.
Sub Main
MyTime = "08:04:23 PM"
MyDate = "03/03/95"
MyDate = "January 27, 1993"
MsgBox Now
MsgBox MyTime
' Returns current system time in the system-defined long time format.
MsgBox Format(Time, "Short Time")
MyStr = Format(Time, "Long Time")
' Returns current system date in the system-defined long date format.
MsgBox Format(Date, "Short Date")
MsgBox Format(Date, "Long Date")
End Sub
If condition Then
[statement(s)]
ElseIf condition Then
[statement(s)]
Else
[statements(s)]
End If
Syntax 2
If conditional Then statement
Example:
Sub IfTest
' demo If...Then...Else
Dim msg as String
Dim nl as String
Dim someInt as Integer
nl = Chr(10)
msg = "Less"
someInt = 4
msg = "Greater"
Beep
Else
msg = "Less"
End If
MsgBox(msg)
If someInt = 1 Then
msg = "Spring"
ElseIf someInt = 2 Then
msg = "Summer"
ElseIf someInt = 3 Then
msg = "Fall"
ElseIf someInt = 4 Then
msg = "Winter"
Else
msg = "Salt"
End If
MsgBox(msg)
End Sub
Input(n , [ #] filenumber )
The input function has two parameters n and filenumber. n is the number of bytes to be read from
a file and filenumber is the number used in the open statement when the file was opened.
Example:
Sub Main ' Start Main Routine
Dim sMyStr As String ' Declare string for raw data
Open "c:\rawdata.txt" For Input As #1 'Open file
Do While Not EOF(1) ' Read file by line
sMyStr = Input(10, #1) ' Input file 10 bytes,from rawdata.txt
MsgBox sMyStr ' Print in ten byte increments
Loop ' Continue until EOF
Close #1 ' Close raw datafile
End Sub ' End Main routine
'End of XCM
InputBox(prompt[,[title][,[default][,xpos,ypos]]])
Title is a string that is displayed at the top of the input dialog box.
Default is a string that is displayed in the text box as the default entry.
Xpos and Ypos and the x and y coodinates of the relative location of the
inpur dialog box.
Example 1:
Sub Main ()
Title$ = "Greetings"
Prompt$ = "What is your name?"
Default$ = ""
X% = 2000
Y% = 4000
N$ = InputBox$(Prompt$, Title$, Default$, X%, Y%)
End Sub
Example 2:
' Keyboardinput.bas
Dim Msg, X,Y ' Declare all variable
Sub Main ' Start main routine
' Default value for x is 100
X = InputBox("Enter a number Between 0 - 100","User Input Required",100)
If (X > 100) Then ' Above limit
Over ' Call over limit sub routine
Elseif (X < 0) Then ' Under Limit
Under ' Call under limit sub routine
Elseif ((X>0) And (X<=100))Then ' Number acceptable
Correct ' Call correct sub routine
End If ' End above limit construct
End Sub ' End Main sub
Sub Over() ' Over subroutine
' This is the message and variable
Msg = "Error.You entered a number greater than 100. It was"& X
MsgBox Msg ' Display Message
Y = InputBox("Re-enter number","Try Again",100) ' New Input
If ((Y>0) And (Y<=100)) Then ' Number acceptable test
Smug ' Call Smug subroutine
Else ' Number still wrong
Msg = "XCM going to abort" ' New message
MsgBox Msg ' Display Message
Abort " Please restart" ' Abort XCM
10.2.58 InStr
The numbegin parameter is not optional and sets the starting point of the
search. numbegin must be a valid positive integer no greater than 65,535.
string1 is the string being searched and string2 is the string we are looking
for.
Example:
Sub Main () ' Start Main Routine
Dim sString As String ' Input String
Dim lPosA As Long ' Declare Position
sString = "Good Bye" ' Assign String value
Int(number )
Example
Sub Main ' Start main routine
Dim dAnfoTon As Double ' Declare ANFO tonnage
Dim iAnfoTon As Double ' Declare ANFO tonnage as integer
dAnfoTon = 1234.345 ' Assign ANFO tonnes
iAnfoTon = Int(dAnfoTon) ' Return Integer value
End Sub ' End routine
'End of XCM
IsArray(variablename )
Example:
Sub Main ' Start Main Routine
Dim iArray(1 To 5) As Integer ' Declare Array
Dim bCheck As Boolean ' Declare Boolean check
bCheck = IsArray(iArray) ' Is array function
Print bCheck ' Yes this is an array
10.2.61 IsDate
IsDate(variant )
10.2.62 IsEmpty
IsEmpty(variant )
Example:
' This sample explores the concept of an empty variant
Sub Main ' Start of Routine
Dim vxValue As Double ' Declare empty
vxValue = 5 ' Not Empty - Long
vxValue = Empty ' Empty
MsgBox vxValue & " IsEmpty: " & IsEmpty(vxValue)
End Sub ' End Routine
'End of XCM
10.2.63 IsNull
IsNull(v)
The NULL value is special because it indicates the that the v parameter
contains no data. This is different from a null-string, which is a zero length
string and an empty string which has not yet been initialized.
10.2.64 IsNumeric
IsNumeric(v)
The parameter v can be any variant, numeric value, Date or string (if the
string can be interpreted as a numeric).
Example:
Sub Form_Click ()
Dim TestVar ' Declare variable.
TestVar = InputBox("Please enter a number, letter, or symbol.")
If IsNumeric(TestVar) Then ' Evaluate variable.
MsgBox "Entered data is numeric." Message if number.
Else
MsgBox "Entered data is not numeric." ' Message if not.
End If
End Sub
IsObject(objectname )
Example:
Sub Main
Print MyCheck
End Sub
Kill filename
Kill will only delete files. To remove a directory use the RmDir Statement
Example:
Const NumberOfFiles = 3
Sub Main ()
Dim Msg ' Declare variable.
Call MakeFiles() ' Create data files.
Msg = "Several test files have been created on your disk. You may see "
Msg = Msg & "them by switching tasks. Choose OK to remove the test files."
MsgBox Msg
For I = 1 To NumberOfFiles
Kill "TEST" & I ' Remove data files from disk.
Next I
End Sub
Sub MakeFiles ()
Dim I, FNum, FName ' Declare variables.
For I = 1 To NumberOfFiles
FNum = FreeFile ' Determine next file number.
FName = "TEST" & I
Open FName For Output As FNum ' Open file.
Print #FNum, "This is test #" & I ' Write string to file.
Print #FNum, "Here is another "; "line"; I
Next I
Close ' Close all files.
Kill FName
End Sub
LBound(array [,dimension] )
Returns the smallest available subscript for the dimension of the indicated array.
Example:
' This example demonstrates some of the features of arrays. The lower bound
' for an array is 0 unless it is specified or option base has set as is
' done in this example.
Option Base 1
Sub Main
Dim a(10) As Double
MsgBox "LBound: " & LBound(a) & " UBound: " & UBound(a)
Dim i As Integer
For i = 0 to 3
a(i) = 2 + i * 3.1
Next i
Print a(0),a(1),a(2), a(3)
End Sub
Lcase[$](string )
Returns a string in which all letters of the string parameter have been
converted to upper case.
Example:
' This example uses the LTrim and RTrim functions to strip leading and
' trailing spaces, respectively, from a string variable. It
' uses the Trim function alone to strip both types of spaces.
' LCase and UCase are also shown in this example as well as the use
' of nested function calls
Sub Main
MyString = " <-Trim-> " ' Initialize string.
10.2.69 Left
Left(string, num)
Example:
Sub Main ()
Dim LWord, Msg, RWord, SpcPos, UsrInp ' Declare variables.
Msg = "Enter two words separated by a space."
UsrInp = InputBox(Msg) ' Get user input.
print UsrInp
SpcPos = InStr(1, UsrInp, " ") ' Find space.
If SpcPos Then
LWord = Left(UsrInp, SpcPos - 1) ' Get left word.
print "LWord: "; LWord
RWord = Right(UsrInp, Len(UsrInp) - SpcPos) ' Get right word.
Msg = "The first word you entered is " & LWord
Msg = Msg & "." & " The second word is "
Msg = "The first word you entered is <" & LWord & ">"
Msg = Msg & RWord & "."
Else
Msg = "You didn't enter two words."
End If
MsgBox Msg ' Display message.
10.2.70 Len
Len(string)
Example:
Sub Main ()
A$ = "Cypress Enable"
StrLen% = Len(A$) 'the value of StrLen is 14
MsgBox StrLen%
End Sub
Let is an optional keyword that is rarely used. The Let statement is required
in older versions of BASIC.
Example:
Sub Form_Click ()
Dim Msg, Pi ' Declare variables.
Let Pi = 4 * _Atn(1) ' Calculate Pi.
Msg = "Pi is equal to " & Str(Pi)
MsgBox Msg ' Display results.
End Sub
The parameter filenumber is used in the open statement to open the file.
The parameter name is the name of a variable used to hold the line of text
from the file.
Example:
' Line Input # Statement Example:
' This example uses the Line Input # statement to read a line from a
' sequential file and assign it to a variable. This example assumes that
' TESTFILE is a text file with a few lines of sample data.
Sub Main
Open "TESTFILE" For Input As #1 ' Open file.
Do While Not EOF(1) ' Loop until end of file.
Line Input #1, TextLine ' Read line into variable.
Print TextLine ' Print to Debug window.
Loop
Close #1' Close file.
End Sub
10.2.73 LOF
LOF(filenumber)
Returns a long number for the number of bytes in the open file.
The parameter filenumber is required and must be an integer.
Example:
Sub Main
Dim FileLength
Open "TESTFILE" For Input As #1
FileLength = LOF(1)
Print FileLength
Close #1
End Sub
Note Use the FileLen function to obtain the length of a file that is not open.
10.2.74 Log
Log(num)
Example:
Sub Form_Click ( )
Dim I, Msg, NL
NL = Chr(13) & Chr(10)
Msg = Exp(1) & NL
For I = 1 to 3
Msg = Msg & Log(Exp(1) ^ I ) & NL
Next I
MsgBox Msg
End Sub
To calculate base n logs for any numeric value “K” just divide by the natural log of “k” by the
natural log of n, which becomes:
Log(K) = log(k) / log(n).
The following XCM highlights the difference between the two logarithm types.
' # Note :This XCM calculates both the natural
' log of 50 and the log base ten of 50.
Sub Main ' Start Main Routine
' Declare Variables
Dim dVALUE As Double ' Double constant
Dim dLogTen As Double ' Variable for log10 output
Dim dTENLOG As Double ' Double constant for log value
Dim dLogLn As Double ' Variable for Natural log output
dVALUE = 50 ' Constant Value in upper case
' Calculate the natural logarithm
dLogLn = Log(dVALUE) ' Returns natural log
' Calculate log base ten
' Constant to base E is log of 10 or 2.718282
dTENLOG = 10 ' Constant Value in upper case
dLogTen = log(dVALUE) / log(dTENLOG) ' Calculate log base 10
End Sub ' End Main routine
string = Mid(strgvar,begin,length)
Example:
Sub Main () ' Start Main Routine
Dim sLWord As String ' Declare left word
Dim vMsg As Variant ' Declare message box
Dim sRWord As String ' Declare right word
Dim lSpcPos As Long ' Declare space position
Dim vUsrInp As Variant ' Declare user input
' variables.
Dim sMidtest As String ' Declare Mid String
vMsg = "Enter two words separated by a space." ' Assign Message
vUsrInp = InputBox(vMsg) ' Get user input.
Print vUsrInp ' Print user input
lSpcPos = InStr(1, vUsrInp, " ") ' Find space.
If (lSpcPos) Then ' Test user input
sLWord = Left(vUsrInp, lSpcPos - 1) ' Get left word.
Print "LWord: "; sLWord ' Print left word
' This example shows various uses of the Format function to format values
' using both named and user-defined formats. For the date separator (/),
' time separator (:), and AM/ PM literal, the actual formatted output
' displayed by your system depends on the locale settings on which the code
' is running. When times and dates are displayed in the development
' environment, the short time and short date formats of the code locale
' are used. When displayed by running code, the short time and short date
' formats of the system locale are used, which may differ from the code
' locale. For this example, English/United States is assumed.
' MyTime and MyDate are displayed in the development environment using
' current system short time and short date settings.
Sub Main ' Start Main routine
Dim sMyTime As String ' Declare time
Dim sMyDate As String ' Declare Date
sMyTime = "08:04:23 PM" ' Assign time
sMyDate = "03/03/02" ' Assign date
MsgBox Now ' Display current time
MsgBox sMyTime ' Display chosen time
MsgBox Second( sMyTime ) & " Seconds" ' Display seconds
MsgBox Minute( sMyTime ) & " Minutes" ' Display Minutes
MsgBox Hour ( sMyTime ) & " Hours" ' Display Hours
MsgBox Day ( sMyDate ) & " Days" ' Display Days
MsgBox Month ( sMyDate ) & " Months" ' Display Months
MsgBox Year ( sMyDate ) & " Years" ' Display Years
End Sub ' End main routine
'End of XCM
10.2.77 MkDir
MkDir path
The parameter path is a string expression that must contain fewer than 128
characters.
Example:
Sub Main
Dim DST As String
DST = "t1"
mkdir DST
mkdir "t2"
End Sub
Month(number)
Returns an integer between 1 and 12, inclusive, that represents the month of
the year.
Example:
Sub Main ' Start Main Routine
Dim dMyDate As Date ' Declare date
Dim lMonth As Long ' Declare month
dMyDate = "03/03/01" ' Assign date
Print dMyDate ' Print Date
lMonth = Month(dMyDate) ' Calculate Month
Print lMonth ' Print Month
Displays a message in a dialog box and waits for the user to choose a
button.
The first parameter msg is the string displayed in the dialog box as the message. The second and
third parameters are optional and respectively designate the type of buttons and the title displayed in
the dialog box.
MsgBox Function returns a value indicating which button the user has chosen; the MsgBox
statement does not.
The first group of values (1-5) describes the number and type of buttons displayed in the dialog
box; the second group (16, 32, 48, 64) describes the icon style; the third group (0, 256, 512)
determines which button is the default; and the fourth group (0, 4096) determines the modality of
the message box. When adding numbers to create a final value for the argument type, use only one
number from each group. If omitted, the default value for type is 0.
title:
String expression displayed in the title bar of the dialog box. If you omit the argument title,
MsgBox has no default title.
Sub Main ' Start Main Routine
Dim dPrdRate As Double ' Declare production rate
dPrdRate = 1234.567 ' Assign Prd Rate (Tonnes per hr)
MsgBox dPrdRate ' Display message
MsgBox dPrdRate, 0,"This is Code 0" ' Display OK button only
MsgBox dPrdRate, 1,"This is Code 1" ' Display OK and Cancel buttons
MsgBox dPrdRate, 2,"This is Code 2" ' Display Abort, Retry, and Ignore buttons
MsgBox dPrdRate, 3,"This is Code 3" ' Display Yes, No, and Cancel buttons
MsgBox dPrdRate, 4,"This is Code 4" ' Display Yes and No buttons
MsgBox dPrdRate, 5,"This is Code 5" ' Display Retry and Cancel buttons
MsgBox dPrdRate, 16,"This is Code 16"' Display Stop Sign
MsgBox dPrdRate, 32,"This is Code 32"' Display Question Sign
MsgBox dPrdRate, 48,"This is Code 48"' Display exclamation sign
MsgBox dPrdRate, 64,"This is Code 64"' Display information sign
MsgBox dPrdRate, 256," Code 256" ' Second button is default
MsgBox dPrdRate, 512," Code 512" ' Third button is default
MsgBox dPrdRate, 4096," Code 4096" ' Await user response
End Sub ' End Main Routine
The value returned by the MsgBox function indicates which button has been selected, as shown
below:
If the dialog box displays a Cancel button, pressing the Esc key has the same effect as choosing
Cancel.
Sub Main ' Start Main Routine
Dim dPrdRate As Double ' Declare production rate
dPrdRate = 1234.567 ' Assign Prd Rate (Tonnes per hr)
MsgBox dPrdRate ' Display message
Dim la As Long ' Declare return value
la = MsgBox (dPrdRate, 0,"This is Code 0") ' Display OK button only
The example uses MsgBox to display a close without saving message in a dialog box with a Yes
button a No button and a Cancel button. The Cancel button is the default response. The MsgBox
function returns a value based on the button chosen by the user. The MsgBox statement uses that
value to display a message that indicates which button was chosen.
Note : NL or 10 is new line but it does the same thing
CR or 13 is normally a carriage return.
Example:
Sub Main
The parameters oldname and newname are string that can optionally
contain a path.
Example:
Sub Main
End Sub
Now
Returns a date that represents the current date and time according to the
setting of the computer’s system date and time
The Now function returns a Variant data type containing a date and time
that are stored internally as a double. The number is a date and time from
January 1, 100 through December 31, 9999, where January 1, 1900 is 2.
Numbers to the left of the decimal point represent the date and numbers to
the right represent the time.
Related Topics:
Example:
Sub Main ' Start Main Routine
Dim vToday ' Declare present date
vToday = Now ' Assign current date/time
MsgBox vToday,48,"Date & Time " ' Display date and time
End Sub ' End Main routine
' End of XCM
Oct (num)
Example:
Sub Main ()
Dim Msg, Num ' Declare variables.
Num = InputBox("Enter a number.") ' Get user input.
Msg = Num & " decimal is &O"
Msg = Msg & Oct(Num) & " in octal notation."
MsgBox Msg ' Display results.
End Sub
10.2.83 OKButton
Sub Main ()
Begin Dialog DialogName1 60, 60, 160, 70, "ASC - Hello"
TEXT 10, 10, 28, 12, "Name:"
TEXTBOX 42, 10, 108, 12, .nameStr
TEXTBOX 42, 24, 108, 12, .descStr
CHECKBOX 42, 38, 48, 12, "&CHECKME", .checkInt
OKBUTTON 42, 54, 40, 12
End Dialog
Dim Dlg1 As DialogName1
Dialog Dlg1
MsgBox Dlg1.nameStr
MsgBox Dlg1.descStr
MsgBox Dlg1.checkInt
End Sub
10.2.84 On Error
Enables error-handling routine and specifies the line label of the error-
handling routine.
The line parameter refers to a label. That label must be present in the code or an error is generated.
Example:
Sub Main
On Error GoTo dude
Dim x as object
x.draw ' Object not set
jpe ' Undefined function call
print 1/0 ' Division by zero
Err.Raise 6 ' Generate an "Overflow" error
MsgBox "Back"
MsgBox "Jack"
Exit Sub
dude:
MsgBox "HELLO"
Print Err.Number, Err.Description
Resume Next
MsgBox "Should not get here!"
MsgBox "What?"
End Sub
Err.Raise x
The list below shows the corresponding descriptions for the defined values
of x.
You must open a file before any I/O operation can be performed on it. The Open statement has
these parts:
Part Description
mode Reserved word that specifies the file mode: Append, Binary
Input, Output
If file doesn't exist, it is created when a file is opened for Append, Binary or Output modes.
The argument mode is a reserved word that specifies one of the following file modes.
Mode
Description
Input Sequential input mode.
Output Sequential
output mode.
Append Sequential output mode. Append sets the file pointer to the end of the file. A Print # or
Write # statement then extends (appends to) the file.
The argument access is a reserved word that specifies the operations that can be performed on the
opened file. If the file is already opened by another process and the specified type of access is not
allowed, the Open operation fails and a Permission denied error occurs. The Access clause works
only if you are using a version of MS-DOS that supports networking (MS-DOS version 3.1 or
later). If you use the Access clause with a version of MS-DOS that doesn't support networking, a
Feature unavailable error occurs. The argument access can be one of the following reserved words.
The following example writes data to a test file and reads it back.
Example :
Sub Main ()
The example uses the Option Base statement to override the default base array subscript value of 0.
Example :
' Example of option base
Option Base 1 ' Global statement.
Sub Main ' Start Main Routine
Dim vArray() As Variant ' Declare Array
Dim vMsg As Variant ' Declare message
Dim sNL As String ' Declare variables.
sNL = Chr(10) ' Define newline by
' character.
ReDim vArray(20) ' Create an array.
vMsg = "The lower bound of the A array is " & LBound(vArray) & "."
vMsg = vMsg & sNL & "The upper bound is " & UBound(vArray) & "."
MsgBox vMsg,4096,"Result of XCM is " ' Display message
End Sub ' End of Routine
'End of XCM
Option Explicit
The Option explicit statement is used outside of the script in the declaration section. This
statement can be contained in a declare file or outside of any script in a file or buffer. If this
statement is contained in the middle of a file the rest of the compile buffer will be affected.
Example :
' This XCM will not run properly as a variable is not defined.
' To correct this problem, just declare the variable dVariableY as Double
Option Explicit ' Forces user to declare all variable
Dim dVariableX As Long ' Declare varaible X
Sub Main ' Start Main Routine
dVariableX = 3.210 ' Assign value to variable X
Print dVariableX ' Print Variable X
Print dVariableY ' dVariableY is not explicitly declared an error will
occur.
End Sub ' End routine
'End of XCM
' The use of option Explicit is advised. This forces all variables to be defined.
' In longer programs the user can lose track of a large number of variables.
' Therefore by declaring each variable more control is achieved.
Related Topics:
Example:
Sub Main ' Start Main routine
Dim vMsg, dPi ' Declare variables.
dPi = 4 * Atn(1) ' Calculate Pi.
vMsg = "Pi is equal to " & Str(dPi)
MsgBox vMsg ' Display results.
Print dPi ' Display results
End Sub ' End Subroutine
Statement
10.2.89 Print # Statement
Print # filenumber,
[ [{Spc(n) | Tab(n)}][ expressionlist] [{; | ,}]]
Writes data to a sequential file.
Print statement Description:
filenumber:
Number used in an Open statement to open
a sequential file. It can be any number of an open file. Note that the number sign (#) preceding
filenumber is not optional.
Spc(n):
Name of the Basic function optionally used to insert n spaces into the printed output. Multiple use
is permitted.
Tab(n):
Name of the Basic function optionally used to tab to the nth column before printing expressionlist.
Multiple use is permitted.
expressionlist :
Numeric and/or string expressions to be written to the file.
{;|,}
Character that determines the position of the next character printed. A semicolon means the next
character is printed immediately after the last character; a comma means the next character is
printed at the start of the next print zone. Print zones begin every 14 columns. If neither character
is specified, the next character is printed on the next line.
If you omit expressionlist, the Print # statement prints a blank line in the file, but you must include
the comma. Because Print # writes an image of the data to the file, you must delimit the data so it is
printed correctly. If you use commas as delimiters, Print # also writes the blanks between print
fields to the file.
The Print # statement usually writes Variant data to a file the same way it writes any other data
type. However, there are some exceptions:
• If the data being written is a Variant of VarType 0 (Empty), Print # writes nothing to the file
for that data item.
• If the data being written is a Variant of VarType 1 (Null), Print # writes the literal #NULL# to
the file.
• If the data being written is a Variant of VarType 7 (Date), Print # writes the date to the file
using the Short Date format defined in the WIN.INI file. When either the date or the time
component is missing or zero, Print # writes only the part provided to the file.
The following example writes data to a test file.
Example :
'The following example writes data to a test file and reads it back.
Sub Main ()
Dim FileData, Msg, NL ' Declare variables.
NL = Chr(10) ' Define newline.
Open "TESTFILE" For Output As #1 ' Open to write file.
Print #2, "This is a test of the Print # statement."
Print #2 ' Print blank line to file.
Print #2, "Zone 1", "Zone 2" ' Print in two print zones.
Print #2, "With no space between" ; "." ' Print two strings together.
Close
Open "TESTFILE" For Input As #2 ' Open to read file.
The ReDim statement is used to size or resize a dynamic array that has already been declared using
the Dim statement with empty parentheses. You can use the ReDim statement to repeatedly change
the number of elements in an array but not to change the number of dimensions in an array or the
type of the elements in the array.
Using Preserve as a ‘keyword’, it will retain any existing data at the point where the re-dimension
occurs.
The Varname datatype holds the name of the array that is to be re-dimensioned
The subscript term refers to the array dimension
For example:
Example:
REM This is a statement only
' This is also a statement
rem this is also a statement
' This whole line is a comment
rem This whole line is a comment
REM This whole line is a comment
Rem This whole line is a comment
Right (stringexpression, n )
The parameter stringexpression is the string from which the rightmost characters are returned.
The parameter n is the number of characters that will be returned and must be a long integer.
Example:
' The example uses the Right function to return the first of two words
' input by the user.
Sub Main ' Start Main Routine
Dim LWord, Msg, RWord, SpcPos, UsrInp ' Declare variables.
Msg = "Enter two words separated by a space." ' Message String
' InputBox Syntax (prompt[,[title][,[default][,xpos,ypos]]])
UsrInp = InputBox(Msg,"User Input","Left Right") ' Get user input.
Print UsrInp ' Print user input
SpcPos = InStr(1, UsrInp, " ") ' Find space.
If (SpcPos) Then ' Does space exist
LWord = Left(UsrInp, SpcPos - 1) ' Get left word.
Print "LWord: "; LWord ' Print string and word
RWord = Right(UsrInp, Len(UsrInp) - SpcPos) ' Get right word.
Msg = "The first word you entered is " & LWord ' Generate Message
Msg = Msg & "." & " The second word is " ' Generate Message
Msg = "The first word you entered is <" & LWord & ">" ' Generate Message
Msg = Msg & RWord & "." ' Generate Message
Else ' Space doesn't exist
RmDir path
Example:
' This sample shows the function mkdir (Make Directory)
' and rmdir (Remove Directory)
Sub Main ' Start Main Routine
Dim sDirName As String ' Declare directory name
sDirName = "TempDir1" ' Assign Directory name
MkDir sDirName ' Make directory
MkDir "TempDir2" ' Make directory
MsgBox "Directories: t1 and t2 created. Press OK to remove them"
RmDir "TepmDir1" ' Remove directory
RmDir "TepmDir2" ' Remove directory
End Sub ' End of Routine
'End of XCM
Rnd (number)
Example:
' Rnd Function Example
' The example uses the Rnd function to simulate rolling a pair of dice by
' generating random values from 1 to 6. Each time this program is run,
Sub Main ' Start Main Routine
Dim lDice1 As Long ' Declare dice one
Dim lDice2 As Long ' Declare dice two
Dim vMsg ' Declare variables.
lDice1 = CInt(6 * Rnd() + 1) ' Generate first die value.
lDice2 = CInt(6 * Rnd() + 1) ' Generate second die value.
vMsg = "You rolled a " & lDice1 ' Generate message string
vMsg = vMsg & " and a " & lDice2 ' Generate message string
vMsg = vMsg & " for a total of " ' Generate message string
vMsg = vMsg & Str(lDice1 + lDice2) & "." ' Generate message string
MsgBox vMsg ' Display message string
End Sub ' End of Routine
' End of XCM
Second (number)
Returns an integer that is the second portion of the minute in the time
parameter.
Example:
' This example shows time function and the Format function to format values
' using both named and user-defined formats. For the date separator (/),
' time separator (:), and AM/ PM literal, the actual formatted output
' displayed by your system depends on the locale settings on which the code
' is running. When times and dates are displayed in the development
' environment, the short time and short date formats of the code locale
' are used. When displayed by running code, the short time and short date
' formats of the system locale are used, which may differ from the code
' locale. For this example, English/United States is assumed.
' sCurrentTime and sCurrentDate are displayed in the development environment using
' current system short time and short date settings.
Seek (filenumber)
The parameter filenumber is used in the open statement and must be a valid
numeric expression.
Seek returns a number that represents the byte position where the next operation is to take place.
The first byte in the file is at position 1.
The parameter filenumber is used in the open statement and must be a valid
numeric expression, the parameter position is the number that indicates
where the next read or write is to occur. In Cypress Enable Basic position
is the byte position relative to the beginning of the file.
Seek statement sets the position in a file for the next read or write
Executes one of the statement blocks in the case based on the test variable
Select Case testvar
Case var1
Statement Block
Case var2
Statement Block
Case Else
Statement Block
End Select
Related Topics: If...Then...Else
Example:
' This rather tedious test shows nested select statements and if uncommented,
' the exit for statement
Sub Main ' Start Main Routine
Dim lRepeat As Long ' Declare Select repeating variable
For lRepeat = 1 To 5 ' Step through 5 iterations
Print lRepeat ' Print current iteration
Select Case lRepeat ' Select current case
Case 2 ' Case two
Print "Outer Case Two" ' Case two string message
Case 3 ' Case three
Print "Outer Case Three" ' Case three string message
Exit For ' Exit loop
Case Else ' Must be something else.
Print "Outer Case Else:",lRepeat ' Other case message
End Select ' End selection procedure
Next lRepeat ' Next increment
Print "Done with For Loop" ' Display final message
End Sub ' End routine
' End of XCM
Sends one or more keystrokes to the active window as if they had been
entered at the keyboard
The SendKeys statement has two parameters. The first parameter keys is a
string and is sent to the active window. The second parameter wait is
optional and if omitted is assumed to be false. If wait is true the keystrokes
must be processed before control is returned to the calling procedure.
Example:
' This example uses Shell to leave the current application and run the
' Calculator program included with Microsoft Windows; it then
' uses the SendKeys statement to send keystrokes to add some numbers.
Sub Main ' Start Main Routine
Dim IRepeat As Long ' Declare repeating variable
Dim vDummy As Variant ' Declare dummy value
Example:
Sub Main
Dim visio As Object
Set visio = CreateObject( "visio.application" )
Dim draw As Object
Set draw = visio.Documents
draw.Open "c:\visio\drawings\Sample1.vsd"
MsgBox "Open docs: " & draw.Count
Dim page As Object
Set page = visio.ActivePage
Dim red As Object
Set red = page.DrawRectangle (1, 9, 7.5, 4.5)
red.FillStyle = "Red fill"
Dim cyan As Object
Set cyan = page.DrawOval (2.5, 8.5, 5.75, 5.25)
cyan.FillStyle = "Cyan fill"
Dim green As Object
Set green = page.DrawOval (1.5, 6.25, 2.5, 5.25)
green.FillStyle = "Green fill"
Dim DarkBlue As Object
Set DarkBlue = page.DrawOval (6, 8.75, 7, 7.75)
DarkBlue.FillStyle = "Blue dark fill"
visio.Quit
End Sub
10.2.101 SGN(Number)
The shell function has two parameters. The first one, app is the name of the
program to be executed. The name of the program in app must include a
.PIF, .COM, .BAT, or .EXE file extension or an error will occur. The
second argument, style is the number corresponding to the style of the
window . It is also optional and if omitted the program is opened
minimized with focus.
Window styles:
Normal with focus 1,5,9
Minimized with focus (default) 2
Maximized with focus 3
normal without focus 4,8
minimized without focus 6,7
Example:
' This example uses Shell to leave the current application and run the
' Calculator program included with Microsoft Windows; it then
' uses the SendKeys statement to send keystrokes to add some numbers.
Sub Main ' Start Main Routine
Dim IRepeat As Long ' Declare repeating variable
Sin (rad)
Example:
' Example of a sin function
Sub Main ' Start Main Routine
Dim vpi, vrad, vSinValue ' Declare variables
vpi = 4 * Atn(1) ' Calculate Pi
vrad = 90 * (vpi/180) ' Calculate Rads
vSinValue = Sin(vrad) ' Sin function
Print vSinValue ' Display Message
End Sub ' End routine
'End of XCM
Space[$] (number )
The parameter number can be any valid integer and determines the number of blank spaces.
Example:
' Example7 of space function which inserts a set number of spaces
Sub Main ' Start Main Routine
MsgBox "Hello " & "There" ' Display message
MsgBox "Hello" & Space(20) & "There"' Display Message with spaces
End Sub ' End routine
'End of XCM
Sqr(num)
The parameter num must be a valid number greater than or equal to zero.
Example:
' Example of square root function
Sub Route () ' Start subroutine route
Dim vMsg As Variant ' Declare messagebox variant
Dim lNumber As Long ' Declare user input number.
vMsg = "Enter a non-negative number." ' Message
lNumber = InputBox(vMsg) ' Return user input
If (lNumber < 0) Then ' Test response is positive
' Negative user input cannot be used therefore display message
vMsg = "Cannot determine the square root of a negative number."
Else ' User repsonse is positive
vMsg = "The square root of " & lNumber & " is "' Combine string and input
number
vMsg = vMsg & Sqr(lNumber) & "." ' Add squre root of input
End If ' End construct
MsgBox vMsg ' Display results
End Sub ' End subroutine Route
Static variable
Used to declare variables and allocate storage space. These variables will retain their value through
the program run
Example:
' This example shows how to use the static keyword to retain the value of
' the variable lRepeat in sub Joe. If Dim is used instead of Static then lRepeat
' is empty when printed on the second call as well as the first.
Sub Main ' Start Main routine
Dim lRepeat As Long ' Declare repeat as Long
For lRepeat = 1 To 2 ' Repeat twice
Joe 2 ' Call subroutine
Next lRepeat ' Next increment
End Sub ' End main routine
Stop
Example:
' This example shows the stop function by looping through one x iteration
' And all y and z iterations.
Sub Main ' Start Main Routine
Dim lRepeatx As Long ' Declare x repeat
Dim lRepeaty As Long ' Declare y repeat
Dim lRepeatz As Long ' Declare z repeat
For lRepeatx = 1 To 5 ' Loop x five times
For lRepeaty = 1 To 5 ' loop y five times
For lRepeatz = 1 To 5 ' Loop z five times
Print "Looping" ,lRepeatz,lRepeaty,lRepeatx ' Print z,y,x
Example:
' This is an example XCM showing string comparison
' The comparison StrComp evaluates the matching ASCII reference.
' For example "A" = ASCII 65 and "E" = 69
' Compare A with A returns a 0 value
' Compare A with E returns a minus one value
' Compare E with A returns a positive one value
Sub Main ' Start Main Routine
Dim sString1 As String ' Declare String one
Dim sString2 As String ' Declare String 2
Dim vCompare As Variant ' Declare comparison
sString1 = "ABCD": sString2 = "today" ' Define strings.
Print sString1, sString2 ' Display Result
vCompare = StrComp(sString1, sString1) ' Returns 0.
Print vCompare ' Display Result
vCompare = StrComp(sString1, sString2) ' Returns -1.
Print vCompare ' Display Result
vCompare = StrComp(sString2, sString1) ' Returns 1.
Print vCompare ' Display Result
End Sub
String is used to create a string that consists of a leading space that is used
for the sign. If the number is poistive there will be a space after the
quotation marks, and it the number is negative the string will be “-69”.
The conversion of a date type must begin with the date being 13.10.99, as
only a full stop decimal separator is recognised.
Related topics: Space Function, CStr
' Example for string function
Sub Main ' Start main Routine
Dim dMaxTruckProd As Double ' Declare Truck max productivity as
Double
Dim sMaxTruckProd As String ' Declare Truck max productivity as
String
dMaxTruckProd = -435.962 ' Max productivity for pit MANU
sMaxTruckProd = Str(dMaxTruckProd) ' String is "-435.962"
sMaxTruckProd = Str(Abs(dMaxTruckProd)) ' String is " 435.962"
sMaxTruckProd = Str(223) ' String is " 223"
End Sub ' End Subroutine
'End of XCM
When the optional argument list needs to be passed the format is as follows:
Example:
Sub Main
Dim sDST As String
sDST = "t1"
mkdir sDST
mkdir "t2"
End Sub
Tan(angle)
Example:
' This XCM Positions A Dialog Box On The Screen Of Set Height
' And Set Width. Within This Dialog Box Are Textboxes That
' Are Used For User Response. These Responses Can Be Used For
' Any Application, But In This Example They Are Displayed On The
' Screen To Confirm Entry.
Sub Main ' Start Main Routine
'------------------------------------------------------
' ## Dialog Properties Posx Posy Width Height Display Name
Begin Dialog DialogName1 60, 60, 160, 70, "ASC - Hello"
'------------------------------------------------------
' ## Position Text 5 In From Lefthand Side, 10 From Top,Width 35, Height 12.
Example:
' This XCM Positions A Dialog Box On The Screen Of Set Height
' And Set Width. Within This Dialog Box Are Textboxes That
' Are Used For User Response. These Responses Can Be Used For
' Any Application, But In This Example They Are Displayed On The
' Screen To Confirm Entry.
Sub Main ' Start Main Routine
'------------------------------------------------------
' ## Dialog Properties Posx Posy Width Height Display Name
Begin Dialog DialogName1 60, 60, 160, 70, "ASC - Hello"
'------------------------------------------------------
' ## Position Text 5 In From Lefthand Side, 10 From Top,Width 35, Height 12.
' Text To Insert = "Trucktype"
TEXT 5, 10, 35, 12, "Trucktype:"
'------------------------------------------------------
' ## Textbox
' Starting X Position, Starting Y Position, Width, Height, Default String
TEXTBOX 50, 10, 100, 12, .truckStr
' Assign Reply To String Variable Truckstr
'------------------------------------------------------
' Position Text 5 In From Lefthand Side, 24 From Top,Width 35, Height 12.
' Text To Insert = "Loader"
TEXT 5, 24, 35, 12, "Loader:"
'------------------------------------------------------
' Textbox Starting X Position, Starting Y Position, Width, Height, Default String
TEXTBOX 50, 24, 100, 12, .loaderStr
' Position A Checkbox 42 From Left,38 Down,
' Assign Reply To String Variable Loaderstr
'------------------------------------------------------
CHECKBOX 42, 38, 48, 12, "&Twopass", .checkInt
' Assign Reply To String Variable Checkint
'------------------------------------------------------
' Position OKButton.
OKBUTTON 42, 54, 40, 12
'------------------------------------------------------
End Dialog ' End of dialog
Dim Dlg1 As DialogName1 ' Declare Dlg1
Dialog Dlg1 ' Dialog function
'------------------------------------------------------
MsgBox Dlg1.truckStr ' Display Trucktype
MsgBox Dlg1.loaderStr ' Display Loader
MsgBox Dlg1.checkInt ' Checkbox yes = 1
End Sub ' End of Routine
'End of XCM
Example:
' This example shows time function and the Format function to format values
' using both named and user-defined formats. For the date separator (/),
' time separator (:), and AM/ PM literal, the actual formatted output
' displayed by your system depends on the locale settings on which the code
' is running. When times and dates are displayed in the development
' environment, the short time and short date formats of the code locale
' are used. When displayed by running code, the short time and short date
' formats of the system locale are used, which may differ from the code
' locale. For this example, English/United States is assumed.
' sCurrentTime and sCurrentDate are displayed in the development environment using
' current system short time and short date settings.
Sub Main ' Start Main Routine
Dim sCurrentTime As String ' Declare Current time
sCurrentTime = Time$(Now) ' Return Time XCM run
Print sCurrentTime ' Display current time HH:MM:SS
Dim sCurrentDate As String ' Declare Current date
sCurrentDate = Date() ' Return XCM date run
Print sCurrentDate ' Print Currentdate DD:MM:YY
' Could use input date for test in the following fashion
Dim sInput As Date ' Declare Input date
' Input box with Prompt Title Default value
sInput = InputBox("Enter Date","dd/mm/yyyy",(#29/05/1959#))
' This input date is not used any further - only and example
Dim sMyStr As String ' Declare MyString
MsgBox Now ' Display date & time now
MsgBox sCurrentTime ' Display Current time
MsgBox Second( sCurrentTime ) & " Seconds" ' Display seconds only
MsgBox Minute( sCurrentTime ) & " Minutes" ' Display minutes only
MsgBox Hour ( sCurrentTime ) & " Hours" ' Display Hours only
MsgBox Day ( sCurrentDate ) & " Days" ' Display Days only
MsgBox Month ( sCurrentDate ) & " Months" ' Display months only
MsgBox Year ( sCurrentDate ) & " Years" ' Display Years only
' Returns current system time in the system-defined long time format
MsgBox Format(Time, "Short Time") ' Display HH:MM
MsgBox Format(Time, "Long Time") ' Display HH:MM:SS
' Returns current system date in the system-defined long date format
MsgBox Format(Date, "Short Date") ' DD:MM:YY
MsgBox Format(Date, "Long Date") ' Dayof week,Date Month Year
MsgBox Format(sCurrentTime, "h:n:s") ' Returns eg "17:4:23"
MsgBox Format(sCurrentTime, "hh:nn:ss") ' Returns eg "05:04:23"
MsgBox Format(sCurrentDate, "dddd, mmm d yyyy")' Returns "dayofweek, Mon day
year"
' If format is not supplied, a string is returned
MsgBox Format(23) ' Returns "23"
' User-defined formats
MsgBox Format(5459.4, "##,##0.00") ' Returns "5,459.40"
MsgBox Format(334.9, "###0.00") ' Returns "334.90"
MsgBox Format(5, "0.00%") ' Returns "500.00%"
MsgBox Format("HELLO", "<") ' Returns "hello"
MsgBox Format("This is it", ">") ' Returns "THIS IS IT"
End Sub
'End of XCM
Timer
Timer Event is used to track elapsed time or can be display as a stopwatch in a dialog. The timers
value is the number of seconds from midnight.
Example:
Sub Main ' Start Main Routine
Dim dTStart As Double ' Declare start time
Dim dTEnd As Double ' Declare end time
Dim dTElapsed As Double ' Declare time elapsed
dTStart = Timer ' Assign Start Time
MsgBox "Starting Timer" ' Display message
dTEnd = Timer ' Assign End time
dTElapsed = dTEnd - dTStart' Calculate Time
Print dTElapsed ' Print time elapsed
End Sub ' End Routine
'End of XCM
Returns the time serial for the supplied parameters hour, minute, second.
Example:
' Time serial example
Sub Main ' Start Main Routine
Dim sMTime As Date ' Declare Date String
Dim lHours As Long ' Decalre hours AS integer
Dim lMinutes As Long ' Declare minutes as integer
Dim lSeconds As Long ' Declare seconds as integer
lHours = InputBox("Enter Hours","0 - 24",(23)) ' Return Hours from user input
lMinutes = InputBox("Enter minutes","0 - 60",(59))' Return Minutes from user
input
lSeconds = InputBox("Enter Seconds","0 - 60",(59))' Return Seconds from user
input
lHours = GetMin(23.99999999,lHours) ' Force Maximum Hours
lMinutes = GetMin(59.99999999,lMinutes) ' Force Maximum Minutes
lSeconds = GetMin(59.99999999,lSeconds) ' Force Maximum Seconds
sMTime = TimeSerial(lHours, lMinutes, lSeconds) ' Return Serial time
Print sMTime ' Display to screen
End Sub ' End of Routine
' End of XCM
TimeValue ( TimeString )
Midnight = TimeValue(“23:59:59”)
Example:
' Time value example
Sub Main ' Start Main Routine
Dim dMTime As Double ' Declare time variable as double
dMTime = TimeValue("12:25:27 PM") ' Return time value as double
Ltrim, Rtrim and Trim all Return a copy of a string with leading, trailing or
both leading and trailing spaces removed.
Example:
' This example uses the LTrim and RTrim functions to strip leading and
' trailing spaces, respectively, from a string variable. It
' uses the Trim function alone to strip both types of spaces.
' LCase and UCase are also shown in this example as well as the use
' of nested function calls
Sub Main ' Start Main routine
Dim sMyString As String ' Declare string variable
Dim sTrimString As String ' Declare trimstring variable
sMyString = " <-Trim-> " ' Assign string
sTrimString = LTrim(sMyString) ' TrimString = "<-Trim->".
MsgBox "|" & sTrimString & "|" ' Display Message
sTrimString = LCase(RTrim(sMyString)) ' TrimString = "<-trim->".
MsgBox "|" & sTrimString & "|" ' Display Message
sTrimString = LTrim(RTrim(sMyString)) ' TrimString = "<-Trim->".
MsgBox "|" & sTrimString & "|" ' Display Message
' Using the Trim function alone achieves the same result.
sTrimString = UCase(Trim(sMyString)) ' TrimString = "<-TRIM->".
MsgBox "|" & sTrimString & "|" ' Display Message
End Sub ' End of routine
'End of XCM
Part Description
Once you have declared a user-defined type using the Type statement, you can
declare a variable of that type anywhere in your script. Use Dim or Static to
declare a variable of a user-defined type. Line numbers and line labels aren't
allowed in Type...End Type blocks.
User-defined types are often used with data records because data records
frequently consist of a number of related elements of different data types. Arrays
cannot be an element of a user defined type in Enable.
Example:
' This sample shows some of the features of user defined types
Type type1
a As Integer
d As Double
s As String
End Type
Type type2
a As String
o As type1
End Type
Type type3
b As Integer
c As type2
End Type
Dim type2a As type2
Dim type2b As type2
Dim type1a As type1
Dim type3a as type3
Sub Form_Click ()
a = 5
type1a.a = 7472
type1a.d = 23.1415
type1a.s = "YES"
type2a.a = "43 - forty three"
type2a.o.s = "Yaba Daba Doo"
type3a.c.o.s = "COS"
type2b.a = "943 - nine hundred and forty three"
type2b.o.s = "Yogi"
MsgBox type1a.a
MsgBox type1a.d
MsgBox type1a.s
MsgBox type2a.a
MsgBox type2a.o.s
MsgBox type2b.a
MsgBox type2b.o.s
MsgBox type3a.c.o.s
MsgBox a
End Sub
Ubound(arrayname[,dimension])
Returns the value of the largest usable subscript for the specified dimension of an
array.
Example:
' This example demonstrates some of the features of arrays. The lower bound
' for an array is 0 unless it is specified or option base is set it as is
' done in this example.
Option Base 1
Sub Main ' Start Main Routine
Dim dArray(10) As Double ' Declare array as Double
Dim lRepeat As Long ' Declare repeating variable as long
MsgBox "LBound "&LBound(dArray) &"UBound: "&UBound(dArray)
For lRepeat = 1 To 3 ' Repeat 3 times
dArray(lRepeat) = 2 + lRepeat ' Add 2 to increment and store in array
Next lRepeat ' Next increment
Print dArray(1),dArray(2), dArray(3) ' Print array
End Sub ' End main routine
' End of XCM
Ucase (String )
Returns a copy of String is which all lowercase characters have been converted to
uppercase.
Example:
' This example uses the LTrim and RTrim functions to strip leading and
' trailing spaces, respectively, from a string variable. It
' uses the Trim function alone to strip both types of spaces.
' LCase and UCase are also shown in this example as well as the use
' of nested function calls
Sub Main ' Start Main routine
Dim sMyString As String ' Declare string variable
Dim sTrimString As String ' Declare trimstring variable
sMyString = " <-Trim-> " ' Assign string
10.2.122 Val
Val(string)
Example:
Sub Main ' Start Main Routine
Dim vMsg As Variant ' Declare message box
Dim dYourVal As Double ' Declare input value
dYourVal = Val(InputBox$("Enter a number")) ' Return value of input
vMsg = "The number you entered is: " & dYourVal' Message
MsgBox vMsg ' Display message
End Sub ' End Main Routine
'End of XCM
10.2.123 VarType
VarType(varname)
Empty 0
Null 1
Integer 2
Long 3
Single 4
Double 5
Currency 6 (not available at this time)
Date/Time 7 (mapped to a string )
String 8
Example:
Sub Main ' Start Main Routine
Dim lMAX As Long ' Declare maximum constant
Dim lRepeat As Long ' Declare repeating integer
Dim bExchange As Boolean ' Declare boolean
Dim sArray(8) As String ' Declare string array
lMAX = 8 ' Assign maximum constant
sArray(0) = "Empty " ' Assign String 0
sArray(1) = "Null " ' Assign String 1
sArray(2) = "Integer " ' Assign String 2
sArray(3) = "Long integer " ' Assign String 3
sArray(4) = "Single " ' Assign String 4
sArray(5) = "Double " ' Assign String 5
sArray(6) = "Currency " ' Assign String 6
sArray(7) = "Date/Time " ' Assign String 7
sArray(8) = "String " ' Assign String 8
bExchange = True ' Set exchange to true
While bExchange ' While true
bExchange = False ' Assign False
For lRepeat = 0 To lMAX ' Loop until lMAX
' Display Message from array showing variable type
MsgBox sArray(lRepeat)&" is Variable Type "&lRepeat
Next lRepeat ' Next increment
Wend ' End control structure
End Sub ' End routine
'End of XCM
Weekday(date,firstdayof week)
Returns an integer containing the whole number for the weekday it is representing.
Example:
Sub Main ' Start Main Routine
Dim lDayNumber As Long ' Declare daynumber
Dim sInput As Date ' Delcare Input date
' Input box with Prompt Title Default value
sInput = InputBox("Enter Date","dd/mm/yyyy",(#29/05/1959#))
' From the input date use the weekday function
lDayNumber = Weekday(sInput)
' Display Message Type Title
MsgBox lDayNumber,4096,"The Date Chosen is the Weekday"
End Sub ' End routine
'End of XCM
While condition
.
[StatementBlock]
.
Wend
While begins the while...Wend flow of control structure. Condition is any numeric
or expression that evaluates to true or false. If the condition is true the statements
are executed. The statements can be any number of valid Enable Basic statements.
Wend ends the While...Wend flow of control structure.
Example:
Sub Main ' Start Main Routine
Dim lMAX As Long ' Declare maximum constant
Dim lRepeat As Long ' Declare repeating integer
Dim bExchange As Boolean ' Declare boolean
Dim sArray(5) As String ' Declare string array
lMAX = 5 ' Assign maximum constant
sArray(1) = "Program" ' Assign String 1
With object
[STATEMENTS]
End With
The With statement allows you to perform a series of commands or statements on a particular
object without again referring to the name of that object. With statements can be nested by putting
one With block within another With block. You will need to fully specify any object in an inner
With block to any member of an object in an outer With block.
Example:
' This sample shows some of the features of user
' Defined types and the with statement
Type type1 ' Assign Type 1
a As Long ' Assign a as long
d As Double ' Assign d as Double
s As String ' Assign s as String
End Type ' End Type 1
Type type2 ' Assign Type 2
a As String ' Assign a as string
o As type1 ' Assign o as type 1
End Type ' End type 2
Dim type1a As type1 ' Declare type 1a as type 1
Dim type2a As type2 ' Declare type 2a as type 2
' This sample shows some of the features of user defined types and the with
' statement
Type type1
a As Integer
d As Double
s As String
End Type
Type type2
a As String
o As type1
End Type
Dim type1a As type1
Dim type2a As type2
Sub Main ()
With type1a
.a = 65
.d = 3.14
End With
With type2a
.a = "Hello, world"
With .o
.s = "Goodbye"
End With
End With
type1a.s = "YES"
MsgBox type1a.a
MsgBox type1a.d
MsgBox type1a.s
MsgBox type2a.a
MsgBox type2a.o.s
End Sub
Writes and formats data to a sequential file that must be opened in output or
append mode.
A comma-delimited list of the supplied parameters is written to the indicated file. If no parameters
are present, the new line character is all that will be written to the file.
Example:
Sub Main ' Start Main Routine
Dim sExcNums As String ' Declare excavator numbers
Dim sTrkNums As String ' Declare Truck numbers
Dim vEquipData As Variant ' Declare equipment data
Open "TESTFILE" For Output As #1 ' Open to write file.
sExcNums = InputBox ("Enter Excavator Numbers")
sTrkNums = InputBox ("Enter Haul Truck Numbers")
Write #1, "This is a test of the Write # statement."
Write #1,sExcNums, sTrkNums ' Write two user inputs.
Close #1 ' Close file 1.
Open "TESTFILE" For Input As #2 ' Open to read file.
Do While Not EOF(2) ' Control structure Do
Line Input #2, vEquipData ' Read a line of data.
Print vEquipData ' Construct message.
Loop ' Loop until control satisfied
Close #2 ' Close all open files.
MsgBox "Testing Print Statement" ' Display message.
Kill "TESTFILE" ' Remove file from disk.
End Sub ' End routine
'End of XCM
Year(serial# )
Example:
Sub Main ' Start Routine
Dim sStartDate As String ' Declare date
Dim lValue As Long ' Declare year variable
sStartDate = "11/11/04" ' Date value
lValue = Year(sStartDate) ' Year Function
Print "Production Start",lValue ' Print Year
End Sub ' End routine
'End of XCM
Activity
Used to over-ride the productive activity associated with the main database data field in the result.
Abort
DESCRIPTION
Stops the XCM processing after the current record has been processed.
Any commands that follow Abort will be processed for the current record. For this reason, it is
common to include the End command after Abort, to ensure that no further processing is performed.
ARGUMENTS
VALUES RETURNED
The Abort function returns a boolean data type. When used under normal circumstances in an XCM it
will always return a True value and it therefore need not be tested.
After Abort has been encountered in an XCM and when the processing of the current record is
complete, the following window will be displayed. The XCM will stop after this message.
EXAMPLES
(1) Stop the XCM if the data is not valid.
Sub Main
'Calculate the block width – Stop the XCM if it is less than 2 metres
M(mBlk_Width) = SafeDivide(M(mBlk_Vol), M(mBlk_Area))
If (M(mBlk_Width) < 2) Then
Abort("Block Width is Not Valid")
Print M(mBlk_Width)
End If
End Sub
RELATED FUNCTIONS
GetLastError, Stop, On Error.
AddDependencyToGroup
SetDependencyEx returns the Group Id for this OR Rule, use AddDependencyToGroup to add to this
group.
For Example: to make the rule B->A or B->C
Dim lGroupId As Long
lGroupId = SetDependencyEx(RecordNoB, RecordNoA, 0, 0, TRUE, “100% lag”)
call AddDependencyToGroup(lGroupId, RecordNoB, RecordNoC, 0, 0, “100% lag”)
CalendarHrs
Returns the accumulated calendar hours for all steps passed by the filter.
CalculateLineIntersection
Calculates whether two lines intersect and optionally at what point that intersection occurs. If
ExtendLines is true, the lines are extended to infinity for the calculation. This function will only work
in 2 dimensions. The values of Z for each of the vertices is ignored.
RELATED FUNCTIONS
SetVertex
Sub Main
' Test whether these lines cross
Dim Line1Start As Vertex
Dim Line1End As Vertex
Dim Line2Start As Vertex
Dim Line2End As Vertex
Dim Intersection As Vertex
SetVertex Line1Start, 0.0, 5.0, 0.0
SetVertex Line1End, 10.0, 5.0, 0.0
SetVertex Line2Start, 5.0, 0.0, 0.0
SetVertex Line2End, 5.0, 10.0, 0.0
CalculateLineIntersection Line1Start, Line1End, Line2Start, Line2End, Intersection
Print “Lines intersect at “ & Intersection.dX & “, “ & Intersection.dY
End Sub
ChangeProductionRate
ARGUMENTS
sResourceName The name of the resource that will have it’s production rate
changed
Example:
call ChangeProductionRate(“Ore”, 1, “100”)
ChangeRoster
This function is used to change a resource’s roster and roster exceptions during a schedule.
ARGUMENTS
sResourceName The name of the resource that will have it’s roster changed
REMARKS
If you do not specify a roster exception the resource will be set to have no roster exceptions to
Example:
call ChangeRoster(“Ore”, “FullTime”, “RosterException”)
ClearData
Sub ClearData(Starting Data Field Number As Integer, optional Ending Data Field
Number As Integer)
DESCRIPTION
Clears all data field values in the current record, from the starting data field number to the ending data
field number.
This subroutine can be used to clear any data field type. Note, Class and Record data field types are
text and they are set to a null string, ie. “”. All other data field types are numeric and they set to zero.
ARGUMENTS
Starting Data The starting data field number is passed to the subroutine by value
Field Number as an integer data type. It may be either a number or a full row
code, and represents the first data field number that is to be
cleared.
It is possible to clear all child data fields that fall within an upper
level data field using this argument alone. This is done by
specifying an upper level data field (using either the number or
code) for the starting data field number, and by not specifying an
ending data field number.
For example, ClearData(mROM_Wst) will clear all child data
fields of the field mROM_Wst, ie. all data fields whose full row
code begins with mROM_Wst.
To clear the field mROM_Wst only, an ending data field number
would have to be specified, ie. ClearData(mROM_Wst,
mROM_Wst).
Ending Data This argument is optional. The ending data field number is passed
Field Number to the subroutine by value as an integer data type. It may be
either a number or a full row code, and represents the last data
field number that is to be cleared.
If the ending data field number is not supplied, then only the
starting data field number and its child data fields will be cleared.
VALUES RETURNED
ClearData is a subroutine, so it does not return any values.
EXAMPLES
The examples below relate to the data fields listed in the table. The same data fields are cleared by
both XCMs and they are marked in the table.
RELATED FUNCTIONS
DbWriteValue, SetClass, SetNote
ClearGlobalObject
DESCRIPTION
Removes the sepecified global object from the internal store.
ARGUMENTS
sObjectName If specified, the name of the object to clear; otherwise, all objects
will be cleared.
RELATED FUNCTIONS
ClearGlobalObject, GetGlobalArray, GetGlobalObject, SetGlobalArray, SetGlobalObject
ClearInputPath
DESCRIPTION
Clears the specified range of steps from the input path. The function returns the number of steps
remaining in the input path, after the steps have been cleared.
The steps to be cleared are defined by their step number. The function clears all steps from the first
step specified to the last step specified, inclusive.
It should be remembered that multiple resources in different scenarios can make use of the same input
path, so be careful when editing them.
ARGUMENTS
Input Path Name The input path from which the steps are to be cleared is defined by
the input path name. It is passed to the function by value as a
string data type.
The input path that is attached to a particular resource and scenario
can be found using the function GetInputPathName.
First Step To The first step to clear in the specified input path is identified by its
Clear step number. It is passed to the function by value as a long data
type.
The first step to clear is an optional argument. If it is not passed to
the function, then it is assumed to be step number one.
If the first step to clear is set to a value less than one, then it is
assumed to be step number one. If the first step to clear is greater
than the last step in the input path, then no records will be deleted.
Last Step To The last step to clear in the specified input path is identified by its
Clear step number. It is passed to the function by value as a long data
type.
The last step to clear is an optional argument. If it is not passed to
the function, then it is assumed to be the last step number in the
input path. If the first step to clear is not passed to the function,
then the last step to clear cannot be passed to the function either.
If the last step to clear is set to a value greater than the last step
number in the input path, then it is assumed to be the last step
number in the input path.
VALUES RETURNED
This function returns the number of steps that are remaining in the input path, after the specified steps
have been cleared. The number of steps is returned as a long data type.
If the entire input path is cleared, then the function will return a value of zero.
If the specified input path does not exist, the function will return a value of –1.
A range of values is returned if the step numbers passed to the function are invalid.
• If the first step to clear is less than one, then it is assumed to be step number one.
• If the first step to clear is not passed to the function, then it is assumed to be step number one.
• If the first step to clear is greater than the number of steps in the input path, then no steps will be
cleared and the function will return a value of –1.
• If the first step to clear is greater than the last step to clear, then the function will return a value of
–1 and no steps will be cleared from the input path.
• If the last step to clear is greater than the number of steps in the input path, then it is assumed to be
the last step in the input path.
• If the last step to clear is not passed to the function, then it is assumed to be the last step in the
input path.
EXAMPLES
(1) Clear a range of steps in an input path.
Sub Main
Const sSCENARIO = "6 Monthly Schedule"
Const sRESOURCE = "30cu.m HydExc"
Dim sInputPathName As String
Dim lRemSteps As Long
'Clear from Step 5 to 10 in the input path.
sInputPathName = GetInputPathName(sSCENARIO, sRESOURCE)
lRemSteps = ClearInputPath(sInputPathName, 5, 10)
Print "The number of steps remaining in the input path is " & lRemSteps
End Sub
(2) Clear all steps that have a specific activity, from an input path.
Sub Main
Const sACTIVITY = "Coal Mining"
Const sINPUTPATH = "Coal and Waste Shovel Path"
Dim lRemSteps As Long
Dim lActNum As Long
Dim lStep As Long
Dim ThisStep As InputPathStep
'Loop through the input path from the last step to the first.
lRemSteps = GetInputPathNoOfSteps(sINPUTPATH)
lActNum = GetActivityNum(sACTIVITY)
For lStep = lRemSteps To 1 Step -1
Call GetInputStep(sINPUTPATH, lStep, ThisStep)
If (ThisStep.Activity = lActNum) Then
lRemSteps = ClearInputPath(sINPUTPATH, lStep, lStep)
End If
Next lStep
End Sub
RELATED FUNCTIONS
ClearGlobalObject, GetGlobalArray, GetGlobalObject, SetGlobalArray, SetGlobalObject
GetInputPathName, GetInputPathNoOfSteps, GetInputStep, InsertIntoInputPath
ClearUserFlag
Clears the User Flag (either 1 or 2) for the give Record Activity combination. If the resource name is
not specified or an empty string, the current resource is used.
VALUES RETURNED
Returns false if the combination is not in the Available Block List.
REMARKS
This function is available only in the User Processing Scripts.
RELATED FUNCTIONS
SetUserFlag
CompletedTask
DESCRIPTION
Filters the report writer sources to pass steps which were completed in the current reporting period.
Returns true if the current block has a Remaining percentage of 0 at the end of the step; otherwise,
false. Also can be used in the result to return a count of how many tasks were completed in the period.
ClosingDumpCapacity
DESCRIPTION
Returns the remaining capacity at the end of the time period, for the specified dump database capacity
data field, for all steps passed by the filter.
ClosingInv
DESCRIPTION
Returns the accumulated inventory at the end of the time period, for the specified main database data
field, for all steps passed by the filter.
ClosingInvSP
ClosingInvSP
DESCRIPTION
Returns the accumulated inventory at the end of the time period, for the specified stockpile database
data field, for all steps passed by the filter.
CreateRecord
DESCRIPTION
This function allows you to add records to the current database using the record names and pil numbers
at each level. The function returns the record number for the lowest level record that is created.
ARGUMENTS
Level 1 Name The Level 1 Name represents the record name at level 1 for the
new record. It is passed by value as a string data type. This
argument is not optional.
Level 1 Pil The Level 1 Pil represents the Pil number at level 1 for the new
record. It is passed by value as a long data type. This argument
is not optional.
If this Level 1 record does not exist, then it will be created by this
function.
Level 2 Name The Level 2 Name represents the record name at level 2 for the
new record. It is passed by value as a string data type. This
argument is optional.
Level 2 Pil The Level 2 Pil represents the Pil number at level 2 for the
required record. It is passed by value as a long data type. This
argument is optional.
If this Level 2 record does not exist, then it will be created by this
function.
If the Level 2 Name argument is included in the function, then the
Level 2 Pil must also be included.
Level 3 Name etc The remaining Level n Name arguments represent the record
name at level n for the required record. They are passed by value
as string data types. These arguments are optional and they can
only be specified if the preceding argument has been included.
Level 3 Pil etc The remaining Level n Pil arguments represent the Pil number at
level n for the required record. They are passed by value as long
data types. These arguments are optional and they can only be
specified if the preceding argument has been included.
If the Level n record does not exist, then it will be created by this
function.
If the Level n Name argument is included in the function, then the
Level n Pil must also be included.
If you want the record at level n to use the pil number as the record name, then define the record name
as a null value, ie. “”.
Similarly, if you want the record at level n to use the next available pil number at that level, then the pil
number should be defined as –1. If records exist at pil numbers 1, 5, and 8, then the next available pil
number is considered to be number 9.
If you have a Position Table defined for one of your levels, this function will honour the Position
Table using the two rules defined above. If the function requests that a new record be added to the
level using the Position Table, that record will be added to the database, but it will not be added to the
Position Table. It is recommended that you add the records to the Position Table manually so that your
database still honours the Position Table.
Note that this function can be used to create records that are not at the lowest level of the database.
VALUES RETURNED
The function returns the record number for the lowest level record that is created. It is returned as a
long data type. If upper level records have to be created in the process, their record numbers are not
returned by the function.
If the function is unable to create the new record, then it will return a value of –1, but the XCM will not
abort. Reasons why the record cannot be created include:
• The specified record already exists.
• A record with the same name but a different pil number already exists at one of the levels.
This function cannot be used to change a record name. If a record already exists at the given pil
number for level n, but that record’s name is different to the level n name specified in the function, then
the name specified in the function will be ignored and the function will continue.
The CreateRecord function cannot be used within user processing scripts.
EXAMPLES
(1) Add a record to a database.
Sub Main
Dim lNewRec As Long
'Add HLT panel, DV05 drive, block 8.
lNewRec = CreateRecord("HLT", 7, "DV05", 5, "8", 8)
'Confirm that the record has been created successfully.
If (lNewRec <= 0) Then Print "Record Creation Failed"
End Sub
RELATED FUNCTIONS
SetRecName, GoRec, GetRecName, DbWriteValue, RemoveRecord
CreateRecordDB
DESCRIPTION
This function allows you to add records to the specified database using the record names and pil
numbers at each level. The function returns the record number for the lowest level record that is
created.
ARGUMENTS
Level 1 Name The Level 1 Name represents the record name at level 1 for the
new record. It is passed by value as a string data type. This
argument is not optional.
Level 1 Pil The Level 1 Pil represents the Pil number at level 1 for the new
record. It is passed by value as a long data type. This argument
is not optional.
If this Level 1 record does not exist, then it will be created by this
function.
Level 2 Name The Level 2 Name represents the record name at level 2 for the
new record. It is passed by value as a string data type. This
argument is optional.
Level 2 Pil The Level 2 Pil represents the Pil number at level 2 for the
required record. It is passed by value as a long data type. This
argument is optional.
If this Level 2 record does not exist, then it will be created by this
function.
If the Level 2 Name argument is included in the function, then the
Level 2 Pil must also be included.
Level 3 Name etc The remaining Level n Name arguments represent the record
name at level n for the required record. They are passed by value
as string data types. These arguments are optional and they can
Level 3 Pil etc The remaining Level n Pil arguments represent the Pil number at
level n for the required record. They are passed by value as long
data types. These arguments are optional and they can only be
specified if the preceding argument has been included.
If the Level n record does not exist, then it will be created by this
function.
If the Level n Name argument is included in the function, then the
Level n Pil must also be included.
If you want the record at level n to use the pil number as the record name, then define the record name
as a null value, ie. “”.
Similarly, if you want the record at level n to use the next available pil number at that level, then the pil
number should be defined as –1. If records exist at pil numbers 1, 5, and 8, then the next available pil
number is considered to be number 9.
If you have a Position Table defined for one of your levels, this function will honour the Position
Table using the two rules defined above. If the function requests that a new record be added to the
level using the Position Table, that record will be added to the database, but it will not be added to the
Position Table. It is recommended that you add the records to the Position Table manually so that your
database still honours the Position Table.
Note that this function can be used to create records that are not at the lowest level of the database.
VALUES RETURNED
The function returns the record number for the lowest level record that is created. It is returned as a
long data type. If upper level records have to be created in the process, their record numbers are not
returned by the function.
If the function is unable to create the new record, then it will return a value of –1, but the XCM will not
abort. Reasons why the record cannot be created include:
• The specified record already exists.
• A record with the same name but a different pil number already exists at one of the levels.
This function cannot be used to change a record name. If a record already exists at the given pil
number for level n, but that record’s name is different to the level n name specified in the function, then
the name specified in the function will be ignored and the function will continue.
The CreateRecordDB function cannot be used within user processing scripts.
RELATED FUNCTIONS
SetRecName, GoRec, GetRecName, DbWriteValue, RemoveRecord
CreateRecordEx
Name As String, optional Level 4 Pil As Long, optional Level 5 Name As String, optional
Level 5 Pil As Long, optional Level 6 Name As String, optional Level 6 Pil As Long,
optional Level 7 Name As String, optional Level 7 Pil As Long, optional Level 8 Name
As String, optional Level 8 Pil As Long, optional Level 9 Name As String, optional Level
9 Pil As Long, optional Level 10 Name As String, optional Level 10 Pil As Long) As Long
DESCRIPTION
This function allows you to add records to the current database using the record names and pil numbers
at each level. The function returns the record number for the lowest level record that is created.
ARGUMENTS
Level 0 Name The Level 0 Name represents the record name at level 0 for the
new record. It is passed by value as a string data type. This
argument is not optional.
Level 0 Pil The Level 0 Pil represents the Pil number at level 0 for the new
record. It is passed by value as a long data type. This argument
is not optional.
If this Level 0 record does not exist, then it will be created by this
function.
Level 1 Name The Level 1 Name represents the record name at level 1 for the
new record. It is passed by value as a string data type. This
argument is not optional.
Level 1 Pil The Level 1 Pil represents the Pil number at level 1 for the new
record. It is passed by value as a long data type. This argument
is not optional.
If this Level 1 record does not exist, then it will be created by this
function.
Level 2 Name The Level 2 Name represents the record name at level 2 for the
new record. It is passed by value as a string data type. This
argument is optional.
Level 2 Pil The Level 2 Pil represents the Pil number at level 2 for the
required record. It is passed by value as a long data type. This
argument is optional.
If this Level 2 record does not exist, then it will be created by this
function.
If the Level 2 Name argument is included in the function, then the
Level 2 Pil must also be included.
Level 3 Name etc The remaining Level n Name arguments represent the record
name at level n for the required record. They are passed by value
as string data types. These arguments are optional and they can
only be specified if the preceding argument has been included.
Level 3 Pil etc The remaining Level n Pil arguments represent the Pil number at
level n for the required record. They are passed by value as long
data types. These arguments are optional and they can only be
specified if the preceding argument has been included.
If the Level n record does not exist, then it will be created by this
function.
If the Level n Name argument is included in the function, then the
Level n Pil must also be included.
If you want the record at level n to use the pil number as the record name, then define the record name
as a null value, ie. “”.
Similarly, if you want the record at level n to use the next available pil number at that level, then the pil
number should be defined as –1. If records exist at pil numbers 1, 5, and 8, then the next available pil
number is considered to be number 9.
If you have a Position Table defined for one of your levels, this function will honour the Position
Table using the two rules defined above. If the function requests that a new record be added to the
level using the Position Table, that record will be added to the database, but it will not be added to the
Position Table. It is recommended that you add the records to the Position Table manually so that your
database still honours the Position Table.
Note that this function can be used to create records that are not at the lowest level of the database.
VALUES RETURNED
The function returns the record number for the lowest level record that is created. It is returned as a
long data type. If upper level records have to be created in the process, their record numbers are not
returned by the function.
If the function is unable to create the new record, then it will return a value of –1, but the XCM will not
abort. Reasons why the record cannot be created include:
• The specified record already exists.
• A record with the same name but a different pil number already exists at one of the levels.
This function cannot be used to change a record name. If a record already exists at the given pil
number for level n, but that record’s name is different to the level n name specified in the function, then
the name specified in the function will be ignored and the function will continue.
The CreateRecord function cannot be used within user processing scripts.
EXAMPLES
(1) Add a record to a database.
Sub Main
Dim lNewRec As Long
'Add HLT panel, DV05 drive, block 8.
lNewRec = CreateRecordEx("Deposit", 0, "HLT", 7, "DV05", 5, "8", 8)
'Confirm that the record has been created successfully.
If (lNewRec <= 0) Then Print "Record Creation Failed"
End Sub
RELATED FUNCTIONS
SetRecName, GoRec, GetRecName, DbWriteValue, RemoveRecord
CSum Function
A new XCM function for use in the Result section of Report Writer allowing the user to sum report
fields. For example, CSum(1,4) would return the sum of the values in the Report in rows 1 through to
4.
CurveValue
DESCRIPTION
Looks up a value from a curve. The curves are stored within an XPAC project and they can be two or
three dimensional curves.
When creating or editing a curve in XPAC, the dimensions of the curve are listed across the page and
the points are listed down the page. For the dimensions, the x axis is in the first column, the y axis is in
the second column and then, if applicable, the z axis is in the third column.
ARGUMENTS
Curve Name The curve name is the internal XPAC name for the curve. The full
list of curves that are available in your model can be found by
accessing View | Curves from the XPAC menu.
The curve name is passed by value as a string data type.
x Value For both two and three dimensional curves, the x value is the value
that is looked up on the x axis of the curve. It is passed by value as
a double data type.
VALUES RETURNED
The function returns a value from the curve as a double data type.
For a two dimensional curve, the x value is supplied to the function and the y value is returned by the
function. The y value is obtained through linear interpolation of the data points. The Curve Mode
argument can be used to control how the data is extrapolated (see above).
For a three dimensional curve, the x and y values are supplied to the function and the z value is
returned by the function. The z value is obtained through interpolation of the data points using inverse
distance weighting to the fourth power. It should be noted that this method is very reliable until the x
and y values get close to the data limits. For this reason you should be careful to ensure that your data
covers all expected x and y values. It may also be worth applying some logic to report any x and y
values that are outside ore near the data limits.
If the specified curve does not exist in the current XPAC project, the XCM will be aborted.
EXAMPLES
(1) Read a value from a two dimensional curve.
Sub Main
Dim sCurveName As String
'Read the specific energy from the Ash-Energy curve for the seam
sCurveName = "Seam " & sSeamName & " Ash-Energy Curve"
M(mROM_Cl_SE) = CurveValue(sCurveName, M(mROM_Cl_Ash), True)
End Sub
RELATED FUNCTIONS
Curve3DValue.
Curve3DValue
DESCRIPTION
Looks up a value from a 3D curve stored within an XPAC project.
When creating or editing a curve in XPAC, the dimensions of the curve are listed across the page and
the points are listed down the page. For the dimensions, the x axis is in the first column, the y axis is in
the second column and the z axis is in the third column.
ARGUMENTS
Curve Name The curve name is the internal XPAC name for the curve. The
associated curve must be a 3D curve, otherwise a run-time error will
occur.
The full list of curves that are available in your model can be found
by accessing View | Curves from the XPAC menu.
The curve name is passed by value as a string data type.
x Value The x value is the value that is looked up on the x axis of the curve.
It is passed by value as a double data type.
y Value The y value is the value that is looked up on the y axis of the curve.
It is passed by value as a double data type.
VALUES RETURNED
The function returns a value from the curve as a double data type.
The x and y values are supplied to the function and the z value is returned by the function. The z value
is obtained by treating the 3D Curve as a series of nested 2D curves, one for each of the x values. It
finds the curves (or curve) nearest the given x value and then looks up the given y value to return z
values. It then does a linear interpolation (or extrapolation) between the resultant z values to arrive at
the actual z value. This method closely approximates the technique used by people when estimating
values from multiple curves. It is also able to extrapolate values beyond the data limits provided care is
taken.
(This method differs from the 3D Curve evaluation obtained from the CurveValue function. The
CurveValue function when used with a 3D curves uses an inverse distance weighting to the fourth
power interpolation technique which doesn’t always match user’s expectations. It should be noted that
this method is very unreliable when the x and y values get close (or beyond) the data limits.)
Curve3DValue should NOT be used if the x values of the curve data are all different i.e. this function
requires at least two (2) data points for each x value in order for the interpolation/extrapolation to work
properly. If this is not the case then probably should use the old CurveValue function instead.
If the specified curve does not exist in the current XPAC project, or it is not a 3D curve, then the XCM
will be aborted.
EXAMPLES
(1) Read a value from a three dimensional curve.
Sub Main
Dim sCurve As String
'Read the waste truck productivity, given the Flat & Ramp haul distances
sCurve = "Waste Truck Productivity - " & GetClass(mTrk_Name)
M(mEQP_Wst_Prod) = Curve3DValue(sCurve, M(mEQP_WstFlat), M(mEQP_WstRamp))
End Sub
RELATED FUNCTIONS
CurveValue
DbReadName
DESCRIPTION
Returns the record name for the record number in the specified database. The record name is the name
of the record at a single level of the database, as opposed to the path name which uniquely identifies the
record. For example, for a record with a path name of East\P06\7\Ramp9, the record name is Ramp9.
ARGUMENTS
Database Name The database name is used to look for the specified record
number. It is passed by reference as a variant data type.
The database name may be provided explicitly as a string in double
quotes. For example “Main”, “5 Year Calendar”, “Default
Parameters”, “Equipment Hours”, etc.
Alternatively, the database name may be one of the following options.
Note that these options should not be in quotes.
Options Description
ACTIVE_MAIN The main database.
ACTIVE_CALENDAR The active calendar database.
ACTIVE_RESULTS The active results database.
Record Number The record number is used to identify the record whose name is
returned by this function. It is passed by value as a long data type.
Note that the record pointers, such as NXT, UP, etc, cannot be
used in this argument.
VALUES RETURNED
This function returns the record name for the specified record as a string data type.
If the record number does not exist in the specified database, then the function will return an empty
string. The XCM will not abort in this situation.
If the database name does not exist, the following message will be displayed during compilation and
the XCM will not be processed.
EXAMPLES
(1) Use the record name to accumulate data from the Main database.
'Declare a script variable to accumulate ramp volumes.
Dim lCumRampVol As Long
Sub Main
Dim lRecNum As Long
lRecNum = GetRecNum(CURRENT)
RELATED FUNCTIONS
GetRecName, GetRecNameAtLevel, GetPilFromPositionName
DbReadValue
DESCRIPTION
Read a value from a data field in a record in the specified database. The data field that is read may
have any field type, ie. Additive, Classified, Note, etc. If the main database is set to a period, the value
will be read from that period. Use ‘ReadBaseValue’ to always read base values.
ARGUMENTS
Database Name The database name is used to look for the specified record
number. It is passed by reference as a variant data type.
The database name may be provided explicitly as a string in
double quotes. For example “Main”, “5 Year Calendar”, “Default
Parameters”, “Equipment Hours”, etc.
Alternatively, the database name may be one of the following
options. Note that these options should not be in quotes.
Options Description
ACTIVE_MAIN The main database.
ACTIVE_CALENDAR The active calendar database.
ACTIVE_RESULTS The active results database.
Record Number The record number is used to identify the record whose value is
returned by this function. It is passed by value as a long data
type.
Note that the record pointers, such as NXT, UP, etc, cannot be
used in this argument.
Data Field Number The value to read in the database is identified by its data field
number. It is passed by value as a long data type.
In general, the full row codes cannot be used in this argument, as
they are only recognised for the database over which the XCM is
being run. However, the function GetRowNumFromCode can
be used to get the data field number, given the full row code and
the database name.
VALUES RETURNED
This function returns a variant data type. The type of return value is dependent on the field type of the
data field.
Additive, Weight Average, If the data field is one of these numeric field types,
Average, Min, Max, Difference, then the function will return a double data type.
Ratio, Product and Sum
Classified and Note If the data field is a string field type, then the
function will return a string data type.
Date (Min) and Date (Max) If the data field is a date field type, then the
function will return a date or a double data type.
EXAMPLES
(1) Read a value from a Calendar database.
Sub Main
'Print the start date for the first calendar year.
Dim tStartDate As Date
tStartDate = DbReadValue("Long Term Calendar", 2, 1)
Print tStartDate
End Sub
Else
M(mIS_Ore_RD) = M(mIMP_Ore_RD)
End If
End Sub
RELATED FUNCTIONS
DbReadName, DbWriteValue
DbWriteValue
DESCRIPTION
Writes a value to the specified data field, record and database. Values may be written to any field type.
If the main database is set to a period, the value will be written to that period. Use ‘WriteBaseValue’ to
always write base values.
ARGUMENTS
Database Name This is the name of the database into which the value is written.
It is passed by reference as a variant data type.
The database name may be provided explicitly as a string in double
quotes. For example “Main”, “5 Year Calendar”, “Default
Parameters”, “Equipment Hours”, etc.
Alternatively, the database name may be one of the following
options. Note that these options should not be in quotes.
Options Description
ACTIVE_MAIN The main database.
ACTIVE_CALENDAR The active calendar database.
ACTIVE_RESULTS The active results database.
Record Number The record number is used to identify the record into which the
value is written. It is passed by value as a long data type.
It may be specified as a number or it may be obtained using other
XCM functions such as GetRecNum. Note that the record
pointers, such as NXT, UP, etc, cannot be used in this argument.
Data Field The value to write in the database is identified by its data field
Number number. It is passed by value as a long data type.
In general, the full row codes cannot be used in this argument, as
they are only recognised for the database over which the XCM is
being run. However, the function GetRowNumFromCode can be
used to get the data field number, given the full row code and the
database name.
Don’t Prompt This argument is only relevant when writing a value to a classified
data field. If the specified data field is any other field type, then
this argument will be ignored. It is an optional argument and it is
passed by value as a boolean data type.
If it is set to True, then you will not receive a prompt when new
classifications are encountered, asking whether you want to create
that new classification.
If it is set to False, then you will receive a prompt when new
classifications are encountered, asking whether you want to create
that new classification.
If the argument is missing and the data field type is a classified
field, then the function will behave as if the argument were set to
False.
VALUES RETURNED
DbWriteValue is a subroutine so it does not return any values.
EXAMPLES
(1) Write a classification to a parameters database.
Sub Main
Dim lParamRec As Long
Dim lParamFld As Long
Dim sTpslClass As Long
'For the top bench in each block, write the topsoil classification
'back to a parameters database
If (IsFirst()) Then
Const sPARAMDB = "Surface Preparation"
lParamRec = GetRecFromPilDB(sPARAMDB, lPitNum, lStripNum, lBlockNum)
lParamFld = GetRowNumFromCode(sPARAMDB, "pSurf_Tpsl_Class")
sTpslClass = GetClass(mMin_Tpsl_Class)
Call DbWriteValue(sPARAMDB, lParamRec, lParamFld, sTpslClass, True)
End If
End Sub
Call GoRec(UP)
dBenchVol = M(mBlk_Tot_Vol)
Call GoRec(HOME)
End If
'Write the total bench volume into the first block on the bench
Call DbWriteValue("Main", lFirstBlockInBench, mBlk_Tot_Vol, dBenchVol)
End Sub
RELATED FUNCTIONS
DbReadValue, DbReadName, GetRecNum, GetRowCodeFromNum
DegToRad
DESCRIPTION
Returns the number of radians in the specified number of degrees.
This function is useful when using the Sin, Cos or Tan functions, as they require the angle to be input
in radians.
ARGUMENTS
Degrees The degrees are passed into the function by value as a double data type.
VALUES RETURNED
The function returns the number of radians in the specified degrees. The relationship between degrees
and radians is as follows.
EXAMPLES
(1) Convert an angle in degrees to radians for use in the Tan function.
Sub Main
Dim dBatterRad As Double
Dim dBatterWdth As Double
Const dBATTERDEG = 50
'Calculate the volume in a batter, given the height and batter angle
dBatterRad = DegToRad(dBATTERDEG)
dBatterWdth = SafeDivide(M(mBlk_Thk), Tan(dBatterRad))
M(mBatt_Vol) = M(mBlk_Thk) * dBatterWdth * M(mBlk_Lgth) / 2
End Sub
RELATED FUNCTIONS
RadToDeg, Sin, Cos, Tan.
DeletePolygon
Note – This function has been superseded by the SavePolygon function.
Delete all the vertices for the given polygon. If RecNum is equal to 0, CURRENT or is not given then
the polygon associated with the current record in the main database will be assumed. If Activity is
equal to 0, DEFAULT_ACTIVITY or is not given then the default activity will be assumed.
Otherwise the polygon associated with the given activity number will be assumed. PolygonIndex is the
1-based index of the polygon to delete.
Returns true if successfully deleted the vertex. Returns false on error.
Destination
This function can be used in the Filter part of the report writer. This function may be used to check
whether the currently mined blocks' destination is a stockpile. This function filters blocks whose
destination name is equal to the passed string.
Export
Function Export(File Name as String, Collection Type as String, optional Item Name As
String) As Boolean
DESCRIPTION
Exports the specified item or all items within the specified Collection Type (eg. Curves, Ranges,
Rosters, etc) to the specified File Name. All properties for that Item(s) will be exported.
ARGUMENTS
File Name This argument represents the name of the file into which the
specified Item and Collection Type will be exported. It is passed
by value as a string data type.
The file name must have an extension of “.tpl”.
It is recommended that an absolute path be specified as part of the
file name, to ensure the file is saved in an appropriate place.
If a path is not supplied as part of the file name, then the file will
be saved in the ‘current’ directory which will vary according to the
last directory that was accessed within XPAC.
Collection Type This argument represents the name of the Collection that you wish
to Export from the current XPAC Model. It is passed by value as
a string data type.
If the Collection Type is an empty string, then all Collection Types
that are present in the current model will be exported.
It may be set to any of the Collection Type names listed in the
following table.
Note that the Collection Type Names are Case Sensitive and
should be entered in exactly the same format as they appear
below.
Item Name This argument represents the name of the Item in the specified
Collection Type that will be exported. It is passed by value as a
string data type.
The Item Name is an optional argument. If it is not included in
the function then All items for the specified Collection Type will
be Exported.
VALUES RETURNED
The function returns a boolean data type which indicates whether the data was exported successfully.
If the specified Item or all Items in the Collection Type are exported successfully to the file, then the
function will return a True value.
If the specified path name for the file does not already exist, then the following message will be
displayed and the data will not be exported.
If the specified file already exists, then it will be over-written if the export process is successful.
If the specified File Name does not contain the extension “.tpl”, then the function will return a False
value and the data will not be exported.
If there are none of the specified Collection Type in the file, then the function will return a True value.
If the Collection Type name is invalid, then the function will return a False value.
If all Collection Types are exported from one model, they can be imported into another (blank) model
to almost recreate the original model.
EXAMPLES
(1) Import the Database Ranges and Fields Templates from the 5 Yr Plan XPAC Model.
Sub Main
Dim bImported As Boolean
'Import the Database Ranges from the 5 Yr Plan XPAC Model
bImported = Import("C:\5YrPlan\Ranges&Fields.tpl", "Ranges")
If (Not(bImported)) Then Print "Ranges Not Imported Successfully."
'Import the Fields Templates from the 5 Yr Plan XPAC Model
bImported = Import("C:\5YrPlan\Ranges&Fields.tpl", "Field Selections")
If (Not(bImported)) Then Print "Fields Not Imported Successfully."
End Sub
(2) Import all data from the Life of Mine XPAC Model.
Sub Main
Dim bSuccessful As Boolean
'Import all data types that have been exported from the LOM Model
bSuccessful = Import("C:\Black Hill Mine\Life of Mine Model.tpl", "")
If (Not(bSuccessful)) Then Print "Failure to Import Data - check File location."
End Sub
RELATED FUNCTIONS
Import
FindDestinationInABL
The Function returns true if the record activity combination is in the available destination block list,
See GetFirstABLDestination for a list of the return values.
ARGUMENTS
iFlags An integer representing the current state of the flags for this item
VALUES RETURNED
Returns true if the given record activity combination exists in the Available Destination Block List
REMARKS
This function is available only in the User Processing Scripts.
RELATED FUNCTIONS
GetFirstABLDestination, GetNextABLDestination
FindRecordInABL
The Function returns true if the record activity combination is in the available block list, See
GetFirstABLItem for a list of the return values.
ARGUMENTS
iFlags An integer representing the current state of the flags for this item
VALUES RETURNED
Returns true if the given record activity combination exists in the Available Block List
REMARKS
This function is available only in the User Processing Scripts.
RELATED FUNCTIONS
GetFirstABLDestination, GetNextABLDestination
FindSourceInABL
The Function returns true if the record activity combination is in the available source block list, See
GetFirstABLSource for a list of the return values.
ARGUMENTS
iFlags An integer representing the current state of the flags for this item
VALUES RETURNED
Returns true if the given record activity combination exists in the Available Source Block List
REMARKS
This function is available only in the User Processing Scripts.
RELATED FUNCTIONS
GetFirstABLSource, GetNextABLSource
FirstCompletedTask
Returns true for the first productive step which was completed (eg end Remaining percentage of 0) in a
given reporting period. It has a side affect that the associated Result field does not pro-rata database
values. The net affect of this filter is that it allows an associated result field to report the full non-
prorated database value of the first productive task completed within a reporting period.
Notes: This function can only be used once in a single filter, and can not be combined with any of its
related functions. It can only be used as a report filter. If reporting tasks based on a timescale, do not
use a timescale with a resolution smaller than that of the calendar used to run the schedule with this
XCM. For example, if a schedule was run using a monthly calendar, do not use a timescale created
based on weekly intervals.
RELATED FUNCTIONS
LastStartedTask, LastCompletedTask, FirstStartedTask, FirstTask, LastTask
FirstStartedTask
DESCRIPTION
Returns true for the first productive step which was started (eg Initial percentage of 100) in a given
reporting period. It has a side affect that the associated Result field does not pro-rata database values.
The net affect of this filter is that it allows an associated result field to report the full non-prorated
database value of the first productive task started within a reporting period.
Notes: This function can only be used once in a single filter, and can not be combined with any of its
related functions. It can only be used as a report filter.
RELATED FUNCTIONS
LastCompletedTask, LastStartedTask, FirstCompletedTask, FirstTask, LastTask
FirstTask
Returns true for the first productive steps in a given reporting period. It has a side affect that the
associated Result field does not pro-rata database values. The net affect of this filter is that it allows an
associated result field to report the full non-prorated database value of the first productive task within a
reporting period.
Notes: This function can only be used once in a single filter, and can not be combined with any of its
related functions. It can only be used as a report filter.
RELATED FUNCTIONS
LastStartedTask, LastCompletedTask, FirstCompletedTask, FirstStartedTask, LastTask
GetActiveCalendarName
DESCRIPTION
Returns the name of the calendar database that is active in the current XPAC project.
The active calendar database is the last one that was accessed. When you run a schedule, the calendar
database assigned to the scenario is made the active calendar. Only one calendar database can be active
at any one time.
ARGUMENTS
There are no arguments for this function.
VALUES RETURNED
This function returns the name of the active calendar database as a variant data type.
If there is only one calendar database in your XPAC project, it cannot be deleted. For this reason there
will always be an active calendar in your project, so this function will always return a value.
EXAMPLES
(1) Confirm that the calendar assigned to the scenario is correct.
Sub Main
'This XCM is run as a "Before Schedule Runs" user processing script
Dim sMsg As String
Dim lAnswer As Long
sMsg = "This Scenario uses the Calendar called "
sMsg = sMsg & GetActiveCalendarName() & ". Is this correct?"
lAnswer = MsgBox(sMsg, MB_YESNO, "CHECK!")
If (lAnswer = IDNO) Then Abort
End Sub
RELATED FUNCTIONS
GetCalendarNameFromScenario, GetFullModelName, GetPeriodFromRecNum
GetActiveScenarioName
DESCRIPTION
Returns the name of the active scenario in the current project.
ARGUMENTS
This function does not have any arguments, however the brackets must be included.
VALUES RETURNED
The function returns a variant data type.
If a valid scenario name is returned, it will be a string data type.
If none of the scenarios in the current project are active, an empty string will be returned.
EXAMPLES
(1) Find the name of the active scenario.
Sub Main
Dim sScenario As String
Dim lNumPSrecords As Long
Dim sMsg As String
'Display a message if there are no records in the preschedule
'table for the active scenario
sScenario = GetActiveScenarioName()
lNumPSrecords = GetPSItemCount(sScenario)
If (lNumPSrecords <= 0) Then
sMsg = "There are no Preschedule Records in this Scenario."
Call MsgBox(sMsg, MB_OK, "NOTE")
End If
End Sub
RELATED FUNCTIONS
SetActiveScenario, RunActiveScenario
GetActivityCount
DESCRIPTION
Returns the number of productive activities in the current project.
Note that productive activities are always numbered sequentially, so the activity count will be equal to
the largest productive activity number.
ARGUMENTS
There are no arguments for this function.
VALUES RETURNED
This function returns the number of productive activities as a long data type.
All new projects start off with one productive activity and it is impossible to delete this activity.
Therefore, there will always be at least one productive activity in a project.
EXAMPLES
(1) Print the number of productive activities.
Sub Main
'Print the number of activities in the current project
Print GetActivityCount()
End Sub
RELATED FUNCTIONS
GetActivityName, GetActivityNum
GetActivityName
DESCRIPTION
Returns the activity name corresponding to the specified activity number. This function can only be
used for productive activities.
ARGUMENTS
Activity Number The activity number is passed into this function by value as a long
data type. Only productive activity numbers are recognised by
this function. Note that productive activities are always numbered
sequentially, so the activity count will be equal to the largest
productive activity number.
To view the list of productive activities, including their number,
click on “Productive Activities” in the Schedule Setup Tree for
any scenario. The list of productive activities is displayed in the
right hand window.
The activity number is an optional argument. If the activity
number is not passed to the function, it will return the string
“Default”. This is useful when using polygon functions, in which
the “Default” activity has a specific meaning.
VALUES RETURNED
The function returns the activity name as a variant data type. If a valid productive activity name is
found, it is returned as a string.
If the activity number is not a valid productive activity, then the function will return a blank string.
If the activity number is not passed into the function, is passed in as zero or is passed in as
DEFAULT_ACTIVITY, then the function will return the string “Default”.
EXAMPLES
(1) Print the name for a specified activity number.
Sub Main
Print GetActivityName(2)
End Sub
RELATED FUNCTIONS
GetActivityCount, GetActivityNum
GetActivityNum
DESCRIPTION
Returns the activity number given the productive activity name.
Note that productive activities are always numbered sequentially, so the activity count will be equal to
the largest productive activity number.
ARGUMENTS
Activity Name The activity name is passed into this function by value as a string
data type. Only productive activity names are recognised by this
function.
To view the list of productive activities, including their number,
click on “Productive Activities” in the Schedule Setup Tree for any
scenario. The list of productive activities is displayed in the right
hand window.
The activity name is an optional argument. If the activity name is
not passed to the function, it will return the activity number for the
“Default” activity, namely zero or DEFAULT_ACTIVITY. This is
useful when using polygon functions, in which the “Default”
activity has a specific meaning.
If the activity name is passed into the function as “Default”, then the
function will also return zero or DEFAULT_ACTIVITY as the
activity number.
VALUES RETURNED
The function returns the activity number as a long data type.
If the activity name is not a valid productive activity, then the function will return a value of -1.
If the activity name is not passed into the function or is passed in as “Default”, then the function will
return a value of zero or DEFAULT_ACTIVITY.
EXAMPLES
(1) Print an actvity number given the activity name.
Sub Main
'Print the drilling activity number for the current project
Print GetActivityNum("Drilling")
End Sub
(2) Use the activity number to change the production rate for a resource, in a user processing script.
Sub Main
Dim lActivityNum As Long
lActivityNum = GetActivityNum("Waste Mining")
'Change the production rate for the resource
Call ChangeProductionRate("Shovel 40cu.m [SP]", lActivityNum, "5100")
End Sub
RELATED FUNCTIONS
GetActivityCount, GetActivityName, GetPSItem, FindRecordInABL
GetApil
DESCRIPTION
This function returns the Absolute Position In Level (Apil) number for a record, at the specified level.
This can be done for the current record or some other record can be specified using its record number.
ARGUMENTS
Level Number The level number is passed by value as an integer data type.
The value of the level number must be between 0 and the level of
the current or specified record. The maximum level number
possible in XPAC is 10.
The level number may also be set to THISLEVEL. In this case
the function will use the level number of the current or specified
record.
Record Number The second argument is optional. It is used to indicate the starting
point for this function.
If the second argument is not supplied, then the starting point for
the function is the current record.
If the second argument is supplied, then the starting point for the
function is the specified record number. This record number is
passed by value as a long data type.
VALUES RETURNED
The function will return the absolute position in level number as a long data type.
If the level number is invalid, the function will a zero.
If the level number is zero, the function will return the absolute position in level number for the Top
record (1) or the Stockpiles record (2), whichever is relevant.
The function returns zero if a record number is specified and it is invalid.
EXAMPLES
(1) In the XPAC structure tree below, the position in level numbers are displayed for each record,
following the tilda (~) character. The record numbers are also displayed, in square brackets and
preceded by the hash (#) character.
If an XCM is currently processing the record RVW\30\R01\1 in the database above, then the GetApil
function will return the values listed below.
In the first set of examples, the record number is not specified, so the starting point is the current
record, ie. RVW\30\R01\1.
GetApil(0) = 1
GetApil(1) = 1
GetApil(2) = 30
GetApil(3) = 1
GetApil(4) = 1
GetApil(THISLEVEL) = 1
In the next set of examples, the absolute position in level numbers are sought in relation to record
number of 24, namely RVW\55\R01\2.
GetApil(1, 24) = 1
GetApil(2, 24) = 55
GetApil(3, 24) = 1
GetApil(4, 24) = 2
GetApil(THISLEVEL,24) = 2
In the last set of examples, the absolute position in level numbers are sought in relation to an upper
level record, namely record number 7 or RVW\30\R03. Note that it is invalid to request levels below
this upper level record, so the function returns zero for level 4.
GetApil(1, 7) = 1
GetApil(2, 7) = 30
GetApil(3, 7) = 3
GetApil(4, 7) = 0
GetApil(THISLEVEL,7) = 3
(2) The record number can be replaced by a variable that represents the record number, such as that
returned by the function GetRecNum. This variable should be a long data type.
Sub Main
' Find the Pit number that the next Block is in
Dim lNextBlkRec As Long
RELATED FUNCTIONS
GetFeatureCount, GetFeatureName, GetLayerCount, GetEntityCount, GetEntity
GetLevelNum, GetRecNum, GetRecNumAtLevel, Predefined Database Level Variables.
GetASLCount
This function returns the number of items in the ABL. It accepts the following parameters:
Optional ByVal lActivity As Long - If present, specifies an activity number to filter by. If zero or not
present, the function will return the count for all activities.
Optional ByVal bAvailable As Boolean - If true, specifies that only records that are not constrainted
will be returned. If false or not specified, all records will be returned.
Optional ByVal sResource As String - If present, specifies a resource to filter by. If not present, the
current resource is used.
GetCalendarNameFromScenario
DESCRIPTION
Returns the name of the calendar database that is assigned to the specified schedule scenario.
ARGUMENTS
Scenario Name The scenario name is passed to the function by value as a string
data type. It is an optional argument. The scenario name is that
name listed in the schedule set up tree.
VALUES RETURNED
This function returns the calendar database name for the specified scenario as a variant data type.
If the scenario name is not specified, or if it is an empty string, then the function will return the
calendar database name for the active scenario.
If the specified scenario does not exist in the current model, then the function will return an empty
string.
EXAMPLES
(1) Find the calendar for a specified scenario.
Sub Main
'Display a message if the calendar for a specified scenario is not active
Dim sActiveCal As String
RELATED FUNCTIONS
GetActiveCalendarName, GetFullModelName, GetPeriodFromRecNum
GetClass
DESCRIPTION
Read the classification that is assigned in the specified data field number in the current record.
ARGUMENTS
Data Field Number The data field number is used to identify the classified data field
in the current database. It may be passed in as a number or as a
full row code. This argument is passed by value as an integer
data type.
VALUES RETURNED
The function returns the classification that is assigned in the specified data field for the current record.
The classification is returned as a string data type.
If the specified data field is not a classified field, then the following error message is displayed and the
XCM will abort.
EXAMPLES
(1) Read the value in a classified field.
Sub Main
'Read the topsoil classification and use it to calculate the area
'to be cleared.
Dim sTopsoil As String
sTopsoil = GetClass(mROM_Flags_Tpsl)
M(mROM_Clear_Ar) = 0
If (sTopsoil = "Exists") Then M(mROM_Clear_Ar) = M(mROM_Wst_Ar)
End Sub
RELATED FUNCTIONS
SetClass, DbWriteValue, GetNote, GetFieldInfo
GetCurrentActivity
Returns the current activity number. Currently only valid for expressions used within polygon graphics
templates. E.g. ‘Z Field/Expression’, ‘Extrusion Depth’ etc. If the ‘Default’ activity is current then will
return 0. If undefined then will return –1.
GetCurrentCalendarTime
GetCurrentDirectory
DESCRIPTION
Returns the current directory. The current directory is that in which the system would open a file using
the Open command.
Each time you access a file from within XPAC, the current directory is changed to that directory in
which the file is located. When you first open a database the current directory will always be that in
which the database is located. Similarly, each time you run an XCM, the current directory becomes
that directory in which the XCM is located.
VALUES RETURNED
The current directory is returned by this function as a variant data type. It consists of the drive letter
and the directory path. For example:
D:\Long Term Planning\Five Year Schedule\XCMs
EXAMPLES
(1) Print the current directory name to a file.
Sub Main
If (IsFirstInRange()) Then
Open "Report.txt" For Output As #1
'Print the XCM Directory Name in the File
Print #1, "XCM Stored in " & GetCurrentDirectory()
End If
'Print the record name and product tonnage to the file
Print #1, GetRecName(CURRENT, PATHNAME) & " " & M(mPrd_Ton)
If (IsLastInRange()) Then Close #1
End Sub
GetCurrentOutputStep
Gets the Current Output step for the current resource that the script is processing.
This function can only be used in Pre/Post Block & Step - User Processing Scripts.
This function can only be used in the following User Processing Scripts:
Pre Block
Pre Step
Post Block
Post Step
For all other User Processing scripts, using the command will cause the schedule to fail.
Returns True when successful, False otherwise.
For Example
' This subroutine Prints out The current output step of the Scenario called Production
Schedule
Sub Main()
End Sub
Note
Because there is no current output step when the Pre Block and Post Block scripts are executing, this
command will retrieve data related to the next input path, when executing a Pre Block, and data related
to the Last output step when executing a Post Block. This means that executing this command within a
post block will have the same effect as executing the GetLastOutputStep within the post block. Also,
care must be taken using results from this function when executing in the Pre Block, because the
processing of the script could cause the output step to change, meaning that the data retreived by this
function may not be correct on completion of the script.
It is preferable to use these functions within the Pre Step and Post Step user scripts.
See also GetLastOutputStep.
GetCurrentPeriod
REMARKS
This function can only be called during a schedule via User Processing Scripts, it also cannot be called
during Pre Schedule events.
GetCurrentResource
This function can only be used in User Processing Scripts it returns the name of the resource that
caused the event (user processing script to be run).
GetCurrentScheduleTime
This function returns the time and date of the current output step.
It was added for user processing and can only be used with Pre / Post Period; TimeSlice; Block; and
Step
Care should be taken when formatting the date cells as 0 is often returned, which results in a row of
hashes in the database field
GetCurrentStepActivity
VALUES RETURNED
When this function can not return the activity it returns –1.
REMARKS
This function is available only in the User Processing Scripts.
RELATED FUNCTION
GetCurrentStepDetails
GetCurrentStepDetails
GetCurrentStepDetails
Returns the percentage mined, released and remaining for the current step.
ARGUMENTS
The function will return a number between 0 and 1 for each argument.
VALUES RETURNED
The function returns ‘True’ if the function can be used.
REMARKS
This function is available only in the Pre/Post Step and Pre/Post Block User Processing scripts.
RELATED FUNCTION
GetCurrentStepActivity
GetDatabaseName
DESCRIPTION
Returns the name of the database over which the XCM is being run. If the XCM is a Run Once XCM,
then it returns the name of the database that was active when the XCM was run.
ARGUMENTS
There are no arguments for this function.
VALUES RETURNED
The function returns the name of the current database as a variant data type.
EXAMPLES
(1) Display the name of the database over which the XCM is being run.
Sub Main
Dim sMsg As String
Dim lReply As Long
'Confirm that the XCM is being run over the correct results database
If (IsFirstInRange()) Then
sMsg = "Do you want to run this XCM over the RESULTS database called "
sMsg = sMsg & GetDatabaseName() & "?"
lReply = MsgBox(sMsg, MB_OKCANCEL, "Warning!")
If (lReply = IDCANCEL) Then Abort
End If
End Sub
RELATED FUNCTIONS
GetFullModelName, GetCurrentDirectory, GetScriptExecutionRange, GetScriptName
GetDependencies
Gets a records dependencies, you must call this function before calling the functions,
GetPredecessor, GetSuccessor, GetNumberOfPredecessors, GetNumberOfSuccessors.
RELATED FUNCTIONS
GetPredecessor,
GetPredecessor, GetSuccessor,
GetSuccessor, GetNumberOfPredecessors,
GetNumberOfPredecessors,
GetNumberOfSuccessors,
GetNumberOfSuccessors, Released
Returns the accumulated released value for the specified main database data field, for all steps passed
by the filter.
RemoveAllDependencies
GetDestApil
This function is used in a conditional statement to filter the scheduled steps according to their
destinations position in level numbers. The function will return the position in level number at the level
specified inside the brackets.
eg. GetDestApil(0) = 3
ARGUMENTS
Level Number - The level number is passed by value as an integer data type. The value of the level
number must be between 0 and the level of the current or specified record. The maximum level
number possible in XPAC is 10.
VALUE RETURNED
The function will return the absolute position in level number as a long data type. If the level number
is invalid, the function will a zero.
GetDestinationABLCount
This function returns the number of items in the Available Destination Block List. It accepts the
following parameters:
Optional ByVal lActivity As Long - If present, specifies an activity number to filter by. If zero or not
present, the function will return the count for all activities.
Optional ByVal bAvailable As Boolean - If true, specifies that only records that are not constrainted
will be returned. If false or not specified, all records will be returned.
Optional ByVal sResource As String - If present, specifies a resource to filter by. If not present, the
current resource is used.
GetEntity
DESCRIPTION
Returns the number of vertices in the Entity defined by the Feature Layer name, the Layer name and
the Entity Index number. The coordinates for each vertex are returned in a user-defined array that you
pass to the subroutine as an argument. In addition, the last argument can be used to determine whether
the specified Entity is closed.
Feature Layers are made up of Layers and Layers are made up of Entities. Entities may be text, lines,
polylines, lightweight polylines, etc.
Note that the function GetEntityCount only returns the number of Entities that contain lines, polylines
or lightweight polylines. Consequently, the Entity Index number and this function both exclude
Entities that contain text.
ARGUMENTS
Feature Layer The Feature Layer name is the name that appears within your
Name XPAC model. It is passed by value as a string data type.
To view the Feature Layer names in your XPAC project, select
View | Polygon Graphics Edit x,y,z Points from the menu. The
Feature Layer names will be displayed in the bottom left pane of
the window, at the top level of the tree.
The Feature Layer Name will most likely be sourced using the
GetFeatureName function.
Layer Name The Layer name is the name that appears within your XPAC
model for the specified Feature Layer. It is passed by value as a
string data type.
If the Layer name is set to an empty string then the Entity Index
number will be an index of all Entities within the specified Feature
Layer.
To view the Layer names in your XPAC project, select View |
Polygon Graphics Edit x,y,z Points from the menu. The Feature
Layer names will be displayed in the bottom left pane of the
window, at the top level of the tree. Expand the tree for the
specified Feature Layer and the Layer names will be displayed at
the second level of the tree.
The Layer Name will most likely be sourced using the
GetLayerName function.
Entity Index This is an internal XPAC number for the required Entity in the
Number specified Feature Layer and Layer. It is passed by value as a long
data type.
The Entity Index number will be between 1 and the total number
of Entities in the specified Layer and Feature Layer.
Note that if the Layer name is set to an empty string then the
Entity Index number will be between 1 and the total number of
Entities in the specified Feature Layer.
There is no way of viewing the Entity Index Number from within
XPAC. It will most likely be sourced by looping through all of the
Entities in the specified Feature Layer and Layer using the
GetEntityCount function.
Element Description
dX The X coordinate for the current Vertex.
dY The Y coordinate for the current Vertex.
dZ The Z coordinate for the current Vertex.
VALUES RETURNED
The function will return the number of vertices in the specified Entity as a long data type.
If the specified Feature Layer name does not exist in your XPAC Model, the function will return the
following message.
If the specified Feature Layer exists in your XPAC Model, but the Layer name is invalid for that
Feature Layer, then the function will return a value of 0.
If the specified Feature Layer exists in your XPAC Model and the Layer exists in that Feature Layer,
but the Entity Index number is invalid for the Layer, then the function will return a value of 0.
If the specified Feature Layer exists in your XPAC Model, the Layer name is an empty string and the
Entity Index number is valid within the entire Feature Layer, then the function will return the number
of vertices in the specified Entity.
If the specified Feature Layer exists in your XPAC Model, the Layer name is an empty string and the
Entity Index number is invalid within the entire Feature Layer, then the function will return a value of
0.
The x, y and z coordinates for each vertex in the Entity are returned in the user-defined array that must
be passed into the function for the “Vertex Coordinates” argument.
If the first vertex of the Entity is the same as the last vertex, then the Entity is considered to be closed.
The last argument for this function can be used to return a boolean value, where True indicates that the
Entity is closed and False indicates that the Entity is not closed.
EXAMPLES
(1) Write the Feature Layer coordinates into a Text File.
Sub Main()
lFeatureCount = GetFeatureCount()
For lFeatureIndex = 1 To lFeatureCount
sFeatureName = GetFeatureName(lFeatureIndex)
lLayerCount = GetLayerCount(sFeatureName)
For lLayerIndex = 1 To lLayerCount
sLayerName = GetLayerName(sFeatureName, lLayerIndex)
lEntityCount = GetEntityCount(sFeatureName, sLayerName)
For lEntityIndex = 1 To lEntityCount
lVertexCount = GetEntity(sFeatureName, sLayerName, lEntityIndex, EntityPts)
For lVertexIndex = 1 To lVertexCount
'Write the Lease Boundary coordinates to a file in csv format
sPrintMsg = sFeatureName & "," & sLayerName & "," & CStr(lEntityIndex)
sPrintMsg = sPrintMsg & "," & CStr(EntityPts(lVertexIndex).dX)
sPrintMsg = sPrintMsg & "," & CStr(EntityPts(lVertexIndex).dY)
sPrintMsg = sPrintMsg & "," & CStr(EntityPts(lVertexIndex).dZ)
Print #1, sPrintMsg
Next lVertexIndex
Next lEntityIndex
Next lLayerIndex
Next lFeatureIndex
End Sub
RELATED FUNCTIONS
GetFeatureCount, GetFeatureName, GetLayerCount, GetLayerName, GetEntityCount
GetEntityCount
DESCRIPTION
Returns the number of Entities in the specified Layer and Feature Layer in your XPAC Model. Note
that this function will only return those Entities that are lines, polylines and lightweight polylines.
Feature Layers are made up of Layers and Layers are made up of Entities. Entities may be text, lines,
polylines, lightweight polylines, etc.
ARGUMENTS
Feature Layer The Feature Layer name is the name that appears within your
Name XPAC model. It is passed by value as a string data type.
To view the Feature Layer names in your XPAC project, select
View | Polygon Graphics Edit x,y,z Points from the menu. The
Feature Layer names will be displayed in the bottom left pane of
the window, at the top level of the tree.
The Feature Layer Name will most likely be sourced using the
GetFeatureName function.
Layer Name The Layer name is the name that appears within your XPAC
model for the specified Feature Layer. It is passed by value as a
VALUES RETURNED
If the specified Layer name exists for the specified Feature Layer name in your XPAC Model, then the
function will return the number of Entities within that Layer. It will be returned as a long data type.
Note that the number of Entities will only include lines, polylines and lightweight polylines. Entities
containing text will be ignored completely.
If the specified Feature Layer name does not exist in your XPAC Model, the function will return the
following message.
If the specified Feature Layer exists in your XPAC Model, but the Layer name is invalid for that
Feature Layer, then the function will return a value of 0.
If the Specified Feature Layer exists in your XPAC Model and the Layer name is set to an empty
string, then the function will return the total number of Entities in the Feature Layer.
EXAMPLES
(1) Refer to the example for the function GetEntity.
RELATED FUNCTIONS
GetFeatureCount, GetFeatureName, GetLayerCount, GetLayerName, GetEntity
GetFeatureCount
DESCRIPTION
ARGUMENTS
There are no arguments for this function.
VALUES RETURNED
The function returns the number of Feature Layers in the current XPAC project as a long data type.
If there are no Feature Layers in the current project then the function will return a value of 0.
EXAMPLES
(1) Write the Feature Layer coordinates into a Text File.
Sub Main()
lFeatureCount = GetFeatureCount()
For lFeatureIndex = 1 To lFeatureCount
sFeatureName = GetFeatureName(lFeatureIndex)
lLayerCount = GetLayerCount(sFeatureName)
For lLayerIndex = 1 To lLayerCount
sLayerName = GetLayerName(sFeatureName, lLayerIndex)
lEntityCount = GetEntityCount(sFeatureName, sLayerName)
For lEntityIndex = 1 To lEntityCount
lVertexCount = GetEntity(sFeatureName, sLayerName, lEntityIndex, EntityPts)
For lVertexIndex = 1 To lVertexCount
'Write the Lease Boundary coordinates to a file in csv format
sPrintMsg = sFeatureName & "," & sLayerName & "," & CStr(lEntityIndex)
sPrintMsg = sPrintMsg & "," & CStr(EntityPts(lVertexIndex).dX)
sPrintMsg = sPrintMsg & "," & CStr(EntityPts(lVertexIndex).dY)
sPrintMsg = sPrintMsg & "," & CStr(EntityPts(lVertexIndex).dZ)
Print #1, sPrintMsg
Next lVertexIndex
Next lEntityIndex
Next lLayerIndex
Next lFeatureIndex
End Sub
RELATED FUNCTIONS
GetFeatureName, GetLayerCount, GetLayerName, GetEntityCount, GetEntity
GetFeatureName
DESCRIPTION
Returns the name of the Feature Layer identified by the Feature Layer index number.
Feature Layers are made up of Layers and Layers are made up of Entities. Entities may be text, lines,
polylines, lightweight polylines, etc.
ARGUMENTS
Feature Layer This is the internal XPAC number for the required Feature Layer.
Index Number It is passed by value as a long data type.
There is no way of viewing the Feature Layer Index Number from
within XPAC. It will most likely be sourced by looping through
all of the Feature Layers in your XPAC model using the
GetFeatureCount function.
VALUES RETURNED
If a valid Feature Layer Index Number is specified, then the function will return the name for that
Feature Layer as a string data type.
If an invalid Feature Layer Index Number is specified, then the function will return an empty string.
EXAMPLES
(1) Refer to the example for the function GetFeatureCount.
RELATED FUNCTIONS
GetFeatureCount, GetLayerCount, GetLayerName, GetEntityCount, GetEntity
GetFeatureVertexCount
Get a count of the number of vertices for the polygons of a feature. The feature selected has the name
given by FeatureName. This returns the total number of vertices for all the polygons plus a count of the
‘separator’ vertices that mark the end of each polygon, except for the last polygon.
GetFeatureVertexXYZ
Get the XYZ coordinates of a given vertex in a feature. Gets the coordinates for the given vertex
number. Should ensure that this value is in the range of 1 to the value returned from
GetFeatureVertexCount. The coordinates are returned in the parameters X, Y and Z. Gets the vertex for
the feature with the name given by FeatureName.
GetFieldInfo
DESCRIPTION
GetFieldInfo is a subroutine, so it cannot return a value. The data field information is returned via the
user-defined variable that you pass to the subroutine in the second argument.
The data field information returned is that information stored within data field design. It is returned for
the data field and the database specified in the arguments of the subroutine. The data field information
includes the code, name, units, field type, activity and protection.
ARGUMENTS
Data Field Number The data field number is used to identify the data field for
which the field information is required. It may be passed in
as a number or as a full row code. This argument is passed
by value as an integer data type.
Data Field Information This argument is passed to the function by reference using
an XPAC-defined data structure called FieldInfo.
A data structure is a data type that contains multiple
elements. This enables you to store multiple values using a
single argument. The elements of the data structure are
defined by XPAC, so it is referred to as XPAC-defined.
The FieldInfo data structure has the following elements.
Element Description
FieldCode Returns the data field code (not the full row code) as a string data
type.
FieldName Returns the data field name as a string data type.
Units Returns the data field units as a string data type.
FieldType This parameter returns a long data type. Constants are defined by
XPAC with meaningful names, to represent the various field type
values that may be returned. These constants are listed below.
Additive returns FTYPE_ADDITIVE
Average returns FTYPE_AVG
Weighted Average returns FTYPE_WTAVG
Title returns FTYPE_TITLE
Note returns FTYPE_NOTE
Class returns FTYPE_CLASS
Date (Min) returns FTYPE_DATEMIN
Date (Max) returns FTYPE_DATEMAX
Record returns FTYPE_RECORD
Min returns FTYPE_MIN
Max returns FTYPE_MAX
Ratio returns FTYPE_RATIO
Product returns FTYPE_PRODUCT
Sum returns FTYPE_SUM
Difference returns FTYPE_DIFF
No Aggregate returns FTYPE_NOAGG
If the field type is set to “Different type for each level”, then this
parameter will return the field type for the lowest level of the
database. The field types for the upper levels of the database
cannot be returned.
Param1 The return value for this parameter is a data field number as a long
data type. What this data field number represents is dependent on
the field type, as follows.
Weight Average – Weighting Field
Minimum – Minimum Of
Maximum – Maximum Of
Difference – Difference1
Ratio – Ratio1
Product – Product1
Sum – Sum1
If the data field is not one of the above field types, then Param1 will
return a value of –1.
Param2 The return value for this parameter is a data field number as a long
data type. What this data field number represents is dependent on
the field type, as follows.
Difference – Difference2
Ratio – Ratio2
Product – Product2
Sum – Sum2
If the data field is not one of the above field types, then Param2 will
return a value of –1.
IncludeZeros For some field type settings there is a check box available to
include or exclude zeros from the field type calculations. This
parameter returns the setting for that checkbox as a boolean data
type.
If it is set to Include Zeros (ie. the box is ticked) then the return
value will be True.
If it is set to not Include Zeros (ie. the box is not ticked) then the
return value will be False.
Activity The return value for this parameter is the activity number for the
data field as a long data type.
If there is no activity assigned, it will return a zero value.
Protection Returns the data field protection as a long data type. Constants
are defined by XPAC with meaningful names, to represent the
various protection values that may be returned. These constants
are listed below.
None returns FPROT_NONE
Edit returns FPROT_EDIT
Database Name The database name is used to look for the specified data field
number. It is passed by reference as a variant data type.
The database name may be provided explicitly as a string in double
quotes. For example “Main”, “5 Year Calendar”, “Default
Parameters”, “Equipment Hours”, etc.
Alternatively, the database name may be one of the following
options. Note that these options should not be in quotes.
Options Description
ACTIVE_MAIN The main database.
ACTIVE_CALENDAR The active calendar database.
ACTIVE_RESULTS The active results database.
VALUES RETURNED
GetFieldInfo is a subroutine, so it cannot return a value.
Data field information is returned via the Data Field Information argument. The information returned
includes the data field name, units, field type, activity, protection, etc. The process for reporting this
information is described above, with the other details about the Data Field Information argument. The
return values for each element of the Data Field Information argument are also provided above.
EXAMPLES
(1) Display a data field name, value and units.
Sub Main
Dim FeGrade As FieldInfo
Call GetFieldInfo(mROM_Grade_Fe, FeGrade, "Main")
'Print the field name, value and units
Call MsgBox(FeGrade.FieldName & "=" & M(mROM_Grade_Fe) & FeGrade.Units)
End Sub
RELATED FUNCTIONS
RELATED FUNCTIONS
GetDependencies,
GetDependencies, GetPredecessor,
GetPredecessor, GetSuccessor,
GetSuccessor,
GetNumberOfPredecessors,, GetNumberOfSuccessors,
GetNumberOfPredecessors GetNumberOfSuccessors, Released
Returns the accumulated released value for the specified main database data field, for all steps passed
by the filter.
RemoveAllDependencies, SetDependency
SetFieldInfo, DbReadValue, DbWriteValue
GetFirstABLItem
ARGUMENTS
Available Flags
0 Available for Selection
1 Failed Capacity Constraint
2 Failed Period Constraint
4 Exclusion Record
8 Stockpiling Record
16 Blocked Delayed
32 User 1 Flag Set
64 User 2 Flag Set
VALUES RETURNED
The Function returns –1 if it fails, otherwise returns the value of the Available Flags
REMARKS
This function is available only in the User Processing Scripts.
RELATED FUNCTIONS
GetFirstABLItem, GetNextABLItem
GetFirstABLDestination
ARGUMENTS
Available Flags
0 Available for Selection
VALUES RETURNED
The Function returns –1 if it fails, otherwise returns the value of the Available Flags
REMARKS
This function is available only in the User Processing Scripts.
RELATED FUNCTIONS
GetFirstABLDestination, GetNextABLDestination
GetFirstABLSource
ARGUMENTS
Available Flags
0 Available for Selection
1 Failed Capacity Constraint
2 Failed Period Constraint
4 Exclusion Record
8 Stockpiling Record
16 Blocked Delayed
32 User 1 Flag Set
VALUES RETURNED
The Function returns –1 if it fails, otherwise returns the value of the Available Flags
REMARKS
This function is available only in the User Processing Scripts.
RELATED FUNCTIONS
GetFirstABLSource, GetNextABLSource
GetFirstInRange
DESCRIPTION
Returns the record number of the first record in the database range in the specified database. If the
database name is not provided, it is assumed to be the database over which the XCM is running.
The record that is returned by this function will be at lowest level.
ARGUMENTS
Database Range The database range is passed into the function by value as a string
data type. It should appear in quotes.
The database range should exist in the specified database. If the
database range does not exist in the specified database, an error
message is displayed and the script aborted.
Database Name This is the database in which the database range is looked for. The
database name is passed into the function by value as a string data
type.
The database name is an optional argument. If it is not supplied to
the function, it is assumed to be the database over which the
current XCM is running.
Note that ACTIVE_CALENDAR, ACTIVE_RESULTS, etc
cannot be used in this function.
VALUES RETURNED
This function returns the record number of the first record in the database range as a long data type.
The following table shows the return values when invalid data is passed into the function.
Abort If the specified database does not exist, then the function will return
an “Unspecified failure” and then Abort.
EXAMPLES
(1) Control the database range from within a Run Once XCM.
Sub Main
Dim lRecNum As Long
Const sRangeName = "Waste < 2m Thick"
Const sDBName = "Main"
'Find the first record in the database range
lRecNum = GetFirstInRange(sRangeName, sDBName)
Do While lRecNum > -1
'Write the fragmentation method to data field 108 for each
'record in the database range
Call DbWriteValue(sDBName, lRecNum, 108, "Ripped")
'Find the next record in the database range
lRecNum = GetNextInRange(lRecNum, sRangeName, sDBName)
Loop
End Sub
RELATED FUNCTIONS
GetNextInRange, IsInRange, IsFirstInRange, IsLastInRange
GetFirstOutputStep
Step will contain the first step from the combined output path of Dragline & FEL, alternatively if you
wanted to include all output paths and include all database records.
Long lSteps = GetFirstOutputStep(Step, “Production Scenario”, “All”)
(Refer to the function GetOutputStep for the definition of the type OutputPathStep)
If a range name is supplied then only output steps for database records in the given range will be
included. In no range is supplied then all output steps will be included.
Note: If a range is explicitly given then it will NOT include any in-path delays as these do not
correspond to a given database record. The only way to include in-path delays is by not supplying a
range name in which case all output steps for the given resource(s) will be returned.
Returns the number of steps.
GetFullModelName
DESCRIPTION
Returns the full name of the XPAC model, including the drive, the directory path and the file name.
ARGUMENTS
VALUES RETURNED
The full name of the XPAC model is returned by this function as a variant data type. It consists of the
drive letter, the directory path and the XPAC model name (ie. the xpk file name). For example:
D:\Long Term Planning\Five Year Schedule\Southern Lease.xpk
EXAMPLES
(1) Generate a reserves file with the model name in a header.
Sub Main
Dim sRecData As String
If (IsFirstInRange()) Then
Open "Ore Reserves.csv" For Output As #1
'Print the XPAC Model Name and Date in the File Header
Print #1, "Reserves exported from " & GetFullModelName()
Print #1, "On " & Date & " " & Time()
End If
'Print the record name, ore tonnage and grade to the file
sRecData = sAreaName & "," & sDriveName & "," & sStopeName
sRecData = sRecData & "," & M(mOre_Ton) & "," & M(mOre_Grd)
Print #1, sRecData
If (IsLastInRange()) Then Close #1
End Sub
GetGlobalArray
DESCRIPTION
Returns the value of an array variable from the temporary store inside XPAC.
ARGUMENTS
Object The object to load the stored value into. The object must be of the
type the global array was declared.
VALUES RETURNED
This function returns True if the object was found; otherwise, False.
EXAMPLES
(1) Get the global array used to store the names of exit nodes in a pit and use it to find the index of the
exit node.
'Names of pit exit nodes
Dim g_sExitNames(50) As String
Dim g_lNumExit As Long
Sub Main
RELATED FUNCTIONS
ClearGlobalObject, GetGlobalArray, GetGlobalObject, SetGlobalArray, SetGlobalObject
GetGlobalObject
DESCRIPTION
Returns the value of an object variable from the temporary store inside XPAC.
ARGUMENTS
Object The object to load the stored value into. The object must be of the
type the global object was declared.
VALUES RETURNED
This function returns True if the object was found; otherwise, False.
EXAMPLES
(1) Get the global object used to store the number of exit nodes in a pit.
'Number of pit exit nodes
Dim g_lNumExit As Long
Sub Main
'Retrieve the global object from memory
GetGlobalObject "Gbl_lNumExit", g_lNumExit
End Sub
RELATED FUNCTIONS
ClearGlobalObject, GetGlobalArray, GetGlobalObject, SetGlobalArray, SetGlobalObject
GetInputPathName
DESCRIPTION
Returns the name of the input path that is attached to the specified resource in the specified scenario.
ARGUMENTS
Scenario Name The scenario name is passed to the function by value as a string
data type.
Resource Name This argument defines which resource the required input path is
attached to. The resource name is passed to the function by value as
a string data type.
VALUES RETURNED
This function returns the name of the input path as a string data type.
If the scenario or the resource names are not valid for the current project, then the function will return
an empty string.
If there is no input path attached to the specified resource, then the function will return an empty string.
EXAMPLES
(1) Use the input path name to get the number of steps for a resource.
Sub Main
Const sSCENARIO = "Long Term Plan"
Const sRESOURCE = "Longwall3"
Dim sInputPath As String
'Use the scenario and the resource to get the input path name.
sInputPath = GetInputPathName(sSCENARIO, sRESOURCE)
Print sInputPath & " steps = " & GetInputPathNoOfSteps(sInputPath)
End Sub
(2) Clear all steps from an input path in the active scenario.
Sub Main
Dim sScenario As String
Dim sInputPathName As String
'Clear the input path for the specified resource in the active scenario.
sScenario = GetActiveScenarioName()
sInputPathName = GetInputPathName(sScenario, "PH4100 Shovel")
Call ClearInputPath(sInputPathName)
End Sub
RELATED FUNCTIONS
GetInputPathNoOfSteps, GetInputStep, ClearInputPath, InsertIntoInputPath
GetInputPathNoOfSteps
DESCRIPTION
Returns the number of steps in the specified input path.
ARGUMENTS
Input Path Name This argument defines the input path for which the number of
steps is required. The Input Path Name is passed to the function
by value as a string data type.
VALUES RETURNED
This function returns the number of steps in the specified input path as a long data type.
If the specified input path does not exist in the current project, then the function will return a value of –
1.
Note that zero is a valid return value as the input path may contain no steps.
EXAMPLES
(2) Use the total number of steps in an input path to loop through the steps.
Sub Main
Const sINPUTPATH = "Shovel 605"
Dim lTotSteps As Long
Dim lStep As Long
Dim StepInfo As InputPathStep
'Find out if the specified input path contains any non-productive steps.
lTotSteps = GetInputPathNoOfSteps(sINPUTPATH)
For lStep = 1 To lTotSteps
Call GetInputStep(sINPUTPATH, lStep, StepInfo)
If (StepInfo.StepType = PE_NONPROD) Then
Print sINPUTPATH & " path - non-productive step " & lStep
End If
Next lStep
End Sub
RELATED FUNCTIONS
Error! Reference source not found., GetInputStep, ClearInputPath, InsertIntoInputPath,
GetOutputPathNoOfSteps
GetInputStep
DESCRIPTION
Returns information for the specified step number in the input path. The information that is returned
includes the step type, record number, activity number, entered percent, entered delay, released percent,
destination, etc.
ARGUMENTS
Input Path Name This argument defines the input path for which step data is
required. The input path name is passed to the function by value
as a string data type.
Step Number This argument defines the specific step in the input path for which
information is sought. The step number is passed to the function
by value as a long data type.
Options Description
StepType The step type is a long data type. In an input path, the step types
can be either of the following:
• PE_PROD for productive steps (ie. database records).
• PE_NONPROD for nonproductive steps (ie. in-path delays).
TaskId The task ID is a long data type. The value that is returned varies
according to the step type:
For productive steps, the task ID returns the record number.
For non-productive steps, the task ID returns a value of zero.
Activity The activity number is returned as an integer data type.
• For productive steps, the activity will return a value between 1
and 100.
• For non-productive steps, the activity will return a value greater
than 101.
EnteredPct The entered percent is the percentage of the specified record and
activity that has been requested for scheduling. It is returned as a
double data type.
• For productive steps, the entered percent will return a value
between 0 and 1.
• For non-productive steps, the entered percent will return a value
of zero.
EnteredDelay The entered delay is the requested time for the non-productive
activity. It is returned as a double data type.
• For productive steps, the entered delay will return a value of
zero.
• For non-productive steps, the entered delay will return the
delay time in days.
EnteredDelay- The entered delay time base units refers to the time base that is
TimeBaseUnits selected for the entered delay. The time base is returned as an
integer data type. It may be one of the following values:
• Zero for productive steps.
• TBU_CALENDAR_TIME for non-productive steps whose
duration is defined in calendar time.
• TBU_ROSTER_TIME for non-productive steps whose
duration is defined in roster time.
• TBU_OPERATING_TIME for non-productive steps whose
duration is defined in operating time.
Note that TBU_CALENDAR_TIME has a value of zero, so the step
type should also be tested to distinguish between calendar time and
productive steps.
ReleasedPct When an activity is scheduled, it is able to release other activities for
which it is a precedence. The released percent defines how much of
these other activities are to be released. It is returned as a double
data type.
• For productive steps, the released percent will be between
0 and 1.
• For non-productive steps, the released percent will be zero.
DestinationSP The destination stockpile is the name of the stockpile to which this
VALUES RETURNED
This function returns a boolean data type.
If the step in the specified input path is successfully found, then the function will return a True value.
The function will return a False value in the following situations:
• If the specified input path does not exist; or
• If the step number does not exist in the specified input path.
If the function returns a False value, then the Step Information variable will retain its original values.
If the Step Information variable is declared as the wrong data type, then the function will report an
error indicating there is a type mismatch.
This function can also return information about the specified step in the input path using the Step
Information argument. The information returned includes the step type, task ID, activity, entered
percent, entered delay, etc. The process for reporting this information is described above, with the
other details about the Step Information argument. The return values for each element of the Step
Information argument are also provided above.
EXAMPLES
(1) Find out whether any steps in the input path have a production rate adjustment.
Sub Main
Const sINPUTPATH = "Dragline89"
RELATED FUNCTIONS
Error! Reference source not found., GetInputPathNoOfSteps, ClearInputPath, InsertIntoInputPath
GetLastError
DESCRIPTION
Returns the last error message that was generated by XPAC during the execution of the function
RunActiveScenario.
ARGUMENTS
The function does not have any arguments, however the brackets must be included.
VALUES RETURNED
This function returns a variant data type. The return value is a string containing information about the
last error reported during the execution of the schedule. The format of the message will vary according
to the result of the schedule, as shown in the following table.
EXAMPLES
(1) Display more information about errors encountered while scheduling.
Sub Main
Dim lSchedResult As Long
'After running a schedule, display information about errors
'that were encountered
Call SetActiveScenario("Life of Mine Schedule")
lSchedResult = RunActiveScenario(1, 30, TRUE)
If (lSchedResult = 0) Then Print "The Schedule was Succeessful."
If (lSchedResult > 0) Then
Call MsgBox(GetLastError(), MB_OK, "Schedule Error")
End If
End Sub
RELATED FUNCTIONS
RunActiveScenario.
GetLastOutputStep
Gets the most recent entry saved to the Output path for the Current Resource that the script is
processing. The most recently saved entry will have been saved when two incremental steps of the
resource differ in the production rate, taskID or activity etc.
This function can only be used in the following User Processing Scripts:
Pre Block
Pre Step
Post Block
Post Step
For all other User Processing scripts, using the command will cause the schedule to fail.
Returns True when successful, False otherwise.
The structure OutputPathStep is defined as follows:
Type OutputPathStep
InputStepNo As Long ' step number in the input path from which this step was generated
StepType As Long ' PE_PROD, PE_NONPROD, PE_ZEROPROD etc.
TaskId As Long ' the record number for productive step, 0 otherwise
Activity As Integer ' 1-100 for productive activity, >= 101 for delay
EnteredDelay As Double ' in Days - undefined for productive steps (StepType = PE_PROD)
EnteredPct As Double ' undefined for non-productive steps (StepType = PE_NONPROD)
ReleasedPct As Double ' undefined for non-productive steps (StepType = PE_NONPROD)
NextActivity As Integer ' the next activity number
ActualDelay As Double ' the actual delay in days
InitialPct As Double '
ActualPct As Double ' actual percent processed by the activity in this step
RemainingPct As Double ' pecent remaining after this step
Period As Integer ' the number of the period that this output step occurred in
StartDate As Date ' the starting date/time of this output step
FinishDate As Date ' the ending date/time of this output step
CalendarTime As Double ' duration of this step in calendar days
OperatingTime As Double ' actual operatiing time for this step in days
WorkTime As Double ' actual working time for this step in days
EnteredProductionRate As Double ' the desired production rate for this step
ActualProductionRate As Double ' the achieved production rate for this step
NumberOfItems As Double '
ActualQuantity As Double '
DestinatonSP As Double ' the Stock pile name
Progress As Double '
Info As String*30
FleetItem As Integer '
ResourceName As String*30 ' Name of the Resource
DestinationFilledPct As Double '
DestinationReleasedPct As Double '
InitialDestinationFilledPct As Double '
DestinationId As Long '
End Type
For Example
' This subroutine Prints out The current output step of the Scenario called Production Schedule
Sub Main()
End If
End Sub
End Sub
Note
Executing this command within a post block will have the same effect as executing the
GetCurrentOutputStep within the post block. Also, care must be taken using results from this function
when executing in the Pre Block, because the processing of the script could cause the output step to
change, meaning that the data retreived by this function may not be correct on completion of the script.
It is preferable to use this function within the Pre Step and Post Step user scripts.
See also GetCurrentOutputStep
GetLastOutputStep
This function now returns the Last output Step in the report writer. The step also includes the
Destination of the Output Step. This may be useful when using Stockpiles.
GetLayerCount
DESCRIPTION
Returns the number of Layers in the specified Feature Layer in your XPAC Model.
Feature Layers are made up of Layers and Layers are made up of Entities. Entities may be text, lines,
polylines, lightweight polylines, etc.
ARGUMENTS
Feature Layer The Feature Layer name is the name that appears within your
Name XPAC model. It is passed by value as a string data type.
To view the Feature Layer names in your XPAC project, select
View | Polygon Graphics Edit x,y,z Points from the menu. The
Feature Layer names will be displayed in the bottom left pane of
the window, at the top level of the tree.
The Feature Layer Name will most likely be sourced using the
GetFeatureName function.
VALUES RETURNED
If the specified Feature Layer name exists in your XPAC Model, then the function will return the
number of Layers within that Feature Layer. It will be returned as a long data type.
If the specified Feature Layer name does not exist in your XPAC Model or it is blank, then the function
will return a value of -1.
EXAMPLES
(1) Write the Feature Layer coordinates into a Text File.
Sub Main()
lFeatureCount = GetFeatureCount()
For lFeatureIndex = 1 To lFeatureCount
sFeatureName = GetFeatureName(lFeatureIndex)
lLayerCount = GetLayerCount(sFeatureName)
For lLayerIndex = 1 To lLayerCount
sLayerName = GetLayerName(sFeatureName, lLayerIndex)
lEntityCount = GetEntityCount(sFeatureName, sLayerName)
For lEntityIndex = 1 To lEntityCount
lVertexCount = GetEntity(sFeatureName, sLayerName, lEntityIndex, EntityPts)
For lVertexIndex = 1 To lVertexCount
'Write the Lease Boundary coordinates to a file in csv format
sPrintMsg = sFeatureName & "," & sLayerName & "," & CStr(lEntityIndex)
sPrintMsg = sPrintMsg & "," & CStr(EntityPts(lVertexIndex).dX)
sPrintMsg = sPrintMsg & "," & CStr(EntityPts(lVertexIndex).dY)
sPrintMsg = sPrintMsg & "," & CStr(EntityPts(lVertexIndex).dZ)
Print #1, sPrintMsg
Next lVertexIndex
Next lEntityIndex
Next lLayerIndex
Next lFeatureIndex
End Sub
RELATED FUNCTIONS
GetFeatureCount, GetFeatureName, GetLayerName, GetEntityCount, GetEntity
GetLayerName
DESCRIPTION
Returns the name of the Layer within the specified Feature Layer name and identified by the Layer
index number.
Feature Layers are made up of Layers and Layers are made up of Entities. Entities may be text, lines,
polylines, lightweight polylines, etc.
ARGUMENTS
Feature Layer This is the name of the Feature Layer in which you want to look
Name for the specified Layer. It is passed by value as a string data
type.
Layer Index This is an internal XPAC number for the required Layer in the
Number specified Feature Layer. It is passed by value as a long data type.
The Layer Index number will be between 1 and the total number
of Layers in the specified Feature Layer.
There is no way of viewing the Layer Index Number from within
XPAC. It will most likely be sourced by looping through all of the
Layers in the specified Feature Layer using the GetLayerCount
function.
VALUES RETURNED
If a valid Feature Layer Name and Layer Index Number are specified, then the function will return the
name for that Layer as a string data type.
If an invalid Feature Layer Name or Layer Index Number are specified, then the function will return an
empty string.
EXAMPLES
(1) Refer to the example for the function GetLayerCount.
RELATED FUNCTIONS
GetFeatureCount, GetFeatureName, GetLayerCount, GetEntityCount, GetEntity
GetLevelNum
DESCRIPTION
Returns the level number for the specified record.
ARGUMENTS
VALUES RETURNED
This function returns the database level number at which the specified record is located. The level
number is returned as an integer data type.
If the specified record number does not exist in the database, then the function will return a value of –1.
If the parameter passed in as the record number is invalid, such as NXT, UP, etc, then the function
returns the error message shown below and then the XCM aborts.
EXAMPLES
(1) Find the level number for the current record.
Sub Main
'Check that data has imported successfully by confirming that all
'records are at the lowest level.
Const lLOWESTLEVEL = 4
Dim lLevelNum As Long
lLevelNum = GetLevelNum()
'If the record is not at the lowest level, print the record number.
If (lLevelNum <> lLOWESTLEVEL) Then Print GetRecNum(CURRENT)
End Sub
(2) Find the level number for a record other than the current record.
Sub Main
'Find the level number for the first record in the database
'(using the database range called All).
Dim lFirstRec As Long
lFirstRec = GetFirstInRange("All")
Print GetLevelNum(lFirstRec)
End Sub
RELATED FUNCTIONS
GetMax
DESCRIPTION
Returns the maximum of two values.
The maximum of three or more values can be done in multiple steps.
ARGUMENTS
The two arguments for this function are the values for which the maximum is returned.
Both of the arguments are double data types and both are passed by value.
VALUES RETURNED
The function will return the maximum value as a double data type.
If both the values are the same, then their value is returned.
If either of the values are strings, they are interpreted as zeros and the maximum is returned.
EXAMPLES
(1) Find the maximum of two values.
Sub Main
Dim dProd100t As Double '100t Truck Productivity
Dim dProd105t As Double '105t Truck Productivity
Dim dMaxTrkProd As Double 'Maximum Truck Productivity
dProd100t = 452.231 'Set Productivity t/hr
dProd105t = 324.556 'Set Productivity t/hr
'Calculate Maximum Productivity and display it in a message box
dMaxTrkProd = GetMax(dProd100t, dProd105t)
MsgBox "Maximum Productivity is " & dMaxTrkProd
End Sub
RELATED FUNCTIONS
GetMin, Abs.
GetMin
DESCRIPTION
Returns the minimum of two values.
The minimum of three or more values can be done in multiple steps.
ARGUMENTS
The two arguments for this function are the values for which the minimum is returned.
Both of the arguments are double data types and both are passed by value.
VALUES RETURNED
The function will return the minimum value as a double data type.
If both the values are the same, then their value is returned.
If either of the values are strings, they are interpreted as zeros and the minimum is returned.
EXAMPLES
(1) Find the minimum of two values.
Sub Main
Dim dTravRouteA As Double 'Travel Time on Route A
Dim dTravRouteB As Double 'Travel Time on Route B
Dim dMinTravTime As Double 'Minimum Travel Time
dTravRouteA = 12.6 'Set Travel Time in minutes
dTravRouteB = 12.6 'Set Travel Time in minutes
'Calculate Minimum Travel Time and display it in a message box
dMinTravTime = GetMin(dTravRouteA, dTravRouteB)
MsgBox "Minimum Travel Time is " & dMinTravTime
End Sub
RELATED FUNCTIONS
GetMax, Abs.
GetMineStatus
DESCRIPTION
Returns the mine status percentage for the specified activity and record, at the required point in time.
The function also returns a True value if it is successful.
The mine status percentages that can be returned include the mined, remaining, released or inventory
percentages.
Note that this function obeys the precedence rules but not dependencies, when reporting released and
inventory percentages.
ARGUMENTS
Record Number This argument defines the main database record for which the
mine status is required. It is passed to the function by value as a
long data type.
In addition to a number or a variable, this argument can be one of
the following options:
Options Description
CURRENT The current active record
HOME The original record the script started with, ie. the record that was
called by the script before the use of GoRec or similar
UP The parent record
DOWNFIRST The first child record
DOWNLAST The last child record
PRVSIB The previous sibling under the same parent
NXTSIB The next sibling under the same parent
PRV The previous sibling regardless of parents
NXT The next sibling regardless of parents
Activity Number This argument defines the productive activity within the main
database record for which the mine status is required. It is passed
to the function by value as an integer data type.
Status Type The function is able to report the mined, remaining, released or
inventory percentage for the specified database record. This
argument is used to define which of these percentages you want to
report. It is passed by value as an integer data type.
The options for this argument are provided in the table below.
Options Description
MS_MINED This is the total percentage of the specified activity that has
been scheduled up to the required point in time. The mined
percentage is equal to 100% minus the remaining
percentage.
MS_REMAINING This is the total percentage of the specified activity that is
remaining to be scheduled at the required point in time. The
remaining percentage is equal to 100% minus the mined
percentage.
MS_RELEASED This is the total percentage of the specified activity that has
been released at the required point in time.
For the Mined Out Quantities and Preschedule, you are
Calculation Point This argument defines the point in time for which the mine status
is sought. The calculation point is passed by value as an integer
data type.
The calculation point is an optional argument. If it is not passed
into the function, then it is assumed to be at the end of the last
schedule that was run, ie. MS_CURRENT.
The calculation point may be set to one of the following values.
Options Description
MS_AFTER_INITIAL This calculation point is after the initial mine status has been
set. That is, after the zero test data fields have been
evaluated but before the Mined Out Quantities and
Preschedule have been evaluated.
MS_AFTER_MOQ This calculation point is after the Mined Out Quantities have
been evaluated but before the Preschedule Table has been
evaluated.
MS_AFTER_PS This calculation point is after the Preschedule Table has been
evaluated but before the schedule begins.
MS_CURRENT This calculation point is at the end of the last schedule that
was run.
VALUES RETURNED
This function returns a boolean data type which indicates whether the requested mine status percentage
was found.
If the requested mine status percentage was found, then the function will return a True value.
If the any of the arguments passed into the function are invalid, then the function will return a range of
values, as indicated below.
• If the specified record number does not exist in the main database, a message will be displayed
saying ‘Invalid Record Supplied to Function “GetMineStatus”’. The function will then return a
False value and the script will be aborted.
• If the specified record number is an upper level record, then the function will return a True value,
but the percentage returned will always be 100%.
• If the specified activity number is not a valid productive activity in the current project, then a
message will be displayed saying ‘Unable to read mine status for supplied record’. The function
will then return a False value.
• If the specified activity number is a valid productive activity, but it is not active in the current
scenario, then the function will return a True value and the percentage mined after the initial status
will be 100%, ie. the activity is not available for scheduling.
• If the status type is not one of the specified options, a message will be displayed saying ‘Invalid
Value for Parameter “Option” used in Function “GetMineStatus”’. The XCM will then stop.
• If the variable passed into the function to store the mine status percentage is not a double data
type, then the function may still return a True value. However, the percentage will either always
be zero or a ‘Type Mismatch’ error will be returned.
• If the calculation point is not one of the specified options, a message will be displayed saying
‘Invalid Value for Parameter “RecalcPoint” used in Function “GetMineStatus”’. The function will
then return a False value and the XCM will be aborted.
• If the schedule has not been recalculated after you have made a change, the results of the last
schedule that you ran will be used for this function. Be careful to always recalculate the schedule
after making any changes.
EXAMPLES
(1) Report any records that were not completely mined at the end of the schedule.
Sub Main
Dim dPct(2) As Double
'Print the percentage of any record that remains to be scheduled,
'for either activity 1 or 2, at the end the schedule.
Call GetMineStatus(CURRENT, 1, MS_REMAINING, dPct(1), MS_CURRENT)
Call GetMineStatus(CURRENT, 2, MS_REMAINING, dPct(2), MS_CURRENT)
If (dPct(1)>0) Then Print "Act 1 not completed in #" & GetRecNum(CURRENT)
If (dPct(2)>0) Then Print "Act 2 not completed in #" & GetRecNum(CURRENT)
End Sub
(2) Print the inventory percentage for a record at the start of the schedule
Sub Main
Dim lRecNum As Long
Dim bStatusFound As Boolean
Dim dPct As Double
lRecNum = GetRecNumFromPath("Stage1\RL505\18")
'Find the percentage of the specified record that is inventory for
'activity 3, at the start of the schedule (ie. the end of the preschedule.
bStatusFound = GetMineStatus(lRecNum, 3, MS_INVENTORY, dPct, MS_AFTER_PS)
If (bStatusFound) Then
Print "Percent Inventory After Preschedule is " & dPct*100
End If
End Sub
RELATED FUNCTIONS
GetMOQItem, GetPSItem, GetInputStep, GetLastOutputStep
GetModelDirectory
DESCRIPTION
Returns the directory that the currently open XPAC model is located in.
ARGUMENTS
There are no arguments for this function.
VALUES RETURNED
This function returns the directory that the currently open XPAC model is located in.
RELATED FUNCTIONS
GetCurrentDirectory, GetDatabaseName, GetFullModelName, GetScriptsDirectory
GetMOQItem
DESCRIPTION
Returns information about records that are listed in the Mined Out Quantities, given their step number
within the list and the activity number. The information that is returned includes the record number,
the percentage released and the percentage mined.
Note that this function obeys the precedence rules but not dependencies, when reporting released
percentages.
ARGUMENTS
Step Number The step number defines the position within the Mined Out
Quantities list. The first record that is added to the Mined Out
Quantities is positioned in step number one and as each new record
is added, they are positioned in the next available step. The records
always remain in the order in which they were created, as opposed
to the database order.
The step number is passed to the function by value as a long data
type.
Activity Number This argument defines the activity number in the specified step for
which information is sought. It is passed to the function by value as
a long data type.
Options Description
TaskID The TaskID is used to store the record number from the specified
step in the Mined Out Quantities list. This element is a long data
type.
If a valid step number is passed into the function, then a valid record
number may be returned. It will always be a lowest level record
number.
ReleasedPct The ReleasedPct stores the percentage of the specified activity in
the record that is released in the Mined Out Quantities. This element
is a double data type.
The user sets the released percentage for an activity, subject to
some basic rules.
• Any activity that does not have any precedences will always be
100% released. This cannot be changed.
• Dependency rules are not followed in the Mined Out
Quantities.
• The percentage of an activity that is released cannot exceed the
percentage mined for any activities that are precedences.
• The percentage of an activity that is released cannot be less
than the percentage of that same activity that is mined.
MinedPct The MinedPct stores the percentage of the specified activity in the
record that is mined in the Mined Out Quantities. This element is a
double data type.
RawReleasedPct Stores the released percentage unadjusted by the zero test data
field.
RawMinedPct Stores the mined percentage unadjusted by the zero test data field.
ReleasedPct Both the released percent and mined percent will return values
and MinedPct between 0 and 1, unless there is an error.
If the released percent or mined percent return a value of –1, this
indicates that the specified activity and record were not available
for scheduling after the initial mine status was processed. This
may happen in the following situations:
• When the specified activity is not active in the current scenario;
or
• If the zero test data field for the specified activity and record has
a value of zero.
example:
MOQInfo.TaskID
MOQInfo.ReleasedPct
MOQInfo.MinedPct
Note: The inventory percentage for the specified activity and
record can be calculated at the end of the Mined Out Quantities as
follows:
Inventory Percent = Released Percent – Mined Percent
VALUES RETURNED
This function returns a boolean data type which indicates whether the requested Mined Out Quantities
step was found.
If the requested Mined Out Quantities step was found, then the function will return a True value.
If the any of the arguments passed into the function are invalid, then the function will return a range of
values, as indicated below.
• If the step number is less than one or greater than the number of steps in the Mined Out
Quantities list (this can be obtained using the function GetMOQItemCount), then the function
will return a False Value.
• If the activity number is not a valid productive activity number in the current project, then the
function will return a False value.
• If the item (the third argument) is not declared as an ItemRemoved type, then the function will
return a True value, however an error message will be displayed indicating that there is a
‘Type mismatch’ and the XCM will then stop.
This function can also return information about the specified step in the Mined Out Quantities using the
Item argument. The information returned includes the record number, released percent and mined
percent. The process for reporting this information is described above, with the other details about the
Item argument. The return values for each element of the Item argument are also provided above.
EXAMPLES
(1) Read a specific step from the Mined Out Quantities.
Sub Main
Const sACTNAME = "Ore Mining"
Dim lActNum As Long
Dim dMOQInfo As ItemRemoved
Dim sRecName As String
Dim sMsg As String
'Read the information for the first step in the Mined Out Quantities.
lActNum = GetActivityNum(sACTNAME)
Call GetMOQItem(1, lActNum, dMOQInfo)
sRecName = GetRecName(dMOQInfo.TaskID, PATHNAME)
sMsg = "Record " & sRecName & ": The " & sACTNAME & " Activity is "
sMsg = sMsg & dMOQInfo.ReleasedPct & "% Released and "
sMsg = sMsg & dMOQInfo.MinedPct & "% Mined."
Call MsgBox(sMsg, MB_OK, "Mined Out Quantities")
End Sub
(2) Find out whether each record is in the Mined Out Quantities.
Sub Main
Const sACTNAME = "Development"
Dim lActNum As Long
Dim lStepNum As Long
Dim dMOQInfo As ItemRemoved
Dim sCurrentRec As String
'Read the information for each step in the Mined Out Quantities.
lActNum = GetActivityNum(sACTNAME)
For lStepNum = 1 to GetMOQItemCount()
Call GetMOQItem(lStepNum, lActNum, dMOQInfo)
If (dMOQInfo.TaskID = GetRecNum(CURRENT)) Then
sCurrentRec = GetRecName(CURRENT, PATHNAME)
Print "Record " & sCurrentRec & " is in the Mined Out Quantities."
End If
Next lStepNum
End Sub
RELATED FUNCTIONS
GetMOQItemCount, GetPSItem, GetPSItemCount, GetMineStatus
GetMOQItemCount
DESCRIPTION
Returns the number of steps in the Mined Out Quantities. Since a record can only appear once in the
Mined Out Quantities, the number of steps is the same as the number of records in the Mined Out
Quantities.
ARGUMENTS
There are no arguments for this function.
VALUES RETURNED
This function returns the number of steps in the mined Out Quantities as a long data type.
The Mined Out Quantities cannot be deleted, so it will always exist, even if it empty. If there are no
steps in the Mined Out Quantities, the function will return a value of zero.
EXAMPLES
(1) In a user processing XCM, notify the user if the Mined Out Quantities contains steps.
Sub Main
Dim lNumMOQSteps As Long
'Display a message if the Mined Out Quantities contains steps
lNumMOQSteps = GetMOQItemCount()
If (lNumMOQSteps > 0) Then
Print "The Mined Out Quantities Contain Data – Check the Entries."
End If
End Sub
(2) Find out whether each record is in the Mined Out Quantities.
Sub Main
Const sACTNAME = "Development"
Dim lActNum As Long
Dim lStepNum As Long
Dim dMOQInfo As ItemRemoved
Dim sCurrentRec As String
'Find out how many steps there are in the Mined Out Quantities and then
'loop through the steps from the first to the last.
lActNum = GetActivityNum(sACTNAME)
For lStepNum = 1 to GetMOQItemCount()
Call GetMOQItem(lStepNum, lActNum, dMOQInfo)
If (dMOQInfo.TaskID = GetRecNum(CURRENT)) Then
sCurrentRec = GetRecName(CURRENT, PATHNAME)
Print "Record " & sCurrentRec & " is in the Mined Out Quantities."
End If
Next lStepNum
End Sub
RELATED FUNCTIONS
GetMOQItem, GetPSItem, GetPSItemCount, GetMineStatus
GetNextABLItem
Returns the next block in the Available Block List. The Record, Activity, and Available Flag are
returned as arguments to the function. The Available Flag when True means that the block is available
for selection. If the resource name is not specified or an empty string, the current resource is used. The
Function returns –1 if it fails. See GetFirstABLItem for a list of the return values. This function is
available only in the User Processing Scripts available to AutoScheduler Resources.
Example:
Dim iRetVal As Integer, lRecord As Long, bAvailable As Boolean
Dim iActivity as integer
iRetVal = GetFirstABLItem( lRecord, iActivity, bAvailable )
Print "Record = " & lRecord & " Activity = " & iActivity & " Available = " & bAvailable
WEnd
GetNextABLDestination
Returns the next block in the Available Destination Block List. The Record, Activity, and Available
Flag are returned as arguments to the function. The Available Flag when True means that the block is
available for selection. If the resource name is not specified or an empty string, the current resource is
used. The Function returns –1 if it fails. See GetFirstABLDestination for a list of the return values.
This function is available only in the User Processing Scripts available to AutoScheduler Resources.
Example:
Dim iRetVal As Integer, lRecord As Long, bAvailable As Boolean
Dim iActivity as integer
iRetVal = GetFirstABLDestination( lRecord, iActivity, bAvailable )
Print "Record = " & lRecord & " Activity = " & iActivity & " Available = " & bAvailable
WEnd
GetNextABLSource
Returns the next block in the Available Source Block List. The Record, Activity, and Available Flag
are returned as arguments to the function. The Available Flag when True means that the block is
available for selection. If the resource name is not specified or an empty string, the current resource is
used. The Function returns –1 if it fails. See GetFirstABLSource for a list of the return values. This
function is available only in the User Processing Scripts available to AutoScheduler Resources.
Example:
Dim iRetVal As Integer, lRecord As Long, bAvailable As Boolean
Dim iActivity as integer
iRetVal = GetFirstABLSource( lRecord, iActivity, bAvailable )
Print "Record = " & lRecord & " Activity = " & iActivity & " Available = " & bAvailable
WEnd
GetNextInRange
DESCRIPTION
Returns the record number of the next record after the specified record number, in the database range in
the specified database. If the database name is not provided, it is assumed to be the database over
which the XCM is running.
The next record that is returned by this function will be at the lowest level.
ARGUMENTS
Record Number The function returns the next record after this record number in the
database range. The record number is passed into the function by
value as a long data type.
The specified record number should be at the same level as the
scanning level in the database range.
Database Range The database range is passed into the function by value as a string
data type. It should appear in quotes.
The database range should exist in the specified database. If the
database range does not exist in the specified database, , an error
message is displayed and the script aborted..
Database Name This is the database in which the database range is looked for. The
database name is passed into the function by value as a string data
type.
The database name is an optional argument. If it is not supplied to
the function, it is assumed to be the database over which the
current XCM is running.
Note that ACTIVE_CALENDAR, ACTIVE_RESULTS, etc
cannot be used in this function.
VALUES RETURNED
This function returns the record number of the next record in the database range as a long data type.
The following table shows the return values when invalid data is passed into the function.
Abort If the specified database does not exist, then the function will return an
“Unspecified failure” and then Abort.
EXAMPLES
(1) Control the database range from within a Run Once XCM.
Sub Main
Dim lRecNum As Long
Const sRangeName = "Waste < 2m Thick"
Const sDBName = "Main"
'Find the first record in the database range
lRecNum = GetFirstInRange(sRangeName, sDBName)
Do While lRecNum > -1
'Write the fragmentation method to data field 108 for each
'record in the database range
Call DbWriteValue(sDBName, lRecNum, 108, "Ripped")
'Find the next record in the database range
lRecNum = GetNextInRange(lRecNum, sRangeName, sDBName)
Loop
End Sub
RELATED FUNCTIONS
GetFirstInRange, IsInRange, IsFirstInRange, IsLastInRange
GetNextOutputStep
Sub Main()
End If
End Sub
End Sub
GetNote
DESCRIPTION
Read the note that is assigned in the specified data field number in the current record.
ARGUMENTS
Data Field Number The data field number is used to identify the note data field in
the current database. It may be passed in as a number or as a full
row code. This argument is passed by value as an integer data
type.
VALUES RETURNED
The function returns the note that is assigned in the specified data field for the current record. The note
is returned as a string data type.
If the specified data field is not a note field, then the following error message is displayed and the XCM
will abort.
EXAMPLES
(1) Read the value in a note field.
Sub Main
'Display information about Block Faulting
Dim sFaultDesc As String
Dim sRecName As String
sFaultDesc = GetNote(mIS_FaultDesc)
'Only print the note field if it contains text
If (sFaultDesc <> "") Then
sRecName = GetRecName(CURRENT, PATHNAME)
Print sRecName & " - " & sFaultDesc
End If
End Sub
RELATED FUNCTIONS
SetNote, DbWriteValue, GetClass, GetFieldInfo
GetNumberOfPredecessors
Dim i As Integer
For i = 0 To iNumOfPredecessor -1
Next i
GetNumberOfSuccessors
Dim i As Integer
For i = 0 To iNumOfSuccessor -1
Next i
GetNumChildren
DESCRIPTION
Returns the number of records at the level immediately below the specified record.
ARGUMENTS
Record Number The record number is passed by value as a long data type.
It may be specified as a number or it may be obtained using other
XCM functions such as GetRecNum.
The options listed below can also be passed into this function as
the record number. The record that each option refers to is
indicated by the description.
VALUES RETURNED
The function will return the number of child records as a long data type.
If the specified record is a lowest level record and therefore has no children, then the function will
return a zero.
If the record number is invalid, then the following error message will be displayed and the XCM will
stop executing.
EXAMPLE
(1) Determine the number of Pits in the deposit.
Sub Main
'Determine the number of Pits in the deposit
Const lTOPREC = 1 'The Top record number is always #1
Dim lNumPits As Long
'Pit is at Level 1, underneath the Top record
lNumPits = GetNumChildren(lTOPREC) 'Number of Pits
Print "There are ", lNumPits, " pits in the deposit."
End Sub
(2) Get the number of child records for the current record’s parent.
Sub Main
Dim lParentRec As Long
Dim lNumChildren As Long
lParentRec = GetRecNum(UP) 'Record number of Parent
lNumChildren = GetNumChildren(lParentRec) 'Number of children
Print "Record Number ", lParentRec, " has ", lNumChildren, " children"
End Sub
RELATED FUNCTIONS
GetRecNum, GetRecNumAtLevel, IsValidRecNum
GetNumFields
DESCRIPTION
Returns the number of Fields in the specified database.
GetNumRecords
DESCRIPTION
Returns the number of lowest level, upper level or sibling records for the specified record in the
database.
ARGUMENTS
Type of Records This argument is used to define what types of records should be
included in the record count. It is passed by value as a long data
type.
It may be set to one of the following values:
Values Description
0 If the type of records is set to zero, the function will return the total number of
lowest level records in the specified database. Note that lowest level records
are those that do not have any children.
The function will return the same value, regardless of whether a record number
is supplied to the function, and regardless of its value if it is supplied.
1 If the type of records is set to one, the function will return the number of lowest
level records underneath the specified record number in the specified database.
If the record number is not supplied, the function will return a value of zero.
2 If the type of records is set to two, the function will return the total number of
upper level records in the specified database. Note that upper level records are
those that have children. The record called Top is also counted as an upper
level record if it has children.
The function will return the same value, regardless of whether a record number
is supplied to the function, and regardless of its value if it is supplied.
3 If the type of records is set to three, the function will return the number of
records at the same level as the specified record number in the specified
database, regardless of the parents.
If the record number is not supplied, the function will return a value of zero.
Database Name This argument defines the database in which to perform the record
count. It is passed by reference as a variant data type.
If the Database Name is an empty string, then the function will use
the database over which the XCM is being run. The options listed
below can also be passed into the function as the Database Name.
Options Description
ACTIVE_MAIN The main database.
ACTIVE_CALENDAR The active calendar database.
VALUES RETURNED
The function returns the number of records as defined by the first argument, namely Type of Records.
The number of records is returned as a long data type.
If the Type of Records is set to any value other than those listed above, the function will return a value
of zero.
If the specified database does not exist in the current XPAC model, the function will return an error
message to indicate this.
If the specified record number does not exist and the Type of Records is set to either one or three, the
function will return a value of zero.
EXAMPLES
(1) Find out how many records there are in the main database.
Sub Main
Dim lLowRecs As Long
Dim lUppRecs As Long
Dim lTotRecs As Long
Dim sMsg As String
'Find out how many records there are in the main database.
lLowRecs = GetNumRecords(0, "Main")
lUppRecs = GetNumRecords(2, "Main")
lTotRecs = lLowRecs + lUppRecs
sMsg = "Total Number of Upper and Lower Level Records"
Call MsgBox(lTotRecs, MB_OK, sMsg)
End Sub
(2) Find out how many blocks there are in each area of a deposit.
Sub Main
Dim lArea As Long
Dim lAreaRecNum As Long
Dim lNumBlks As Long
'Find out how many mining blocks there are in each area.
For lArea = 1 to 5
lAreaRecNum = GetRecFromPilDB("Main", lArea)
(3) Find out how many records there are at a particular level of the database.
Sub Main
Dim lFirstQuarter As Long
Dim lNumQuarters As Long
'Find out how many Quarters there are in the calendar
If (IsFirstInRange()) Then
'Quarter is at level 2 of the database.
lFirstQuarter = GetRecFromPilDB("Detailed Calendar", 1, 1)
lNumQuarters = GetNumRecords(3, "Detailed Calendar", lFirstQuarter)
Print "The Detailed Calendar has " & lNumQuarters & " quarters."
End If
End Sub
RELATED FUNCTIONS
GetNumChildren, GetDatabaseName, GetRecNum, GetRecNumAtLevel,
GetOutputPathNoOfSteps
GetOutputPathNoOfSteps
DESCRIPTION
Returns the number of steps in the output path for the specified resource. The steps include productive
steps, non-productive steps, end of period markers and end of schedule markers.
A database range name can be specified to obtain the number of output path steps within that range.
This step count will also include end of period markers and end of schedule markers.
ARGUMENTS
Scenario Name Since the same resource can be assigned to multiple scenarios, the
scenario name must be specified to identify the required output path
for the resource. The scenario name is passed to the function by
value as a string data type.
ResourceName The resource name defines which output path, within the specified
scenario, to interrogate for this function. The resource name is
passed to the function by value as a string data type.
Range Name The range name is an optional argument. It is passed to the function
by value as a string data type.
If a range name is not passed to the function, then the step count will
include:
• productive steps;
• non-productive steps;
VALUES RETURNED
The function returns the number of steps within the specified range in the output path as a long data
type.
The function will return a value of –1 in the following circumstances:
• if the specified scenario name does not exist in the current project; or
• if the specified resource name does not exist in the scenario.
The range name is an optional argument and it has the following affect on the return value
of the function:
• If a range name is not passed to the function, then the step count will include all types of steps in
the output path.
• If a range name is passed to the function, then the step count will include those productive steps
that are within the database range, the end of period markers and the end of schedule markers.
Non-productive steps will not be included.
• If the specified range name does not exist in the main database, then the function will return the
total number of end of period and end of schedule steps.
The status of the schedule also affects the return values for the function.
• If the schedule needs to be re-calculated (ie. the output path is red), then the function will
interrogate the output path as it currently stands.
• If the schedule has not been calculated at all, then there will be no steps in the output path and the
function will return a value of zero.
EXAMPLES
(1) Display the number of steps in an output path.
Sub Main
Const sSCENARIO = "3 Month Plan"
Const sRESOURCE = "Continuous Miner"
Dim lOutSteps As Long
'Print the number of steps in the output path for the continuous miner.
lOutSteps = GetOutputPathNoOfSteps(sSCENARIO, sRESOURCE)
Print "Number of Steps for " & sRESOURCE & " is " & lOutSteps
End Sub
(2) Find out whether a resource schedules records in a particular area of the deposit.
Sub Main
Const sSCENARIO = "Yr 1 Budget"
Const sRESOURCE = "Electric Rope Shovel"
Dim lPit4Steps As Long
Dim lEOPSteps As Long
'No of steps from Pit 4 (incl end of period and end of schedule markers).
lPit4Steps = GetOutputPathNoOfSteps(sSCENARIO, sRESOURCE, "Pit4")
'No of end of period and end of schedule markers (using empty db range).
lEOPSteps = GetOutputPathNoOfSteps(sSCENARIO, sRESOURCE, "EmptyRange")
'Are any steps from Pit 4 in the output path?
If (lPit4Steps > lEOPSteps) Then Print sRESOURCE & " schedules Pit 4."
End Sub
RELATED FUNCTIONS
GetOutputStep, GetOutputRange, GetInputPathNoOfSteps
GetOutputRange
GetOutputRange
Gets the range of output path steps associated with a given input path step. The output path is specified
via the given scenario and resource names. The input step number is specified in InputStep. The first
step in the output path associated with this input path is returned in the parameter FirstOutputStep. The
last step in the output path associated with this input path is returned in the parameter LastOutputStep.
Returns the number of steps in the output range or -1 on failure. Will return zero (0) if the input path
and output paths exist but there are no steps in the output path associated with the input step. In the
case of an empty range (ie. a return value less than 1) then the FirstOutputStep will be set to zero (0)
and the LastOutputStep will be set to minus one (-1). In the case of an output range containing exactly
one step then the FirstOutputStep and the LastOutputStep will be the same.
RELATED FUNCTIONS
GetInputPathNoOfSteps, GetOutputPathNoOfSteps, GetInputStep, GetOutputStep,
GetOutputRangeForRecord
GetOutputRangeForPeriod
Gets the range of output path steps associated with a given period. The output path is specified via the
given scenario and resource names. The first step in the output path associated with this period is
returned in the parameter FirstOutputStep. The last step in the output path associated with this period is
returned in the parameter LastOutputStep. Note: The range returned will include all steps associated
with a given period and so will also contain any End-of-Period (StepType = PE_EOP) markers etc.
which apply to that period.
Returns the number of steps in the output range or -1 on failure. Will return zero (0) if the output path
exists but there are no steps in the output path associated with the period. In the case of an empty range
(ie. a return value less than 1) then the FirstOutputStep will be set to zero (0) and the LastOutputStep
will be set to minus one (-1). In the case of an output range containing exactly one step then the
FirstOutputStep and the LastOutputStep will be the same.
RELATED FUNCTIONS
GetInputPathNoOfSteps, GetOutputPathNoOfSteps, GetInputStep, GetOutputStep, GetOutputRange,
GetRecNumFromPeriod, GetPeriodFromRecNum
GetOutputRangeForRecord
Given the Scenario, Resource, Record and Activity the First and Last Step numbers are returned. The
function returns true if the step exists for the nominated resource’s output path.
GetOutputStep
This method should be avoided for performance reasons. The recommended way of traversing the
output path is by using GetFirstOutputStep and GetNextOutputStep.
Gets the details for step number Step from the output path for the given scenario and resource and
places them in the structure referenced by OutStep. The structure OutputPathStep is defined as follows:
Type OutputPathStep
InputStepNo As Long ' step number in the input path from which this step was generated
StepType As Long ' PE_PROD, PE_NONPROD, PE_ZEROPROD etc.
TaskId As Long ' the record number for productive step, 0 otherwise
Activity As Integer ' 1-100 for productive activity, >= 101 for delay
EnteredDelay As Double ' in Days - undefined for productive steps (StepType = PE_PROD)
EnteredPct As Double ' undefined for non-productive steps (StepType = PE_NONPROD)
ReleasedPct As Double ' undefined for non-productive steps (StepType = PE_NONPROD)
NextActivity As Integer ' the next activity number
ActualDelay As Double ' the actual delay in days
InitialPct As Double '
ActualPct As Double ' actual percent processed by the activity in this step
RemainingPct As Double ' pecent remaining after this step
Period As Integer ' the number of the period that this output step occurred in
StartDate As Date ' the starting date/time of this output step
FinishDate As Date ' the ending date/time of this output step
CalendarTime As Double ' duration of this step in calendar days
OperatingTime As Double ' actual operatiing time for this step in days
WorkTime As Double ' actual working time for this step in days
EnteredProductionRate As Double ' the desired production rate for this step
ActualProductionRate As Double ' the achieved production rate for this step
NumberOfItems As Double '
ActualQuantity As Double '
DestinatonSP As Double ' the Stock pile name
Progress As Double '
Info As String*30
FleetItem As Integer '
ResourceName As String*30 ' Name of the Resource
DestinationFilledPct As Double '
DestinationReleasedPct As Double '
InitialDestinationFilledPct As Double '
DestinationId As Long '
End Type
Returns true on success or false on failure. On failure, OutStep will retain it original values (or remain
un-initialised). Percentages will be in that range of 0 to 1.
The StepType can have one of the following values
PE_PROD ' Productive Step - Uses Percentage
PE_NONPROD ' Non Productive Step - Uses TimeSpan
PE_ZEROPROD ' Zero Production Step - Uses TimeSpan
PE_ ROFF_NOP ' Rostered Off Time – Non Operating - Uses TimeSpan
PE_ ROFF_OP ' Rostered Off Time – Operating - Uses TimeSpan
PE_EXTOP ' Extended Operation - Uses Percentage
PE_EOP ' End of Period - N/A
PE_EOS ' End of Schedule - N/A
RELATED FUNCTIONS
GetOutputPathNoOfSteps, GetOutputRange, GetOutputRangeForPeriod
For Example
' This subroutine has the following purpose
'-----------------------------------
Sub Main '
Dim sResName(2) As String ' Array of Resource Names
Dim lResNo As Long ' Resource Loop Counter
Dim lNumOutSteps As Long ' Number of Steps in current Output Path
Dim lStep As Long ' Current Step Number
Dim objOutStep As OutputPathStep ' Current Output Step Details
sResName(1) = "DRAGLINE" ' Assign Dragline
sResName(2) = "FLEETFEL" ' Assign Fleet Front End Loaders
For lResNo = 1 To 2 ' Loop through each Resource
'-----------------------------------
' Get Number of Steps for this resource
'-----------------------------------
lNumOutSteps = GetOutputPathNoOfSteps( "Scenario A", sResName(lResNo) )
For lStep = 1 To lNumOutSteps ' Loop through each step for this resource
'-----------------------------------
' Get the Details for this step
'-----------------------------------
GetOutputStep "Scenario A", sResName(lResNo), lStep, objOutStep
'-----------------------------------
' Process if Productive (ie a record mined)
'-----------------------------------
If (objOutStep.StepType = PE_PROD And objOutStep.TaskId > 0) Then
'-----------------------------------
' Write Start Date to Database
'-----------------------------------
Call GoRec( objOutStep.TaskId )
R(rStartDate) = objOutStep.StartDate
End If ' End mined construct
Next lStep ' Next Step in Output Path
Next lResNo ' Next Resource
End Sub ' End routine
'End of XCM
GetParam
DESCRIPTION
Returns a value from the active parameters database for the specified data field number and record
number.
The required parameters database should be made active before the XCM is run. This is done by
selecting View | Parameters from the menu, then highlighting the required parameters database in the
list and clicking on the Activate button.
Note that it is recommended that the function DbReadValue be used in preference to GetParam, as it
allows you to define the name of the parameters database, rather than rely on the correct parameters
database being active.
ARGUMENTS
Data Field Number This argument is the data field number in the active parameters
database, from which you want to read a value. It is passed by
value as an integer data type. The data field code cannot be
used in this argument.
Record Number The record number defines the record from which to read a
value in the active parameters database. It is passed by value
as an Long data type.
VALUES RETURNED
This function returns a double data type.
If the specified data field is a numeric type of field (ie. Additive, Weighted Average, Average, Date,
Record, Min, Max, Difference, Ratio, Product, Sum) the value returned is the numeric value from the
active parameters database record.
If the specified data field is a classified field, the value returned is the number of the classification. The
number for each classification can be viewed by clicking on the classified field for a record and
selecting Classification from the right click menu.
If the specified data field is a note, the value returned is zero.
If the data field number does not exist in the active parameter database, then the function will return a
value of zero.
If the record number does not exist in the active parameter database, then the function will return an
error message to indicate this.
EXAMPLES
(1) Read a value from the active parameters database using the record number.
Sub Main
Dim lParFld As Long
Dim lParRec As Long
'Read the default waste density from the "By Pit and Area"
'parameters database
Const sParDBName = "By Pit and Area"
lParFld = GetRowNumFromCode(sParDBName, "pDef_Wst_RD")
lParRec = GetRecNumFromPath(sPitName & "\" & sAreaName, sParDBName)
M(mIS_Wst_RD) = GetParam(lParFld, lParRec)
End Sub
RELATED FUNCTIONS
SetParam, GetParamFromPil, SetParamFromPil, DbReadValue
GetParamFromPil
DESCRIPTION
Returns a value from the active parameters database for the specified data field number and for the
record defined by the position in level numbers at each level.
The required parameters database should be made active before the XCM is run. This is done by
selecting View | Parameters from the menu, then highlighting the required parameters database in the
list and clicking on the Activate button.
Note that it is recommended that the functions DbReadValue and GetRecFromPilDB be used in
preference to GetParamFromPil, as they allow you to define the name of the parameters database,
rather than rely on the correct parameters database being active.
ARGUMENTS
Data Field Number This argument is the data field number in the active parameters
database, from which you want to read a value. It is passed by
value as an integer data type. The data field code cannot be
used in this argument.
Level 1 Pil The Level 1 Pil represents the Pil number at level 1 for the
required record in the active parameters database. It is passed
by value as an integer data type. This argument is not
optional.
Level 2 Pil The Level 2 Pil represents the Pil number at level 2 for the
required record. It is passed by value as an integer data type.
This argument is optional.
Level 3 Pil etc The remaining arguments represent the Pil number at level n
for the required record. They are passed by value as integer
data types. These arguments are optional and they can only be
specified if the preceding argument has been included.
VALUES RETURNED
This function returns a double data type.
If the specified data field is a numeric type of field (ie. Additive, Weighted Average, Average, Date,
Record, Min, Max, Difference, Ratio, Product, Sum) the value returned is the numeric value from the
active parameters database record.
If the specified data field is a classified field, the value returned is the number of the classification. The
number for each classification can be viewed by clicking on the classified field for a record and
selecting Classification from the right click menu.
If the specified data field is a note, the value returned is zero.
If the data field number does not exist in the active parameter database, then the function will return a
value of zero.
If the record defined by the position in level numbers does not exist in the active parameter database,
then the function will return an error message to indicate this.
EXAMPLES
(1) Read a value from the active parameters database using pil numbers.
Sub Main
Dim lParFld As Long
'Read the haul distance from the current strip to the crusher
'from the "Pit and Strip" parameters database
Const sParDBName = "Pit and Strip"
lParFld = GetRowNumFromCode(sParDBName, "pHaul_Csh")
M(mEqp_Haul_Csh) = GetParamFromPil(lParFld, lPitNum, lStripNum)
End Sub
RELATED FUNCTIONS
SetParamFromPil, GetParam, SetParam, DbReadValue
GetPctThroughPeriod
VALUES RETURNED
Long value will be returned in the range of 0 to 1.
REMARKS
This function is available only in the User Processing Scripts.
GetPeriodDuration Function
DESCRIPTION
Returns the length of a calendar period in days. The calendar period is defined by its period number
and the calendar database name. The period duration is calculated using the start date for each period.
The duration of each period is the number of days between the start date for the current period and the
start date for the following period.
ARGUMENTS
Period Number The period number is passed to the function by value as a long data type.
Period numbers are assigned to all lowest level calendar records, in
database order. Period one is always the first lowest level record in the
database. The first period scheduled does not have to be period number
one.
The period number is an optional argument, but only if the function is
being used in a User Processing script. For all other types of XCMs, the
period number must be passed into the function. When the period number
is not supplied, it is assumed to be the current period. This is the period
number that is returned by the GetCurrentPeriod function.
Calendar The calendar database name is used to look for the specified period
Start Date Field The start date field number is the number of the data field containing the
Number period start dates. It is passed by value as an integer field type.
The start date field number is an optional argument. If it is not passed into
the function, then it is assumed to be the first date type field in the
specified calendar database.
VALUES RETURNED
This function returns the period duration in days as a double data type. The period duration is the
number of days between the start date for the current period and the start date for the following period.
For the last time period in the calendar database, the period duration cannot be calculated. It is reported
as the same number of days as the period duration for the second last period.
If the period number does not exist in the specified calendar database, then the function returns a value
of –1 for the period duration.
If the calendar database does not exist, or if the specified start date field number is not a date field type,
then the function reports an error.
EXAMPLES
(1) Use the period duration to calculate the target for each period in the calendar database.
Sub Main
'This XCM is run over the calendar database
Dim lPerNum As Long
Dim dPerDur As Double
Dim sCalName As String
Const dDAILYTARGET = 30000
'Calculate the target for each period using the period duration
lPerNum = GetPeriodFromRecNum(GetRecNum(CURRENT))
sCalName = GetDatabaseName()
dPerDur = GetPeriodDuration(lPerNum, sCalName)
C(cPer_Targ) = dPerDur * dDAILYTARGET
End Sub
(2) Display the period duration during the schedule using a User Processing XCM.
Sub Main
Dim sMsg As String
'This XCM is a "Pre Period" User Processing XCM
sMsg = "The Next Period to be scheduled is " & GetPeriodDuration()
sMsg = sMsg & " days in length."
Print sMsg
End Sub
RELATED FUNCTIONS
DbReadValue, GetFieldInfo, GetCurrentPeriod, GetPeriodFromRecNum
GetPeriodFromRecNum
DESCRIPTION
Returns the period number for the specified record number in the calendar database. If no calendar
database is specified, then the active calendar database is assumed.
Period numbers are assigned to all lowest level calendar records, in database order. Period one is
always the first lowest level record in the database. The first period scheduled does not have to be
period number one.
ARGUMENTS
Record Number The record number is from the specified database. It is passed by
value as a long data type.
Note that the record pointers, such as NXT, UP, etc, cannot be
used in this argument.
VALUES RETURNED
This function returns the period number for the specified calendar period. It is returned as a long data
type.
If the specified record number does not exist in the calendar database, the function will return a value
of –1.
EXAMPLES
(1) Find the period number for a specified calendar record.
Sub Main
Const sCALNAME = "Weekly Calendar"
Dim lPerRec As Long
Dim lPerNum As Long
'Get the period number for the first week of December in 2002
lPerRec = GetRecFromPilDB(sCALNAME, 2002, 12, 1)
lPerNum = GetPeriodFromRecNum(lPerRec, sCALNAME)
Print "First Week of December, 2002 is Period Number " & lPerNum
End Sub
(2) Find out how many scheduled steps there are in each period, given the period number.
Sub Main
Dim lYear As Long
Dim sCalName As String
Dim lPerRec As Long
Dim lPerNum As Long
RELATED FUNCTIONS
GetRecNumFromPeriod, GetRecNameFromPeriod, GetCalendarNameFromScenario,
GetOutputRangeForPeriod
GetPeriodRangeForResource
Given a Scenario and Resource this function returns the range of the periods that the resource has been
scheduled. The function returns True if successful. The function fails if the Scenario or resource do
not exist.
GetPeriodRangeForScenario
Given a Scenario this function returns the range of the periods that the Scenario has been scheduled.
The function returns True if successful. The function fails if the Scenario does not exist or there are no
steps in any of the scenario’s output paths.
' Function GetPeriodRangeForScenario (ScenarioName As String, ByRef FirstPeriod As
' Long, ByRef LastPeriod As Long ) As Boolean
Sub Main ' Start Main Routine
Dim sActScen As String ' Declare scenario
Dim lFstPeriod As Long ' Declare First period
Dim lLstPeriod As Long ' Declare Last period
Dim bPeriodRng As Boolean ' Declare period range
sActScen = GetActiveScenarioName () ' Return active scenario
bPeriodRng = GetPeriodRangeForScenario(sActScen,lFstPeriod,lLstPeriod)
MsgBox bPeriodRng,1,"Period Range " &sActScen ' Display Period Range
MsgBox lFstPeriod,1,"First Period" ' Display First Period
MsgBox lLstPeriod,1,"Last Period" ' Display Last Period
End Sub ' End Main Routine
' End of XCM
GetPilFromPositionName
DESCRIPTION
Returns the Position In Level (Pil) number for the specified position name by looking up the level in
the position table.
ARGUMENTS
Level Number The Level Number is an optional argument. It can only be specified
if the Position Name is specified. The Level Number is passed by
value as a long data type.
If no Level Number is specified, or if the pre-defined value
THISLEVEL is used, then the Level Number of the current record
will be assumed.
If a Database Name is specified, then THISLEVEL should not be
used for the Level Number as the function will return an error
message, a value of –1 and then the XCM will abort.
Options Description
ACTIVE_MAIN The main database.
ACTIVE_CALENDAR The active calendar database.
ACTIVE_RESULTS The active results database.
VALUES RETURNED
The function will return the position in level number as a long data type.
If the specified level in the database does not have a Position Table, or if the Position Table is not
enabled for that level, then the function will return –1.
If a Database Name is specified, and THISLEVEL is used for the Level Number, the function will
return an error message, a value of –1 and then the XCM will abort.
EXAMPLES
The following examples assume that the main database hierarchy is Pit\Stage\Material and that the
active calendar database hierarchy is Year\Quarter.
(1) Find the position in level (pil) number for the material called High Grade.
Sub Main
Dim lMatPil As Long
'Find the Pil number for the Material called High Grade
lMatPil = GetPilFromPositionName("High Grade", 3, "Main")
Print lMatPil
End Sub
(2) Find the pil number of the Year 2001 in the active calendar.
Sub Main
Dim lYearPil As Long
'Find the pil number of the Year 2001 in the active calendar
lYearPil = GetPilFromPositionName("2001", 1, ACTIVE_CALENDAR)
Print lYearPil
End Sub
RELATED FUNCTIONS
GetPositionNameFromPil, GetRecName, GetApil
GetPilFromPositionNameEx
DESCRIPTION
Returns the Position In Level (Pil) number for the specified position name by looking up the level in
the position table. This version allows you to specify Level 0 as the Level Number, please note that
you cannot use the THIS_LEVEL Keyword with this function.
ARGUMENTS
Level Number The Level Number is an optional argument. It can only be specified
if the Position Name is specified. The Level Number is passed by
value as a long data type.
If no Level Number is specified, the default value will be Level 0.
Options Description
ACTIVE_MAIN The main database.
ACTIVE_CALENDAR The active calendar database.
ACTIVE_RESULTS The active results database.
VALUES RETURNED
The function will return the position in level number as a long data type.
If the specified level in the database does not have a Position Table, or if the Position Table is not
enabled for that level, then the function will return –1.
EXAMPLES
The following examples assume that the main database hierarchy is Pit\Stage\Material and that the
active calendar database hierarchy is Year\Quarter.
(1) Find the position in level (pil) number for the material called High Grade.
Sub Main
Dim lMatPil As Long
'Find the Pil number for the Material called High Grade
lMatPil = GetPilFromPositionName("High Grade", 3, "Main")
Print lMatPil
End Sub
(2) Find the pil number of the Year 2001 in the active calendar.
Sub Main
Dim lYearPil As Long
'Find the pil number of the Year 2001 in the active calendar
lYearPil = GetPilFromPositionName("2001", 1, ACTIVE_CALENDAR)
Print lYearPil
End Sub
RELATED FUNCTIONS
GetPositionNameFromPilEx, GetRecName, GetApil
GetPolygonArea
Calculates the area of a polygon. Will work for convex or concave polygons, but doesn’t work for
polygons that self intersect/cross.
Returns the absolute area if successful. Returns 0.0 on error.
RELATED FUNCTIONS
LoadPolygon, SavePolygon, GetPolygonCount, GetPolygonVertexCount
GetPolygonAreaXY
Note – This function has been superseded by the GetPolygonArea function.
Calculates the 2D area of a polygon. If RecNum is equal to 0, CURRENT or is not given then the
polygon associated with the current record in the main database will be assumed. If Activity is equal to
0, DEFAULT_ACTIVITY or is not given then the default activity will be assumed. Otherwise the
polygon associated with the given activity number will be assumed. PolygonIndex is the 1-based index
of the use. Will work for convex or concave polygons, but doesn’t work for polygons that self
intersect/cross.
Returns the absolute area if successful. Returns 0.0 on error.
Sub Main ' Start Main Routine
Dim lStart As Long ' Declare record number of start
Dim dPolArea As Double ' Declare polygon area
lStart = GetRecNum(CURRENT) ' Return Current Record number
dPolArea = GetPolygonAreaXY(lStart) ' Return Current polygon area
MsgBox " Polygon Area = " & dPolArea ' Display Polygon Area
End Sub ' End MAIN Subroutine
'End of XCM
RELATED FUNCTIONS
GetPolygonVertexCount, GetPolygonVertexXYZ, GetPolygonCentroidXY, InPoly, InPolyRec
GetPolygonCentroid
Calculates the centroid of a polygon. In the event that the polygon has less than 3 points, or it has zero
area, then the simple average of the given points is calculated.
RELATED FUNCTIONS
LoadPolygon, SavePolygon, GetPolygonCount, GetPolygonVertexCount
GetPolygonCentroidXY
Note – This function has been superseded by the GetPolygonCentroid function.
Calculates the 2D centroid of a polygon. In the event that the polygon has less than 3 points, or it has
zero area, then the simple average of the given points is calculated. If RecNum is equal to 0,
CURRENT or is not given then the polygon associated with the current record in the main database
will be assumed. If Activity is equal to 0, DEFAULT_ACTIVITY or is not given then the default
activity will be assumed. Otherwise the polygon associated with the given activity number will be
assumed. PolygonIndex is the 1-based index of the use.
Returns true if the successfully got the centroid. Returns false on error.
Sub Main ' Start Main Routine
Dim lStart As Long ' Declare record number of start
Dim dStartE As Double ' Declare start easting
Dim dStartN As Double ' Declare start northing
Dim dBool As Boolean ' Declare centrod boolean test
lStart = GetRecNum(CURRENT) ' Return current record number
dBool = GetPolygonCentroidXY (dStartE, dStartN, lStart) ' Returns Start centroid
details for 2nd block'
If (dBool = True) Then ' If the polygon record exists
MsgBox "Centroid Easting = " & dStartE ' Show Easting Coordinate
MsgBox "Centroid Northing = " & dStartN ' Show Northing Coordinate
End If ' End existence construct
End Sub ' End MAIN Subroutine
RELATED FUNCTIONS
GetPolygonVertexCount, GetPolygonVertexXYZ, GetPolygonCentroidXY, InPoly, InPolyRec
GetPolygonCount
Get a count of the number of sub-polygons for the given record. Gets the count for the given RecNum.
If RecNum is equal to 0, CURRENT or is not given then the polygons associated with the current
record in the main database will be assumed. If Activity is equal to 0, DEFAULT_ACTIVITY or is
not given then the default activity will be assumed. Otherwise the polygons associated with the given
activity number will be assumed.
Returns the number of polygons for the record, -1 on failure. Will return zero (0) if the record exists but
there are no polygons.
RELATED FUNCTIONS
LoadPolygon, SavePolygon, GetPolygonVertexCount
GetPolygonVertexCount
Get a count of the number of vertices for the given record. Gets the count for the given RecNum. If
RecNum is equal to 0, CURRENT or is not given then the polygon associated with the current record
in the main database will be assumed. If Activity is equal to 0, DEFAULT_ACTIVITY or is not given
then the default activity will be assumed. Otherwise the polygon associated with the given activity
number will be assumed. PolygonIndex is the 1-based sub-polygon index of the use. If it is 0 or not
specified, the total number of vertices in all sub-polygons (including end-of-sequence markers) will be
returned.
Returns the number of vertices in the polygon -1 on failure. Will return zero (0) if the record exists but
there are no vertices in the polygon.
RELATED FUNCTIONS
LoadPolygon, SavePolygon, GetPolygonCount
GetPolygonVertexXYZ
Note – This function has been superseded by the LoadPolygon function.
Get the XYZ coordinates of a given vertex within a polygon. Gets the coordinates for the given vertex
number. Should ensure that this value is in the range of 1 to the value returned from
GetPolygonVertexCount. The coordinates are returned in the parameters X, Y and Z. Gets the vertex
for the given RecNum. If RecNum is equal to 0, CURRENT or is not given then the polygon
associated with the current record in the main database will be assumed. If Activity is equal to 0,
DEFAULT_ACTIVITY or is not given then the default activity will be assumed. Otherwise the
polygon associated with the given activity number will be assumed. PolygonIndex is the 1-based index
of the use.
Returns true if it successfully got the vertex. Returns false on an error.
RELATED FUNCTIONS
GetPolygonVertexCount, GetPolygonCentroidXY, GetPolygonAreaXY, GetActivityNum, InPoly,
InPolyRec
For Example See Inpoly Function
GetPositionNameFromPil
DESCRIPTION
Returns the position name for the specified Position In Level (Pil) number by looking up the level in
the position table.
ARGUMENTS
Level Number The Level Number is an optional argument. It can only be specified
if the Pil Number is specified. The Level Number is passed by
value as a long data type.
If no Level Number is specified, or if the pre-defined value
THISLEVEL is used, then the Level Number of the current record
will be assumed.
If a Database Name is specified, then THISLEVEL should not be
used for the Level Number as the function will return an empty
string.
Options Description
ACTIVE_MAIN The main database.
ACTIVE_CALENDAR The active calendar database.
ACTIVE_RESULTS The active results database.
VALUES RETURNED
The function will return the position name as a string data type.
If the specified level in the database does not have a Position Table, or if the Position Table is not
enabled for that level, then the function will return an empty string.
If a Database Name is specified, and THISAPIL is used for the Pil Number, the function will return an
empty string.
If a Database Name is specified, and THISLEVEL is used for the Level Number, the function will
return an empty string.
EXAMPLES
The following examples assume that the main database hierarchy is Pit\Stage\Material and that the
active calendar database hierarchy is Year\Quarter.
(1) Find the name of the material in position 7.
Sub Main
Dim sMatName As String
'Find the name of the Material in position 7
sMatName = GetPositionNameFromPil(7, 3, "Main")
Print sMatName
End Sub
(2) Find the name of the first year in the active calendar.
Sub Main
Dim sFirstYear As String
'Find the name of the First Year in the active calendar
sFirstYear = GetPositionNameFromPil(1, 1, ACTIVE_CALENDAR)
Print sFirstYear
End Sub
RELATED FUNCTIONS
GetPilFromPositionName, GetRecName, GetApil
GetPositionNameFromPilEx
DESCRIPTION
Returns the position name for the specified Position In Level (Pil) number by looking up the level in
the position table. This version allows you to specify Level 0. Please note you cannot use the
THIS_LEVEL keyword with this function.
ARGUMENTS
Level Number The Level Number is an optional argument. It can only be specified
if the Pil Number is specified. The Level Number is passed by
value as a long data type.
If no Level Number is specified, the default level will be level 0.
Options Description
ACTIVE_MAIN The main database.
ACTIVE_CALENDAR The active calendar database.
ACTIVE_RESULTS The active results database.
VALUES RETURNED
The function will return the position name as a string data type.
If the specified level in the database does not have a Position Table, or if the Position Table is not
enabled for that level, then the function will return an empty string.
If a Database Name is specified, and THISAPIL is used for the Pil Number, the function will return an
empty string.
EXAMPLES
The following examples assume that the main database hierarchy is Pit\Stage\Material and that the
active calendar database hierarchy is Year\Quarter.
(1) Find the name of the material in position 7.
Sub Main
Dim sMatName As String
'Find the name of the Material in position 7
sMatName = GetPositionNameFromPilEx(7, 3, "Main")
Print sMatName
End Sub
(2) Find the name of the first year in the active calendar.
Sub Main
Dim sFirstYear As String
'Find the name of the First Year in the active calendar
sFirstYear = GetPositionNameFromPilEx(1, 1, ACTIVE_CALENDAR)
Print sFirstYear
End Sub
RELATED FUNCTIONS
GetPilFromPositionNameEx, GetRecName, GetApil
GetPredecessor
This function returns the record number and activity of the predecessor in the position indexed by Pos.
The function returns the Successors activity number.
Example
Dim lRecordPredecessor As Long
Dim iActivityOfPredecessor As Integer
Dim iFromActivity As Integer
Dim i As Integer
For i = 0 To iNumOfPredecessor -1
iFromActivity = GetPredecessor( i, lRecordPredecessor, iActivityOfPredecessor)
…
Next i
GetPSItem
DESCRIPTION
Returns information about records that are listed in the Preschedule table that is attached to the
specified scenario, given their step number within the list and the activity number. The information
that is returned includes the record number, the percentage released and the percentage mined.
Note that this function obeys the precedence rules but not dependencies, when reporting released
percentages.
ARGUMENTS
Scenario Name Each scenario can have a different Preschedule table attached to it,
so the scenario name must be specified in this function to define
which Preschedule table to interrogate. The scenario name is
passed to the function by value as a string data type.
Step Number The step number defines the position within the Preschedule table.
The first record that is added to the Preschedule table is positioned
in step number one and as each new record is added, they are
positioned in the next available step. The records always remain
in the order in which they were created, as opposed to the database
order.
The step number is passed to the function by value as a long data
type.
Activity Number This argument defines the activity number in the specified step for
which information is sought. It is passed to the function by value
as a long data type.
Options Description
TaskID The TaskID is used to store the record number from the specified
step in the Preschedule table. This element is a long data type.
If a valid step number is passed into the function, then a valid record
number or task ID may be returned. It will always be a lowest level
record number.
ReleasedPct The ReleasedPct stores the percentage of the specified activity in
the record that is released in the Preschedule table. This element is
a double data type.
The user sets the released percentage for an activity, subject to
some basic rules.
• Any activity that does not have any precedences will always be
100% released. This cannot be changed.
• Dependency rules are not followed in the Preschedule table.
• The percentage of an activity that is released cannot exceed the
percentage mined for any activities that are precedences.
• The percentage of an activity that is released cannot be less
than the percentage of that same activity that is mined.
MinedPct The MinedPct stores the percentage of the specified activity in the
record that is mined in the Preschedule Table. This element is a
double data type.
RawReleasedPct Stores the released percentage unadjusted by the zero test data
field.
RawMinedPct Stores the mined percentage unadjusted by the zero test data field.
ReleasedPct Both the released percent and mined percent will return values
and MinedPct between 0 and 1, unless there is an error.
If the released percent or mined percent return a value of –1, this
indicates that the specified activity and record were not available
for scheduling after the initial mine status was processed. This
may happen in the following situations:
• When the specified activity is not active in the current scenario;
or
• If the zero test data field for the specified activity and record has
a value of zero.
VALUES RETURNED
This function returns a boolean data type which indicates whether the requested Preschedule step was
found.
If the requested Preschedule step was found, then the function will return a True value.
If the any of the arguments passed into the function are invalid, then the function will return a range of
values, as indicated below.
• If the scenario name does not exist in the current project, then the function will return a False
value.
• If the specified scenario name does not have a Preschedule table attached to it, then the
function will return a False value.
• If the step number is less than one or greater than the number of steps in the Preschedule
table (this can be obtained using the function GetPSItemCount), then the function will return a
False value.
• If the activity number is not a valid productive activity number in the current project, then
the function will return a False value.
• If the item (the third argument) is not declared as an ItemRemoved type, then the function will
return a True value, however an error message will be displayed indicating that there is a
‘Type mismatch’ and the XCM will then stop.
This function can also return information about the specified step in the preschedule table using the
Item argument. The information returned includes the record number, released percent and mined
percent. The process for reporting this information is described above, with the other details about the
Item argument. The return values for each element of the Item argument are also provided above.
EXAMPLES
(1) Read a specific step from the Preschedule table.
Sub Main
Const sSCENARIO = "Five Year Plan"
Const sACTNAME = "Ore Mining"
Dim lActNum As Long
Dim dPSInfo As ItemRemoved
Dim sRecName As String
Dim sMsg As String
'Read the information for the third step in the Preschedule table.
lActNum = GetActivityNum(sACTNAME)
Call GetPSItem(sSCENARIO, 3, lActNum, dPSInfo)
sRecName = GetRecName(dPSInfo.TaskID, PATHNAME)
sMsg = "Record " & sRecName & ": The " & sACTNAME & " Activity is "
sMsg = sMsg & dPSInfo.ReleasedPct & "% Released and "
sMsg = sMsg & dPSInfo.MinedPct & "% Mined."
Call MsgBox(sMsg, MB_OK, "Preschedule")
End Sub
(2) Find out whether each record is in the Preschedule table for the active scenario.
Sub Main
Const sACTNAME = "Development"
Dim sScenarioName As String
Dim lActNum As Long
Dim lStepNum As Long
Dim dPSInfo As ItemRemoved
Dim sCurrentRec As String
'Read the information for each step in the Preschedule table.
sScenarioName = GetActiveScenarioName()
lActNum = GetActivityNum(sACTNAME)
For lStepNum = 1 to GetPSItemCount()
Call GetPSItem(sScenarioName, lStepNum, lActNum, dPSInfo)
If (dPSInfo.TaskID = GetRecNum(CURRENT)) Then
sCurrentRec = GetRecName(CURRENT, PATHNAME)
Print "Record " & sCurrentRec & " is in the Preschedule."
End If
Next lStepNum
End Sub
RELATED FUNCTIONS
GetPSItemCount, GetMOQItem, GetMOQItemCount, GetMineStatus
GetPSItemCount
GetPSItemCount
DESCRIPTION
Returns the number of steps in the Preschedule table that is attached to the specified scenario. Since a
record can only appear once in a Preschedule table, the number of steps is the same as the number of
records in the Preschedule table.
ARGUMENTS
Scenario Name The scenario name defines which Preschedule table this function
will interrogate. It is passed to the function by value as a string data
type.
VALUES RETURNED
This function returns the number of steps in the specified Preschedule table as a long data type.
If the specified scenario does not have a Preschedule table attached to it, then the function will return a
value of –1.
If the Preschedule table attached to the specified scenario does not contain any steps, then the function
will return a value of zero.
If the specified scenario does not exist, then the function will return a value of –1.
EXAMPLES
(1) In a user processing XCM, notify the user if the Preschedule table attached to the active scenario
contains steps.
Sub Main
Dim sActiveScenario As String
Dim lNumPSSteps As Long
'Display a message if the Preschedule table contains steps
sActiveScenario = GetActiveScenarioName()
lNumPSSteps = GetPSItemCount(sActiveScenario)
If (lNumPSSteps > 0) Then
Print "The Preschedule Table Contains Data – Check the Entries."
End If
End Sub
sActiveScenario = GetActiveScenarioName()
For lStepNum = 1 to GetPSItemCount(GetActiveScenarioName())
Call GetPSItem(sActiveScenario, lStepNum, lActNum, dPSInfo)
If (dPSInfo.TaskID = GetRecNum(CURRENT)) Then
sCurrentRec = GetRecName(CURRENT, PATHNAME)
Print "Record " & sCurrentRec & " is in the Preschedule Table."
End If
Next lStepNum
End Sub
RELATED FUNCTIONS
GetPSItem, GetMOQItem, GetMOQItemCount, GetMineStatus
GetRecFromName
DESCRIPTION
This function should only be used if your model does not contain any Dump or Stockpile records. It
returns the record number of the record identified by the name at each level. This function can be used
to find the record number for upper or lower level records.
ARGUMENTS
Level 1 Name The Level 1 Name represents the record name at level 1 for the
required record. It is passed by value as a string data type.
This argument is not optional.
Level 2 Name The Level 2 Name represents the record name at level 2 for the
required record. It is passed by value as a string data type.
This argument is optional.
Level 3 Name The remaining arguments represent the record name at level n
etc for the required record. They are passed by value as string data
types. These arguments are optional and they can only be
specified if the preceding argument has been included.
VALUES RETURNED
The function will return the record number as a long data type.
If the requested record does not exist, then the function will return –1, but the XCM will not abort.
EXAMPLES
(1) Find the record number for Pit 3, Cutback 1, Bench 210.
Sub Main
Dim lRecNum As Long
'Find the record number for Pit 3, Cutback 1, Bench 210.
lRecNum = GetRecFromName("Pit3", "1", "RL210")
Print lRecNum
End Sub
(2) Use the pre-defined level variables to find the record number for the same block in the next strip.
Sub Main
Dim sNextStrip As Long
Dim lBlkInNextStrip As Long
'Look for the same block in the next strip
sNextStrip = CStr(lStripNum+1)
lBlkInNextStrip = GetRecFromName(sPitName, sNextStrip, sBlkName)
Print lBlkInNextStrip
End Sub
RELATED FUNCTIONS
GetRecFromNameEx, GetRecFromPil, GetRecFromPilEx, GetRecNameAtLevel,
GetRecNumFromPath
GetRecFromNameDB
GetRecFromNameDB
DESCRIPTION
This function returns the record number of the record identified by the name at each level. This
function can be used to find the record number for upper or lower level records.
ARGUMENTS
Level 1 Name The Level 1 Name represents the record name at level 1 for
the required record. It is passed by value as a string data
type. This argument is not optional.
Level 2 Name The Level 2 Name represents the record name at level 2 for
the required record. It is passed by value as a string data
type. This argument is optional.
Level 3 Name The remaining arguments represent the record name at level n
etc for the required record. They are passed by value as string
data types. These arguments are optional and they can only
be specified if the preceding argument has been included.
VALUES RETURNED
The function will return the record number as a long data type.
If the requested record does not exist, then the function will return –1, but the XCM will not abort.
GetRecFromNameDBEx
GetRecFromNameDBEx
DESCRIPTION
This function returns the record number of the record identified by the name at each level. This
function can be used to find the record number for upper or lower level records.
ARGUMENTS
Level 0 Name The Level 0 Name represents the record name at level 0 for
the required record. It is passed by value as a string data
type. This argument is not optional.
Level 1 Name The Level 1 Name represents the record name at level 1 for
the required record. It is passed by value as a string data
type. This argument is optional.
Level 2 Name The Level 2 Name represents the record name at level 2 for
the required record. It is passed by value as a string data
type. This argument is optional.
Level 3 Name The remaining arguments represent the record name at level n
etc for the required record. They are passed by value as string
data types. These arguments are optional and they can only
be specified if the preceding argument has been included.
VALUES RETURNED
The function will return the record number as a long data type.
If the requested record does not exist, then the function will return –1, but the XCM will not abort.
GetRecFromNameEx
DESCRIPTION
Returns the record number of the record identified by the name at each level. This function can be used
to find the record number for upper or lower level records. The difference between this function and
GetRecFromName is that the Level 0 record name must be specified in this function. If your XPAC
model contains Dumps or Stockpiles, then this function must be used (even for Deposit records).
ARGUMENTS
Level 0 Name The Level 0 Name represents the record name at level 0 for the
required record. It is passed by value as a string data type.
This argument is not optional. It may only be set to “Deposit”,
“Dumps” or “Stockpiles”.
Level 1 Name The Level 1 Name represents the record name at level 1 for the
required record. It is passed by value as a string data type.
This argument is not optional.
Level 2 Name The remaining arguments represent the record name at level n
etc for the required record. They are passed by value as string data
types. These arguments are optional and they can only be
specified if the preceding argument has been included.
VALUES RETURNED
The function will return the record number as a long data type.
If the requested record does not exist, then the function will return –1, but the XCM will not abort.
EXAMPLES
(1) Find the record number for a Dump record.
Sub Main
Dim lRecNum As Long
'Find the record number for the Expit dump at RL 170, block 5.
lRecNum = GetRecFromNameEx("Dumps", "Expit", "RL170", "5")
Print lRecNum
End Sub
(2) Use the pre-defined level variables to find the record number for the same block in the next strip.
Sub Main
Dim sNextStrip As Long
Dim lBlkInNextStrip As Long
'Look for the same block in the next strip
sNextStrip = CStr(lStripNum+1)
lBlkInNextStrip = GetRecFromNameEx("Deposit", sPitName, sNextStrip, sBlkName)
Print lBlkInNextStrip
End Sub
RELATED FUNCTIONS
GetRecFromName, GetRecFromPilEx, GetRecNameAtLevel, GetRecNumFromPath
GetRecFromPil
DESCRIPTION
Returns the record number of the record identified by the Position In Level (Pil) numbers. This
function can be used to find the record number for upper or lower level records.
ARGUMENTS
Level 1 Pil The Level 1 Pil represents the Pil number at level 1 for the required
record. It is passed by value as a long data type. This argument is not
optional.
Level 2 Pil The Level 2 Pil represents the Pil number at level 2 for the required
record. It is passed by value as a long data type. This argument is
optional.
Level 3 Pil The remaining arguments represent the Pil number at level n for the
etc required record. They are passed by value as long data types. These
arguments are optional and they can only be specified if the preceding
argument has been included.
VALUES RETURNED
The function will return the record number as a long data type.
If the record defined by the pil numbers does not exist, then the function will return –1, but the XCM
will not abort.
If the pil number for a level, and all of the levels below it, are passed in with a value of zero, then the
function will look for an upper level record.
EXAMPLE
(1) Find the record number for Pit 3, Cutback 1, Bench 210.
Sub Main
Dim lRecNum As Long
'Find the record number for Pit 3, Cutback 1, Bench 210.
lRecNum = GetRecFromPil(3, 1, 210)
Print lRecNum
End Sub
(2) Use the pre-defined level variables to find the record number for the same block in the next strip.
Sub Main
Dim lBlkInNextStrip As Long
'Look for the same block in the next strip
lBlkInNextStrip = GetRecFromPil(lPitNum, lStripNum+1, lBlkNum)
Print lBlkInNextStrip
End Sub
RELATED FUNCTIONS
GetRecFromPilDB, GetRecFromName, GetApil
GetRecFromPilDB
DESCRIPTION
Returns the record number of the record identified by the Position In Level (Pil) numbers, in the
specified database. This function can be used to find the record number for upper or lower level
records.
ARGUMENTS
Database The name of the database from which the record number will be
Name returned. It is passed by reference as a variant data type.
If the Database Name is an empty string, then the function will use
the database over which the XCM is being run.
The options listed below can also be passed into the function as the
Database Name.
Options Description
ACTIVE_MAIN The main database.
ACTIVE_CALENDAR The active calendar database.
ACTIVE_RESULTS The active results database.
Level 1 Pil The Level 1 Pil represents the Pil number at level 1 for the required
record. It is passed by value as a long data type. This argument is
not optional.
Level 2 Pil The Level 2 Pil represents the Pil number at level 2 for the required
record. It is passed by value as a long data type. This argument is
optional.
Level 3 Pil The remaining arguments represent the Pil number at level n for the
etc required record. They are passed by value as long data types. These
arguments are optional and they can only be specified if the
preceding argument has been included.
VALUES RETURNED
The function will return the record number as a long data type.
If the requested record does not exist, then the function will return –1, but the XCM will not abort.
EXAMPLES
(1) Get a record number from the Pit\Bench Parameters database, from within an XCM that is running over
the Main database.
Sub Main
Dim lParamRec As Long
'Find the record number for Pit 5, Bench 440 in the Pit\Bench
'Parameters database
lParamRec = GetRecFromPilDB("Pit\Bench Parameters", 5, 440)
Print lParamRec
End Sub
(2) Get the record number for the First Quarter, 2004 from the active calendar database, from within an
XCM that is running over the Main database.
Sub Main
Dim lPeriodRec As Long
'Find the record number for January, 2004.
lPeriodRec = GetRecFromPilDB(ACTIVE_CALENDAR, 2004, 1)
Print lPeriodRec
End Sub
RELATED FUNCTIONS
GetRecFromPil, GetRecFromName, GetApil
GetRecFromPilEx
DESCRIPTION
Returns the record number of the record identified by the Position In Level (Pil) numbers. This
function can be used to find the record number for upper or lower level records.
ARGUMENTS
Level 0 Pil The Level 0 Pil represents the Pil number at level 0 for the required
record. It is passed by value as a long data type. This argument is not
optional.
Level 1 Pil The Level 1 Pil represents the Pil number at level 1 for the required
record. It is passed by value as a long data type. This argument is
optional.
Level 2 Pil The remaining arguments represent the Pil number at level n for the
etc required record. They are passed by value as long data types. These
arguments are optional and they can only be specified if the preceding
argument has been included.
VALUES RETURNED
The function will return the record number as a long data type.
If the record defined by the pil numbers does not exist, then the function will return –1, but the XCM
will not abort.
If the pil number for a level, and all of the levels below it, are passed in with a value of zero, then the
function will look for an upper level record.
EXAMPLE
(1) Find the record number for a dump record.
Sub Main
Dim lRecNum As Long
'Find the record number for the Expit Dump at RL170, block 5.
lRecNum = GetRecFromPilEx(3, 2, 170, 5)
Print lRecNum
End Sub
(2) Use the pre-defined level variables to find the record number for the same block in the next strip.
Sub Main
Dim lBlkInNextStrip As Long
'Look for the same block in the next strip
lBlkInNextStrip = GetRecFromPilEx(1, lPitNum, lStripNum+1, lBlkNum)
Print lBlkInNextStrip
End Sub
RELATED FUNCTIONS
GetRecFromPil, GetRecFromPilDB, GetRecFromName, GetRecFromNameEx, GetApil
GetRecName
DESCRIPTION
Returns the full name, path name or record name for the specified record.
ARGUMENTS
Record Number The record number for which the name is required. It is passed by
value as a long data type.
In addition to a number or a variable, this argument can be one of
Options Description
CURRENT The current active record
HOME The original record the script started with, ie. the record that was
called by the script before the use of GoRec or similar
UP The parent record
DOWNFIRST The first child record
DOWNLAST The last child record
PRVSIB The previous sibling under the same parent
NXTSIB The next sibling under the same parent
PRV The previous sibling regardless of parents
NXT The next sibling regardless of parents
Name Type This parameter indicates the type of name that is required for the
record. It is passed by value as an integer data type. There are three
options as follows:
VALUES RETURNED
The function will return either the record name, path name or full name as a string data type, depending
on the Name Type that is specified in the second argument.
If the requested record number does not exist, the following message will be displayed and the XCM
will then abort.
EXAMPLES
(1) Print the full name for record number 178.
Sub Main
'Print the full name for record number 178.
Print GetRecName(178, FULLNAME)
End Sub
(3) Print the name of the Last Seam in the current Block.
Sub Main
'Print the name of the Last Seam in the current Block.
Call GoRec(UP)
Print GetRecName(DOWNLAST, RECORDNAME)
Call GoRec(HOME)
End Sub
RELATED FUNCTIONS
GetRecNum, GetRecNameAtLevel, GoRec, GetPositionNameFromPil
GetRecNameAtLevel
DESCRIPTION
Returns the record name at the specified level in the database. If the starting record is not specified,
then the current record is assumed.
ARGUMENTS
Level Number The level number defines the database level for which the
record name is to be returned. It is passed to the function by
value as an integer data type.
The level number may be between 1 and 10, however it
cannot be greater than the level number of the starting
record.
VALUES RETURNED
The function will return the record name at the specified level as a string data type.
If the level number is invalid, then the function will return a value of “No Record”.
If the record number is not a valid record in the current database, then the function will return the
following error message and then the XCM will abort.
EXAMPLES
(1) Get the record name at a level above the current record.
Sub Main
'Find the name of the Pit (Level 1) that the current record is in.
Dim sPitName As String
sPitName = GetRecNameAtLevel(1)
Print sPitName
End Sub
(2) Get the record name at a level above a record other than the current record.
Sub Main
'Find out whether the next record is on the same bench (Level 2)
'as the current record.
Const lBENCH = 2
Dim sBnchNameThisRec As String
RELATED FUNCTIONS
GetRecName, GetRecFromName, GetRecNumAtLevel
GetRecNameFromPeriod
DESCRIPTION
Returns the record name for the specified period number in the calendar database. If no calendar
database is specified, then the active calendar database is assumed.
The format of the record name that is returned is dependent on the second argument of the function,
namely the name type.
ARGUMENTS
Period Number Period numbers are assigned to all lowest level calendar records, in
database order. Period one is always the first lowest level record in
the database. The first period scheduled does not have to be period
number one.
The period number is passed into the function by value as a long
data type.
Name Type This parameter indicates the type of name that is required for the
record. It is passed by value as an integer data type and it is an
optional argument. If the name type is not supplied to the function,
the path name will be returned (see below).
The three options for this argument are as follows:
Options Description
RECORDNAME The name of the record at that level. For example, Aug.
PATHNAME The name of the record at each level, separated by forward
slashes. For example, 2015\Qtr3\Aug.
FULLNAME The record number followed by the path name of the record.
For example, 146: 2015\Qtr3\Aug.
Calendar This is the calendar database in which to look for the specified
Database Name time period. It is passed by value as a string data type and it is an
optional argument.
If the calendar database name is not passed in, then the function
will look for the specified period number in the active calendar
database.
VALUES RETURNED
The function returns the name of the time period as a variant data type.
If the period number does not exist in the specified calendar database, then the function will return an
empty string.
EXAMPLES
(1) Store period names in an array.
Sub Main
Dim sCalName As String
Dim lPerNum As Long
Dim sPerName(20) As String
'Store the period names in an array.
sCalName = GetCalendarNameFromScenario("20 Year Schedule")
For lPerNum = 1 to 20
sPerName(lPerNum) = GetRecNameFromPeriod(lPerNum, PATHNAME, sCalName)
Next lPerNum
'The period names could then be used in a list in a dialog box.
End Sub
RELATED FUNCTIONS
GetRecNumFromPeriod, GetPeriodFromRecNum, GetCalendarNameFromScenario,
GetOutputRangeForPeriod
GetRecNum
DESCRIPTION
Returns the record number of a record, relative to the specified record.
ARGUMENTS
Record Pointer The Record Pointer describes the record that is returned by this
function, relative to the Starting Record. It is passed by value as a
long data type.
If the Starting Record is not specified, then it is relative to the
current record.
The Record Pointer may be set to one of the following options:
Options Description
CURRENT The current active record
CURRENTDESTINATION In User Processing and Objectives, the current destination
record (if applicable)
HOME The original record the script started with, ie. the record that
was called by the script before the use of GoRec or similar
UP The parent record
DOWNFIRST The first child record
DOWNLAST The last child record
PRVSIB The previous sibling under the same parent
NXTSIB The next sibling under the same parent
PRV The previous sibling regardless of parents
NXT The next sibling regardless of parents
Starting Record The record that is returned by this function may be specified
relative to some record other than the current record. This other
record is the Starting Record and it is passed to the function as a
record number. It is passed by value as a long data type.
The Starting Record is an optional argument. If it is not specified,
then it is assumed to be the current record.
Database Name This function can also be used to return a record number from a
database other than the current database. The Database Name is
passed by value as a string data type.
The Database Name is an optional argument. If it is not specified,
then it is assumed to be the current database.
In this function, the Database Name must be entered as a string.
VALUES RETURNED
The function will return the record number as a long data type.
If the requested record does not exist, then the function will return –1, but the XCM will not abort.
EXAMPLES
(1) Get the record number for the current record.
Sub Main
'Print the current record number.
Print GetRecNum(CURRENT)
End Sub
(2) In a database where the lowest level is Block and the level above Block is Panel, get the record
number for the last block in the current panel.
Sub Main
'Get the record number for the last block in the current panel.
Dim lPanelRec As Long
Dim lLastBlkInPanel As Long
lPanelRec = GetRecNum(UP)
lLastBlkInPanel = GetRecNum(DOWNLAST, lPanelRec)
Print lLastBlkInPanel
End Sub
(3) Find the record number for the first year in the Long Term Calendar database.
Sub Main
'Print the record number for the first year in the calendar.
Const lTopRec = 1
Dim lFirstCalYear As Long
lFirstCalYear = GetRecNum(DOWNFIRST, lTopRec, "Long Term Calendar")
Print lFirstCalYear
End Sub
RELATED FUNCTIONS
GoRec, GetRecName, GetRecNumAtLevel, IsValidRecNum
GetRecNumAtLevel
DESCRIPTION
Returns the record number at the specified level in the database. If the starting record is not specified,
then the current record is assumed.
ARGUMENTS
Level Number The level number defines the database level for which the
record number is to be returned. It is passed to the function
by value as an integer data type.
The level number may be between 1 and 10, however it
cannot be greater than the level number of the starting
record.
VALUES RETURNED
The function will return the record number at the specified level as a long data type.
If the level number is invalid, then the function will return a value of –1.
If the starting record number is not a valid record in the current database, then the function will return
the following error message and then the XCM will abort.
EXAMPLES
(1) Get the record number at a level above the current record.
Sub Main
'Find the record number at the Pit Level (Level 1) above the
'current record.
Dim lPitRecNum As Long
lPitRecNum = GetRecNumAtLevel(1)
Print lPitRecNum
End Sub
(2) Get the record number at a level above a record other than the current record.
Sub Main
'Find out whether the next record is on the same bench (level 2)
'and in the same pit (level 1) as the current record.
'If they are, the bench record numbers will be the same for each.
Const lBENCH = 2
Dim sBnchRecThisRec As String
Dim lNextRec As Long
Dim sBnchRecNextRec As String
sBnchRecThisRec = GetRecNumAtLevel(lBENCH)
lNextRec = GetRecNum(NXT)
sBnchRecNextRec = GetRecNumAtLevel(lBENCH, lNextRec)
If (sBnchRecThisRec <> sBnchRecNextRec) Then
Call MsgBox("New Pit\Bench Encountered")
End If
End Sub
RELATED FUNCTIONS
GetRecNum, GetRecNumFromPath, GetRecNameAtLevel
GetRecNumFromPath
DESCRIPTION
Returns the record number for the record identified by the path name. If the record is not in the current
database, then the database name must be specified.
ARGUMENTS
Path Name The path name for a record consists of the record name at each
successive level of the database, with each name separated by the
back slash character, ie. \. For example, “Pit2\P40\5”.
The path name is passed by value as a string data type. As a string,
the path name should be in double quotes, ie. “”.
Options Description
ACTIVE_MAIN The main database.
ACTIVE_CALENDAR The active calendar database.
ACTIVE_RESULTS The active results database.
VALUES RETURNED
The function will return the record number as a long data type.
If the path name is invalid, the function returns a value of –1, but the XCM will not abort.
If the database is invalid, the function returns an error when the XCM is compiled.
EXAMPLES
(1) Get the record number for a specific record in the current database.
Sub Main
'Get the record number for Panel East1, Drive 2, Block 1.
Print GetRecNumFromPath("East1\Drv2\1")
End Sub
End Sub
RELATED FUNCTIONS
GetRecNum, GetRecNumAtLevel, GetRecName
GetRecNumFromPeriod
DESCRIPTION
Returns the record number for the specified period number in the calendar database. If no calendar
database is specified, then the active calendar database is assumed.
ARGUMENTS
Period Number Period numbers are assigned to all lowest level calendar records,
in database order. Period one is always the first lowest level
record in the database. The first period scheduled does not have to
be period number one.
The period number is passed into the function by value as a long
data type.
Calendar This is the calendar database in which to look for the specified
Database Name time period. It is passed by value as a string data type and it is an
optional argument.
If the calendar database name is not passed in, then the function
will look for the specified period number in the active calendar
database.
VALUES RETURNED
The function returns the record number for the time period as a long data type.
If the period number does not exist in the specified calendar database, then the function will return a
value of –1.
EXAMPLES
(1) Use the period record numbers to read data from the calendar database.
Sub Main
Dim sCalName As String
Dim lPerNum As Long
Dim lPerRec As Long
Dim dSchedTarg(50) As Double
'Read the schedule targets from field 25 in the active calendar.
sCalName = GetActiveCalendarName()
For lPerNum = 1 to 50
lPerRec = GetRecNumFromPeriod(lPerNum, sCalName)
If (lPerRec > 0) Then
dSchedTarg(lPerNum) = DbReadValue(sCalName, lPerRec, 25)
End If
Next lPerNum
RELATED FUNCTIONS
GetPeriodFromRecNum, GetRecNameFromPeriod, GetCalendarNameFromScenario,
GetOutputRangeForPeriod
GetResourceCount
DESCRIPTION
Returns the number of resources that are assigned to the specified scenario.
All types of resources (Standard Target, Standard Production and Auto Target) are included in the
count. If a resource has been flagged as two different types in a scenario, each type will be included in
the resource count.
ARGUMENTS
Scenario Name The scenario name is passed into the function by value as a string
data type.
It is an optional argument. If the scenario name is not passed to the
function, then it is assumed to be the active scenario.
VALUES RETURNED
The function returns the number of resources in the specified scenario as a long data type.
If the specified scenario name does not exist in the current project, then a message will be displayed to
indicate this and the function will return a value of zero and then abort.
If the scenario name is not passed into the function and there is no active scenario, then the function
will return a value of zero and then abort.
If there are no resources assigned to the specified scenario, then the function will return a value of zero.
EXAMPLES
(1) Print the number of resources in the active scenario.
Sub Main
Print GetResourceCount()
End Sub
RELATED FUNCTIONS
GetResourceName, Error! Reference source not found., GetOutputStep
GetResourceLocation
This function can only be used in User Processing Scripts it returns the location of a resource.
ARGUMENTS
Example:
Dim lRecord as Long
Dim iActivity as Integer
call GetResouceLocation(“Ore”, lRecord, iActivity)
GetResourceName
DESCRIPTION
Returns the name of a resource, given the scenario name and the resource number.
ARGUMENTS
Resource Number The resource number is passed into the function by value as a
long data type.
The resources are numbered according to their order in the full
list of resources in your project, not their order in the scenario
tree. The full list of resources can be obtained by clicking on
“Resource” in the Schedule Setup Tree. It will be displayed on
the right hand window. Note that any resources that are not
assigned to the specified scenario will not be given a number.
If a resource is assigned to a scenario as more than one resource
type, these resources will be numbered as they appear across the
screen, ie. Standard Production, Standard Target then Auto
Target.
Scenario Name The scenario name is passed to the function by value as a string
data type.
VALUES RETURNED
The function returns the name of the resource, specified by the resource number and the scenario name,
as a variant data type. If a valid resource name is found, it is returned as a string.
If the specified scenario name does not exist in the current project, then a message will be displayed to
indicate this and the function will return an empty string and then abort.
The error message “Invalid Value for Parameter ‘Index’ use in Function ‘GetResourceName’” is
displayed in the following situations:
• If the scenario name is not passed into the function and there is no active scenario;
• If there are no resources assigned to the specified scenario; or
• If the specified resource number does not exist for the scenario.
EXAMPLES
(1) Print the name of the second resource in the active scenario.
Sub Main
Print GetResourceName(2)
End Sub
RELATED FUNCTIONS
GetResourceCount, Error! Reference source not found., GetOutputStep
GetResourceRoster
DESCRIPTION
Returns the RosterName and RosterException that was used by the Scenario Resource. If the Scenario
Resource does not exist, then the function returns FALSE. If the Roster or RosterException is not set
for the Scenario Resource, the respective field is returned as an empty string.
EXAMPLES
GetRosterHrs
DESCRIPTION
Returns the number of rostered hours performed within the two supplied dates for the specified roster
and roster exception.
GetRowCodeFromNum
DESCRIPTION
Returns the full row code of a data field, given its row number and the database name.
ARGUMENTS
Database Name The database name defines where to look for the full row code. It is
passed by value as a string data type.
Note that ACTIVE_CALENDAR, ACTIVE_RESULTS, etc cannot
be used in this function.
Data Field Row The data field Row Number is passed into the fulction by value as a
Number long data type.
VALUES RETURNED
The function will return the data field’s full row code in the specified database.
If the database does not exist in the current XPAC project, the function will return an unspecified
failure.
If the full row code does not exist in the specified database, then the function will return an empty
string.
EXAMPLES
(1) Get the 2nd Row’s Row Code in the Parameter Database
Sub Main
Dim sDrillSpac As String
Dim lParRec As Long
Const sPARDBNAME = "Equipment Parameters"
'Get the Row Code for Row 2 in the Parameters Database
sDrillSpac = GetRowCodeFromNum(sPARDBNAME, 2)
End Sub
RELATED FUNCTIONS
DbReadValue, DbWriteValue, GetFieldInfo, GetRowNumFromCode
GetRowNumFromCode
DESCRIPTION
Returns the data field number, given its full row code and the database name.
This function is useful when you are reading from or writing to some other database using
DbReadValue and DbWriteValue, as the full row codes cannot be used directly in these functions.
ARGUMENTS
Database Name The database name defines where to look for the full row code. It is
passed by value as a string data type.
Note that ACTIVE_CALENDAR, ACTIVE_RESULTS, etc cannot
be used in this function.
Data Field Full The data field full row code is passed into the function by value as a
Row Code string data type. Note that it must appear in double quotes.
The full row code is the portion of the data field code that would
normally appear inside the brackets when referring to that data field
in an XCM.
For example, “mCsh_Feed”, “pDef_RD”, “rEqp_Trk_OpHr”.
VALUES RETURNED
The function will return the number of the data field that has the specified full row code in the specified
database.
If the database does not exist in the current XPAC project, the function will return an unspecified
failure.
If the full row code does not exist in the specified database, then the function will return a value of –1.
EXAMPLES
(1) Read a value from a parameters database.
Sub Main
Dim lDrillSpac As Long
Dim lParRec As Long
Const sPARDBNAME = "Equipment Parameters"
'Read the drill hole spacing from the "Equipment Parameters" database
lParRec = GetRecFromPilDB(sPARDBNAME, lDistrictNum, lDriveNum)
lDrillSpac = GetRowNumFromCode(sPARDBNAME, "pDB_Drl_Spac")
M(mEqp_DB_DrlSpac) = DbReadValue(sPARDBNAME, lParRec, lDrillSpac)
End Sub
RELATED FUNCTIONS
DbReadValue, DbWriteValue, GetFieldInfo, GetRowCodeFromNum
GetScheduleStartPeriod
GetScriptExecutionRange
DESCRIPTION
Returns the name of the range over which the current script is being executed.
ARGUMENTS
There are no arguments for this function.
VALUES RETURNED
The name of the range over which the current script is being executed.
If the script is being executed as a run-once script, the string “< RunOnce >” will be returned.
If the script is being executed over the ABL (as a user processing script), the string “< RunABL >” will
be returned.
If the script is being executed from another script, the range specified in RunScript will be returned.
This function can be called from Run Once XCMs, Run Range XCMs, User Processing XCMs, and
from a range condition script (where it will return the name of the range for which the condition is
being evaluated).
GetScriptName
DESCRIPTION
Returns the file name of the XCM that is currently being processed. The directory path name for the
XCM is not returned.
ARGUMENTS
There are no arguments for this function.
VALUES RETURNED
The XCM or script name is returned as a variant data type.
If the XCM that is being processed is running over a database range, is a run once XCM, is running in
debug or is a user processing script, then the name of the XCM file will be returned by this function, ie.
“XCM Name.bas”.
If the XCM that is being processed is an Immediate XCM, then the function will return “(Immediate
XCM)”.
EXAMPLES
(1) Display the name of the XCM in a message.
Sub Main
Dim sMsg As String
Dim lAnswer As Long
'Display a warning message at the start of the XCM
If (IsFirstInRange()) Then
sMsg = GetScriptName() & " deletes the ROM Reserves. "
sMsg = sMsg & "Do you want to continue?"
lAnswer = MsgBox(sMsg, MB_YESNO, "WARNING!")
If (lAnswer = IDNO) Then Abort
End If
ClearData mROM
End Sub
RELATED FUNCTIONS
GetCurrentDirectory, GetDatabaseName, GetFullModelName, GetRecName
GetScriptsDirectory
DESCRIPTION
Returns the scripts directory of the currently open model, as set in Global Options.
ARGUMENTS
There are no arguments for this function.
VALUES RETURNED
This function returns the scripts directory of the currently open model, as set in Global Options.
RELATED FUNCTIONS
GetCurrentDirectory, GetDatabaseName, GetFullModelName, GetModelDirectory
GetSourceABLCount
This function returns the number of items in the Available Source Block List. It accepts the following
parameters:
Optional ByVal lActivity As Long - If present, specifies an activity number to filter by. If zero or not
present, the function will return the count for all activities.
Optional ByVal bAvailable As Boolean - If true, specifies that only records that are not constrainted
will be returned. If false or not specified, all records will be returned.
Optional ByVal sResource As String - If present, specifies a resource to filter by. If not present, the
current resource is used.
GetSPCreationDate
M(mEndDt) = dEnd
M(mPeriodNo) = GetCurrentPeriod
GetSuccessor
This function returns the record number and activity of the successor in the position indexed by Pos.
The function returns the Predecessors activity number.
Example
Dim lRecordSuccessor As Long
Dim iActivityOfSuccessor As Integer
Dim iFromActivity As Integer
Dim i As Integer
For i = 0 To iNumOfSuccessor -1
Next i
GetTrackingField
DESCRIPTION
To being tracking a field, call InitTrackingField. You can then call GetTrackingField to get the current
value. Additive and Weighted Average (WTG) fields are only supported in XPAC 2003 onwards.
Every time a Record is mined the Progress Tracking Field(s) will be updated.
ARGUMENTS
ActivityNum The Activity Number you want to track. To track All Activities,
specify 0 here.
ResourceName The Resource you want to Track, specify “All” if you would like to
track All Resources.
VALUES RETURNED
The function will return the value of the Tracked Field specified.
RELATED FUNCTIONS
InitTrackingField
GetValue
Returns the value from a line in the report for a previous period.
iFieldNo can be either a physical line number or valid row code from the report.
iPeriod can be used 2 ways: if iPeriod <= 0, it is used as the number of periods previous.
If iPeriod > 0, it is the absolute period number.
Note: the period must be between the starting period for the report and the current period, otherwise the
value returned is zero.
This function is designed to be used as a report filter or result, and can’t be run outside a scheduling
report.
GetValue(rROM_Coal_Vol , -2) returns the value of the rROM_Coal_Vol field from 2 periods
previous. Of course, if the report is run from period 1 of the schedule, this will return 0 for periods 1
and 2.
GetValue(rROM_Coal_Vol , 4) returns the value of the rROM_Coal_Vol field from period 4. If the
report is run from period 1 of the schedule, this will return 0 for periods 1, 2 and 3.
Note: because the values are taken from the report as it is generated, using the first example shown
above in a report run from period 5 will not return results from periods 3 and 4 of the schedule into
periods 5 and 6 of the report.
GetVertexEOS
Returns TRUE if the specified vertex is an end-of-sequence marker. Use GetVertexEOS when the
vertex is a single variable, and GetVertexEOSA when the vertex is in an array, passing in the array and
the index of the vertex to test.
GetVertexEOSA
Returns TRUE if the specified vertex is an end-of-sequence marker. Use GetVertexEOS when the
vertex is a single variable, and GetVertexEOSA when the vertex is in an array, passing in the array and
the index of the vertex to test.
GoRec
DESCRIPTION
Returns a True value if the requested record is made the current record.
ARGUMENT
Record Pointer This argument defines the record that is to become the current
record. It is passed to the function by value as a long data type.
The record pointer may be defined as an absolute record number
using either a number or a variable. It may also be set to one of the
following relative values:
Options Description
CURRENT The current active record
HOME The original record the script started with, ie. the record that was
called by the script before the use of GoRec or similar
UP The parent record
DOWNFIRST The first child record
DOWNLAST The last child record
PRVSIB The previous sibling under the same parent
NXTSIB The next sibling under the same parent
PRV The previous sibling regardless of parents
NXT The next sibling regardless of parents
VALUES RETURNED
The function returns a boolean data type.
It returns a True value if the specified record is made the current record.
It returns a False value if it cannot move to the specified record, ie. if the specified record does not exist
in the current database.
EXAMPLES
(1) Move to a specific record to read some data, then move back to the original record and write the
data into a data field.
Sub Main
Dim lPitRec As Long
Dim dPitWstVol As Double
'Go to the current pit record (level 1) and read the total
'waste volume for the pit.
lPitRec = GetRecNumAtLevel(1)
Call GoRec(lPitRec)
dPitWstVol = M(mWst_Vol)
'Go back to the original record and write the total waste
'volume for the pit into a data field.
Call GoRec(HOME)
M(mTotPit_Wst_Vol) = dPitWstVol
End Sub
Do While (lNextRecNum = 0)
'Go to the next record if it exists
If (GoRec(NXT)) Then
If (M(mOre_Ton) > 0) Then lNextRecNum = GetRecNum(CURRENT)
'If there are no more records, then finish the loop
Else
lNextRecNum = 1
End If
Loop
'Write the next record containing ore into the original record
Call GoRec(HOME)
M(mNext_OreRec) = lNextRecNum
End Sub
RELATED FUNCTIONS
GetRecNum, GetRecNumFromPath, GetRecFromPil, DbReadValue
IIf
DESCRIPTION
Returns either the True Value or the False Value, depending on the evaluation of the Expression. If the
Expression returns a true, then the function will return the True Value. If the Expression returns a
false, then the function will return the False Value.
IIf signifies Immediate If. It is used mainly where an expression must be evaluated, such as in a
polygon graphics template. In an XCM, the more versatile If…Then…Else statement is generally
used.
ARGUMENTS
Expression This argument is passed by value as a boolean data type. The value of
the expression is used to determine what the function will return.
For example, the expression may be:
M(mBench_Thk) < 10
M(mOre_Grd) >= 0.4 And M(mOre_Grd) < 0.5
GetClass(mFrag_Method) = “DrillBlast”
GetRecName(CURRENT, RECORDNAME) = “SouthExt”
True Value If the expression (above) evaluates to true, then the value in this
argument will be returned by the function. The True Value is passed to
the function by value as a variant data type.
False Value If the expression (above) evaluates to false, then the value in this
argument will be returned by the function. The False Value is passed to
the function by value as a variant data type.
VALUES RETURNED
This function returns either the True Value or the False Value, depending on the evaluation of the
expression. They are returned as a variant data type.
Note that the IIf function evaluates both the True Value and the False Value, regardless of which one it
returns. This may generate a confusing error message in some situations. For example, if the False
Value results in a division by zero, this generates an error even if the expression evaluates to true.
It should also be noted that IIf will not generate a ‘Type Mismatch’ error if the expression cannot be
converted to a boolean value. Instead it just returns the False Value.
EXAMPLES
(1) Polygon Plot Annotation - display the ore grade where it is greater than 60% or “Wst” where it is
less than 60%.
IIf(M(mOre_Grd)>60, M(mOre_Grd), "Wst")
(2) Polygon Plot Z Value – in those areas where there are no benches (bench pil number is 999) set the
Z value to the coal seam floor RL, otherwise set the Z value to the Bench RL.
IIf(GetApil(3) = 999, M(mSm_Flr_RL), GetApil(3))
(3) Polygon Plot Shading – display the polygons for all mining blocks, but only shade those blocks that
contain sulphide ore.
IIf(GetClass(mOre_Type) = "Sulphide", M(mOre_Grd), "")
RELATED FUNCTIONS
If, Then, Else, GetClass, GetApil, GetLevelNum
Import
DESCRIPTION
Imports the specified Collection Type (eg. Curves, Ranges, Rosters, etc) from the specified File Name.
All properties for that Collection Type will be imported.
ARGUMENTS
File Name This argument represents the name of the file from which the
Collection Type will be imported. It is passed by value as a string
data type.
The file must be a tpl file, such as can be exported from an XPAC
model. The file name must also have an extension of “.tpl”. No
other file types will be recognised.
An absolute path name should be specified as part of the file name
to ensure the correct file is located.
Collection Type This argument represents the name of the Collection that you wish
to Import from the specified file. It is passed by value as a string
data type.
If the Collection Type is an empty string, then all Collection Types
that are present in the specified file will be imported.
It may be set to any of the Collection Type names listed in the
following table.
VALUES RETURNED
The function returns a boolean data type which indicates whether the import was successful.
If the specified Collection Type is imported successfully from the file, then the function will return a
True value.
If the specified File Name does not exist, then an error message will be displayed as follows.
If the specified File Name exists but does not contain the extension “.tpl”, then the function will return
a False value.
If the specified File Name exists but it does not have the format of a tpl file, then the function will
return a False value.
If there are none of the specified Collection Type in the file, then the function will return a True value.
If the Collection Type name is invalid, then the function will return a False value.
If all Collection Types are exported from one model, they can be imported into another (blank) model
to almost recreate the original model.
EXAMPLES
(1) Import the Database Ranges and Fields Templates from the 5 Yr Plan XPAC Model.
Sub Main
Dim bImported As Boolean
'Import the Database Ranges from the 5 Yr Plan XPAC Model
bImported = Import("C:\5YrPlan\Ranges&Fields.tpl", "Ranges")
If (Not(bImported)) Then Print "Ranges Not Imported Successfully."
'Import the Fields Templates from the 5 Yr Plan XPAC Model
bImported = Import("C:\5YrPlan\Ranges&Fields.tpl", "Field Selections")
If (Not(bImported)) Then Print "Fields Not Imported Successfully."
End Sub
(2) Import all data from the Life of Mine XPAC Model.
Sub Main
Dim bSuccessful As Boolean
'Import all data types that have been exported from the LOM Model
bSuccessful = Import("C:\Black Hill Mine\Life of Mine Model.tpl", "")
If (Not(bSuccessful)) Then Print "Failure to Import Data - check File location."
End Sub
RELATED FUNCTIONS
Export
InitTrackingField
DESCRIPTION
To being tracking a field, call InitTrackingField. You must call this function before you can call
GetTrackingField to get the current value. Additive and Weighted Average (WTG) fields are only
supported in XPAC 2003 onwards. Every time a Record is mined the Progress Tracking Field(s) will
be updated.
ARGUMENTS
ActivityNum The Activity Number you want to track. To track All Activities,
specify 0 here.
ResourceName The Resource you want to Track, specify “All” if you would like to
track All Resources.
VALUES RETURNED
The function will return true if the Tracked Field was successfully initialised.
RELATED FUNCTIONS
GetTrackingField
InPoly
Note – This function has been superseded by the PointInPolygon function.
Determines if the given point (dY, dY) is inside the 2D polygon whose coordinates are given in the
arrays dXArray and dYArray. The arrays, dXArray and dYArray, must both be single dimensional
arrays containing the same number of values.
The optional parameter dEdgeWidth is used to handle points that are near the polygon edge. Points that
are within dEdgeWidth units of the polygon edge are considered to be on the edge of the polygon. If
dEdgeWidth is greater than or equal to zero (dEdgeWidth >= 0.0) then points that are on the edge are
considered to be inside the polygon. If dEdgeWidth is negative (dEdgeWidth < 0.0) then points on the
edge are considered outside the polygon. By default, dEdgeWidth is zero (dEdgeWidth = 0.0).
The optional parameter lMode is used to determine which parts of complex polygon are considered to
be inside. For a simple path it is obvious which points are considered to lie inside. For more complex
polygon (eg. a polygon that intersects itself or contains sub-polygons) this is not so obvious. If lMode
is set to ALTERNATE (= 1) then a point is considered inside if a ray drawn from the point to infinity
in any direction crosses an odd number of polygon edges. (This is also know as the Even-odd method).
If lMode is set to WINDING(=2) then a point is considered inside if a ray drawn from the point to
infinity in any direction crosses is crossed by a different number of polygon edges going from left to
right than those crossing it from right to left. (see diagram for InPolyRec). By default, lMode is
ALTERNATE (lMode = 1).
Returns True if the points is inside. Otherwise returns False.
' This XCM evaluates points inside a polygon.
Dim iValid As Integer ' Flag
Dim dEast As Double ' Variable for Easting record
Dim dNorth As Double ' Variable for Northing record
Dim dEPnt(10) As Double ' Eastings Of Points In Creek Polygon
Dim dNPnt(10) As Double ' Northings Of Points In Creek Polygon
RELATED FUNCTIONS
GetPolygonVertexCount, GetPolygonVertexXYZ, GetPolygonCentroidXY, InPoly, InPolyRec
InPolyRec
Note – This function has been superseded by the PointInPolygon function.
Determines if the given point (dX, dY) is inside the 2D polygon stored in the database specified by the
given parameters. . If lRecNum is equal to 0, CURRENT or is not given then the polygon associated
with the current record in the main database will be assumed. If lActivity is equal to 0,
DEFAULT_ACTIVITY or is not given then the default activity will be assumed. Otherwise the
polygon associated with the given activity number will be assumed. If the lPolygonIndex is –1, 0, or
not given then all the polygons will be tested otherwise just the polygon with the given index will be
used in the InPolyRec test.
The optional parameter dEdgeWidth is used to handle points that are near the polygon edge. Points that
are within dEdgeWidth units of the polygon edge are considered to be on the edge of the polygon. If
dEdgeWidth is greater than or equal to zero (dEdgeWidth >= 0.0) then points that are on the edge are
considered to be inside the polygon. If dEdgeWidth is negative (dEdgeWidth < 0.0) then points on the
edge are considered outside the polygon. By default, dEdgeWidth is zero (dEdgeWidth = 0.0).
The optional parameter lMode is used to determine which parts of complex polygon are considered to
be inside. For a simple path it is obvious which points are considered to lie inside. For more complex
polygon (eg. a polygon that intersects itself or contains sub-polygons) this is not so obvious. If lMode
is set to ALTERNATE (= 1) then a point is considered inside if a ray drawn from the point to infinity
in any direction crosses an odd number of polygon edges. (This is also know as the Even-odd method).
If lMode is set to WINDING(=2) then a point is considered inside if a ray drawn from the point to
infinity in any direction crosses is crossed by a different number of polygon edges going from left to
right than those crossing it from right to left. (see diagram). By default, lMode is ALTERNATE
(lMode = 1).
Returns True if the points is inside. Otherwise returns False.
RELATED FUNCTIONS
GetPolygonVertexCount, GetPolygonVertexXYZ, GetPolygonCentroidXY, InPoly, InPolyRec
InsertIntoInputPath
DESCRIPTION
Returns the number of steps in the input path, after the specified step has been inserted. The details of
the step to insert are stored in the InputPathStep structure, which is passed into the function.
ARGUMENTS
Input Path Name This argument defines the input path into which the new step is to
be inserted. The input path name is passed to the function by
value as a string data type.
Step Number The step number is passed to the function by value as a long data
type.
This argument defines the position in the input path into which the
new step is to be inserted. If there is a step in this position
already, then that step and all that follow will be moved down by
one, to make rooom for the new step. To append a step to the end
of the path, use a step number less than 1 (eg. 0 or –1) or greater
than the number of steps in the input path.
Options Description
StepType The step type is a long data type. In an input path, the step types can
be either of the following.
• PE_PROD for productive steps (ie. database records).
• PE_NONPROD for nonproductive steps (ie. in-path delays).
TaskId The task ID is a long data type. Its value varies according to the
step type:
For productive steps, the task ID is the record number.
For non-productive steps, the task ID is ignored.
Activity The activity number is an integer data type.
• For productive steps, the activity number should be between 1
and 100.
• For non-productive steps, the activity number should be greater
than 101.
If the activity number does not match its relevant step type, the step
will still be created but with an invalid activity number.
EnteredPct The entered percent is the percentage of the specified record and
activity that is requested for scheduling. It is passed in as a double
data type.
• For productive steps, the entered percent will be a value
between 0 and 1.
• For non-productive steps, the entered percent will be ignored.
EnteredDelay The entered delay is the requested time for the non-productive
activity. It is passed in as a double data type.
• For productive steps, the entered delay will be ignored.
• For non-productive steps, the entered delay will be the
delay time in days.
EnteredDelay- The entered delay time base units refers to the time base that is
TimeBaseUnits selected for the entered delay. The time base is passed in as an
integer data type. It may be one of the following values:
• Zero for productive steps.
• TBU_CALENDAR_TIME for non-productive steps whose
duration is defined in calendar time.
VALUES RETURNED
This function returns the total number of steps in the input path, after the specified step has been
inserted. It is returned as a long data type.
If the data supplied to the Step Information structure is valid, then a new step will be created in the
input path, and the function will return the number of steps in the input path.
If the Step Type is set to some value other than PE_PROD or PE_NONPROD, then the new step will
not be added to the input path and the function will return a value of –1.
If the Entered Delay Time Base Units is set to some value other than those listed, then the new step will
not be added to the input path and the function will return a value of –1.
If the Step Type is valid, but some of the other elements of the Step Information structure are invalid,
then a new step will still be added to the input path. However, the new step that is inserted may contain
invalid data. Examples of this are if the step type is defined as productive but an upper level record
number is passed in for the task ID or if the step type is defined as non-productive but the activity
number is less than 101. In this situation, the number of steps returned by the function will include the
new step.
EXAMPLES
(1) Add a step to an input path
Sub Main
Const sINPUTPATH = "Prestrip"
Dim lTotSteps As Long
Dim NewStepInfo As InputPathStep
NewStepInfo.StepType = PE_PROD
NewStepInfo.TaskID = GetRecNumFromPath("Main\T04\RL560\8")
NewStepInfo.Activity = GetActivityNum("Prestrip Waste")
NewStepInfo.EnteredPct = 0.5
'Insert the new step information before the current step 5.
lTotSteps = InsertIntoInputPath(sINPUTPATH, 5, NewStepInfo)
Print sINPUTPATH & " input path contains " & lTotSteps & " steps."
End Sub
RELATED FUNCTIONS
GetInputStep, Error! Reference source not found., GetInputPathNoOfSteps, ClearInputPath
InsertResourceDelay
DESCRIPTION
This subroutine is used in user processing scripts to insert a delay into the output path of the given
resource. If the resource name is not specified it will default to the resource which called the script.
PARAMETERS
EnteredDelay The entered delay can measured in one of the following types
TimeBase
Units
TBU No Description
TBU_ 0 Uses Calendar Time for the entered delay
CALENDAR_
TIME
TBU_ROSTER 1 Uses Roster/Working Time for the entered
_ TIME delay
TBU_ 2 Uses Operating Time for the entered delay
OPERATING_
TIME
Resource Name This parameter describes the resource for which the delay will be
inserted into output path.
VALUES RETURNED
The function will insert a delay into the output path of the given resource.
In the event of a failure an error message will be displayed.
EXAMPLES
(1) Insert a panel extension of 4 shifts into the output of the current resource before each block is
mined.
(2) Insert a delay of two weeks into the output path of CM1 to allow for the installation of a drivehead
at the end of the second block in a panel.
If (lBlockNum = 3) Then
End If
RELATED FUNCTIONS
ChangeProductionRate, ChangeRoster
IsCombinationConstrained
IsCombinationConstrained
DESCRIPTION
Returns True if the specified combination of source task (record number and activity) and destination
record is currently constrained. Period constraints, capacity constraints, proximity constraints, and user
flags are checked.
ARGUMENTS
VALUES RETURNED
The function returns a boolean data type.
If the specified combination is constrained, then the function returns a True value, otherwise it returns a
False value.
RELATED FUNCTIONS
IsTaskConstrained, IsTaskReserved
IsFirst
DESCRIPTION
Returns a true value if the current record is the first child of its parent record.
ARGUMENTS
This function does not have any arguments, however the brackets must be included.
VALUES RETURNED
The function returns a boolean data type.
If the current record is the first child of its parent record, then the function returns a true value.
If the current record is not the first child of its parent record, then the function returns a false value.
EXAMPLES
(1) In the following Structure Tree the record number is shown in square brackets and is preceded by a
hash (#) character.
The IsFirst function applies to the current record in your XCM. (Note that to make any upper level
records the current record, the GoRec function should be used).
For the records displayed in the Structure Tree above, if they were the current record in your XCM,
then the following records would return a true value for the IsFirst function:
#1: Top
#2: RVW
#3: RVW\30
#5: RVW\30\R01
#8: RVW\30\R01\1
#22: RVW\55\R01
#24: RVW\55\R01\2
Sub Main
'Clear the cumulative Drill Metres for the first Block in the Panel.
If (IsFirst()) Then dCumDrillMtr = 0
'Accumulate Drill metres.
dCumDrillMtr = dCumDrillMtr + M(mDrl_Mtr)
M(mCum_Drl_Mtr) = dCumDrillMtr
End Sub
RELATED FUNCTIONS
IsLast, IsFirstInRange, GetRecNum
IsFirstInRange
DESCRIPTION
Returns a true value if the current record is the first record in the current database range.
ARGUMENTS
This function does not have any arguments, however the brackets must be included.
VALUES RETURNED
The function returns a boolean data type.
If the current record is the first record in the current database range, then the function returns a true
value.
If the current record is not the first record in the current database range, then the function returns a false
value.
EXAMPLES
(1) Open a file at the beginning of an XCM.
Sub Main
If (IsFirstInRange()) Then
'Open a file once in preparation for writing to it.
Open "Blocks Containing Ore.txt" For Output As #1
End If
'If the record contains ore, then write the record number to the file.
If (M(mOre_Ton)>0) Then Print #1, "Record Number " & GetRecNum(CURRENT)
'Close the file.
If (IsLastInRange()) Then Close #1
End Sub
RELATED FUNCTIONS
IsLastInRange, IsFirst, GetFirstInRange
IsInRange
Returns true if the current record exists in a nominated range. The record will be checked against the
full tree of records built from the range.
If run over a database from a script, checks for the specified range name from the list of ranges relevant
to that database.
If used as a filter in Report Writer, checks for the range in Main, then the default Calendar.
IsLast
DESCRIPTION
Returns a true value if the current record is the last child of its parent record.
ARGUMENTS
This function does not have any arguments, however the brackets must be included.
VALUES RETURNED
The function returns a boolean data type.
If the current record is the last child of its parent record, then the function returns a true value.
If the current record is not the last child of its parent record, then the function returns a false value.
EXAMPLES
(1) In the following Structure Tree the record number is shown in square brackets and is preceded by a
hash (#) character.
The IsLast function applies to the current record in your XCM. (Note that to make any upper level
records the current record, the GoRec function should be used).
For the records displayed in the Structure Tree above, if they were the current record in your XCM,
then the following records would return a true value for the IsLast function:
#1: Top
#17: RVW\30\R01\10
#7: RVW\30\R03
#4: RVW\55
#22: RVW\55\R01
#31: RVW\55\R01\5
#25: MBP
(2) Use IsLast to write a value into the last child record.
'Declare a script variable to accumulate the number of Seams with coal.
Dim lCumSeamsWithCoal As Long
Sub Main
'Clear the number of Seams for the first Seam in the Block.
If (IsFirst()) Then lCumSeamsWithCoal = 0
'Accumulate Seams with Coal.
If (M(mCl_Ton) > 0) Then lCumSeamsWithCoal = lCumSeamsWithCoal + 1
'Write the number of Seams with coal into the last Seam in the Block
If (IsLast()) Then M(mCl_Seam_Num) = lCumSeamsWithCoal
End Sub
RELATED FUNCTIONS
IsFirst, IsLastInRange, GetRecNum
IsLastInRange
DESCRIPTION
Returns a true value if the current record is the last record in the current database range.
ARGUMENTS
This function does not have any arguments, however the brackets must be included.
VALUES RETURNED
The function returns a boolean data type.
If the current record is the last record in the current database range, then the function returns a true
value.
If the current record is not the last record in the current database range, then the function returns a false
value.
EXAMPLES
(1) Close a file at the end of an XCM.
Sub Main
If (IsFirstInRange()) Then
'Open a file once in preparation for writing to it.
Open "Blocks Containing Ore.txt" For Output As #1
End If
'If the record contains ore, then write the record number to the file.
If (M(mOre_Ton)>0) Then Print #1, "Record Number " & GetRecNum(CURRENT)
'Close the file.
If (IsLastInRange()) Then Close #1
End Sub
RELATED FUNCTIONS
IsLast, IsFirstInRange, GetNextInRange
IsTaskConstrained
DESCRIPTION
Returns True if the specified task (record number and activity) is currently constrained. Period
constraints, capacity constraints, proximity constraints, and user flags are checked.
ARGUMENTS
VALUES RETURNED
The function returns a boolean data type.
If the specified task is constrained, then the function returns a True value, otherwise it returns a False
value.
RELATED FUNCTIONS
IsCombinationConstrained, IsTaskReserved
IsTaskReserved
DESCRIPTION
Returns True if the specified task (record number and activity) is currently reserved to be mined by one
or more resources.
ARGUMENTS
VALUES RETURNED
The function returns a boolean data type.
If the specified task is partially or completely reserved, then the function returns a True value,
otherwise it returns a False value.
RELATED FUNCTIONS
IsCombinationConstrained, IsTaskConstrained
IsValidRecNum
DESCRIPTION
Returns a True value if the specified record number exists in the database.
ARGUMENTS
Record Number The record number identifies the record that is being sought
in the current database. It is passed by value as a long data
type.
The record number can be entered as a numeric value or as a
variable. Note that the record pointers, such as NXT, UP,
etc, cannot be used in this argument.
VALUES RETURNED
The function returns a boolean data type.
If the specified record number exists in the database, then the function returns a True value.
If the specified record number does not exist in the database, then the function returns a False value.
EXAMPLES
(1) Find out whether the next record exists.
Sub Main
Dim lNextRec As Long
lNextRec = GetRecNum(NXT)
'Write the record number for the next record into the current record.
If (IsValidRecNum(lNextRec)) Then M(mBlock_Next) = lNextRec
End Sub
RELATED FUNCTIONS
GetRecNum, GetRecNumFromPath, GetRecFromPil
LastCompletedTask
Returns true for all productive steps which were completed (eg end Remaining percentage of 0) in a
given reporting period, but resets the associated result fields accumulated value whenever returning
true. It has a side affect that the associated Result field does not pro-rata database values. The net
affect of this filter is that it allows an associated result field to report the full non-prorated database
value of the last productive task completed within a reporting period.
Notes: This function can only be used once in a single filter, and can not be combined with any of its
related functions. It can only be used as a report filter. If reporting tasks based on a timescale, do not
use a timescale with a resolution smaller than that of the calendar used to run the schedule with this
XCM. For example, if a schedule was run using a monthly calendar, do not use a timescale created
based on weekly intervals.
RELATED FUNCTIONS
LastStartedTask, FirstCompletedTask, FirstStartedTask, FirstTask, LastTask
LastStartedTask
DESCRIPTION
Returns true for all productive steps which were started (eg Initial percentage of 100) in a given
reporting period, but resets the associated result fields accumulated value whenever returning true. It
has a side affect that the associated Result field does not pro-rata database values. The net affect of this
filter is that it allows an associated result field to report the full non-prorated database value of the last
productive task started within a reporting period.
Notes: This function can only be used once in a single filter, and can not be combined with any of its
related functions. It can only be used as a report filter.
RELATED FUNCTIONS
LastTask
Returns true for all productive steps in a given reporting period, but resets the associated result fields
accumulated value whenever returning true. It has a side affect that the associated Result field does not
pro-rata database values. The net affect of this filter is that it allows an associated result field to report
the full non-prorated database value of the last productive task within a reporting period.
Notes: This function can only be used once in a single filter, and can not be combined with any of its
related functions. It can only be used as a report filter.
RELATED FUNCTIONS
LastStartedTask, LastCompletedTask, FirstCompletedTask, FirstStartedTask, FirstTask
LoadPolygon
Loads the vertices for the specified record, activity and polygon index. If RecNum is equal to 0,
CURRENT or is not given then the polygon associated with the current record in the main database
will be assumed. If Activity is equal to 0, DEFAULT_ACTIVITY or is not given then the default
activity will be assumed. Otherwise the polygon associated with the given activity number will be
assumed. PolygonIndex is the 1-based index of the sub-polygon to load. If it is 0 or not specified, all
sub-polygons will be returned.
Returns the number of vertices in the array (see note below) or -1 on failure. Will return zero (0) if the
record exists but there are no vertices in the polygon.
RELATED FUNCTIONS
SavePolygon, GetPolygonCount, GetPolygonVertexCount
Note: If VertexArray has been defined as a fixed-sized array, LoadPolygon will load as many vertices
as possible into the array. If VertexArray has been defined as a resizeable array, it will be resized to
accommodate as many vertices as are present in the polygon being loaded. LoadPolygon will always
return the number of vertices loaded into the array regardless of the array type. It is important to note
that if a fixed-size array is used, this may be different from the number of vertices in the database.
Sub Main
Dim lVertexCount As Long ' To get the number of vertices returned
Dim lVertex As Long
Dim Polygon() As Vertex ' The polygon data (a resizeable array)
lVertexCount = LoadPolygon(Polygon) ' Load the polygon for the current record
Print “Vertices for record #” & GetRecNum(CURRENT)
For lVertex = 1 To lVertexCount
Print “ “ & Polygon(lVertex).dX & “ “ & Polygon(lVertex).dY & “ “
Polygon(lVertex.dZ)
Next lVertex
End Sub
M, C, P, R Accessors
DESCRIPTION
Provides access to field values for the current database and record. Either a constant or variable integer,
or one of the field row constants, can be used to index into the array. The value in the array is based
upon the field type as follows:
Additive, Weight Average, If the data field is one of these numeric field types,
Average, Min, Max, Difference, then the accessor will return the value of the field.
Ratio, Product and Sum
Classified and Note If the data field is a string field type, then the
accessor will return the internal ID of the string.
Date (Min) and Date (Max) If the data field is a date field type, then the
accessor will return the date as a double.
MakeRGB
DESCRIPTION
Returns the RGB colour number as a long data type. The RGB colour number is a unique number that
represents a certain combination of red, green and blue.
ARGUMENTS
Red Value The red value is passed by value as an integer data type. Valid inputs
range from zero to 255.
Green Value The green value is passed by value as an integer data type. Valid
inputs range from zero to 255.
Blue Value The blue value is passed by value as an integer data type. Valid
inputs range from zero to 255.
If the number assigned to the red, green or blue values is outside the specified range, then values below
zero become zero and values above 255 become 255.
If you wish to see a dull red then you would use a combination like MakeRGB (50, 0, 0). If you want a
brighter red then you could use MakeRGB (255, 0, 0).
The colours are mixed in the same way as your colour television. Below is a rough guide to the colours
produced with different mixes of red, green and blue.
VALUES RETURNED
The function returns the RGB colour number as a long data type.
EXAMPLES
(1) Assign an RGB number to a data field so it can be plotted.
Sub Main
Dim lRGBNum As Long
'Assign a colour according to the ore grade
If (M(mOre_Grd)<=2.0) Then lRGBNum = MakeRGB(255, 255, 255) 'White
If (M(mOre_Grd)> 2.0) Then lRGBNum = MakeRGB(255, 255, 0) 'Yellow
If (M(mOre_Grd)> 2.5) Then lRGBNum = MakeRGB(0, 255, 255) 'Cyan
If (M(mOre_Grd)> 3.0) Then lRGBNum = MakeRGB(0, 255, 0) 'Green
If (M(mOre_Grd)> 3.5) Then lRGBNum = MakeRGB(0, 0, 255) 'Blue
If (M(mOre_Grd)> 4.0) Then lRGBNum = MakeRGB(255, 0, 255) 'Magenta
If (M(mOre_Grd)> 4.5) Then lRGBNum = MakeRGB(255, 0, 0) 'Red
'Write the RGB Colour number to a data field
M(mOre_Colour) = lRGBNum
'This data field can now be used in a data field polygon plot to
'determine the colour the block is shaded. In the polygon template,
'set the Legend Type to "RGB Colour Field/Expression" and set the
'Field/Expression to M(mOre_Colour).
End Sub
RELATED FUNCTIONS
QBColor
OffsetPolygon
RELATED FUNCTIONS
LoadPolygon, SavePolygon, GetPolygonCount, GetPolygonVertexCount, ScalePolygon
OpeningDumpCapacity
Returns the remaining capacity at the start of the time period, for the specified dump database capacity
data field, for all steps passed by the filter.
OpeningInv
Returns the accumulated inventory at the start of the time period, for the specified main database data
field, for all steps passed by the filter
OpeningInvSP
OpeningInvSP
Returns the accumulated inventory at the start of the time period, for the specified stockpile database
data field, for all steps passed by the filter.
OperatingHrs
Returns the accumulated productive and non-productive operating hours for all steps passed by the
filter.
OriginalValue
Returns the value for a specified data field at the beginning of the schedule based on the position in
level number at each database level.
PeriodEnd
PeriodStart
Pil
Used to only pass record that have the specified position in level number at the specified database level.
PointInPolygon
RELATED FUNCTIONS
LoadPolygon, SavePolygon, GetPolygonCount, GetPolygonVertexCount
Dim lParentRec As Long
Dim binside As Boolean
Dim Poly As vertex
Sub Main()
Dim MyTestPoint As vertex
lParentRec = 4 ' Hard coded, I know record 4 has valid poly
information !
LoadPolygon Poly, lParentRec
MyTestPoint.dx = 3000 ' Your dx
MyTestPoint.dy = 2500 ' Your dY
bInside = PointInPolygon(Poly, MyTestPoint)
MsgBox binside
End Sub
PolygonArithmetic
Performs arithmetic with polygons. The polygon specified by Poly1 is modified with the operation
specified and Poly2, and the result returned in ResultPoly.
The available operations are:
PA_UNION – returns the union of Poly1 and Poly2.
PA_INTERSECTION – returns the intersection of Poly1 and Poly2.
PA_REMAINDER – returns the result of Poly1 minus Poly2.
This function will only use the first sub-polygon in Poly1 and Poly2 if an intersection or remainder
operation is being performed, although it may return multiple sub-polygons in Result, depending on the
operation specified and the input polygons. For union operations, all sub-polygons in Poly1 and Poly2
are processed, and one or more resultant polygons are returned in Result, depending on the input
polygons.
Returns the total number of vertices output in Result.
Sub Main
' Intersect the polygon for activity 1 and activity 2 of the current record
‘ and save the result in activity 3
Dim Poly1() As Vertex
Dim Poly2() As Vertex
Dim Result() As Vertex
End Sub
RELATED FUNCTIONS
LoadPolygon, SavePolygon, GetPolygonCount, GetPolygonVertexCount
Polygon 1
Polygon2
Operation
PA_UNION
PA_INTERSECTION
PA_REMAINDER
QBColor
This method is obsolete from XPAC 2005 onwards. To use, place the above function prototype in the
script file above the Sub Main declaration.
DESCRIPTION
Returns the RGB colour number for one of the following standard colours.
0 Black 8 Grey
The RGB colour number is a unique number that represents a certain combination of red, green and
blue. This function allows you to specify a standard colour without knowing its red, green and blue
components.
Note that the American spelling of color has been used for this function, as with most other computer
programs.
ARGUMENTS
Standard Colour The standard colour number should be in the range of zero to 15.
Number It represents a standard colour from the above table.
The standard colour number is passed by value as an integer data
type.
VALUES RETURNED
The function returns the RGB colour number as a long data type.
If the standard colour number passed into the function is outside the range of zero to 15, then the
function will report an error.
EXAMPLES
(1) Assign an RGB number to a data field so it can be plotted.
Sub Main
Dim lStdColNum As Long
'Assign a standard colour number according to the block RL
If (M(mBlk_RL)<=200) Then lStdColNum = 0 'Black
RELATED FUNCTIONS
M, C, P, R Accessors
DESCRIPTION
Provides access to field values for the current database and record. Either a constant or variable integer,
or one of the field row constants, can be used to index into the array. The value in the array is based
upon the field type as follows:
Additive, Weight Average, If the data field is one of these numeric field types,
Average, Min, Max, Difference, then the accessor will return the value of the field.
Ratio, Product and Sum
Classified and Note If the data field is a string field type, then the
accessor will return the internal ID of the string.
Date (Min) and Date (Max) If the data field is a date field type, then the
accessor will return the date as a double.
MakeRGB
RadToDeg
DESCRIPTION
Returns the number of degrees in the specified number of radians.
This function is useful when using the arc tangent function, as it returns an angle in radians.
ARGUMENTS
Radians The radians are passed into the function by value as a double data type.
VALUES RETURNED
The function returns the number of degrees in the specified number of radians. The relationship
between degrees and radians is as follows.
EXAMPLES
(1) Convert an angle in radians to degrees.
Dim dRLFirstBlk As Double
Sub Main
Dim lNumBlocks As Long
Dim dDrvDipRad As Double
Const dBLKLENGTH = 50
'To determine whether mining equipment can travel along the floor of
'a Drive, calculate the dip of the floor
If (IsFirst()) Then dRLFirstBlk = M(mCent_RL) 'RL of First Block in Drive
If (IsLast()) Then 'All other calculations done for Last Block in Drive
lNumBlocks = GetNumChildren(UP)
dDrvDipRad = Atn((dRLFirstBlk–M(mCent_RL)) / (lNumBlocks*dBLKLENGTH))
'Write the overall dip of the Drive into the last Block
M(mDrv_Dip) = RadToDeg(dDrvDipRad)
End If
End Sub
RELATED FUNCTIONS
DegToRad, Atn, Sin, Cos, Tan.
ReadBaseValue
DESCRIPTION
Read a value from a data field in a record in the specified database. The data field that is read may
have any field type, ie. Additive, Classified, Note, etc. The function will read base values and not
period values. Only the Main Database has period values. Use “DbReadValue” to read period values.
ARGUMENTS
Database Name The database name is used to look for the specified record
number. It is passed by reference as a variant data type.
The database name may be provided explicitly as a string in
double quotes. For example “Main”, “5 Year Calendar”, “Default
Parameters”, “Equipment Hours”, etc.
Alternatively, the database name may be one of the following
Options Description
ACTIVE_MAIN The main database.
ACTIVE_CALENDAR The active calendar database.
ACTIVE_RESULTS The active results database.
Record Number The record number is used to identify the record whose value is
returned by this function. It is passed by value as a long data
type.
Note that the record pointers, such as NXT, UP, etc, cannot be
used in this argument.
Data Field Number The value to read in the database is identified by its data field
number. It is passed by value as a long data type.
In general, the full row codes cannot be used in this argument, as
they are only recognised for the database over which the XCM is
being run. However, the function GetRowNumFromCode can
be used to get the data field number, given the full row code and
the database name.
VALUES RETURNED
This function returns a variant data type. The type of return value is dependent on the field type of the
data field.
Additive, Weight Average, If the data field is one of these numeric field types,
Average, Min, Max, Difference, then the function will return a double data type.
Ratio, Product and Sum
Classified and Note If the data field is a string field type, then the
function will return a string data type.
Date (Min) and Date (Max) If the data field is a date field type, then the
function will return a date or a double data type.
EXAMPLES
(1) Read a base value from the Main database.
Sub Main
Dim dValue As Double
dValue = ReadBaseValue("Main", 2, 1)
Print CStr(dValue)
End Sub
RELATED FUNCTIONS
WriteBaseValue, DbReadName, DbReadValue, DbWriteValue, GetRecNum, GetRowNumFromCode
ReadValue
DESCRIPTION
Reads a value from a data field in a record in the specified database. The data field that is read may
have any field type, ie. Additive, Classified, Note, etc
ARGUMENTS
Database Name The database name is used to look for the specified record
number.
The database name may be provided explicitly as a string in
double quotes. For example “Main”, “5 Year Calendar”, “Default
Parameters”, “Equipment Hours”, etc.
Alternatively, the database name may be one of the following
options. Note that these options should not be in quotes.
Options Description
ACTIVE_MAIN The main database.
ACTIVE_CALENDAR The active calendar database.
ACTIVE_RESULTS The active results database.
Full Row Code The full row code of the field to read. It is passed by value as a
string data type.
Lvl0 – lvl10 An identifier for each level in the database down to the desired
record. The identifier at each level can be either the record name
as a string, or the record APIL as an integer or long.
Below the level of the desired record, either a value of -1 or an
empty string should be used to specify that the level is not
significant.
VALUES RETURNED
This function returns a variant data type. The type of return value is dependent on the field type of the
data field.
Additive, Weight Average, If the data field is one of these numeric field types,
Average, Min, Max, Difference, then the function will return a double data type.
Ratio, Product and Sum
Classified and Note If the data field is a string field type, then the
function will return a string data type.
Date (Min) and Date (Max) If the data field is a date field type, then the
function will return a date or a double data type.
record number.
EXAMPLES
(1) Read a value from the Parameters database.
Sub Main
Dim dValue As Double
dValue = ReadValue("Parameters", "pTest", 1, "Dozer1", 3, -1, -1, -1, _
-1, -1, -1, -1, -1)
Print CStr(dValue)
End Sub
RELATED FUNCTIONS
WriteValue, ReadBaseValue, DbReadValue, DbWriteValue
RecalculateDatabase
DESCRIPTION
Recalculates the specified database. If no Database Name is specified, it will recalculate the selected
database. Set bFullRecalc to true to make this function perform a Full Recalc rather than a Quick
Recalc.
ReducePolygonComplexity
DESCRIPTION
Eliminates duplicate or redundant points in the specified polygon. For example, if three points are
collinear in the polygon, the middle point will be removed, as it does not affect the shape of the
polygon. When determining whether points are collinear, the tolerance factor specified by the optional
argument dTolerance is used. If it is not defined, it will default to a small number.
RELATED FUNCTIONS
LoadPolygon, SavePolygon, GetPolygonCount, GetPolygonVertexCount
Note: If Poly has been defined as a fixed-sized array, ReducePolygonComplexity will not resize the
array before returning to the caller. If VertexArray has been defined as a resizeable array, it will be
resized to accommodate the reduced number of vertices based on the simplification of the polygon.
Released
Returns the accumulated released value for the specified main database data field, for all steps passed
by the filter.
RemoveAllDependencies
Sub RemoveAllDependencies()
DESCRIPTION
Unloads the active scenario dependencies and removes the applied rules.
This does not delete the rule sets, the rules sets will all go red and need to be re-applied the next time
you schedule.
Note: This function cannot be called during scheduling.
RemoveDependency
This removes a dependency between the Current Record activity 1 and the previous record activity 3.
RELATED FUNCTIONS
GetDependencies,
GetDependencies, GetPredecessor,
GetPredecessor, GetSuccessor,
GetSuccessor,
GetNumberOfPredecessors,, GetNumberOfSuccessors,
GetNumberOfPredecessors GetNumberOfSuccessors,
SetDependency,
SetDependency, Released
Returns the accumulated released value for the specified main database data field, for all steps passed
by the filter.
RemoveAllDependencies
RemoveRecord
DESCRIPTION
Removes the specified record number from the database over which the XCM is running. This
function should be used with extreme care as the record(s) cannot be retrieved after they have been
removed.
Upper level records can be removed using this function. When an upper level record is removed, all of
its children are also removed.
ARGUMENTS
Record Number This argument represents the record number for the record that
you want to remove. The record will be removed from the
VALUES RETURNED
The function returns a boolean data type. If the record has been successfully removed from the
database it will return a True value. If the record is not removed from the database, the function will
return a False value.
If you specify a record number of one, for the Top record, the following message will be displayed and
neither the record nor its children will be removed.
If the specified record number does not exist in the database, then the following message will be
displayed. The XCM will then stop processing.
EXAMPLES
(1) Remove records from a database.
Sub Main
Dim sBlockName As String
Dim bRecRemoved As Boolean
'Remove all ramp records from the main database
sBlockName = GetRecNameAtLevel(3)
If (sBlockName = "Ramp") Then
bRecRemoved = RemoveRecord(CURRENT)
If (bRecRemoved = False) Then Print GetRecNum(CURRENT) & "Not Removed"
End If
End Sub
RELATED FUNCTIONS
ClosingInv
DESCRIPTION
Returns the accumulated inventory at the end of the time period, for the specified main database data
field, for all steps passed by the filter.
ClosingInvSP
ClosingInvSP
DESCRIPTION
Returns the accumulated inventory at the end of the time period, for the specified stockpile database
data field, for all steps passed by the filter.
CreateRecord, GoRec, GetRecNum
RemoveTask
DESCRIPTION
This function will remove the specified task from the Available Block List.
ARGUMENTS
sResourceName The name of the resource from whose ABL to remove the task
REMARKS
This function is available only in User Processing Scripts.
ResetMaxCapacity
DESCRIPTION
This function will reset the maximum capacity of the capacity constraints.
ARGUMENTS
lRecord This argument represents the record number for the record that
you want to reset.
The record number is passed to the function by value and is a long
data type.
A record of value of –1 will reset all records in the constraints
REMARKS
This function is available only in User Processing Scripts.
All blocks in the available block list flagged as over capacity will be retested against the capacity
constraints.
If you change the constraint maximum in the Main Database you must call ResetMaxCapacity
for your changes to take effect in the current period.
Note: The “Allow Database Writes” option on the AutoScheduler Modes tree item, must be ticked on
for you to change the value of fields that are being used while scheduling.
Example :
If an area is constrainted to only allow 1000 tonnes of material to be moved, and a total of 800 tonnes
has so far been removed, and a script changes the maximum capacity to 1100, after calling this
function the amount allowed to be moved will be changed from 200 to 300 tonnes.
Resource
Used to only pass steps that were scheduled by the specified resource.
RNOEXDB
This method is obsolete from XPAC 2005 onwards. To use, place the above function prototype in the
script file above the Sub Main declaration.
DESCRIPTION
Returns a record number from some other XPAC project. The record is defined by its path name and
the name of the database it is within. The XPAC project is uniquely identified using its full path name
and file name.
ARGUMENTS
Project Name This argument is the full path and file name for the XPAC project,
ie. the location and name of the xpk file. It is passed by reference
as a variant data type. It should appear in quotes.
Database Name This argument is the name of the database within the XPAC project
specified in the first argument. It is passed by reference as a
variant data type. It should appear in quotes.
Note that in this function, the database name is case sensitive.
Record Path The record for which the record number is sought is defined by its
Name full path name in this argument. This argument is passed by value
as a string data type. Note that the record can be an upper or lowest
level record.
The record path name consists of the name at each level, separated
by a back slash (\). It should appear in quotes.
For example, “AreaC\RL350\37”.
VALUES RETURNED
The function returns the record number for the specified record as a long data type.
If the path or file name for the XPAC project do not exist, an error message will be displayed to
indicate this.
If the database does not exist in the specified project, the XCM will return an “Unspecified failure”.
If the project and database names are valid, but the specified record does not exist in the database, the
function will return a value of –1.
EXAMPLES
(1) Find the record number for a record in a different XPAC project.
Sub Main
Dim sProjPath As String
Dim sProjName As String
Dim sDBName As String
Dim sRecPath As String
'Find the record number for the same record in an old version
'of the database.
sProjPath = "D:\July 2001\Two Year Plan\"
sProjName = "Mt Black Gold Mine.xpk"
sDBName = "Main"
RELATED FUNCTIONS
GetRecNum, GetRecNumFromPath, DbReadName
RosterHrs
This function returns the number of rostered hours within the reporting period (in the report writer), for
the specified roster with the specified roster exceptions applied. The specified roster and roster
exceptions do not have to be utilised in the active schedule scenario.
' This function is used in the Report Writer in the Results column.
' Calculate the Rostered Hours for the roster called “5 Day Roster”
' and the roster exceptions called “Public Holidays”.
RosterHrs(“5 Day Roster”, “Public Holidays”)
' Calculate the Rostered Hours for the roster called “Continuous Shift Roster”
' without any roster exceptions applied.
RosterHrs(“Continuous Shift Roster”, “”)
RosterHrsResource
' This function is used in the Report Writer in the Results column.
' Calculate the Rostered Hours for the resource called “Large Rope Shovel”
RosterHrsResource(“Large Rope Shovel”)
RunActiveScenario
DESCRIPTION
Runs the schedule for the active scenario in the current project. The schedule is run from the specified
start period to the specified finish period. A schedule progress bar can be optionally displayed.
ARGUMENTS
Start Period The start period number is passed into the function by value as a
Number long data type. This is the first period over which the schedule
will be run.
Each lowest level record in the calendar database is assigned a
consecutive number, which is the period number. Refer to the
calendar database for the active scenario to locate the relevant
period numbers.
Passing -1 as the start period number will force the scenario to be
run from initial status.
Finish Period The finish period number is passed into the function by value as a
Number long data type. This is the last period over which the schedule will
be run.
Each lowest level record in the calendar database is assigned a
consecutive number, which is the period number. Refer to the
calendar database for the active scenario to locate the relevant
period numbers.
Display Progress The third argument is passed into the function by value as a
Bar boolean data type.
If it is set to True, the schedule progress dialog will be displayed
while the active scenario is being scheduled, to indicate the
progress through the schedule.
If it is set to False, the schedule progress dialog will not be
displayed.
VALUES RETURNED
This function returns an integer data type. The return value indicates whether the schedule ran
successfully or whether some error was encountered.
Additional information can be obtained about these errors using the function called GetLastError.
Return Description
Value
0 The schedule was successfully run for the active scenario over the requested
periods.
1 The user pushed the Cancel button while the schedule was running, so the
schedule was not completed for all periods.
2 A general error occurred during the schedule.
For example, the active scenario did not have a calendar attached, a field
code used in the schedule setup was invalid, there was no accumulation field
assigned for a resource, an input path was not assigned to a standard
resource, an error was found compiling a user processing script, etc.
3 An objective could not be achieved for one of the resources.
4 There was a run-time error in a user processing script.
The user tried to schedule from a time period later than the schedule start
period, while the “Disable Advance to Start” option was ticked on in the Global
Options.
5 Reserved for future use.
EXAMPLES
(1) Run the active scenario and report whether it was successful.
Sub Main
Dim lSchedResult As Long
'Run a schedule scenario and confirm that it was successful
Call SetActiveScenario("Life of Mine Schedule")
lSchedResult = RunActiveScenario(1, 30, TRUE)
If (lSchedResult = 0) Then Print "Schedule Succeessful."
If (lSchedResult > 0) Then Print "Error Encountered in Schedule."
End Sub
RELATED FUNCTIONS
GetActiveScenarioName, SetActiveScenario
RunMacro
DESCRIPTION
Runs a macro from within the current XCM, over the current project.
ARGUMENTS
Macro Name This argument is the name of the macro and it is passed to the
function by value as a string data type.
Macro Location The macro location defines where the specified macro is stored. It
is passed by value as an integer data type.
The macro location is an optional argument. If it is not passed into
the function, then it is assumed to have a value of zero.
The macro location may be set to one of the following values:
Value Description
0 XPAC will first look for the macro in the current project (This Model). If
it is not found there, then it will look for it in the Personal Macro File
which is called “XPACPreferences.mdb” and is stored under “My
Documents”.
1 XPAC will only look for the macro in the current project (This Model).
2 XPAC will only look for the macro in the Personal Macro File which is
called “XPACPreferences.mdb” and is stored under “My Documents”.
VALUES RETURNED
This function returns an integer data type, which indicates whether the macro was run successfully.
The following values may be returned.
Abort The macro name does not exist in the specified macro location.
EXAMPLES
(1) Run a number of macros from within a Run Once XCM.
Sub Main
Dim lResult As Long
'Run the current schedule scenario
lResult = RunMacro("RunSchedule", 1)
If (lResult <> 0) Then Print "Run Schedule Unsuccessful"
'Generate a period progress plot for the schedule
lResult = RunMacro("PeriodProgress", 1)
If (lResult <> 0) Then Print "Plot Unsuccessful"
End Sub
RELATED FUNCTIONS
RunScript
RunScheduleReport
Returns true if the report was able to be run successfully (even if cancelled in interactive mode).
This function can be called from an XCM, either standalone or called by a User Processing event. This
allows a PostSchedule script to automatically run one or more reports. To call this function from an
event other than PostSchedule would get incorrect results.
There are two modes: silent (bInteractive = false, the default) and interactive (bInteractive = true).
Silent mode runs as if you opened the report selection dialog and pressed Select, whereas interactive
mode brings up the Report Writer designer and allows you to edit the output options before running, as
if you pressed Edit.
RunScript
DESCRIPTION
This function is used to run an XCM (a script) from within the XCM that is currently running. The
new script can be run over any database and any range within that database.
ARGUMENTS
Database Name This is the name of the database in which the XCM is to be run.
It is passed by reference as a variant data type.
The database name may be provided explicitly as a string in double
quotes. For example “Main”, “5 Year Calendar”, “Default
Parameters”, “Equipment Hours”, etc.
Alternatively, the database name may be one of the following options.
Note that these options should not be in quotes.
Options Description
ACTIVE_MAIN The main database.
ACTIVE_CALENDAR The active calendar database.
ACTIVE_RESULTS The active results database.
Script Name This is the name of the XCM that you want to run. It is passed by
value as a string data type.
The XCM name should be in double quotes and it should include
the .bas extension.
If the XCM is not in the same directory as the current XCM that is
running, then the full path name should be provided for the XCM.
For example, “D:\Five Year Plan\Xpac\M05 Equipment
Data.bas”.
Database Range This argument is the name of the database range over which the
Name XCM should be run. The database range should exist in the
specified database. It is passed to the function by value as a string
data type.
The database range name is an optional argument. If it is not
provided, then the XCM will be run once.
If the database range cannot be found in the specified database,
then the XCM will not be run and an error 3 will be returned. The
user will also be presented with an error message box.
VALUES RETURNED
This function returns an integer data type. It may be one of five values as described below.
0 The function returns a value of zero if the XCM has been successfully run
over the specified database.
The requested script name is the same as the running script name.
The requested script doesn’t exist.
EXAMPLES
(1) Run a number of XCMs from within one XCM.
Sub Main
Dim lRes(2) As Long
Const sDBName = "Main"
Const sRangeName = "Area 49R"
'Run a series of XCMs over the Main database and print a message to
'indicate whether each one was successful.
If IsFirstInRange() Then
lRes(1) = RunScript(sDBName, "M01 Insitu Reserves.bas", sRangeName)
If (lRes(1) > 0) Then Print "M01 was not Successful."
lRes(2) = RunScript(sDBName, "M02 ROM Reserves.bas", sRangeName)
If (lRes(2) > 0) Then Print "M02 was not Successful."
End If
End Sub
RELATED FUNCTIONS
GetDatabaseName, GetActiveCalendarName, RunMacro
SafeDivide
DESCRIPTION
Returns the result of dividing the numerator by the denominator.
ARGUMENTS
The two arguments for this function are double data types and both are passed by value.
VALUES RETURNED
The function will return a double data type.
If the denominator is zero, the function will return zero instead of giving an error. Conversely, the
division character (/) will return an error when dividing by zero.
EXAMPLES
(1) Use SafeDivide if the denominator may be zero.
Sub Main
RELATED FUNCTIONS
If…Then.
SavePolygon
Sub SavePolygon ( ByRef Poly() As Vertex, optional ByVal RecNum As Long, optional
ByVal Activity As Long, optional ByVal PolygonIndex As Long )
Saves the vertices for the specified record, activity and polygon index. If Vertex is an empty array, the
polygon associated with the specified record, activity and polygon index will be deleted. If RecNum is
equal to 0, CURRENT or is not given then the polygon associated with the current record in the main
database will be assumed. If Activity is equal to 0, DEFAULT_ACTIVITY or is not given then the
default activity will be assumed. Otherwise the polygon associated with the given activity number will
be assumed. PolygonIndex is the 1-based index of the sub-polygon to replace. If it is 0 or not specified,
all existing sub-polygons will be replaced.
RELATED FUNCTIONS
LoadPolygon, GetPolygonCount, GetPolygonVertexCount
Sub Main
' Delete all the polygons for the current record and activity
Dim Polygon() As Vertex
While GetPolygonCount > 0
SavePolygon P
Wend
End Sub
ScalePolygon
Sub ScalePolygon ( ByRef Poly() As Vertex, ByVal Scale As Double, optional ByVal
AsLinearScale As Boolean )
Scales a polygon up or down. Scale specifies either a fixed distance to move the points or a percentage
to grow or shrink the polygon. If AsLinearScale is false (the default), Scale specifies a fixed distance,
with negative values shrinking the polygon and positive values expanding it. If AsLinearScale is true,
Scale specifies a percentage multiplier, with 1.0 maintaining the current size, smaller values shrinking
the polygon, and larger values expanding it.
RELATED FUNCTIONS
LoadPolygon, SavePolygon, GetPolygonCount, GetPolygonVertexCount, OffsetPolygon
ScanCircleReference
This method is obsolete from XPAC 2005 onwards. To use, place the above function prototype in the
script file above the Sub Main declaration.
Returns true if a circular reference is found.
Refer to “Circular Referenece Testing” section in the “AutoScheduler UserGuide.doc” for more
information about what circular references are and how to remove them.
ScanCircleReferenceFrom
This method is obsolete from XPAC 2005 onwards. To use, place the above function prototype in the
script file above the Sub Main declaration.
Returns true if a circular reference is found
Starts scanning from lRecord and only visits records that are connected with lRecord via a dependency
chain.
Refer to “Circular Referenece Testing” section in the “AutoScheduler UserGuide.doc” for more
information about what circular references are and how to remove them.
SetActivePolygonSet
Sets the active polygon set that all polygon functions will use. The script will default to the first
polygon set.
Returns true if successfully loaded the set. Returns false on error.
SetActiveScenario
DESCRIPTION
Set the specified scenario to be the active scenario in the current project.
ARGUMENTS
Scenario Name This argument defines the scenario that you want to make active in
the current project. The scenario name is passed into the function
by value as a string data type.
The scenario name should be in quotes and it should be exactly the
same as it appears in the schedule setup tree.
VALUES RETURNED
This function returns a boolean data type.
If the specified scenario exists in the current project, then it will be made active and the function will
return a True value. If the specified scenario is already active in the current project, then it will remain
active and the function will still return a True value.
If the specified scenario does not exist in the current project, a message will be displayed to indicate the
specified scenario could not be made active and the function will return a False value. The scenario
that was active before the function was called will remain active in this case.
EXAMPLES
(1) Set the active scenario.
Sub Main
Dim bScenarioSet As Boolean
Dim sMsg As String
'Set a scenario to be active then run the schedule
bScenarioSet = SetActiveScenario("Three Month Schedule")
If (Not(bScenarioSet)) Then
sMsg = "Requested scenario does not exist. Schedule cannot be run."
Call Abort(sMsg)
End If
Call RunActiveScenario(1, 10, TRUE)
End Sub
RELATED FUNCTIONS
GetActiveScenarioName, RunActiveScenario
SetClass
DESCRIPTION
Assign the classification to the specified classified data field in the current record.
ARGUMENTS
Data Field Number The data field number is passed by value as an integer data type.
It is used to identify the classified data field in the current
database. The data field number may be passed in as a number
or as a full row code.
VALUES RETURNED
The function returns a boolean data type, indicating whether the classification was successfully
assigned to the data field.
If the classification was successfully assigned, the function will return a True value.
If the classification was not successfully assigned, the function will return a False value. This may
happen if the data field is not a classified field or if the classification is not a string.
EXAMPLES
(1) Set a classified field.
Sub Main
'Test the Gold Grade (g/t) to class material as Ore or Waste
If (M(mBlk_Au_Grade) > 1.2) Then
Call SetClass(mBlk_Mat_Type, "Ore", True)
Else
Call SetClass(mBlk_Mat_Type, "Waste", True)
End If
End Sub
RELATED FUNCTIONS
GetClass, DbWriteValue, GetNote, GetFieldInfo
SetDependency
Call SetDependency(1,2,0,0)
Will set a dependency between record number 1 (all activities) and record number 2 (all activities).
Call SetDependency(1,2,1,3)
Will set a dependency between record number 1 (activity 1) and record number 2 (activity 3).
Call SetDependency (CURRENT, PRVSIB, 1, 3)
This adds a dependency between the current record (activity 1) and the previous record (activity 3)
RELATED FUNCTIONS
GetDependencies,
GetDependencies, GetPredecessor,
GetPredecessor, GetSuccessor,
GetSuccessor,
GetNumberOfPredecessors,
GetNumberOfPredecessors, GetNumberOfSuccessors,
GetNumberOfSuccessors, Released
Returns the accumulated released value for the specified main database data field, for all steps passed
by the filter.
RemoveAllDependencies, SetDependencyOnRange
SetDependencyEx
This function extends the functionality of the SetDepedency function use this only if you want to add
“or rules” or a dependency with a release profile.
The function returns the id of the new dependency rule, this id can be used to add other rules to form an
“or” group.
Returns -1 on failure, 0 when it successfully creates an “and” rule, and the group number of the new
dependency rule if it successfully creates an “or” rule.
Example: to make the rule B->A or B->C
Dim lGroupId As Long
lGroupId = SetDependencyEx(RecordNoB, RecordNoA, 0, 0, TRUE, “100% lag”)
call AddDependencyToGroup(lGroupId, RecordNoB, RecordNoC, 0, 0, “100% lag”)
SetDependencyOnRange
Similar function to SetDependency but allows the dependencies to be set over a range
Either lSuccessor is set to a non-negative record or sSuccessorRange is given a non-empty string for
the range, but not both. Likewise for lPredecessor and sPredessorRange.
SetDependencyOnRange calls SetDependency for each record in each range given. So if
sSuccessorRange contains 4 records and sPredecessorRange contains 7 records then 28 ( = 4 * 7 )
dependencies will be set.
RELATED FUNCTIONS
GetDependencies,
GetDependencies, GetPredecessor,
GetPredecessor, GetSuccessor,
GetSuccessor,
GetNumberOfPredecessors,
GetNumberOfPredecessors, GetNumberOfSuccessors,
GetNumberOfSuccessors, Released
Returns the accumulated released value for the specified main database data field, for all steps passed
by the filter.
RemoveAllDependencies, SetDependency
SetFieldInfo
DESCRIPTION
Sets data field information within data field design, for the specified data field in the specified
database. The data field information that can be set includes the code, name, units, field type, activity
and protection.
This function is often used in conjunction with the subroutine GetFieldInfo to change one or two of the
data field parameters. This is illustrated in Example 2.
Note that any changes that you make to the data field design using SetFieldInfo will not be displayed
until you close the database and reopen it.
ARGUMENTS
Data Field Number The data field number is used to identify the data field for
which parameters are to be assigned. It may be passed in
as a number or as a full row code. This argument is passed
by value as an integer data type.
Data Field Information This argument is passed to the function by reference using
an XPAC-defined data structure called FieldInfo.
A data structure is a data type that contains multiple
elements. This enables you to store multiple values using a
single argument. The elements of the data structure are
defined by XPAC, so it is referred to as XPAC-defined.
The elements of the FieldInfo data structure are provided
below.
Element Description
FieldCode Sets the data field code (not the full row code) as a string
data type.
FieldName Sets the data field name as a string data type.
Units Sets the data field units as a string data type.
FieldType This parameter is a long data type. Constants are defined
by XPAC with meaningful names, to represent the various
field type values that may be set. These constants are
listed below.
FTYPE_ADDITIVE sets it to Additive
FTYPE_AVG sets it to Average
FTYPE_WTAVG sets it to Weighted Average
If the data field is not one of the above field types, then
Param1 should be set to –1.
If the data field is not one of the above field types, then
Param2 should be set to –1.
IncludeZeros For some field type settings there is a check box available
to include or exclude zeros from the field type calculations.
This parameter is a boolean data type that sets this
checkbox.
To Include Zeros (ie. tick the box) the parameter should be
set to True.
To not Include Zeros (ie. the box not ticked) the parameter
should be set to False.
Activity This parameter should be set to the activity number for the
When this function is used, a variable should be passed in for the Data
Field Information argument. That variable must be declared as a
FieldInfo type. For example:
Dim DataField As FieldInfo.
The elements of the FieldInfo structure can be referenced using the
variable name, followed by a full stop and then the relevant element
name. For example:
DataField.FieldCode
DataField.Activity
DataField.Protection
To assign data field parameters using this function, the elements of this
structure should have their values set before the function is called.
If you only want to change one or two of the data field parameters, it is
best to read all of the current parameters, change the relevant ones and
then set all of the data field parameters. This is done using GetFieldInfo
and then SetFieldInfo and is illustrated in Example 2.
Database Name The database name is used to look for the specified data field
number. It is passed by reference as a variant data type.
The database name may be provided explicitly as a string in double
quotes. For example “Main”, “5 Year Calendar”, “Default
Parameters”, “Equipment Hours”, etc.
Alternatively, the database name may be one of the following
options. Note that these options should not be in quotes.
Options Description
ACTIVE_MAIN The main database.
ACTIVE_CALENDAR The active calendar database.
ACTIVE_RESULTS The active results database.
VALUES RETURNED
This function returns a boolean data type.
If the data field design is successfully updated, then the function returns a True value. This is the case,
even if the values of the data field parameters are not altered.
If the data field design is not successfully update, then the function returns a False value. For example,
if you attempt to use SetFieldInfo with protection or field type values other than those listed above, the
function will not be able to update the data field design and it will return a False value. For this reason
it is important to check the return value of the function.
EXAMPLES
(1) Set data field information.
Sub Main
Dim NewField As FieldInfo
Dim bFieldCreated As Boolean
'Set the data field name and field type
NewField.FieldName = "Roadway Length"
NewField.FieldType = FTYPE_ADDITIVE
bFieldCreated = SetFieldInfo(20, NewField, "Main")
If (bFieldCreated = False) Then Print "Unsuccessful Data Field Creation"
End Sub
RELATED FUNCTIONS
GetFieldInfo, DbReadValue, DbWriteValue
SetGlobalArray
DESCRIPTION
Saves the value of an array variable to the temporary store inside XPAC.
ARGUMENTS
Object The object to save. The object must be of the type that the global
array was declared.
EXAMPLES
(1) Use a global array to store the names of the exit nodes in a pit.
'Names of pit exit nodes
Dim g_sExitNames(50) As String
Sub Main
Dim lThisExit As Long
Dim lExitField As Long
lExitField = GetRowNumFromCode("Pit Data"p_ID_Exit")
lThisExit = GetRecNum(DOWNFIRST, 1, "Pit Data")
'Repeat while pit exit node exists
Do While lThisExit > 0
'Add name of exit into exit node name array
g_sExitNames(g_lNumExit) = DbReadValue ("Pit Data", lThisExit, lExitField)
'Point to next exit point in database
lThisExit = GetRecNum(NXTSIB,lThisExit, "Pit Data")
Loop
SetGlobalArray "Gbl_sExitNames", g_sExitNames
End Sub
RELATED FUNCTIONS
ClearGlobalObject, GetGlobalArray, GetGlobalObject, SetGlobalArray, SetGlobalObject
SetGlobalObject
DESCRIPTION
Saves the value of a variable to the temporary store inside XPAC.
ARGUMENTS
Object The object to save. The object must be of the type that the global
object was declared.
EXAMPLES
(1) Use a global object to store the number of exit nodes in a pit.
'Number of pit exit nodes
Dim g_lNumExit As Long
Sub Main
'Record number of first pit exit node in database
lThisExit = GetRecNum(DOWNFIRST, 1, "Pit Data")
'Repeat while pit exit node exists
Do While lThisExit > 0
'Increment number of pit exit nodes
g_lNumExit = g_lNumExit + 1
'Point to next exit point in database
lThisExit = GetRecNum(NXTSIB,lThisExit, "Pit Data")
Loop
SetGlobalObject "Gbl_lNumExit", g_lNumExit
End Sub
RELATED FUNCTIONS
ClearGlobalObject, GetGlobalArray, GetGlobalObject, SetGlobalArray, SetGlobalObject
SetMOQItem
DESCRIPTION
Add or change an entry in the Mined Out Quantities table.
ARGUMENTS
Record Number The record number is used to identify the record that will be
placed into the Mined Out Quantities table. If the record already
exists in the Mined Out Quantities table, then the details for that
record will be changed according to the following arguments.
This argument is passed by value as a long data type.
Activity Number The activity number to modify the percentages for in the specified
record in the Mined Out Quantities table. This argument is passed
by value as a long data type.
Released Percent The percentage of the specified activity that will be released prior
to the start of the schedule. It should be entered as a decimal
between zero and one. This argument is passed by value as a
double data type.
Note that no checks will be done to ensure that it is possible for
this percentage of the specified activity to be mined. You can do
this manually from the Mined Out Quantities table by selecting
Check Entries or Remove Errors from the right click menu .
Mined Percent The percentage of the specified activity that will be mined prior to
the start of the schedule. It should be entered as a decimal
between zero and one. This argument is passed by value as a
double data type.
Note that no checks will be done to ensure that it is possible for
this percentage of the specified activity to be released. You can do
this manually from the Mined Out Quantities table by selecting
Check Entries or Remove Errors from the right click menu.
VALUES RETURNED
If the specified record and activity were successfully added to or changed in the Mined Out Quantities
table, then this function will return a value of True.
If the specified record or activity do not exist, then this function will return a value of False.
EXAMPLES
(1) description.
Sub Main
Dim bSetMOQValue As Boolean
If (M(mMined_Pct_Act2) > 0) Then
bSetMOQValue = SetMOQItem(GetRecNum(CURRENT), 2, 1, M(mMined_Pct_Act2))
If (bSetMOQValue = False) Then Print "MOQ Entry Invalid"
End If
End Sub
RELATED FUNCTIONS
GetMOQItem, GetPSItem, SetPSItem
SetNote
DESCRIPTION
Assign the note to the specified note data field in the current record.
ARGUMENTS
Data Field Number The data field number is passed by value as an integer data type.
It is used to identify the note data field in the current database.
The data field number may be passed in as a number or as a full
row code.
Note The note is the value that is assigned to the note data field in the
current record. It is passed by value as a string data type.
VALUES RETURNED
The function returns a boolean data type, indicating whether the note was successfully assigned to the
data field.
If the note was successfully assigned, the function will return a True value.
If the note was not successfully assigned, the function will return a False value. This may happen if the
data field is not a note field or if the note is not a string.
EXAMPLES
(1) Enter a note in a note field.
Sub Main
'Where a ramp is within a free dig block, change it to drill/blast
'and enter a note explaining why this has been done
Dim sNote As String
If (GetClass(mBlk_Type)="Ramp" And GetClass(mWst_Frg)="Free Dig") Then
Call SetClass(mWst_Frg, "Drill/Blast")
sNote = "Ramp blocks must be drill/blast for dozing."
Call SetNote(mWst_Frg_Note, sNote)
End If
End Sub
RELATED FUNCTIONS
GetNote, DbWriteValue, SetClass, SetFieldInfo
SetParam
DESCRIPTION
Assigns a value to a data field in the specified record in the active parameters database.
The required parameters database should be made active before the XCM is run. This is done by
selecting View | Parameters from the menu, then highlighting the required parameters database in the
list and clicking on the Activate button.
Note that it is recommended that the function DbWriteValue be used in preference to SetParam, as it
allows you to define the name of the parameters database, rather than rely on the correct parameters
database being active.
Note that the value must be numeric, so classifications and notes (ie. strings) cannot be assigned using
this function. The data field type should therefore also be numeric, ie. Additive, Weighted Average,
Average, Date, Record, Min, Max, Difference, Ratio, Product or Sum.
If the data field type is classified or note, then the value will not generally be written to the database.
However, for a classified field, the classifications each have a number. This number can be viewed by
clicking on the classified field for a record and selecting Classification from the right click menu. If
the integer portion of the value being assigned matches the number for one of the classifications, then
that classification will be assigned. For example, if a value of 2.7 is assigned to a classified field, and
that field has the classification OreType2 in position 2, then OreType2 will be assigned to the classified
data field in the record.
ARGUMENTS
Data Field Number This argument is the data field number in the active parameters
database, into which you want to write a value. It is passed by
value as an integer data type. The data field code cannot be
used in this argument.
Value This argument is the value that is assigned to the data field in
the specified record. It is passed by value as a double data
type.
Record Number The record number defines the record into which to write a
value in the active parameters database. It is passed by value
as an Long data type.
VALUES RETURNED
SetParam is a subroutine, so it does not return any values.
EXAMPLES
(1) Set a value in a parameters database using the record number.
Sub Main
Dim lPitRecNum As Long
Dim dAvgOreGrd As Double
Dim lParFld As Long
Dim lParRec As Long
'Read the average ore grade for the pit
lPitRecNum = GetRecNumAtLevel(1)
dAvgOreGrd = DbReadValue("Main", lPitRecNum, mOre_Grd)
'Make the average ore grade the default ore grade in the "Pit
'Parameters" database
lParFld = GetRowNumFromCode("Pit Parameters", "pDef_Ore_Grd")
lParRec = GetRecNumFromPath(sPitName, "Pit Parameters")
Call SetParam(lParFld, dAvgOreGrd, lParRec)
End Sub
RELATED FUNCTIONS
GetParam, SetParamFromPil, GetParamFromPil, DbWriteValue
SetParamFromPil
DESCRIPTION
Assigns a value to the specified data field in the active parameters database, for the record defined by
the position in level numbers at each level.
The required parameters database should be made active before the XCM is run. This is done by
selecting View | Parameters from the menu, then highlighting the required parameters database in the
list and clicking on the Activate button.
Note that it is recommended that the functions DbWriteValue and GetRecFromPilDB be used in
preference to SetParamFromPil, as they allow you to define the name of the parameters database, rather
than rely on the correct parameters database being active.
Note that the value must be numeric, so classifications and notes (ie. strings) cannot be assigned using
this function. The data field type should therefore also be numeric, ie. Additive, Weighted Average,
Average, Date, Record, Min, Max, Difference, Ratio, Product or Sum.
If the data field type is classified or note, then the value will not generally be written to the database.
However, for a classified field, the classifications each have a number. This number can be viewed by
clicking on the classified field for a record and selecting Classification from the right click menu. If
the integer portion of the value being assigned matches the number for one of the classifications, then
that classification will be assigned. For example, if a value of 2.7 is assigned to a classified field, and
that field has the classification OreType2 in position 2, then OreType2 will be assigned to the classified
data field in the record.
ARGUMENTS
Data Field Number This argument is the data field number in the active parameters
database, into which you want to write a value. It is passed by
value as an integer data type. The data field code cannot be
used in this argument.
Value This argument is the value that is assigned to the data field in
the specified record. It is passed by value as a double data
type.
Level 1 Pil The Level 1 Pil represents the Pil number at level 1 for the
required record in the active parameters database. It is passed
by value as an integer data type. This argument is not
optional.
Level 2 Pil The Level 2 Pil represents the Pil number at level 2 for the
required record. It is passed by value as an integer data type.
This argument is optional.
Level 3 Pil etc The remaining arguments represent the Pil number at level n
for the required record. They are passed by value as integer
data types. These arguments are optional and they can only be
specified if the preceding argument has been included.
VALUES RETURNED
SetParamFromPil is a subroutine, so it does not return any values.
EXAMPLES
(1) Set a value in a parameters database using pil numbers.
Sub Main
Dim dWstTrkProd As Double
Dim lParFld As Long
'For the first block on each bench, read the waste truck productivity
RELATED FUNCTIONS
GetParamFromPil, SetParam, GetParam, DbWriteValue
SetProgressBar
DESCRIPTION
Displays a progress bar in a window to illustrate the progress of the XCM.
XCMs that are run over a database range automatically display their own progress window.
SetProgressBar can be used in an XCM that is run once, or in a large section of an XCM that is run
once (eg. IsFirstInRange), to give an indication of the progress through the XCM code.
ARGUMENTS
Bar Progress This argument is used to determine the length of the progress bar.
It is passed by value as an integer data type.
Its value should be between 0 and 100, where 0 represents no
progress through the XCM and 100 represents the XCM being
completed.
A value of –1 can also be passed to the subroutine. This tells
XPAC to disable any user messages and to continue using the
automatic progress window. This feature can be used to stop
displaying the user created progress bar and to revert back to the
automatic progress window.
For example, consider an XCM in which IsFirstInRange takes a
significant time to be processed. During this time, the automatic
progress window would only display the name of the first record
in the database range and the progress bar would not move. The
SetProgressBar subroutine can be used to display the progress
through IsFirstInRange. However when it finishes you will want
the automatic progress window to take over and display the
progress through the database range. To make this happen, the
SetProgressBar subroutine should be called with a value of –1 in
the Bar Progress argument. It doesn’t matter what message is
passed into the subroutine in this case.
Message This argument contains the message that will appear in the
progress window below the progress bar. It is passed by value as
a string data type.
VALUES RETURNED
EXAMPLES
(1) Show the progress through a Run Once XCM.
Sub Main
Dim lPit As Long
Dim lRecNum As Long
Dim dPitGrade As Double
'Loop through the Pits in the Main database
For lPit = 1 to 10
'Read the average grade for each Pit
lRecNum = GetRecFromPilDB("Main", lPit)
dPitGrade = DbReadValue("Main", lRecNum, 159)
'Write the average grade to a parameters database
Call DbWriteValue("Summary", 2, lPit, dPitGrade)
Call SetProgressBar(lPit*10, "Processing Pit " & CStr(lPit))
Next lPit
End Sub
RELATED FUNCTIONS
Loops, IsFirstInRange, Run Once XCMs.
SetPSItem
DESCRIPTION
Add or change an entry in the Preschedule table that is assigned to the specified schedule scenario.
ARGUMENTS
Scenario Name The scenario name is used to define which Preschedule table will
be modified. This argument is passed by value as a string data
type.
Note that a Preschedule table may be assigned to multiple
scenarios and if it is changed for one of these scenarios then it will
Record Number The record number is used to identify the record that will be
placed into the specified Preschedule table. If the record already
exists in the Preschedule table, then the details for that record will
be changed according to the following arguments. This argument
is passed by value as a long data type.
Activity Number The activity number to modify the percentages for in the specified
record in the Preschedule table. This argument is passed by value
as a long data type.
Released Percent The percentage of the specified activity that will be released prior
to the start of the schedule. It should be entered as a decimal
between zero and one. This argument is passed by value as a
double data type.
Note that no checks will be done to ensure that it is possible for
this percentage of the specified activity to be mined. You can do
this manually from the Precshedule table by selecting Check
Entries or Remove Errors from the right click menu .
Mined Percent The percentage of the specified activity that will be mined prior to
the start of the schedule. It should be entered as a decimal
between zero and one. This argument is passed by value as a
double data type.
Note that no checks will be done to ensure that it is possible for
this percentage of the specified activity to be released. You can do
this manually from the Precshedule table by selecting Check
Entries or Remove Errors from the right click menu.
VALUES RETURNED
If the specified record and activity were successfully added to or changed in the Preschedule table, then
this function will return a value of True.
If the specified scenario, record or activity do not exist, then this function will return a value of False.
EXAMPLES
(1) description.
Sub Main
Dim bSetPSValue As Boolean
If (M(mMined_Pct_Act2) > 0) Then
bSetPSValue = SetPSItem(GetRecNum(CURRENT), 2, 1, M(mMined_Pct_Act2))
If (bSetPSValue = False) Then Print "Preschedule Entry Invalid"
End If
End Sub
RELATED FUNCTIONS
GetPSItem, GetMOQItem, ClearGlobalObject, GetGlobalArray, GetGlobalObject, SetGlobalArray,
SetGlobalObject
SetMOQItem
SetRecName
DESCRIPTION
This function sets the record name for the specified record.
ARGUMENT
Record Number The record number identifies the record that is to be renamed in
the current database. It is passed by value as a long data type.
The record number may be entered as an absolute record number
using either a number or a variable. It may also be set to one of
the following relative values:
Options Description
CURRENT The current active record
HOME The original record the script started with, ie. the record that was
called by the script before the use of GoRec or similar
UP The parent record
DOWNFIRST The first child record
DOWNLAST The last child record
PRVSIB The previous sibling under the same parent
NXTSIB The next sibling under the same parent
PRV The previous sibling regardless of parents
NXT The next sibling regardless of parents
New Record Name The new record name should follow the standard record naming
conventions. The name is only assigned to the level at which the
record number is located. The new record name is passed by
value as a string data type.
VALUES RETURNED
The function returns a boolean data type.
The function returns a True value if the record name is set successfully, even if the record name does
not change.
The function returns a False value if the record name is not set successfully. This may happen if:
• the specified record number does not exist in the current database;
• one of the record’s siblings already has the new record name;
• the new record name contains more than twelve characters; or
• a position table is active at the level at which the specified record is located.
In each of these cases, the function returns a zero value and the XCM is aborted.
If the specified record is the Top record, then the function generates a message indicating the Top
record cannot be renamed, and then the XCM stops.
EXAMPLES
RELATED FUNCTIONS
GoRec, GetRecName, GetRecNameAtLevel, DbReadName
SetUserFlag
Sets the User Flag (either 1 or 2) for the give Record Activity combination.
This stops the supplied record and activity from being selected until the flag is cleared using the
ClearUserFlag function
ARGUMENTS
VALUES RETURNED
Returns false if the combination is not in the Available Block List.
REMARKS
This function is available only in the User Processing Scripts.
RELATED FUNCTIONS
ClearUserFlag
SetVertex
Helper function to set the value of a vertex. Use SetVertex where the vertex is a single variable, and
SetVertexA when the vertex is in an array, passing the array and the index of the vertex to set. A vertex
is defined as follows:
Type Vertex
dX As Double
dY As Double
dZ As Double
End Type
A polygon is made up of an array of vertices. The best way to declare one is:
Dim Polygon() As Vertex ' The polygon data (a resizeable array)
Note that the array is resizeable (a resizeable array is an array whose size is not specified when it is
‘Dim’ed.
A polygon can be made up of sub-polygons. In the editing screen for XPAC, sub-polygons are
separated by a blank line. They can be used to represent a record/activity with a more complex
structure than would otherwise be allowed. In XCM programming, it is possible to load and manipulate
sub-polygons as if they were one polygon. The sub-polygons are separated by an end-of-sequence
(EOS) marker. The functions GetVertexEOS and SetVertexEOS are used to test for the marker, and to
create a marker.
SetVertexA
Sub SetVertexA ( ByRef Poly() As Vertex, ByVal Index As Long, ByVal X As Double,
ByVal Y As Double, ByVal Z As Double )
Helper function to set the value of a vertex. Use SetVertex where the vertex is a single variable, and
SetVertexA when the vertex is in an array, passing the array and the index of the vertex to set. A vertex
is defined as follows:
Type Vertex
dX As Double
dY As Double
dZ As Double
End Type
A polygon is made up of an array of vertices. The best way to declare one is:
Dim Polygon() As Vertex ' The polygon data (a resizeable array)
Note that the array is resizeable (a resizeable array is an array whose size is not specified when it is
‘Dim’ed.
A polygon can be made up of sub-polygons. In the editing screen for XPAC, sub-polygons are
separated by a blank line. They can be used to represent a record/activity with a more complex
structure than would otherwise be allowed. In XCM programming, it is possible to load and manipulate
sub-polygons as if they were one polygon. The sub-polygons are separated by an end-of-sequence
(EOS) marker. The functions GetVertexEOS and SetVertexEOS are used to test for the marker, and to
create a marker.
SetVertexEOS
Sets the specified vertex to be an end-of-sequence marker. Use SetVertexEOS when the vertex is a
single variable, and SetVertexEOSA when the vertex is in an array, passing in the array and the index of
the vertex to set.
SetVertexEOSA
Sets the specified vertex to be an end-of-sequence marker. Use SetVertexEOS when the vertex is a
single variable, and SetVertexEOSA when the vertex is in an array, passing in the array and the index of
the vertex to set.
StartedTask
DESCRIPTION
Filters the report writer sources to pass steps which were started in the current reporting period.
Returns true if the current block has a Initial percentage of 100; otherwise, false. Also can be used in
the result to return a count of how many tasks were started in the period.
StepType
Used for filtering records according to their step type. Valid values for x are:
1 – Productive
2 – Non-Productive Non-Operating
3 – Non-Productive Operating
4 – Non-Productive Extended Operations
5 – Non-Rostered Non-Operating
StockpileInventory
DESCRIPTION
Filters the report writer sources to pass only that data which has been mined form, or mined to the
specified stockpile, or a child of the specified stockpile. Returns true if the current block is in the
specified stockpile, or is being mined to the specified stockpile; otherwise, false.
WorkHrs
Returns the accumulated productive operating hours for all steps passed by the filter.
WriteABLToFile
The Function writes the contents of the Available Block list to the File that has a name of sFileName.
If the file cannot be written for any reason false is returned. The file name can include a directory path.
If no path is supplied the file will be created in the existing directory.
If bAppend is true the file will be opened and the new current ABL will be appended to the bottom of
the file. When false a new file will be created.
If sComment contains a string this will be printed with the ABL table. You may wish to make a
comment such as after period N. N can be determined by using the function GetCurrentPeriod()
RELATED FUNCTIONS
GetCurrentPeriod, GetCurrentResource
WriteBaseValue
DESCRIPTION
Writes a value to the specified data field, record and database. Values may be written to any field type.
The function will write base values and not period values. Only the Main Database has period values.
Use “DbWriteValue” to write period values.
ARGUMENTS
Database Name This is the name of the database into which the value is written.
It is passed by reference as a variant data type.
The database name may be provided explicitly as a string in double
quotes. For example “Main”, “5 Year Calendar”, “Default
Parameters”, “Equipment Hours”, etc.
Alternatively, the database name may be one of the following
options. Note that these options should not be in quotes.
Options Description
ACTIVE_MAIN The main database.
ACTIVE_CALENDAR The active calendar database.
ACTIVE_RESULTS The active results database.
Record Number The record number is used to identify the record into which the
value is written. It is passed by value as a long data type.
Data Field The value to write in the database is identified by its data field
Number number. It is passed by value as a long data type.
In general, the full row codes cannot be used in this argument, as
they are only recognised for the database over which the XCM is
being run. However, the function GetRowNumFromCode can be
used to get the data field number, given the full row code and the
database name.
Don’t Prompt This argument is only relevant when writing a value to a classified
data field. If the specified data field is any other field type, then
this argument will be ignored. It is an optional argument and it is
passed by value as a boolean data type.
If it is set to True, then you will not receive a prompt when new
classifications are encountered, asking whether you want to create
that new classification.
If it is set to False, then you will receive a prompt when new
classifications are encountered, asking whether you want to create
that new classification.
If the argument is missing and the data field type is a classified
field, then the function will behave as if the argument were set to
False.
VALUES RETURNED
WriteBaseValue is a subroutine so it does not return any values.
EXAMPLES
(1) Write a value to a different main database record.
Dim lFirstBlockInBench As Long
Sub Main
Dim lBenchRec As Long
Dim dBenchVol As Double
'Remember the record number for the first block in the bench
If (IsFirst()) Then lFirstBlockInBench = GetRecNum(CURRENT)
'Calculate the total block volume
M(mBlk_Tot_Vol) = M(mOre_Vol) + M(mWst_Vol)
'After the last block has been calculated, read the bench volume
If (IsLast()) Then
Call GoRec(UP)
dBenchVol = M(mBlk_Tot_Vol)
Call GoRec(HOME)
End If
'Write the total bench volume into the first block on the bench
Call WriteBaseValue("Main", lFirstBlockInBench, mBlk_Tot_Vol, dBenchVol)
End Sub
RELATED FUNCTIONS
DbReadValue, DbWriteValue, ReadBaseValue, ReadValue, WriteValue
WriteDestinationABLToFile
The Function writes the contents of the Available Destination Block list to the File that has a name of
sFileName. If the file cannot be written for any reason false is returned. The file name can include a
directory path. If no path is supplied the file will be created in the existing directory.
If bAppend is true the file will be opened and the new current ADL will be appended to the bottom of
the file. When false a new file will be created.
If sComment contains a string this will be printed with the ADL table. You may wish to make a
comment such as after period N. N can be determined by using the function GetCurrentPeriod()
RELATED FUNCTIONS
GetCurrentPeriod, GetCurrentResource
WriteSourceABLToFile
The Function writes the contents of the Available SourceBlock list to the File that has a name of
sFileName. If the file cannot be written for any reason false is returned. The file name can include a
directory path. If no path is supplied the file will be created in the existing directory.
If bAppend is true the file will be opened and the new current ASL will be appended to the bottom of
the file. When false a new file will be created.
If sComment contains a string this will be printed with the ASL table. You may wish to make a
comment such as after period N. N can be determined by using the function GetCurrentPeriod()
RELATED FUNCTIONS
GetCurrentPeriod, GetCurrentResource
WriteValue
DESCRIPTION
Writes a value to the specified data field, record and database. Values may be written to any field type.
ARGUMENTS
Database Name This is the name of the database into which the value is written.
The database name may be provided explicitly as a string in double
quotes. For example “Main”, “5 Year Calendar”, “Default
Parameters”, “Equipment Hours”, etc.
Alternatively, the database name may be one of the following
options. Note that these options should not be in quotes.
Options Description
ACTIVE_MAIN The main database.
ACTIVE_CALENDAR The active calendar database.
ACTIVE_RESULTS The active results database.
Full Row Code he full row code of the field to read. It is passed by value as a
string data type.
Lvl0 – lvl10 An identifier for each level in the database down to the desired
record. The identifier at each level can be either the record name as
a string, or the record APIL as an integer or long.
Below the level of the desired record, either a value of -1 or an
empty string should be used to specify that the level is not
significant.
VALUES RETURNED
WriteValue is a subroutine so it does not return any values.
EXAMPLES
(1) Read a value to the Parameters database.
Sub Main
Dim dValue As Double
dValue = 42.0
dValue = WriteValue("Parameters", "pTest", dValue, 1, "Dozer1", 3, -1, -1, -1, _
-1, -1, -1, -1, -1)
End Sub
RELATED FUNCTIONS
ReadValue, ReadBaseValue, WriteBaseValue, DbReadValue, DbWriteValue