Download as pdf or txt
Download as pdf or txt
You are on page 1of 394

XCM PROGRAMMING

Guidelines for XPAC Users


May, 2006
XCM Reference Guide

1 Overview of XCM Programming ................................................................................................15


2 Managing Your XCMs.................................................................................................................16
2.1 Choosing an XCM Editor ....................................................................................................16
2.2 The Built in Text Editor ......................................................................................................17
2.3 Creating an XCM ................................................................................................................17
2.4 Naming XCMs ....................................................................................................................17
2.5 Storage of XCMs.................................................................................................................18
2.6 Editing an XCM ..................................................................................................................19
2.7 Deleting an XCM ................................................................................................................19
3 How to Run an XCM....................................................................................................................20
3.1 Running your XCM.............................................................................................................20
3.2 Run XCM Over Range ........................................................................................................20
3.2.1 Choosing the Database ...................................................................................................20
3.2.2 Running the XCM...........................................................................................................20
3.2.3 Choosing the Range........................................................................................................21
3.3 Run XCM Once...................................................................................................................21
3.4 Run Immediate XCM ..........................................................................................................22
3.5 XCM Running .....................................................................................................................22
3.6 Running Multiple XCMs .....................................................................................................23
3.7 XCM Compile Errors ..........................................................................................................24
3.7.1 Line Number...................................................................................................................24
3.7.2 Syntax Errors ..................................................................................................................24
3.7.3 Undeclared Variables......................................................................................................24
3.8 XCM Run Errors .................................................................................................................25
3.8.1 Endless Loop ..................................................................................................................25
3.8.2 Divide by Zero................................................................................................................25
3.8.3 Invalid Parameter in Function.........................................................................................25
3.8.4 Function and Subroutine Return Values .........................................................................26
3.8.5 Overflow Error ...............................................................................................................26
3.9 Protected Data Fields...........................................................................................................26
3.10 Debugging an XCM ............................................................................................................26
3.10.1 Debug Toolbar................................................................................................................27
3.10.2 Debug Window...............................................................................................................30
4 Structure of an XCM....................................................................................................................32
4.1 XCM Header .......................................................................................................................32
4.2 Indentation of Code .............................................................................................................32
4.3 Declaring Script Constants and Variables ...........................................................................34
4.4 Sub Main .............................................................................................................................35
4.5 Declaring Local Constants and Variables............................................................................35
4.6 XCM Initialisation Logic ....................................................................................................35

Runge Ltd May, 2006 Page 2


XCM Reference Guide

4.7 Clearing Data Fields ............................................................................................................36


4.8 Main Procedure ...................................................................................................................36
4.9 XCM Termination Logic .....................................................................................................36
4.10 End Sub ...............................................................................................................................37
4.11 User-Defined Functions and Subroutines ............................................................................37
5 XCM Language Elements ............................................................................................................38
5.1 Comments............................................................................................................................38
5.2 Statements ...........................................................................................................................38
5.3 Line Continuation Character ...............................................................................................39
5.4 Numbers ..............................................................................................................................39
5.5 Variables and Constants ......................................................................................................39
5.6 Operators .............................................................................................................................39
5.7 Control Structures................................................................................................................41
5.8 Functions and Subroutines ..................................................................................................41
5.9 Syntax..................................................................................................................................41
6 XCM Variables and Constants....................................................................................................42
6.1 Introduction .........................................................................................................................42
6.1.1 User-Defined Variables ..................................................................................................42
6.1.2 Arrays .............................................................................................................................42
6.1.3 Data Field Variables .......................................................................................................42
6.1.4 Constants ........................................................................................................................42
6.2 Variable Data Types ............................................................................................................42
6.3 Declaring Variables .............................................................................................................44
6.4 Defining Constants ..............................................................................................................44
6.5 Scope of Variables and Constants .......................................................................................44
6.5.1 Global Variables and Constants......................................................................................45
6.5.2 Script Variables and Constants .......................................................................................45
6.5.3 Local Variables and Constants .......................................................................................45
6.6 User-Defined Variable and Constant Names.......................................................................46
6.7 Example Variable and Constant Names ..............................................................................46
6.8 Data Field Variables ............................................................................................................47
6.9 Data Field Number or Full Row Code.................................................................................47
6.10 XPAC Commands Added to Your XCM ............................................................................48
6.11 Forced Declaration of Variables..........................................................................................48
6.12 Predefined Database Level Variables..................................................................................48
6.13 Full Row Codes ...................................................................................................................49
7 Control Structures........................................................................................................................51
7.1 What is a Control Structure .................................................................................................51
7.2 If Statements........................................................................................................................51
7.2.1 If…Then .........................................................................................................................51

Runge Ltd May, 2006 Page 3


XCM Reference Guide

7.2.2 If…Then…End If ...........................................................................................................51


7.2.3 If…Then…Else…End If ................................................................................................52
7.2.4 If…Then…ElseIf…End If..............................................................................................52
7.3 Select Case Statements ........................................................................................................53
7.4 Do Loops .............................................................................................................................54
7.4.1 Do While…Loop ............................................................................................................54
7.4.2 Do…Loop While ............................................................................................................54
7.4.3 Do Until…Loop..............................................................................................................55
7.4.4 Do…Loop Until..............................................................................................................55
7.4.5 Exit Do............................................................................................................................55
7.5 While Loops ........................................................................................................................56
7.6 For Loops ............................................................................................................................56
7.7 GoTo Statements .................................................................................................................57
8 Functions and Subroutines ..........................................................................................................58
8.1 Introduction .........................................................................................................................58
8.2 Functions .............................................................................................................................58
8.2.1 Function Arguments .......................................................................................................58
8.2.2 Calling a Function...........................................................................................................59
8.2.3 Combining Functions......................................................................................................60
8.3 Subroutines..........................................................................................................................60
8.3.1 Subroutine Arguments ....................................................................................................60
8.3.2 Calling a Subroutine .......................................................................................................60
8.4 ByRef and ByVal ................................................................................................................61
8.5 XPAC Functions and Subroutines .......................................................................................62
8.6 User-Defined Functions and Subroutines ............................................................................63
8.6.1 Syntax for Functions and Subroutines ............................................................................63
8.6.2 Function and Subroutine Names.....................................................................................63
8.6.3 Arguments ......................................................................................................................63
8.6.4 Function Types ...............................................................................................................64
8.6.5 End Statement.................................................................................................................64
8.7 Functions and Subroutines Sharing Parameters...................................................................64
9 XCM Commands ..........................................................................................................................66
9.1 Introduction .........................................................................................................................66
9.2 Cypress EnableTM Commands .............................................................................................66
9.3 XPAC Functions and Subroutines .......................................................................................66
10 Cypress EnableTM Commands.................................................................................................67
10.1 Quick Reference of the Functions and Statements Available.............................................67
10.1.1 Type/Functions/Statements.............................................................................................67
10.1.2 Data Types......................................................................................................................68
10.1.3 Operators ........................................................................................................................69

Runge Ltd May, 2006 Page 4


XCM Reference Guide

10.1.4 Operator Precedence.......................................................................................................69


10.1.5 Relational Operators .......................................................................................................70
10.1.6 Logical Operators ...........................................................................................................70
10.1.7 Functions, Statements, Reserved Words - Quick Reference..........................................70
10.2 Language Reference A - Z...................................................................................................72
10.2.1 Abs Function...................................................................................................................72
10.2.2 AppActivate Statement ...................................................................................................73
10.2.3 Asc Function...................................................................................................................73
10.2.4 Atn Function ...................................................................................................................74
10.2.5 Beep Statement ...............................................................................................................74
10.2.6 Call Statement.................................................................................................................75
10.2.7 CBool Function...............................................................................................................76
10.2.8 CDate Function...............................................................................................................76
10.2.9 CDbl Function ................................................................................................................77
10.2.10 ChDir Statement.........................................................................................................77
10.2.11 ChDrive Statement.....................................................................................................78
10.2.12 CheckBox...................................................................................................................79
10.2.13 Choose Function ........................................................................................................79
10.2.14 Chr Function ..............................................................................................................80
10.2.15 CInt Function .............................................................................................................80
10.2.16 CLng Function ...........................................................................................................81
10.2.17 Close Statement .........................................................................................................81
10.2.18 Const Statement .........................................................................................................82
10.2.19 Cos Function ..............................................................................................................83
10.2.20 CreateObject Function ...............................................................................................83
10.2.21 CSng Function ...........................................................................................................85
10.2.22 CStr Function .............................................................................................................85
10.2.23 CVar Function............................................................................................................86
10.2.24 CurDir Function .........................................................................................................86
10.2.25 Date Function.............................................................................................................87
10.2.26 DateSerial Function ...................................................................................................88
10.2.27 DateValue Function ...................................................................................................88
10.2.28 Day Function..............................................................................................................89
10.2.29 Declare Statement ......................................................................................................89
10.2.30 Dialog, Dialog Function.............................................................................................91
10.2.31 Dim Statement ...........................................................................................................92
10.2.32 Dir Function ...............................................................................................................93
10.2.33 DlgEnable Statement .................................................................................................94
10.2.34 DlgText Statement .....................................................................................................95
10.2.35 DlgVisible Statement .................................................................................................95

Runge Ltd May, 2006 Page 5


XCM Reference Guide

10.2.36 Do...Loop Statement ..................................................................................................96


10.2.37 End Statement ............................................................................................................97
10.2.38 EOF Function.............................................................................................................97
10.2.39 Erase Statement..........................................................................................................98
10.2.40 Exit Statement............................................................................................................98
10.2.41 Exp .............................................................................................................................99
10.2.42 FileCopy Function .....................................................................................................99
10.2.43 FileLen Function......................................................................................................100
10.2.44 Fix Function .............................................................................................................100
10.2.45 For each … Next Statement .....................................................................................100
10.2.46 For...Next Statement ................................................................................................101
10.2.47 Format Function.......................................................................................................101
10.2.48 FreeFile Function .....................................................................................................111
10.2.49 Function Statement ..................................................................................................111
10.2.50 Get Object Function .................................................................................................112
10.2.51 Global Statement......................................................................................................112
10.2.52 GoTo Statement .......................................................................................................113
10.2.53 Hex...........................................................................................................................114
10.2.54 Hour Function ..........................................................................................................114
10.2.55 If...Then...Else Statement.........................................................................................116
10.2.56 Input Function..........................................................................................................117
10.2.57 InputBox Function ...................................................................................................117
10.2.58 InStr .........................................................................................................................119
10.2.59 Int Function..............................................................................................................120
10.2.60 IsArray Function ......................................................................................................120
10.2.61 IsDate .......................................................................................................................121
10.2.62 IsEmpty....................................................................................................................121
10.2.63 IsNull .......................................................................................................................121
10.2.64 IsNumeric.................................................................................................................122
10.2.65 IsObject Function.....................................................................................................122
10.2.66 Kill Statement ..........................................................................................................123
10.2.67 LBound Function .....................................................................................................124
10.2.68 LCase, Function .......................................................................................................124
10.2.69 Left...........................................................................................................................125
10.2.70 Len ...........................................................................................................................126
10.2.71 Let Statement ...........................................................................................................126
10.2.72 Line Input # Statement.............................................................................................127
10.2.73 LOF..........................................................................................................................127
10.2.74 Log ...........................................................................................................................128
10.2.75 Mid Function............................................................................................................129

Runge Ltd May, 2006 Page 6


XCM Reference Guide

10.2.76 Minute Function.......................................................................................................130


10.2.77 MkDir ......................................................................................................................130
10.2.78 Month Function........................................................................................................131
10.2.79 MsgBox Function MsgBox Statement ....................................................................132
10.2.80 Name Statement .......................................................................................................135
10.2.81 Now Function ..........................................................................................................135
10.2.82 Oct Function ............................................................................................................136
10.2.83 OKButton.................................................................................................................137
10.2.84 On Error ...................................................................................................................137
10.2.85 Open Statement........................................................................................................140
10.2.86 Option Base Statement.............................................................................................142
10.2.87 Option Explicit Statement........................................................................................143
10.2.88 Print Method ............................................................................................................143
10.2.89 Print # Statement......................................................................................................144
10.2.90 ReDim Statement .....................................................................................................146
10.2.91 Rem Statement .........................................................................................................146
10.2.92 Right Function .........................................................................................................147
10.2.93 RmDir Statement .....................................................................................................149
10.2.94 Rnd Function............................................................................................................149
10.2.95 Second Function ......................................................................................................150
10.2.96 Seek Function ..........................................................................................................151
10.2.97 Seek Statement.........................................................................................................152
10.2.98 Select Case Statement ..............................................................................................152
10.2.99 SendKeys Function ..................................................................................................153
10.2.100 Set Statement ...........................................................................................................154
10.2.101 SGN(Number)..........................................................................................................155
10.2.102 Shell Function ..........................................................................................................156
10.2.103 Sin Function .............................................................................................................157
10.2.104 Space Function.........................................................................................................157
10.2.105 Sqr Function.............................................................................................................158
10.2.106 Static Statement .......................................................................................................159
10.2.107 Stop Statement .........................................................................................................159
10.2.108 StrComp Function....................................................................................................160
10.2.109 String Function ........................................................................................................160
10.2.110 Sub Statement ..........................................................................................................161
10.2.111 Tan Function ............................................................................................................162
10.2.112 Text Statement .........................................................................................................162
10.2.113 TextBox Statement...................................................................................................163
10.2.114 Time Function..........................................................................................................165
10.2.115 Timer Event ............................................................................................................166

Runge Ltd May, 2006 Page 7


XCM Reference Guide

10.2.116 TimeSerial - Function ..............................................................................................167


10.2.117 TimeValue - Function ..............................................................................................167
10.2.118 Trim, LTrim, RTrim Functions................................................................................168
10.2.119 Type Statement ........................................................................................................169
10.2.120 UBound Function.....................................................................................................171
10.2.121 UCase Function........................................................................................................171
10.2.122 Val............................................................................................................................172
10.2.123 VarType ...................................................................................................................172
10.2.124 Weekday Function ...................................................................................................174
10.2.125 While...Wend Statement ..........................................................................................174
10.2.126 With Statement ........................................................................................................175
10.2.127 Write # - Statement ..................................................................................................177
10.2.128 Year Function ..........................................................................................................177
11 XPAC Functions and Subroutines ........................................................................................179
Activity ................................................................................................................................179
Abort.........................................................................................................................................179
AddDependencyToGroup.........................................................................................................180
CalendarHrs .........................................................................................................................180
CalculateLineIntersection .........................................................................................................180
ChangeProductionRate .............................................................................................................181
ChangeRoster ...........................................................................................................................181
ClearData..................................................................................................................................182
ClearGlobalObject ....................................................................................................................183
ClearInputPath ..........................................................................................................................184
ClearUserFlag...........................................................................................................................185
CompletedTask ...................................................................................................................186
ClosingDumpCapacity ........................................................................................................186
ClosingInv ...........................................................................................................................186
ClosingInvSP .......................................................................................................................186
CreateRecord ............................................................................................................................186
CreateRecordDB.......................................................................................................................189
CreateRecordEx........................................................................................................................190
CSum Function .........................................................................................................................193
CurveValue...............................................................................................................................193
Curve3DValue ..........................................................................................................................194
DbReadName ...........................................................................................................................195
DbReadValue ...........................................................................................................................197
DbWriteValue...........................................................................................................................199
DegToRad.................................................................................................................................201
DeletePolygon ..........................................................................................................................201

Runge Ltd May, 2006 Page 8


XCM Reference Guide

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

Runge Ltd May, 2006 Page 9


XCM Reference Guide

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

Runge Ltd May, 2006 Page 10


XCM Reference Guide

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

Runge Ltd May, 2006 Page 11


XCM Reference Guide

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

Runge Ltd May, 2006 Page 12


XCM Reference Guide

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

Runge Ltd May, 2006 Page 13


XCM Reference Guide

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

Runge Ltd May, 2006 Page 14


XCM Reference Guide Overview of XCM Programming

1 Overview of XCM Programming


XCM is a facility within XPAC that can be used to calculate, report and manipulate
data. The data may include any information that you are storing in a main,
parameters, calendar or results database, and it may also include schedule inputs and
results. XCM stands for XPAC Command Module.
An XCM is a set of instructions that are written in a particular language. XCM makes
use of a language called Cypress EnableTM, which has a very similar syntax to the
MicrosoftTM Visual Basic for Applications. In addition to the commands that are
available in Enable, there are XPAC commands that have been written to perform
tasks that are specific to an XPAC project. From a users point of view, there is no
difference between the Enable commands and the XPAC commands in an XCM.
XCM will allow XPAC users to launch and manipulate other applications via OLE
automation and to access any DLL (including ODBC).
To write your own XCM, you will need to understand what commands are available
and how they can be structured. To process your XCM you will need an
understanding of the different run options that are available. To effectively manage
your XCMs, we provide suggestions on their naming, storage, etc.
The information that is provided on XCM programming covers both a new user
getting started with XCM and also those users requiring detailed reference
information on a particular function, statement, etc.
Finally, don’t be afraid of using XCMs. When you first start out, they can be used to
do very simple manipulation of data. Then, as you get more comfortable with them
you can experiment with some of the more powerful commands.

Runge Ltd May, 2006 Page 15


XCM Reference Guide Managing Your XCMs

2 Managing Your XCMs


An XCM is stored in a text file, separate from your XPAC project. They can be
edited from within or outside XPAC. Within XPAC you can specify the text editor to
use when editing your XCMs.
It is important to manage your XCMs well to ensure that you not lose them or end up
with multiple copies where you don’t know which is the correct one. This is done
through logical naming and storage of your XCMs. We would encourage you to
follow our recommendations, so that your XCMs can be easily retrieved.

2.1 Choosing an XCM Editor


XCMs are stored separately to your XPAC project. They are text files, which means
that they can be opened and modified in any text editor. Before you start creating and
editing XCMs, you should choose a text editor to use from within XPAC. This text
editor will be opened each time you create or edit an XCM.
A very simple text editor is provided with XPAC. If you don’t have access to a more
sophisticated editor, then the editor supplied will get you by. However, we strongly
recommend that you purchase a good editor, that has syntax highlighting, column edit,
search and replace facilities, etc. The editor that we recommend is called UltraEdit.
It has all of these features and can be down-loaded from the web at
www.ultraedit.com. It is good value at approximately USD30 for a single licence.
In addition to its use in editing XCMs, UltraEdit has also proven useful in editing
large data files, such as those produced by geological models.
To choose an editor for your XCMs, go to Tools on the application menu, select
XCM and then Choose Editor. The following window is displayed.

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.

Runge Ltd May, 2006 Page 16


XCM Reference Guide Managing Your XCMs

2.2 The Built in Text Editor


The text editor that is supplied with XPAC is part of the XCM Debugger. Refer to
Section 3.10 for details of how to edit and save your XCM in the Debugger.

2.3 Creating an XCM


There are two ways in which you can create a new XCM. These are described below.
From within XPAC
Go to the Tools option on the application menu, select XCM and then select Edit.
Alternatively, the button on the toolbar can be used. You are now asked for the
name and location of the XCM. Locate the directory where you want to create your
XCM and then enter a name. After you select you are presented with a
message indicating that the file you have specified does not exist. Select
to create the file and it will then be opened in the text editor. If you don’t get this
message then the file name that you entered must already exist. Close the editor and
repeat the steps using a different file name.
When this method is used to open a file, a template is copied into the new XCM. This
template contains lots of comment lines and some command lines that will assist you
with the structure of your XCM. The contents of the blank template are described in
Section 4.
The template is stored in the directory where XPAC was installed and is called
XCM_Template.bas. You can edit this file to customise the template for your
company or mine site. If you reinstall XPAC, your customised template will be over-
written, so be sure tomake a copy first.
From outside XPAC
Since an XCM is just a text file, it can also be created from outside XPAC. For
example you may want to copy some other XCM, to use it as a starting point for your
new XCM.
Alternatively, you may want to begin writing the XCM from scratch. We would
strongly recommend that you don’t do this as you are more likely to leave out the
valuable comments and descriptions that will help others to understand your XCM.

2.4 Naming XCMs


The following conventions should be followed when naming your XCMs. There is
nothing to force you to adopt these conventions, however it will make the task of
managing your XCMs easier and it will also make them more logical for others who
will need to understand your XPAC project.
• XCMs should have a file extension of bas.
• All XCM names should begin with a letter that indicates the database or facility in
XPAC on which the XCM is run.

Runge Ltd May, 2006 Page 17


XCM Reference Guide Managing Your 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

2.5 Storage of XCMs


The location of your XCMs is important, as it will tend to indicate the project or
projects to which the XCMs belong. We recommend the following conventions be
applied to the storage of your XCMs.
• Each XPAC project (ie. *.xpk file) should have its own directory. If you have
different versions of the same project, then they can be stored in the same
directory but they should be clearly and appropriately named.

Runge Ltd May, 2006 Page 18


XCM Reference Guide Managing Your XCMs

• 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.

2.6 Editing an XCM


An existing XCM can be edited from within or outside XPAC.
From within XPAC
Select Tools from the application menu, then select XCM and Edit. Alternatively,
the button on the toolbar can be used. You are now asked for the name and
location of the XCM. Locate the directory in which the XCM is stored and then click
on the XCM filename. Click on to open the selected XCM in the text
editor.
From outside XPAC
To edit an XCM outside XPAC, open a text editor and then open the XCM. It is now
ready for editing.

2.7 Deleting an XCM


XCMs cannot be deleted from within XPAC. Once the XCM has been closed in your
text editor, use Windows explorer to delete the file.

Runge Ltd May, 2006 Page 19


XCM Reference Guide How to Run an XCM

3 How to Run an XCM

3.1 Running your XCM


There are three different ways in which an XCM can be run, namely:
• Run over Range – the XCM commands are repeated for each record in the
specified database range.
• Run Once – the XCM commands are processed once only, for no specific
database.
• Run Immediate – the XCM commands are entered in a temporary window and
they are not saved. XCMs run in this way must be run over a database range.
Each of these run options is discussed in further detail in the following sections.

3.2 Run XCM Over Range


If your XCM has been written to perform a series of calculations on the records in a
database, then it is likely that you will want to run it over a database range. Such
XCMs will always run over the lowest level records in the database, as this is where
the data is stored. All of the commands in the XCM are processed for each lowest
level record in the selected database range. The records can be processed in forward
or reverse order, as specified in the database range.

3.2.1 Choosing the Database


Before you run an XCM over a database range, you should first move to the relevant
database. This means that the relevant database should be active. For example, if the
XCM is calculating data for your mining blocks, then you will want to run it over the
Main database. If the XCM assigns schedule information for a calendar, then you will
want to run it over one of your Calendar databases. To make the relevant database
active, go to View on the application menu and select Main, Calendars, Results or
Parameters. There is only one Main database in an XPAC project, so this database
will immediately be opened. All of the other database types allow multiple databases,
so after selecting these options you will be asked to select the required database from
the list.
If you try to run an XCM over a range when you are in one of the scheduling screens,
you will be asked to select a database from a list. This list will contain the Main
database and it will contain the current active calendar, results and parameters
databases. If there is no active database for one of these database types, then the last
active database will be displayed. Select the relevant database from this list or quit
from the window and make the required database active.

3.2.2 Running the XCM

Runge Ltd May, 2006 Page 20


XCM Reference Guide How to Run an XCM

An XCM can be run over a database range as follows:


• Select Tools from the application menu, select XCM and then select Run Range;
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 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.

3.2.3 Choosing the Range


The next item that you will be asked to specify is the database range over which the
XCM is to be run. A list of all database ranges in the selected database will be
displayed. A new database range can be created by selecting the button.
Highlight the relevant database range and then click on to proceed.

3.3 Run XCM Once


Some XCMs do not need to run over a specific database. For example, an XCM
might be used to retrieve information from your schedule and to write it into a text
file. Or an XCM might read data from multiple databases and write it into a
spreadsheet. Rather than running these XCMs over multiple records in a database
range, they can simply be run once. The commands in the XCM are only processed
once.
To run an XCM once only, use either of the following:
• Select Tools from the application menu, select XCM and then select Run Once;
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 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.

Runge Ltd May, 2006 Page 21


XCM Reference Guide How to Run an XCM

3.4 Run Immediate XCM


Immediate XCMs are entered in a temporary window and they cannot be saved. They
should be used when you want to quickly calculate a value or display a parameter.
They should not be used for any calculation that may need to be repeated or
documented.
Immediate XCMs are always run over a database range and they will run over the
database (main, parameter, calendar or results) that was active when the Immediate
XCM was opened.
To run an Immediate XCM, use either of the following:
• Select Tools from the application menu, select XCM and then select Run
Immediate; 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 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.

3.5 XCM Running


When an XCM is running successfully over a database range, a window is displayed
indicating the following:
• The record name that is currently being processed;
• The progress through the selected database range as a percentage; and
• The progress through the selected database range as a bar.

Runge Ltd May, 2006 Page 22


XCM Reference Guide How to Run an XCM

An example of this window is displayed below.

3.6 Running Multiple XCMs


It is possible to set multiple XCMs running without waiting for the first one to finish.
When you get to the step where you select the XCM from the relevant directory, you
select multiple XCMs instead of just one.
To select multiple XCMs, highlight the first XCM. If all of the XCMs that you want
to run are sequential in the list, then hold down the Shift key and highlight the last
XCM. All of the XCMs to be run should now be highlighted. If the XCMs that you
want to run are not sequential in the list, then hold down the Control key. Left click
on each XCM, until all of the ones that you want to run are highlighted.

Change XCM Order


All of the XCM names will now be displayed in the File Name field. Click on
and the selected XCMs will be displayed in a list. The order of the
XCMs in this list is the order in which they will be run. To change the order, click on
an XCM name and then click on the or buttons.

Change Database Range


In the second column of this window, the database range over which each XCM is to
be run is displayed. These will initially default to the range called “All”. To change

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

before clicking on the button.

Running the XCMs


When you are happy with the order of the XCMs and the database ranges over which

they will be run, click on the button. They will then start to run in the
specified order.

Runge Ltd May, 2006 Page 23


XCM Reference Guide How to Run an XCM

3.7 XCM Compile Errors


Errors
When you set an XCM running, either over a database range or once only, the first
thing that happens is that the XCM is compiled. During this process, your XCM code
is checked for the correct syntax. If any errors are detected, then a message will be
displayed immediately and the process will be stopped. If this occurs, you will need
to read the error message to determine the location and nature of the error.

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.

3.7.1 Line Number


The error message will usually indicate the line number on which the error occurred.
Most of the time this line number will direct you to the problem in your code. In
some cases, the line number will only indicate where the compiler first became
confused. If you can’t see any problems on the given line number, look at earlier
code, rather than later code.
If you get an error message indicating there is a problem with the line End Sub, this
indicates that you may have missed out one or more End If statements. A typical
error is putting End instead of End If. Check all of your If statements and be sure to
use indenting to minimise the occurrence of this problem.

3.7.2 Syntax Errors


If you get a message saying “Syntax Error on line:”, then you should examine the
syntax of the functions, statements or variables on the given line number. You may
have missed a bracket, left out a parameter in a function, misspelt a variable or
function name, etc.
In amongst the line of code displayed in the error message, there will be an
underscore character. This is used to indicate where the syntax error may be located.
A common mistake that occurs with functions and subroutines is that the Call
statement is left out. If brackets are used around the function or subroutine
parameters, then the Call statement must be included before the function or
subroutine name. If the value the function returns is being assigned to a variable, then
the Call statement is not required.

3.7.3 Undeclared Variables

Runge Ltd May, 2006 Page 24


XCM Reference Guide How to Run an XCM

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.

3.8 XCM Run Errors


After an XCM has been compiled successfully, the XCM will start to run. This may
be over a range of database records or it may be once only. Errors may occur while
the XCM is runningand such errors will stop the XCM and prevent it from finishing.
When an XCM is being run over a database range and a run error occurs, you should
be aware that some of the records will have been processed and some not. Similarly,
when an XCM is being run once only and a run error occurs, some of the code will
have been processed and some not.
If you cannot identify the error in your XCM from the error message provided, then
you may need to use the XCM Debug program, which is described in Section 3.10.

3.8.1 Endless Loop


If an XCM appears to get stuck on a particular record in the database range, then it is
likely that it has encountered an endless loop. This can be caused by a variety of
mistakes. You will have to close XPAC down using Control Alt Delete and then use
the Debugger to locate the problem.

3.8.2 Divide by Zero


If you attempt to divide a number by zero, you will get the following error message
and the XCM will stop.

This can be avoided by always using the SafeDivide function, which will return a
value of zero when dividing by zero.

3.8.3 Invalid Parameter in Function


If you pass invalid data into a function, you will get an error message indicating this
has been done. This may include passing in a one data type (eg. a string) when the
parameter has been defined as some other data type (eg. a double).

Runge Ltd May, 2006 Page 25


XCM Reference Guide How to Run an XCM

3.8.4 Function and Subroutine Return Values


The first point to note here is that Subroutines do not return a value. If you try to
assign a subroutine to a variable, you will end up with some strange results, so do not
do this.
Functions will always return a particular data type. If the function return value is
being assigned to a variable, then that variable should be declared as the correct data
type.

3.8.5 Overflow Error


If your XCM run error message includes the word “Overflow”, then it is likely that
you have tried to assign a number that is too large to a variable or to a parameter in a
function.
For example, the first parameter required in the GetApil function is the database level
number as an integer. An integer must be a number between –32,000 and +32,000. If
the record number is accidentally entered as the first parameter in the GetApil
function instead of the level number, and it is a very large number (eg. 40,000), then
an Overflow error will be reported. This is because you are trying to fit a long data
type (ie. 40,000) into a parameter that requires an integer (ie. level number).
If you get an Overflow error, start by looking at the data types and the values of
numbers that are being handled by the XCM on the given line number.

3.9 Protected Data Fields


The data field values in your database can be protected from manual editing, from
alteration by an XCM or from both.
If the protection for a data field is set to either Script or Both, then you will be
presented with an error message if you attempt to modify the value of that data field
in an XCM. The error message that is displayed is as follow.

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.

3.10 Debugging an XCM

Runge Ltd May, 2006 Page 26


XCM Reference Guide How to Run an 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.

3.10.1 Debug Toolbar


The buttons on the toolbar are used to start and stop the XCM as required. The
function of each button is described below. In addition to the toolbar buttons, these
options can be selected from the Debug menu or using the quick keys listed in the
brackets.

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.

Runge Ltd May, 2006 Page 27


XCM Reference Guide How to Run an XCM

Execute Script (Ctrl+F5)


This option is currently not available.

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.

Break Execution (Ctrl+Break)


While an XCM is running, it can be paused using this button. The XCM will stop at
the current line being executed. To resume the XCM use the Run button. While an
XCM is paused you are still able to access the tooltips on variables and quick watch.

Stop Debugging (Shift+F5)


This button is used to stop the current XCM running. Once an XCM has been
stopped, it cannot be resumed, only restarted. Tooltips and quick watch are not
available after an XCM has been stopped.

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.

Step Into (F8)


This button can be used to step through your XCM one line at a time, when it is in a
paused state. If the next line to be processed in your XCM calls a subroutine, then
that subroutine will also be stepped through one line at a time. If your XCM is not
running, then this button will start the XCM and step to the first line of code.

Step Over (Shift+F8)


This option works in a similar way to Step Into. When your XCM is in a paused state,
it will step through the XCM one line at a time. The difference is that if the line calls
a subroutine then it will be processed, but not one line at a time, rather as a single
step. As with Step Into, if the XCM is not running, this will start the XCM and step to
the first line of code.
Step Out Of (Ctrl+Shift+F8)
This option is currently not available.

Run to Cursor (Ctrl+F8)


This button is used to run the XCM up to the line on which your cursor is positioned.
It is equivalent to putting a break point on that line and then selecting Run. This

Runge Ltd May, 2006 Page 28


XCM Reference Guide How to Run an XCM

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.

Show Next Statement (Alt+Num *)


This option is used to display the next statement to be executed in the visible part of
the window. It can disappear from the window if the scroll bars are used to move it
elsewhere in the XCM. The next statement to be executed has a dotted border
surrounding it.

Quick Watch (Shift+F9)


It is possible to display the value of a variable in a window using Quick Watch. This
button is only available when the XCM is running and paused, and when a variable
name is highlighted. The current value of the variable will be displayed in a window
as shown below. This option has largely been superseded by the tooltips that are
available for variables.

Insert/Remove Breakpoint (F9)


Breakpoints are used to pause your XCM at set places, so that the code can be
examined more closely. Position your cursor on the line on which you wish the XCM
to pause and then click on this button. A red stop sign will be placed in the left
margin to indicate the breakpoint. Breakpoints can be inserted in your XCM when it
is running or paused. The button works like a toggle, so to remove a breakpoint,
position your cursor on the line and click on the button again.
Breakpoints do not work if they are placed on comment lines or lines at the end of a
control structure, eg. End If, Wend, Loop, etc. When the Debug program is closed,
the breakpoints will be cleared.

Enable/Disable Breakpoint (Ctrl+F9)


It is possible to temporarily disable a breakpoint in your XCM without removing it.
Position your cursor on the line containing the breakpoint and then select this button.
The red stop sign marking the breakpoint point will change to a white stop sign with a
red boundary. This button works as a toggle, so it is also used to enable a breakpoint
that has been disabled.

Remove All Breakpoints (Ctrl+Shift+F9)


Use this button to remove all of the breakpoints that you have inserted, regardless of
whether they have been enabled or disabled.

Runge Ltd May, 2006 Page 29


XCM Reference Guide How to Run an XCM

Disable All Breakpoints


This option is used to disable all of the breakpoints that you have set in your XCM, so
that it can run uninterrupted. The button cannot be used to enable breakpoints in the
XCM, rather they must be individually enabled.

3.10.2 Debug Window


There is a range of features available on the Debug window. These are described
below.
Variable Tooltips
When you have an XCM running in the debugger, it is possible to display the current
value of any variable in your XCM. This can only be done when the XCM is paused.
To display the value of a variable, hover your cursor over the variable name,
anywhere in the XCM. After a short delay a tooltip will appear containing the
variable name and its current value. This feature is extremely useful for tracking the
changes in variable values while your XCM is being processed and consequently
locating errors in your logic.
Debugger Window Title Bar
On the title bar of the debug window, important information is displayed about your
current debug session.
• Name of the XCM being debugged. If the name is followed by an asterisk(*), this
indicates the XCM has been modified and not saved.
• The state of the debugger (in square brackets), eg. paused, running, error, etc.
Note that in the error state you can still check the values of variables.
• The database range over which the XCM is being run.
• The number of records that have been processed and the total number to process
in the range.
• The full path name for the current record being processed.
Text Colours
In the debugger, the commands in your XCM are displayed in specific colours, as
follows:
Comments – green.
Enable statements and functions – blue.
Other – black.
Line and Column Number
On the lower right of the debug window, the row and column numbers are displayed
for your current cursor position. When you get an error message while running your
XCM, it may refer to a line number where the problem occurred. The row number on
the lower right of the window can be used to locate this line.

Runge Ltd May, 2006 Page 30


XCM Reference Guide How to Run an XCM

Editing your XCM


While you have an XCM open in the debugger, you are able to modify it. When you
close the debug window, if you have made changes to your XCM then you will be
asked if you would like to save them.
The following options are available from the Edit menu in the debug window.
Undo – undoes the last modification.
Cut – removes the highlighted text and stores it on the clipboard.
Copy – copies the highlighted text to the clipboard.
Paste – insert the contents of the clipboard at the cursor position or paste it over
the highlighted text.
Delete – delete the highlighted text.
Select All – highlight the whole XCM.
Find – search the XCM for the specified text.
Find Next – find the next occurrence of the text included in the previous Find.
Replace – search the XCM for the specified text and replace it with the specified
text.
Go To – move your cursor to the specified line number.

Runge Ltd May, 2006 Page 31


XCM Reference Guide Structure of an XCM

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.

4.1 XCM Header


The XCM header consists of a series of comment lines whose purpose is to provide an
overview of the XCM. We strongly recommend that you complete this section, to
ensure your XCMs are well documented and easily transferred between XPAC users.
The comment lines in the XCM header are as follows:
Company/Job Name – Your company name and/or job name should be entered at the
top of the XCM.
Description of XCM – This section should contain a brief description of all of the
calculations carried out in the XCM. If complex formulae or logic are used, they may
also be described here. Alternatively, they could be placed within the XCM before
the relevant section of code.
XCM History – The history should be filled in each time a significant change is made
to the XCM. This includes the date, the person making the changes and a description
of the changes. The first entry in the XCM History will refer to when the XCM was
written. The XCM history may be useful in determining whether you have the correct
version of an XCM, when an error may have been introduced into an XCM, who to
follow up with questions about an XCM, etc.

4.2 Indentation of Code


To make the code in your XCMs more readable, different lines are indented by
various amounts. Blocks of code that are within a function, subroutine or control
structure are indented by one increment to the right of the start of that function,
subroutine or control structure. Comment lines should be indented in line with the
code around them. We recommend that one increment consist of three spaces.

Runge Ltd May, 2006 Page 32


XCM Reference Guide Structure of an XCM

Example XCM Structure

'========================================================================='
'! !'
'! This XCM has been written for COMPANY NAME under Job Number ####. !'
'! !'
'========================================================================='

'==================
'DESCRIPTION OF XCM
'==================
'

'===========
'XCM HISTORY
'===========

' Date (dd-mmm-yy) Author/Company Description of Modifications


'--------------------------------------------------------------------------------

'================================================================================================

'Declare Script Constants - use upper case


'========================

'Declare Script Variables - use prefixes d:double l:long s:string b:boolean etc
'========================

'================================================================================================

'========
Sub Main
'========

'Declare Local Constants - use upper case


'=======================

'Declare Local Variables - use prefixes d:double l:long s:string b:boolean etc
'=======================

'Initialise Local Variables


'==========================

'XCM Initialisation Logic


'========================

'The following logic is applied ONCE, BEFORE the first record in the range is processed

If IsFirstInRange() Then

End If

'Initialise Data Fields


'======================

'Clear Database Data Fields (eg. ClearData rFirst_Row_Code, rLast_Row_Code)

'---------------------------------------------------------------------------------------------

'MAIN PROCEDURE
'==============

'---------------------------------------------------------------------------------------------

'XCM Termination Logic


'=====================

'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

Runge Ltd May, 2006 Page 33


XCM Reference Guide Structure of an 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

In UltraEdit TM it is possible to set the Tab key so that it represents a specified


number of spaces. Each time it is pressed, that number of spaces will be inserted.
The Tab key is set from within UltraEdit TM as follows.
• Open the Advanced menu and select Configuration.
• Click on the Edit tab.
• Tick the option Use spaces in place of Tabs.
• Set the option Tab Stop Value or number of spaces to use in place of tabs to 3.
• Click on OK.
It is important that spaces are used in place of tabs. If tabs are used, the XCM may
look different in each editor in which it is opened, depending on how a tab character is
displayed. If spaces are used, the XCM should look the same in any editor.

4.3 Declaring Script Constants and Variables


The different types of constants and variables that are available in an XCM are
explained in the following section, along with how to declare them and why they need
to be declared.
Script constants and variables are those that are available to all subroutines and
functions within the current XCM. Script constants and variables will retain their
value from one record to the next, but when the XCM has finished running, their
value will be lost.
Since any subroutine or function within the XCM can use these constants and
variables, it makes sense that they must be declared outside of and before all
subroutines and functions in the XCM. For this reason, in an XCM they are declared
before the Main subroutine.
For information about the syntax to use for declaring script constants and variables,
refer to the following section (XCM Language Elements).

Runge Ltd May, 2006 Page 34


XCM Reference Guide Structure of an XCM

4.4 Sub Main


The Sub Main command indicates the start of the subroutine called Main. Each
XCM must contain one Main subroutine and without it, the XCM will not run. When
an XCM is run, the Main subroutine is processed as follows:
• If the XCM is run over a range, then the Main subroutine is processed for each
lowest level record in that range.
• If the XCM is run once only, then the Main subroutine is processed once only.
Other subroutines and functions may be called from within the Main subroutine. The
Main subroutine ends on the command End Sub.

4.5 Declaring Local Constants and Variables


The first set of commands that should appear within the Main subroutine is the
declaration of the local constants and variables. The different types of constants and
variables that are available in an XCM are explained in the following section, along
with how to declare them and why they need to be declared.
Local constants and variables are those that are available to the current subroutine
only. So constants and variables that are declared after the Sub Main command and
before the next End Sub command, will only be available for use within the Main
subroutine. Local constants and variables will not retain their value from one record
to the next. Local constants and variables may also be declared within the user-
defined functions and subroutines, but they will only be available from there and their
values will not be retained after the function or subroutine has been processed.
When variables are declared, their values are initialised as follows:
• Doubles are set to zero;
• Longs are set to zero;
• String variables are set to null;
• Boolean variables are set to False; and
• Date variables are set to 12am, 30 December, 1899 (note that 12am is midnight).
If you want a local variable to start with some different value, then you must initialise
it. This should be done under the heading “Initialise Local Variables”.
For information about the syntax to use for declaring script constants and variables,
refer to the following section (XCM Language Elements).

4.6 XCM Initialisation Logic


For XCM’s that are being run over a database range, every command within the Main
subroutine will be processed for each lowest level record in that range. However,
sometimes there are commands that you only want to process once. Examples of such
commands include opening a file so that it can be written to, setting a global variable,
asking the user for input, etc.

Runge Ltd May, 2006 Page 35


XCM Reference Guide Structure of an XCM

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.

4.7 Clearing Data Fields


When an XCM is run over any record in a database range, the current data field values
in that record are not automatically cleared out before they are reassigned. In some
situations this can be used to your advantage, but most of the time you will need to
manually clear the data field values in your XCM.
We recommend that you make a habit of clearing all relevant data fields at the start of
each XCM. Even if there appears to be no need to do this when the XCM is written, a
change may be made to the XCM at a later stage making it necessary.
Data fields are cleared by assigning a zero or null value to them, depending on the
type of data field. This can be done in a number of ways.
• To clear data field number 36 which is a numeric type field, you could include the
command: M(36) = 0
• To clear data field number 48 which is a string type field, you could include the
command: Call SetClass(48, "")
• To clear data fields 50 to 60, which are a mixture of numeric and string type
fields, you could include the command: ClearData 50, 60
There is an obvious advantage in using the ClearData function, as you are able to
clear a range of data field values in a single command.

4.8 Main Procedure


The largest and most complex section of your XCM will usually be that part under the
heading “Main Procedure”. This is where you enter the logic and calculations for
manipulating your database data. This section will be significantly different in each
XCM. All of the recommendations about indentation and use of comments are
particularly relevant to this section.

4.9 XCM Termination Logic


For XCM’s that are being run over a database range, every command within the Main
subroutine will be processed for each lowest level record in that range. However,

Runge Ltd May, 2006 Page 36


XCM Reference Guide Structure of an XCM

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.10 End Sub


The end of the Main subroutine is marked by the command “End Sub”. Without this
command, you are likely to get an error message during the compilation of the XCM.

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.

Runge Ltd May, 2006 Page 37


XCM Reference Guide XCM Language Elements

5 XCM Language Elements


To be able to read or write an XCM, you need to have an understanding of the rules
under which it is written. This concept is very similar to learning a new language,
such as French or Cantonese.
As with any language, there are many words available for use in your XCM. Before
we look at these words, we need to understand the different types of words that exist
in an XCM and how they can be put together. This can be compared to nouns, verbs,
punctuation, etc in the English language. In XCM, these are called the language
elements and each one is discussed in the following sections.

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)

Runge Ltd May, 2006 Page 38


XCM Reference Guide XCM Language Elements

can also be written as:


x = GetRecNum(UP) : y = GetNumChildren(x)

5.3 Line Continuation Character


When you are writing a long formula in an XCM, you may find that the line of code
extends beyond the viewing window or wraps onto the next line when the XCM is
printed. One way of getting around these problems is to manually break the line of
code up into multiple lines. This is done using the line continuation character, which
is an underscore. The line continuation character is placed on the end of the line that
is to be continued and there must be a space before and after it. An example is
provided below.
M(mROM_Cl_is RD) = SafeDivide(M(mROM_Cl_ad_RD) * (100 – MSTad), _
100 + M(mROM_Cl_ad_RD) * (MSTis – MSTad) – MSTis)

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.5 Variables and Constants


Variables and constants are used to permanently and temporarily store values for use
in your XCM. There are different rules and naming conventions for variables and
constants, and there are many different types of variables. XCM variables and
constants are discussed in detail in the following section.

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.

Runge Ltd May, 2006 Page 39


XCM Reference Guide XCM Language Elements

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

There is an order of precedence that is applied to the operators to interpret statements.


For example, the arithmetic operators follow the mathematical rules of precedence, so
the following statements give different results for x.
x = 2 + 3 * 4 = 14
x = (2+3) * 4 = 20
The following table defines the order of precedence for all of the XCM operators.
Operator Precedence
Operator Description Order
() Parenthesis Highest
^ Exponentiation
- Unary Minus
/, * Division, Multiplication
Mod Modulo
+, -, & Addition, Subtraction, Concatenation
=, <>, <, >, Relational
<=, >=
Not Logical Negation
And Logical Conjunction
Or Logical Disjunction
Xor Logical Exclusion
Eqv Logical Equivalence
Imp Logical Implication Lowest

Runge Ltd May, 2006 Page 40


XCM Reference Guide XCM Language Elements

5.7 Control Structures


Control structures are blocks of code that run multiple times or that branch on the
basis of some condition. They are very powerful tools and they should help to
simplify your XCM code. The following control structures are available in XCM and
are discussed in detail in a later section.
• Do Loops
• While Loops
• For Loops
• Select Case
• If Then and If Then Else
• GoTo

5.8 Functions and


and Subroutines
Functions and subroutines are blocks of code that can be called at any time within
your XCM. Their biggest advantage is that they minimise repetition of code and
therefore make your XCMs easier to read and to modify. The difference between a
function and a subroutine is that a function will return a value, whereas a subroutine
will not.
All XCMs must contain at least one subroutine, which is called Main. In addition,
there are predefined functions and subroutines that come with XPAC, or you can
create your own functions and subroutines. Refer to the section on functions and
subroutines for more information.

5.9 Syntax
Syntax describes the rules controlling how code can be put together. It is analogous
to grammar in the English language.

Runge Ltd May, 2006 Page 41


XCM Reference Guide XCM Variables and Constants

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.3 Data Field Variables


Data field variables are a special type of array that XPAC creates, so that you can read
from and write to the data fields in your databases. The names of these arrays are
defined by XPAC and they are different for each type of database in your model.

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

Runge Ltd May, 2006 Page 42


XCM Reference Guide XCM Variables and Constants

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.

Runge Ltd May, 2006 Page 43


XCM Reference Guide XCM Variables and Constants

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.

6.3 Declaring Variables


All user-defined variables must be declared in an XCM, including user-defined arrays.
The place in which they are declared in your XCM will depend on the scope of the
variable. When declaring a variable you must specify its data type. Variables are
declared using the following statement.
Dim VariableName As DataType
Some examples are provided below.
Dim lBenchRL As Long
Dim sProcMethod(10) As String
Dim dOreGrade As Double
Dim bLastBenchInPit As Boolean

You do not have to declare data field variables. XPAC does this automatically for
you.

6.4 Defining Constants


Constants are used to store values that will not change during the execution of your
XCM. The values may be either long, double or string data types, however when you
define a constant, you do not need to specify its data type. There is no need to use
data type prefixes for a constant, although we recommend that you do, as it will make
the expected value of the constant clearer in your XCM. Constants are defined using
the following statement.
Const ConstantName = Value
Some examples are provided below.
Const dDEFAULTRD = 2.45
Const sFILENAME = "Error Report.txt"

6.5 Scope of Variables and Constants


Scope refers to the realm from which you can access a variable or constant. In
XPAC, variables and constants may belong to one of three scopes, namely global,
script or local. Some variables or constants must be prefixed with a character,
depending on their scope. The scope character will always be the first character in
the name.

Runge Ltd May, 2006 Page 44


XCM Reference Guide XCM Variables and Constants

6.5.1 Global Variables and Constants


Global variables and constants belong to an XPAC project and are available to any
XCM run within that project. They can only be set up from within the project, under
the menu option View | Global Variables.
• When this option is selected a table appears, containing all current global variables
and constants. The name of the variable or constant is entered in the first column
of the next available row, and a description can be entered in the second column.
If the Storage Class is set to variable, then its value can be changed by an XCM.
If the Storage Class is set to constant, then its value cannot be changed by an
XCM. The Variable Type can be set to either Number or Date. Note that global
variables and constants cannot currently be strings. The last column in the table
stores the initial value of the global variable or constant.
• Global variables and constants should begin with a lower case g. This is then
followed by the standard naming convention.
• Global variables and constants should not be declared in an XCM.
• Arrays cannot be defined as global variables.

6.5.2 Script Variables and Constants


Script variables and constants are declared inside an XCM, but outside all
subroutines and functions (including the Main subroutine). They are available to all
sub-routines within that XCM, but they are not available to other XCMs.
• When an XCM is run over a database range, a script variable will retain its value
from one record to the next. They are therefore ideal for storing cumulative
values and flags. The value of a script variable will be lost when the XCM
finishes running.
• Script variables and constants are not assigned a prefix character to indicate their
scope. Their names follow the standard naming convention.
• Script variables and constants must be declared at the start of the XCM, before
Sub Main or any other subroutine or function.
• Arrays can be declared as script variables.

6.5.3 Local Variables and Constants


Local variables and constants are declared inside a subroutine or function, and they
are only available to that subroutine or function.
• When an XCM is run over a database range, a local variable will not retain its
value from one record to the next, rather it will be initialised for each new record.
• Local variables are not assigned a prefix character to indicate their scope. Their
names follow the standard naming convention.
• Local variables and constants must be declared at the start of the subroutine or
function.
• Arrays can be declared as local variables.

Runge Ltd May, 2006 Page 45


XCM Reference Guide XCM Variables and Constants

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.

6.7 Example Variable and Constant Names

Runge Ltd May, 2006 Page 46


XCM Reference Guide XCM Variables and Constants

Some example names for variables and constants are listed in the following table.

Description Scope Data Type Variable, Name


Array or
Constant

Dragline Dig Depth Global Double Constant gdDLDEPTH

Number of Loaders Global Long Variable glNumLoaders

Output File Name Script String Variable sOutFileName

Edge Blocks Script Boolean Variable BIsEdgeBlock

Gold Recovery Script Double Array DAuRec(20)

Bottom Bench Number Script Long Constant LBASEBENCH

Insitu Waste Density Local Double Constant DISWSTRD

Seam Name Local String Array SSmName(10)

FEL Productivity Local Double Variable DFELProd

6.8 Data Field Variables


An XPAC database is made up of records and a user-defined number of data fields.
When an XCM is run over a database range, calculations are performed using the
current data field values in each record. Values may also be written back into data
fields. To do this, XCM needs some way of referencing the data fields and this is
done using data field variables.
Since an XCM only processes one record at a time, the same data field variables can
be used to reference all of the database records. Data field variables are therefore one-
dimensional arrays, where the dimension represents the number of the data field. The
name of the array is different for each of the four database types, as shown in the
following table.
Database Type Data Field Variable
Main database M(data field number or full row code)
Calendar database C(data field number or full row code)
Parameters database P(data field number or full row code)
Results database R(data field number or full row code)

6.9 Data Field Number or Full Row Code


You can use the data field number to reference a data field, however if you do you
are likely to encounter some problems. If you insert data fields into your database the
data field numbers will change, so the references to particular data fields will be
incorrect and you will have to manually update your XCMs. The data field numbers

Runge Ltd May, 2006 Page 47


XCM Reference Guide XCM Variables and Constants

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.

6.10 XPAC Commands Added to Your XCM


When an XCM is compiled, XPAC automatically adds some commands to the
beginning of the XCM to save you some time and effort. The addition of these
commands to your XCMs is not permanent, so you will not see any changes when the
XCMs are edited. The commands that are added are related to special XPAC
variables and constants, and they include:
• Forced Declaration of Variables;
• Predefined Database Level Variables; and
• Full Row Codes.

6.11 Forced Declaration of Variables


If the command Option Explicit appears at the beginning of an XCM, then all of the
variables must be declared. Any variable that is not declared will be reported in an
error message and the XCM cannot be run until it is declared or removed. This feature
is useful for locating variable names that have been misspelt.
XPAC forces you to declare all of your variables by automatically adding this line to
the beginning of all XCMs. There is no way of removing this option.

6.12 Predefined Database Level Variables


When writing XCMs, it is common to use variables to store the position in level
numbers and the record names at each database level for the current record. Such
variables are automatically declared and assigned for you when your XCM is
compiled. These variables are added to the beginning of your XCM, so they are
available for use anywhere within your XCM.
The following commands are added to your XCM.

Runge Ltd May, 2006 Page 48


XCM Reference Guide XCM Variables and Constants

• 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.

6.13 Full Row Codes


Full row codes can often be used in an XCM instead of the data field numbers. When
an XCM is compiled, each full row code that is in that XCM is automatically defined
as a constant. The value of the constant is the current data field number and it is
determined by interrogating the database over which the XCM is being run.
For example, the full row code for field number 35 might be mROM_Ore_Grd.
Using this information, the following line is added to the beginning of the XCM.
Const mROM_Ore_Grd = 35

Runge Ltd May, 2006 Page 49


XCM Reference Guide XCM Variables and Constants

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

Runge Ltd May, 2006 Page 50


XCM Reference Guide Control Structures

7 Control Structures

7.1 What is a Control Structure


A control structure is a set of commands that test some condition and then use the
result of this test to determine what action should be taken. Control structures can be
useful in minimising code repetition.
The following control structures are available in XCM:
• If Statements;
• Do Loops;
• While Loops;
• For Loops;
• Select Case: and
• GoTo Statements.

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

Runge Ltd May, 2006 Page 51


XCM Reference Guide Control Structures

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

Runge Ltd May, 2006 Page 52


XCM Reference Guide Control Structures

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.3 Select Case Statements


If you have many conditions to test in an If statement, your code may become long
and complex. In this situation, you should consider using Select Case. The Select
Case statement tests the same variable for many different values. The test variable
can store long, double, string or boolean data types. Note that with the Select Case
statement, the test variable must be equal to the values. The greater than or less than
operators cannot be used. The syntax for this statement is:
Select Case TestVariable
Case Value1
Statements if TestVariable = Value1
Case Value2
Statements if TestVariable = Value2
Case Else
Statements for all other values of TestVariable
End Select
Example:
'Set the Yield according to the Processing Method
Select Case sProcessMethod
Case "Bypass"
dYield = 100
Case "Washed"
dYield = CurveValue("Ash-Yield", M(mROM_Ash))
Case Else
Abort "Warning: Processing Method is invalid."
End Select

Runge Ltd May, 2006 Page 53


XCM Reference Guide Control Structures

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.2 Do…Loop While


This loop is similar to the Do While loop described above, except that the condition is
checked after the statements have been processed. The statements will always be
processed at least once then, while the condition is true, the statements inside the Do
Loop will continue to be processed. Once the condition is false the loop will be
finished, and the next execution point will be after the Loop While statement. The
syntax is:
Do
Statements
Loop While Condition
Example:
'Store the Bench Number where the Maximum Waste Depth is reached.
Do
dCumWstThk = dCumWstThk + M(mROM_Wst_Thk)
lBaseBenchNum = GetApil(3)
Call GoRec(NXT)
Loop While (dCumWstThk < dMaxWstDpth)

Runge Ltd May, 2006 Page 54


XCM Reference Guide Control Structures

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.4 Do…Loop Until


This loop is similar to the Do Until loop described above, except that the condition is
checked after the statements have been processed. The statements will always be
processed at least once then, until the condition is true, the statements inside the Do
Loop will continue to be processed. Once the condition is true the loop will be
finished, and the next execution point will be after the Loop Until statement. The
syntax is:
Do
Statements
Loop Until Condition
Example:
'Store the Bench Number where the Maximum Waste Depth is reached.
Do
dCumWstThk = dCumWstThk + M(mROM_Wst_Thk)
lBaseBenchNum = GetApil(3)
Call GoRec(NXT)
Loop Until (dCumWstThk >= dMaxWstDpth)

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

Runge Ltd May, 2006 Page 55


XCM Reference Guide Control Structures

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

7.5 While Loops


The While loop is similar to the Do While loop. A condition is checked before
entering a loop. While the condition is true, the statements inside the While 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:
While Condition
Statements
WEnd
Example:
'Store the Bench Number where the Maximum Waste Depth is reached.
While (dCumWstThk < dMaxWstDpth)
dCumWstThk = dCumWstThk + M(mROM_Wst_Thk)
lBaseBenchNum = GetApil(3)
Call GoRec(NXT)
WEnd

7.6 For Loops


For loops have a counter variable and they repeat a block of statements a set number
of times. The counter variable increases or decreases with each repetition through the
loop. The counter increment is specified using the Step statement. This statement is
optional and if it is not included, the increment will be one. The starting and ending
values must also be specified for the counter. The syntax is:
For CounterName = StartValue To EndValue [Step Increment]
Statements
Next CounterName
Note that it is optional to repeat the counter variable name after the Next statement.
We recommend that you do repeat it, as it will help to match up the For and Next
statements in your code.

Runge Ltd May, 2006 Page 56


XCM Reference Guide Control Structures

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

7.7 GoTo Statements


We recommend that you do not use GoTo statements, as it is very easy to get caught
in endless loops. You should find that the other control structures can be used in most
situations.
GoTo statements are used to branch to a specified point in your code. The point is
specified using a label, which can be any mixture of alpha-numeric characters. When
a GoTo statement is encountered, the execution point will jump to the line that begins
with the label and continue processing from there onwards. The line of code
containing the label may occur either before or after the GoTo statement, but it should
be within the same subroutine. Each label must be unique, however multiple GoTo
statements can access the same label.
The syntax is:
GoTo Label
Statements
Label: Statements
Statements
Example:
'The following code uses GoTo statements in place of If..Then..Else..End If
If (M(mBlk_Grade) < dHighGrdCutOff) Then GoTo Waste
If (M(mBlk_Grade) >= dHighGrdCutOff) Then GoTo Ore
Waste: M(mWaste_Ton) = M(mBlk_Ton)
M(mHighGrd_Ton) = 0
GoTo Haulage
Ore: M(mWaste_Ton) = 0
M(mHighGrd_Ton) = M(mBlk_Ton)
Haulage:

Runge Ltd May, 2006 Page 57


XCM Reference Guide Functions and Subroutines

8 Functions and Subroutines

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.

8.2.1 Function Arguments


There are generally two kinds of functions, namely those that take an argument and
those for which no argument is required. An argument (also called a parameter) is a
value that is passed to the function and is used during the processing of the function.
The following examples show functions with and without arguments.
Function with no arguments - IsFirstInRange:
'Open a File at the start of the XCM
If (IsFirstInRange()) Then
Open "Reserves Summary by Strip.txt" For Output As #1
End If

Functions with one argument – GetRecNum and GetNumChildren:

Runge Ltd May, 2006 Page 58


XCM Reference Guide Functions and Subroutines

'Find out how many Blocks in the current Panel


lPanelRec = GetRecNum(UP)
lNumBlocksInPanel = GetNumChildren(lPanelRec)

Function with multiple arguments - GetRecFromPil:


'Does the current Seam exist in the adjacent Strip
lSeamInAdjStrip = GetRecFromPil(lPitNum, lStripNum+1, lSeamNum)
If (lSeamInAdjStrip > 0) Then Print "Seam Exists in Adjacent Strip"

8.2.2 Calling a Function


All functions return a value, which is the result of the function’s operation. Even
functions that do not have any arguments return a value. The return value of a
function is almost always assigned to a variable. For this reason, functions are
generally called when they are assigned to a variable, although they can also be called
using the Call statement. The syntax is:
Variable = FunctionName(Argument1, Argument2,..)
Or
Call FunctionName(Argument1, Argument2,..)

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"

Function called using the Call statement:


'Display a Message when the Last Record in the Range is Reached
lNextRec = GetRecNum(NXT)
If (lNextRec > 0) Then
Call GoRec(lNextRec)
Else
Print "Reached Last Record in Database Range"
End If

Runge Ltd May, 2006 Page 59


XCM Reference Guide Functions and Subroutines

8.2.3 Combining Functions


XCM also permits the combination of functions within a single expression. When
this is done, the innermost function is processed first. In the following example, the
function DegToRad is processed and then the function Tan is processed.
'Calculate the Tan of an Angle that is in Degrees
dBatterHt = dBatterWdth * Tan(DegToRad(65))

8.3 Subroutines
A subroutine is a set of code that can be called and processed from within your XCM.

8.3.1 Subroutine Arguments


Like functions, there are generally two kinds of subroutines, namely those that take an
argument and those for which no argument is required. An argument (also called a
parameter) is a value that is passed to the subroutine and is used during the processing
of the subroutine. The following examples show subroutines with and without
arguments.
Subroutine with no arguments – RemoveAllDependencies:
'Remove all Dependencies from the current Project
Call RemoveAllDependencies()

Subroutine with one argument – Add:


'Combine the two Half Year Time Periods into a single Year Record
If (sHalfYearName = "1stHalf") Then
lSecondHalfRec = GetRecNum(NXTSIB)
If (lSecondHalfRec > 0) Then Call Add(lSecondHalfRec)
End If

Subroutine with multiple arguments - DbWriteValue:


'Write the Name of the Seam Above into each Seam Record
If (Not(IsLast()) Then
sSeamName = GetRecName(CURRENT, RECORDNAME)
lNextSeamRec = GetRecNum(NXTSIB)
Call DbWriteValue("Main", lNextSeamRec, mSeam_Above, sSeamName)
End If

8.3.2 Calling a Subroutine


Subroutine
Subroutines do not return a value themselves. Since subroutines do not return a
value, they cannot be assigned to a variable like functions can be. Subroutines can
only be called using the Call statement. The syntax is:
Call SubroutineName(Argument1, Argument2,..)

Runge Ltd May, 2006 Page 60


XCM Reference Guide Functions and Subroutines

8.4 ByRef and ByVal


You can pass arguments to a function or subroutine by value or by reference.
Passing an argument by value means that a copy of the argument is sent to the
function or subroutine. The function or subroutine cannot change the value of the
actual argument, because it is only working with a copy of the argument. The key
word ByVal is used in this case.
Passing an argument by reference means that the function is actually passing a
pointer to the address where the value of the argument is stored. In this case it is
possible for the function or subroutine to actually change the value of the argument,
since it is working with the actual address where the argument’s value is stored and
not just a copy of the argument’s value. The key word ByRef is used in this case.
In a function, arguments must be passed by reference when there is a need to return
more than one value. In a subroutine, arguments must be passed by reference when
there is a need to return any values. When the contents of a variable are large (eg. a
string or an array), by reference is preferred as it does not duplicate the data.
The syntax for passing arguments by value or by reference is the same for both
functions and subroutines. The various arguments in a function or subroutine can be
passed by any combination of by value or by reference.
Sub Name(ByRef Argument1 As Type, ByVal Argument2 As Type,….)
Statements
End Sub

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

In the following example, the effects of passing arguments to a subroutine by value


and by reference are illustrated.
Sub Main
'Waste Volume
Dim dWstVol As Double
Call CalcVol(M(mWst_Area), M(mWst_Thk), dWstVol)
M(mWst_Vol) = dWstVol
'Ore Volume
Dim dOreVol As Double
Call CalcVol(M(mOre_Area), M(mOre_Thk), dOreVol)
M(mOre_Vol) = dOreVol
End Sub

Runge Ltd May, 2006 Page 61


XCM Reference Guide Functions and Subroutines

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

8.5 XPAC Functions and Subroutines


There are a large number of predefined functions and subroutines that are supplied
with XPAC and they are available for use in any of your XCMs. The XPAC
functions and subroutines perform a variety of tasks, ranging from calculating the

Runge Ltd May, 2006 Page 62


XCM Reference Guide Functions and Subroutines

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.

8.6.1 Syntax for Functions and Subroutines


User-defined functions and subroutines are called in the same way as other functions
and subroutines.
The syntax for defining user-defined functions and subroutines is provided below. A
description of each element is provided in the following sections.
Functions:
Function FunctionName(Argument1 As Type, Argument2 As Type,….) As Type
Statements
End Function

Subroutines:
Sub SubroutineName(Argument1 As Type, Argument2 As Type,….)
Statements
End Sub

8.6.2 Function and Subroutine Names


You define the function or subroutine name. The name can contain upper and lower
case letters, the digits 0 to 9 and the underscore character. The limitations on the
names are that they must begin with a letter, they must not be greater than 40
characters in length and reserved words cannot be used.
We recommend that you use the same naming conventions for user-defined functions
and subroutines as have been suggested for user-defined variables (subject to the rules
described above). It is important that the names are meaningful.

8.6.3 Arguments

Runge Ltd May, 2006 Page 63


XCM Reference Guide Functions and Subroutines

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

8.6.4 Function Types


Since a function returns a value, the Type of that value must be defined. In the
example above, the function returns the Insitu RD, so the function Type is defined as
a Double. Function Types can be any of those Types described for variables.
Subroutines do not return a value, so you should not define a Type for them.

8.6.5 End Statement


All functions and subroutines must finish with the End statement. For functions, it is
End Function and for subroutines it is End Sub.

8.7 Functions and Subroutines Sharing


Parameters
Multiple functions and/or subroutines can access and change the same variable if it is
declared as a Script or a Global variable.
Script variables are declared within an XCM, but outside all functions and
subroutines, including the Main subroutine. They are available to all functions and
subroutines within the current script. They will retain their value from one function or

Runge Ltd May, 2006 Page 64


XCM Reference Guide Functions and Subroutines

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"

If (sOreType = "Type1") Then RecMethodA = 98 – 16 * M(mImpurity_Grd)


If (sOreType = "Type2") Then RecMethodA = 96 – 17 * M(mImpurity_Grd)
End Function

Runge Ltd May, 2006 Page 65


XCM Reference Guide XCM Commands

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.

9.2 Cypress EnableTM Commands


Cypress EnableTM is the language that XPAC uses behind the scenes for XCM. It has
a very similar syntax to MicrosoftTM Visual Basic for Applications. To make use of
the wide range of commands associated with Cypress EnableTM, you must understand
their syntax and application. This information is provided alphabetically in Section
10.2.

9.3 XPAC Functions


Functions and Subroutines
The XPAC functions and subroutines are available from within any XCM and they
can be used to manipulate or extract information from your XPAC databases and
schedules. Unlike user-defined functions and subroutines, these have been created for
you and they do not have to be defined in your XCM. To make use of them, all you
have to know is their syntax, which is described in Section 11 for each function and
subroutine. There are a large number of functions and subroutines available and they
are listed alphabetically.

Runge Ltd May, 2006 Page 66


XCM Reference Guide Cypress Enable Commands

10 Cypress EnableTM Commands

10.1 Quick Reference of the Functions and


Statements Available

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,
______________________________________________________

Runge Ltd May, 2006 Page 67


XCM Reference Guide Cypress Enable Commands

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.2 Data Types

Variable Type Specifier Usage


String $ Dim Str_Var As String
Integer % Dim Int_Var As Integer
Long & Dim Long_Var As Long
Single ! Dim Sing_Var As Single
Double # Dim Dbl_Var As Double
Variant Dim X As Any
Boolean Dim X As Boolean
Byte Dim X As Byte
Object Dim X As Object
Currency (Not currently supported)

Runge Ltd May, 2006 Page 68


XCM Reference Guide Cypress Enable Commands

10.1.3 Operators

Arithmetic Operators

Operator Function Usage


^ Exponentiation x = y^2
- Negation x = -2
* Multiplication x% = 2 * 3
/ Division x = 10/2
Mod Modulo x = y Mod z
+ Addition x=2+3
- Subtraction x=6-4

*Arithmetic operators follow mathematical rules of precedence.


* '+' or '&' can be used for string concatenation.

10.1.4 Operator Precedence


Operator Description Order

() 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

Runge Ltd May, 2006 Page 69


XCM Reference Guide Cypress Enable Commands

10.1.5 Relational Operators

Operator Function Usage

< Less than x < Y


<= Less than or equal to x <= Y
= Equals x = Y
>= Greater than or equal to x >= Y
> Greater than x > Y
<> Not equal to x <> Y

10.1.6 Logical Operators

Operator Function Usage


Not Logical Negation If Not (x)
And Logical And If (x> y) And (x < Z)
Or Logical Or If (x = y) Or (x = z)

10.1.7 Functions, Statements, Reserved Words


- Quick Reference
_______________________________________________

Abs, Access, Alias, And Any


App, AppActivate, Asc, Atn, As
Base, Beep, Begin, Binary, ByVal
Call, Case, ChDir, ChDrive, Choose, Chr, Const, Cos, CurDir, CDbl, CInt,
CLng, CSng, CStr, CVar, CVDate,Close, CreateObject
Date, Day, Declare, Dim, Dir, Do...Loop,Dialog, DDEInitiate
DDEExecute, DateSerial, DateValue, Double
Else, ElseIf, End, EndIf, EOF, Eqv, Erase, Err, Error
Exit, Exp, Explicit
False, FileCopy, FileLen, Fix, For,
For...Next, Format, Function
GetAttr, GoSub, GoTo, Global, Get Object
Hex, Hour
If...Then...Else...[End If], Imp, Input, InputBox, InStr, Int, Integer, IsEmpty, IsNull,
IsNumeric, IsDate
Kill
LBound, LCase, Left, Len, Let, LOF,Log, Long, Loop, LTrim Line Input
Mid,Minute, MkDir, Mod, Month, MsgBox
Name, Next, Not, Now
Oct,On, Open, OKButton,Object, Option, Or, On Error
Print, Print #, Private
Rem, ReDim, RmDir, Rnd, Return, RTrim

Runge Ltd May, 2006 Page 70


XCM Reference Guide Cypress Enable Commands

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

Runge Ltd May, 2006 Page 71


XCM Reference Guide Cypress Enable Commands

10.2 Language Reference A - Z

10.2.1 Abs Function

Abs (int number)

Returns the absolute value of a number.

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

Runge Ltd May, 2006 Page 72


XCM Reference Guide Cypress Enable Commands

10.2.2 AppActivate Statement

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.

Related Topics: Shell, SendKeys

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

10.2.3 Asc Function

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

Runge Ltd May, 2006 Page 73


XCM Reference Guide Cypress Enable Commands

10.2.4 Atn Function

Atn (rad )

Returns the arc tangent of a number (tan-1)

The argument rad can be any numeric expression. The result is expressed
in radians

Related Topics: Cos, Tan, Sin

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

10.2.5 Beep Statement

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

Runge Ltd May, 2006 Page 74


XCM Reference Guide Cypress Enable Commands

End Sub ' End of Routine


' End of XCM

10.2.6 Call Statement

Call name [(parameter(s)]


Or name [parameter(s)]

Activates an Enable Subroutine called name or a DLL function with the


name name. The first parameter is the name of the function or subroutine
to call, and the second is the list of arguments to pass to the called function
or subroutine.

You are never required to use the Call statement when calling an 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

Runge Ltd May, 2006 Page 75


XCM Reference Guide Cypress Enable Commands

10.2.7 CBool Function

CBool (expression)

Converts expressions from one data type to a boolean. The parameter


expression must be a valid string or numeric 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

10.2.8 CDate Function

CVDate (expression)

Converts any valid expression to a Date variable with a vartype of 7.


The parameter expression must be a valid string or numeric date expression
and can represent a date from January 1, 100 through December 31, 9999.

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.

Runge Ltd May, 2006 Page 76


XCM Reference Guide Cypress Enable Commands

dStartTime = CDate(sStartTime) ' Convert to Date data type.


Print dStartDate ' Print result
Print dStartTime ' Print result
End Sub ' End Routine
'End of XCM

10.2.9 CDbl Function

CDbl (expression)

Converts expressions from one data type to a double. The parameter


expression must be a valid string or numeric 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

10.2.10 ChDir Statement

ChDir pathname

Changes the default directory

Syntax: [drive:] [ \ ] dir[\dir]...

The parameter pathname is a string limited to fewer then 128 characters.


The drive parameter is optional. The dir parameter is a directory name.
ChDir changes the default directory on the current drive, if the drive is
omitted.

Related Topics: CurDir, CurDir$, ChDrive, Dir, Dir$, MkDir, RmDir

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.

Runge Ltd May, 2006 Page 77


XCM Reference Guide Cypress Enable Commands

sNL = Chr(10) ' Define newline.


sCurPath = CurDir() ' Get current path.
ChDir "\" ' Change directory
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."
lAnswer = 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.11 ChDrive Statement

ChDrive drivename

The parameter drivename is a string and must correspond to a an existing


drive. If drivename contains more than one letter, only the first character
is used.

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

Related Topics: ChDir, CurDir, CurDir$, MkDir, RmDir

Runge Ltd May, 2006 Page 78


XCM Reference Guide Cypress Enable Commands

10.2.12 CheckBox

CheckButton starting x position, starting y position, width, Height

For selecting one or more in a series of choices

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

10.2.13 Choose Function

Choose(number, choice1, [choice2,] [choice3,]… )

Returns a value from a list of arguments

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:

Runge Ltd May, 2006 Page 79


XCM Reference Guide Cypress Enable Commands

Sub Main ' Start Main Routine


Dim lNumber As Long ' Declare choice number
Dim sGetChoice As String ' Declare choice string
lNumber = 2 ' Choose second Choice
sGetChoice = Choose(lNumber, "Choice 1", "Choice 2", "Choice 3")
Print sGetChoice ' Print Second choice
End Sub ' End main routine
'End of XCM

10.2.14 Chr Function

Chr(int )

Returns a one-character string whose ASCII number is the argument

Chr returns a String

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

10.2.15 CInt Function

CInt (expression)

Converts any valid expression to an integer.

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

Runge Ltd May, 2006 Page 80


XCM Reference Guide Cypress Enable Commands

If VarType(dDoubleVar) > 1 Then ' Check data type


Print dDoubleVar ' Print double value
iIntegerVar = CInt(dDoubleVar) ' Double value integer
Print iIntegerVar ' Print integer value
End If ' End Construct
End Sub ' End subroutine
' End of XCM

10.2.16 CLng Function

CLng (expression)

Converts any valid expression into a long.

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

10.2.17 Close Statement

Close [[#filenumber] [, [#]filenumber],,,

The Close Statement takes one argument filenumber. Filenumber is the


number used with the Open Statement to open the file. If the Close
Statement is used without any arguments it closes all open files.

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

Runge Ltd May, 2006 Page 81


XCM Reference Guide Cypress Enable Commands

Loop ' Continue until EOF


Close #1 ' Close raw datafile
End Sub ' End Main routine
'End of XCM

10.2.18 Const Statement


Statement

Const name = expression

Assigns a symbolic name to a constant value.

A constant must be defined before it is used.

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

Runge Ltd May, 2006 Page 82


XCM Reference Guide Cypress Enable Commands

10.2.19 Cos Function

Cos (rad)

Returns the cosine of an angle

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

10.2.20 CreateObject Function

CreateObject (class)

Creates an OLE automation object.


Sub Command1_Click ()
Dim word6 As object
Set word6 = CreateObject("Word.Basic")
word6.FileNewDefault
word6.InsertPara
word6.Insert "Attn:"
word6.InsertPara
word6.InsertPara
word6.InsertPara
word6.Insert " Vender Name: "
word6.Bold 1
name = "Some Body"

Runge Ltd May, 2006 Page 83


XCM Reference Guide Cypress Enable Commands

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

Vender Name: Client Name


Vender Address:
Vender Product:

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.

Runge Ltd May, 2006 Page 84


XCM Reference Guide Cypress Enable Commands

10.2.21 CSng Function

CSng (expression)

Converts any valid expression to a Single.

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

10.2.22 CStr Function


CStr(expression)

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

Data type CStr Function

Numeric Value Number as String


Boolean True/False as String
Error Error as String
Empty "" as String
Null Produces a run time error
Date System Date as String

For Example
' Example for string conversion
Sub Main ' Start main Routine

Runge Ltd May, 2006 Page 85


XCM Reference Guide Cypress Enable Commands

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 = CStr(dMaxTruckProd) ' String is "435.962"
End Sub ' End Subroutine
' End of XCM

10.2.23 CVar Function

CVar (expression)

Converts any valid expression to a Variant.


Example:
Sub Main ' Start Routine
Dim iMyInt As Integer ' Declare Integer type
Dim vMyVar As Variant ' Declare Variant type
iMyInt = 4534 ' Assign Integer value
vMyVar = CVar(iMyInt & "000")' Change to variant
' and add thousand
End Sub ' End of subroutine
' End of XCM

10.2.24 CurDir Function

CurDir (drive)

Returns the current path for the specified drive

CurDir returns a Variant; CurDir$ returns a String.

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

Runge Ltd May, 2006 Page 86


XCM Reference Guide Cypress Enable Commands

10.2.25 Date Function

Date, Date()

Returns the current system date

Date returns a Variant of VarType 8 (String) containing a date.

Example:

' Format Function Example


' This example shows various uses of the Format function to format values
' using both named and user-defined formats. For the date separator (/),
' 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 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"

Runge Ltd May, 2006 Page 87


XCM Reference Guide Cypress Enable Commands

MsgBox Format(Time, "Long Time") & "Long Time"


' Returns current system date in the system-defined long date format.
MsgBox Format(Date, "Short Date") & " Short Date"
MsgBox Format(Date, "Long Date") & " Long Date"
sMyDate = "30 December 91" ' use of European date
Print sMydate
MsgBox sMyDate,0,"MyDate International..."
MsgBox Day(sMyDate),0,"day"
MsgBox Month(sMyDate),0,"month"
MsgBox Year(sMyDate),0,"year"
sMyDate = "30-Dec-91" ' another of European date usage
Print sMydate
MsgBox sMyDate,0,"MyDate International..."
MsgBox Day(sMyDate),0,"day"
MsgBox Month(sMyDate),0," month"
MsgBox Year(sMyDate),0,"year"
MsgBox Format("This is it", ">") ' Returns "THIS IS IT".
End Sub ' End Main Routine
'End of XCM

10.2.26 DateSerial Function

DateSerial (year, month,day)

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.

Related Topics: DateValue. TimeSerial, TimeValue

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

10.2.27 DateValue Function

DateValue(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, time or both a date and a time.

Runge Ltd May, 2006 Page 88


XCM Reference Guide Cypress Enable Commands

Related Topics: DateSerial. TimeSerial, TimeValue

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

10.2.28 Day Function

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.

Related Topics: Month, Weekday, Hour, Second

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

10.2.29 Declare Statement

Declare Sub procedurename Lib Libname$ [Alias aliasname$][(argument


list)]

Declare Function procedurename Lib Libname$ [Alias aliasname$]


[(argument list)][As Type]

The Declare statement makes a reference to an external procedure in a


Dynamic Link Library (DLL).

The procedurename parameter is the name of the function or subroutine


being called.

The Libname parameter is the name of the DLL that contains the procedure.

Runge Ltd May, 2006 Page 89


XCM Reference Guide Cypress Enable Commands

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:

([ByVal] variable [As type] [,ByVal] variable [As type] ]…])

The optional ByVal parameter specifies that the variable is [passed by


value instead of by reference (see “ByRef and ByVal” in this manual).
The optional As type parameter is used to specify the data type. Valid
types are String, Integer, Double, Long, and Varaint (see “Variable Types”
in this manual).

If a procedure has no arguments, use double parentheses () only to assure


that no arguments are passed. For example:

Declare Sub OntTime Lib “Check” ()

Cypress Enable extentions to the declare statement. The following


syntax is not supported by Microsoft Visual Basic.

Declare Function procedurename App [Alias aliasname$] [(argument


list)][As Type]

This form of the Declare statement makes a reference to a function located


in the executable file located in the application where Enable is embedded.

Related Topics: Call

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

Runge Ltd May, 2006 Page 90


XCM Reference Guide Cypress Enable Commands

10.2.30 Dialog, Dialog Function

Dialog(DialogRecord )

Returns a value corresponding to the button the user chooses.

The Dialog() function is used to display the dialog box specified by


DialogRecord . DialogRecord is the name of the dialog and must be
defined in a preceeding Dim statement.

The return value or button:


-1 = OK button
0 = Cancel button
> 0 A command button where 1 is the first PushButton in the definition of
the dialog and 2 is the second and so on.

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"

Runge Ltd May, 2006 Page 91


XCM Reference Guide Cypress Enable Commands

GroupBox 132, 125, 70, 36, "Group"


CheckBox 142, 100, 48, 12, "Check &A", .Check1
CheckBox 142, 110, 48, 12, "Check &B", .Check2
CheckBox 142, 136, 48, 12, "Check &C", .Check3
CheckBox 142, 146, 48, 12, "Check &D", .Check4
CancelButton 42, 168, 40, 12
OKButton 90, 168, 40, 12
PushButton 140, 168, 40, 12, "&Push Me 1"
PushButton 190, 168, 40, 12, "Push &Me 2"
End Dialog
Dim Dlg1 As DialogName1
Dlg1.joe = "Explosives"
Dlg1.sMyList1 = 1
Dlg1.Combo1 = "No 10 DETs"
Dlg1.DropList1 = 2
Dlg1.grp2 = 1
' Dialog returns -1 for OK, 0 for Cancel, button # for PushButtons
vbutton = Dialog( Dlg1 )
'MsgBox "button: " & vbutton 'uncomment for button return vale
If (vbutton = 0) Then
MsgBox "Script Cancelled",48,"Cancelled pushed"
Exit Sub
End If
MsgBox "TextBox: "& Dlg1.joe
MsgBox "ListBox: " & Dlg1.sMyList1
MsgBox Dlg1.Combo1
MsgBox Dlg1.DropList1
MsgBox "grp1: " & Dlg1.grp1
MsgBox "grp2: " & Dlg1.grp2
Begin Dialog DialogName2 60, 60, 160, 60, "Test Dialog 2"
Text 10, 10, 28, 12, "Name:"
TextBox 42, 10, 108, 12, .fred
OkButton 42, 44, 40, 12
End Dialog
If (vbutton = 2) Then
Dim Dlg2 As DialogName2
Dialog Dlg2
MsgBox Dlg2.fred
ElseIf (vbutton = 1) Then
Dialog Dlg1
MsgBox Dlg1.Combo1
End If
End Sub ' End Main Routine
'End of XCM

10.2.31 Dim Statement

Runge Ltd May, 2006 Page 92


XCM Reference Guide Cypress Enable Commands

Dim variablename[(subscripts)][As Type][,name][As Type]]

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

Related Function: See 10.2.90Re-Dim statement.

10.2.32 Dir Function

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

Dim frame As BitmapDlg

' Show the bitmap dialog


Dialog frame
End Sub

Function DlgFunc( controlID As String, action As Integer, suppValue As Integer )

DlgFunc = 1 ' Keep dialog active

Runge Ltd May, 2006 Page 93


XCM Reference Guide Cypress Enable Commands

Select Case action


Case 1 ' Initialize
temp = Dir( "c:\Windows\*.bmp" )
count = 0
While temp <> ""
count = count + 1
temp = Dir
Wend
Dim x() As String
ReDim x(count)
x(0) = Dir( "c:\Windows\*.bmp" )
For i = 1 To count
x(i) = dir
Next i
DlgListBoxArray "List1", x()
Case 2 ' Click
fileName = "c:\windows\" & DlgText("List1")
DlgSetPicture "Picture1", fileName
End Select
End Function

10.2.33 DlgEnable Statement

DlgEnable “ControlName”, Value

This statement is used to enable or disable a particular control on a dialog


box.

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.

Related Topics: DlgVisible, DlgText

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

Dim Dlg2 As UserDialog2


Dlg2.FText = "Your default string goes here"

Runge Ltd May, 2006 Page 94


XCM Reference Guide Cypress Enable Commands

Select Case Action%

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

If ControlID$ = "Chk2" Then


DlgText "History", "Push to display nested dialog"
End If

If ControlID$ = "History" Then


Enable =1
Number = 4
MsgBox SQR(Number) & " The sqr of 4 is 2"
x = Dialog( Dlg2 )
End If

If ControlID$ = "but1" Then

End If

Case Else

End Select
Enable =1

End Function

10.2.34 DlgText Statement

DlgText “ControlName”, String

This statement is used to set or change the text of a dialog control.

The parameter ControlName is the name of the control on the dialog box.
The parameter String is the value to set it to.

Related Topics: DlgEnable, DlgVisible

Example:
If ControlID$ = "Chk2" Then
DlgText "History", "Push to display nested dialog"
End If

10.2.35 DlgVisible Statement

DlgVisible “ControlName”, Value

This statement is used to hide or make visible a particular control on a


dialog box.

Runge Ltd May, 2006 Page 95


XCM Reference Guide Cypress Enable Commands

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.

Related Topics: DlgEnable, DlgText

Example:
If ControlID$ = "Chk1" Then
DlgEnable "Group", On
DlgVisible "Chk2"
DlgVisible "History"
End If

10.2.36 Do...Loop Statement

Do [{While|Until} condition]
[statements]
[Exit Do]
[statements]
Loop

Do
[statements]
[Exit Do]
[statements]
Loop [{While|Until} condition]

Repeats a group of statements while a condition is true or until a condition


is met.

Related Topics: While, Wend

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

Runge Ltd May, 2006 Page 96


XCM Reference Guide Cypress Enable Commands

10.2.37 End Statement

End[{Function | If | Sub}]

Ends a program or a block of statements such as a Sub procedure or a


function.

Related Topics: Exit, Function, If...Then...Else, Select Case, Stop

Example:
Sub Main()

Dim Var1 as String

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

End Sub

Sub Test(wvar1 as string)

wvar1 = "goodbye"
MsgBox "Use of End Statement"
End

End Sub

10.2.38 EOF Function


EOF(Filenumber)

Returns a value during file input that indicates whether the end of a file has
been reached.

Related Topics: Open Statement

Example:
' Input Function Example

Runge Ltd May, 2006 Page 97


XCM Reference Guide Cypress Enable Commands

' 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

10.2.39 Erase Statement

Erase arrayname[,arrayname ]

Reinitializes the elements of a fixed array.

Related Topics: Dim

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

10.2.40 Exit Statement

Exit {Do | For | Function | Sub }

Exits a loop or procedure

Runge Ltd May, 2006 Page 98


XCM Reference Guide Cypress Enable Commands

Related Topics End Statement, Stop Statement

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)

Returns the base of the natural log raised to a power (e ^ num).

The value of the constant e is approximately 2.71828.

Related Topics: Log

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

10.2.42 FileCopy Function

FileCopy( sourcefile, destinationfile)

Copies a file from source to destination.

Runge Ltd May, 2006 Page 99


XCM Reference Guide Cypress Enable Commands

The sourcefile and destinationfile parameters must be valid string


expressions. sourcefile is the file name of the file to copy, destinationfile
is the file name to be copied to.

10.2.43 FileLen Function

FileLen( filename )

Returns a Long integer that is the length of the file in bytes

Related Topics: LOF Function

Example:
Sub Main
Dim MySize
MySize = FileLen("TESTFILE") ' Returns file length (bytes).
Print MySize
End Sub

10.2.44 Fix Function


Function

Fix(number )

Returns the integer portion of a number

Related Topics: Int

10.2.45 For each … Next Statement

For Each element in group


[statements]
[Exit For]
[statements]
Next [element]

Repeats the group of statments for each element in an array of a collection.


For each … Next statements can be nested if each loop element is unique.
The For Each…Next statement cannot be used with and array of user
defined types.

Example:
Sub Main
dim z(1 to 4) as double
z(1) = 1.11
z(2) = 2.22

Runge Ltd May, 2006 Page 100


XCM Reference Guide Cypress Enable Commands

z(3) = 3.33
For Each v In z
Print v
Next v
End Sub

10.2.46 For...Next Statement

For counter = expression1 to expression2 [Step increment]


[statements]
Next [counter]

Repeats the execution of a block of statements for a specified number of


times.

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

10.2.47 Format Function

Format (expression [,fmt ] )

Formats a string, number or variant datatype to a format expression.

Format returns returns a string

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.

Runge Ltd May, 2006 Page 101


XCM Reference Guide Cypress Enable Commands

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.

Predefined numeric format names:

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

Scientific Use standard scientific notation.

True/False Display False if number is 0, otherwise display True.

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

Runge Ltd May, 2006 Page 102


XCM Reference Guide Cypress Enable Commands

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.”

E-E+e-e+ Scientific format.

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.

Runge Ltd May, 2006 Page 103


XCM Reference Guide Cypress Enable Commands

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

- + $ ( ) Space Display a literal character.

To display a character other than one of those listed, precede it with a backslash (\).

\ Display the next character in the format string.

The backslash itself isn’t displayed. To display a backslash, use two backslashes (\\).

Examples of characters that can’t be displayed as literal characters are the date- and time-
formatting characters (a,c,d,h,m,n,p,q,s,t,w,y, and /:), the numeric -formatting
characters(#,0,%,E,e,comma, and period), and the string- formatting characters (@,&,<,>, and
!).

“String” Display the string inside the double quotation marks.

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.

* Display the next character as the fill character.

Any empty space in a field is filled with the character following the asterisk.

Unless the fmt argument contains one of the predefined formats, a format expression for
numbers can have from one to four sections separated by semicolons.

If you use The result is

One section The format expression applies to all values.


only

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.

Runge Ltd May, 2006 Page 104


XCM Reference Guide Cypress Enable Commands

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

Format (fmt) Positive 3 Negative 3 Decimal .3 Null

Null string 3 -3 0.3

0 3 -3 1

0.00 3.00 -3.00 0.30

#,##0 3 -3 1

#,##0.00;;;Nil 3.00 -3.00 0.30 Nil

$#,##0;($#,##0) $3 ($3) $1

$#,##0.00;($#,##0.00) $3.00 ($3.00) $0.30

0% 300% -300% 30%

0.00% 300.00% -300.00% 30.00%

0.00E+00 3.00E+00 -3.00E+00 3.00E-01

0.00E-00 3.00E00 -3.00E00 3.00E-01

Runge Ltd May, 2006 Page 105


XCM Reference Guide Cypress Enable Commands

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.

d Display the day as a number without a leading zero (1-31).

Runge Ltd May, 2006 Page 106


XCM Reference Guide Cypress Enable Commands

dd Display the day as a number with a leading zero (01-31).

ddd Display the day as an abbreviation (Sun-Sat).

ddddd Display a date serial number as a complete date (including day , month, and year).

Character Meaning

w Display the day of the week as a number (1- 7 ).

ww Display the week of the year as a number (1-53).

m Display the month as a number without a leading zero (1-12). If m immediately


follows h or hh, the minute rather than the month is displayed.

mm Display the month as a number with a leading zero (01-12). If mm immediately


follows h or hh, the minute rather than the month is displayed.

mmm Display the month as an abbreviation (Jan-Dec).

mmmm Display the month as a full month name (January-December).

q display the quarter of the year as a number (1-4).

y Display the day of the year as a number (1-366).

yy Display the day of the year as a two-digit number (00-99)

yyyy Display the day of the year as a four-digit number (100-9999).

h Display the hour as a number without leading zeros (0-23).

hh Display the hour as a number with leading zeros (00-23).

n Display the minute as a number without leading zeros (0-59).

nn Display the minute as a number with leading zeros (00-59).

s Display the second as a number without leading zeros (0-59).

Runge Ltd May, 2006 Page 107


XCM Reference Guide Cypress Enable Commands

ss Display the second as a number with leading zeros (00-59).

ttttt Display a time serial number as a complete time (including hour, minute, and
second) formatted using the time separator defined by the Time Format in the
International section of the Control Panel. A leading zero is displayed if the
Leading Zero option is selected and the time is before 10:00 A.M. or P.M. The
default time format is h:mm:ss.

AM/PM Use the 12-hour clock and display an uppercase AM/PM

am/pm Use the 12-hour clock display a lowercase am/pm

Character Meaning

A/P Use the 12-hour clock display a uppercase A/P

a/p Use the 12-hour clock display a lowercase a/p

AMPM Use the 12-hour clock and display the contents of the 11:59 string (s1159)
in the WIN.INI file with any hour before noon; display the contents of the 2359 string (s2359)
with any hour between noon and 11:59 PM. AMPM can be either uppercase or lowercase, but
the case of the string displayed matches the string as it exists in the WIN.INI file. The default
format is AM/PM.

The following are examples of user-defined date and time formats:

Format Display

m/d/yy 2/26/65

d-mmmm-yy 26-February-65

d-mmmm 26 February

mmmm-yy February 65

hh:mm AM/PM 06:45 PM

h:mm:ss a/p 6:45:15 p

h:mm:ss 18:45:15

Runge Ltd May, 2006 Page 108


XCM Reference Guide Cypress Enable Commands

m/d/yy/h:mm 2/26/65 18:45

Strings can also be formatted with Format[$]. A format expression for strings can have one
section or two sections separated by a semicolon.

If you use The result is

One section only The format applies to all string data.

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

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.

& Character placeholder. Display a character or nothing.

< Force lowercase.

> Force uppercase.

! Force placeholders to fill from left to right instead of right to left.

Related Topic: Str, Str$ Function..

Example:

' Format Function Example

' This example shows various uses of the Format function to format values
' using both named and user-defined formats. For the date separator (/),
' time separator (:), and AM/ PM literal, the actual formatted output
' displayed by your system depends on the locale settings on which the code

Runge Ltd May, 2006 Page 109


XCM Reference Guide Cypress Enable Commands

' 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

MsgBox Second( MyTime ) & " Seconds"


MsgBox Minute( MyTime ) & " Minutes"
MsgBox Hour( MyTime ) & " Hours"

MsgBox Day( MyDate ) & " Days"


MsgBox Month( MyDate ) & " Months"
MsgBox Year( MyDate ) & " Years"

' Returns current system time in the system-defined long time format.
MsgBox Format(Time, "Short Time")
MyStr = Format(Time, "Long Time")

' Returns current system date in the system-defined long date format.
MsgBox Format(Date, "Short Date")
MsgBox Format(Date, "Long Date")

MyStr Format(MyTime, "h:n:s") ' Returns "17:4:23".


MyStr Format(MyTime, "hh:nn:ss")' Returns "20:04:22 ".
MyStr Format(MyDate, "dddd, mmm d yyyy")' Returns "Wednesday, Jan 27 1993".

' If format is not supplied, a string is returned.


MsgBox Format(23) ' Returns "23".

' User-defined formats.


MsgBox Format(5459.4, "##,##0.00") ' Returns "5,459.40".
MsgBox Format(334.9, "###0.00") ' Returns "334.90".
MsgBox Format(5, "0.00%") ' Returns "500.00%".
MsgBox Format("HELLO", "<") ' Returns "hello".

Runge Ltd May, 2006 Page 110


XCM Reference Guide Cypress Enable Commands

MsgBox Format("This is it", ">") ' Returns "THIS IS IT".


End Sub

10.2.48 FreeFile Function

FreeFile

Returns an integer that is the next available file handle to be used by the
Open Statement.

Related Topics: Open, Close, Write

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

Open "c:\e1\test1" For Input As #1


Do While Not EOF(1)
MyStr = Input(10, #1)
MsgBox MyStr
Loop
Close #1
End Sub

10.2.49 Function Statement

Function Fname [(Arguments)] [As type]


[statements]
Functionname = expression
[statements]
Functionname = expression
End Function

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:

Runge Ltd May, 2006 Page 111


XCM Reference Guide Cypress Enable Commands

([ByVal] variable [As type] [,ByVal] variable [As type] ]…])

The optional ByVal parameter specifies that the variable is [passed by


value instead of by reference (see “ByRef and ByVal” in this manual).
The optional As type parameter is used to specify the data type. Valid
types are String, Integer, Double, Long, and Varaint (see “Variable Types”
in this manual).

Related Topics: Dim, End, Exit, Sub

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

10.2.50 Get Object 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.

Related Topics: CreateObject

10.2.51 Global Statement

Runge Ltd May, 2006 Page 112


XCM Reference Guide Cypress Enable Commands

Global Const constant

The Global Statement must be outside the procedure section of the script. Global variables are
available to all functions and subroutines in your program

Related Topics: Dim, Const and Type Statements

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

10.2.52 GoTo Statement

GoTo label

Branches unconditionally and without return to a specified label in a


procedure.

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

Runge Ltd May, 2006 Page 113


XCM Reference Guide Cypress Enable Commands

If y > 3 Then
GoTo Label1
End If
Next z
Next y
Next x
Label1:

End Sub

10.2.53 Hex

Hex (num)

Returns the hexadecimal value of a decimal parameter.

Hex returns a string

The parameter num can be any valid number. It is rounded to nearest


whole number before evaluation.

Related Topics: Oct, Oct$

Example:
Sub Main ()

Dim Msg As String, x%


x% = 10
Msg =Str( x%) & " decimal is "
Msg = Msg & Hex(x%) & " in hex "
MsgBox Msg
End Sub

10.2.54 Hour Function

Runge Ltd May, 2006 Page 114


XCM Reference Guide Cypress Enable Commands

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

MsgBox Second( MyTime ) & " Seconds"


MsgBox Minute( MyTime ) & " Minutes"
MsgBox Hour( MyTime ) & " Hours"

MsgBox Day( MyDate ) & " Days"


MsgBox Month( MyDate ) & " Months"
MsgBox Year( MyDate ) & " Years"

' Returns current system time in the system-defined long time format.
MsgBox Format(Time, "Short Time")
MyStr = Format(Time, "Long Time")

' Returns current system date in the system-defined long date format.
MsgBox Format(Date, "Short Date")
MsgBox Format(Date, "Long Date")

' This section not yet supported

Runge Ltd May, 2006 Page 115


XCM Reference Guide Cypress Enable Commands

'MyStr = Format(MyTime, "h:m:s") ' Returns "17:4:23".


'MyStr = Format(MyTime, "hh:mm:ss AMPM")' Returns "05:04:23 PM".
'MyStr = Format(MyDate, "dddd, mmm d yyyy")' Returns "Wednesday, Jan 27 1993".

' If format is not supplied, a string is returned.


MsgBox Format(23) ' Returns "23".

' User-defined formats.


MsgBox Format(5459.4, "##,##0.00") ' Returns "5,459.40".
MsgBox Format(334.9, "###0.00") ' Returns "334.90".
MsgBox Format(5, "0.00%") ' Returns "500.00%".
MsgBox Format("HELLO", "<") ' Returns "hello".
MsgBox Format("This is it", ">") ' Returns "THIS IS IT".

End Sub

10.2.55 If...Then...Else Statement

If condition Then
[statement(s)]
ElseIf condition Then
[statement(s)]
Else
[statements(s)]
End If

Syntax 2
If conditional Then statement

Allows conditional statements to be executed in the code.

Related Topics: Select Case

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

If 5 > someInt Then msg = "Greater" : Beep


MsgBox(msg)

If 3 > someInt Then

Runge Ltd May, 2006 Page 116


XCM Reference Guide Cypress Enable Commands

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

10.2.56 Input Function

Input(n , [ #] filenumber )

Input returns characters from a sequential file.

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

10.2.57 InputBox Function

InputBox(prompt[,[title][,[default][,xpos,ypos]]])

InputBox returns a String.

Prompt is string that is displayed usually to ask for input type or


information.

Title is a string that is displayed at the top of the input dialog box.

Runge Ltd May, 2006 Page 117


XCM Reference Guide Cypress Enable Commands

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

Runge Ltd May, 2006 Page 118


XCM Reference Guide Cypress Enable Commands

End If ' End Number Construct


End Sub ' End Over Sub Routine
Sub Under() ' Under subroutine
' This is the message and variable
Msg = "The number was less than 0. It was" & X
MsgBox Msg ' Display Message
' New Input note default is now zero
Y = InputBox(" Re-enter the percentage","This time greater than zero",0.0)
If ((Y>0) And (Y<=100)) Then ' Number acceptable test
Smug ' Call Smug subroutine
Else ' Number still wrong
Msg = "XCM aborted" ' New message
MsgBox Msg ' Display Message.
Abort" Please restart" ' Abort XCM
End If ' End Number construct
End Sub ' End Under Sub Routine
Sub Correct() ' Good message
' This is the message and variable
Msg = "The percentage you entered is " & X
MsgBox Msg ' Display Message.
End Sub ' End Good message Sub Routine
Sub Smug() ' Smug sub routine
Msg = "The right number was" & Y' This is the message and variable
MsgBox Msg ' Display Message.
End Sub ' End Smug Sub Routine
'End of XCM

10.2.58 InStr

InStr(numbegin, string1, string2)

Returns the character position of the first occurrence of string2 within


string1.

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.

Related Topics: Mid Function

Example:
Sub Main () ' Start Main Routine
Dim sString As String ' Input String
Dim lPosA As Long ' Declare Position
sString = "Good Bye" ' Assign String value

Runge Ltd May, 2006 Page 119


XCM Reference Guide Cypress Enable Commands

lPosA = InStr(2,sString,"Bye") ' Determine position


End Sub ' End of Routine
'End of XCM

10.2.59 Int Function

Int(number )

Returns the integer portion of a number

Related Topics: Fix

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

10.2.60 IsArray Function

IsArray(variablename )

Returns a boolean value True or False indicating whether the parameter


variablename is an array. This is used when using the ‘Array function’ as it
returns a variant containing an array.

Related Topics: IsEmpty, IsNumeric, VarType, IsObject

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

Runge Ltd May, 2006 Page 120


XCM Reference Guide Cypress Enable Commands

End Sub ' End Routine


'End of XCM

10.2.61 IsDate

IsDate(variant )

Returns a value that indicates if a variant parameter can be converted to a


date.

Related Topics: IsEmpty, IsNumeric, VarType

10.2.62 IsEmpty

IsEmpty(variant )

Returns a value that indicates if a variant parameter has been initialized.

Related Topics: IsDate, IsNull, IsNumeric, VarType

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)

Returns a value that indicates if a variant contains the NULL value.

The parameter v can be any variant. IsNull returns a TRUE if v contains


NULL. If isNull returns a FALSE the NULL the variant expression is not
NULL.

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.

Related Topics: IsDate, IsEmpty, IsNumeric, VarType

Runge Ltd May, 2006 Page 121


XCM Reference Guide Cypress Enable Commands

10.2.64 IsNumeric

IsNumeric(v)

Returns a TRUE or FALSE indicating if the v parameter can be converted


to a numeric data type.

The parameter v can be any variant, numeric value, Date or string (if the
string can be interpreted as a numeric).

Related topics: IsDate, IsEmpty, IsNull, VarType

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

10.2.65 IsObject Function

IsObject(objectname )

Returns a boolean value True or False indicating whether the parameter


objectname is an object.

Related Topics: IsEmpty, IsNumeric, VarType, IsObject

Example:

Sub Main

Dim MyInt As Integer, MyCheck


Dim MyObject As Object

Runge Ltd May, 2006 Page 122


XCM Reference Guide Cypress Enable Commands

Dim YourObject As Object


Set MyObject = CreateObject("Word.Basic")

Set YourObject = MyObject


MyCheck = IsObject(YourObject)

Print MyCheck

End Sub

10.2.66 Kill Statement

Kill filename

Kill will only delete files. To remove a directory use the RmDir Statement

Related Topics: RmDir

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

Runge Ltd May, 2006 Page 123


XCM Reference Guide Cypress Enable Commands

10.2.67 LBound Function

LBound(array [,dimension] )

Returns the smallest available subscript for the dimension of the indicated array.

Related Topics: UBound Function

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

10.2.68 LCase, Function

Lcase[$](string )

Returns a string in which all letters of the string parameter have been
converted to upper case.

Related Topics: Ucase Function

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.

Runge Ltd May, 2006 Page 124


XCM Reference Guide Cypress Enable Commands

TrimString = LTrim(MyString) ' TrimString = "<-Trim-> ".


MsgBox "|" & TrimString & "|"
TrimString = LCase(RTrim(MyString)) ' TrimString = " <-trim->".
MsgBox "|" & TrimString & "|"
TrimString = LTrim(RTrim(MyString)) ' TrimString = "<-Trim->".
MsgBox "|" & TrimString & "|"
' Using the Trim function alone achieves the same result.
TrimString = UCase(Trim(MyString)) ' TrimString = "<-TRIM->".
MsgBox "|" & TrimString & "|"
End Sub

10.2.69 Left

Left(string, num)

Returns the left most num characters of a string parameter.

Left returns a Variant, Left$ returns a String

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.

Runge Ltd May, 2006 Page 125


XCM Reference Guide Cypress Enable Commands

MidTest = Mid("Mid Word Test", 4, 5)


Print MidTest
End Sub

10.2.70 Len

Len(string)

Returns the number of characters in a string.

Related Topics: InStr

Example:
Sub Main ()
A$ = "Cypress Enable"
StrLen% = Len(A$) 'the value of StrLen is 14
MsgBox StrLen%
End Sub

10.2.71 Let Statement

[Let] variablename = expression

Let assigns a value to a variable.

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

Runge Ltd May, 2006 Page 126


XCM Reference Guide Cypress Enable Commands

10.2.72 Line Input # Statement

Line Input # filenumber and name

Reads a line from a sequential file into a String or Variant variable.

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.

Related Topics: Open

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.

Related Topics: FileLen

Example:

Runge Ltd May, 2006 Page 127


XCM Reference Guide Cypress Enable Commands

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)

Returns the natural log of a number(double)


The parameter num must be greater than zero and be a valid number.

Related Topics: Exp, Sin, Cos

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

Runge Ltd May, 2006 Page 128


XCM Reference Guide Cypress Enable Commands

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

10.2.75 Mid Function

string = Mid(strgvar,begin,length)

Returns a substring within a string.

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

Runge Ltd May, 2006 Page 129


XCM Reference Guide Cypress Enable Commands

sRWord = Right(vUsrInp, Len(vUsrInp) - lSpcPos) ' Get right word.


vMsg = "The first word you entered is " & sLWord ' Assign Message
vMsg = "The second word you entered is <" & sRWord & ">"
Else ' User input invalid
vMsg = "You didn't enter two words." ' Display message
End If ' End input construct
MsgBox vMsg ' Display message.
sMidTest = Mid("Mid Word Test", 4, 5) ' Calculate mid word
MsgBox sMidTest,0,"Mid String = " ' Display message
End Sub ' End main routine
' End of XCM

10.2.76 Minute Function


Minute(string)
Returns an integer between 0 and 59 representing the minute of the hour.
' Format Function Example

' This example shows various uses of the Format function to format values
' using both named and user-defined formats. For the date separator (/),
' 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

Runge Ltd May, 2006 Page 130


XCM Reference Guide Cypress Enable Commands

MkDir path

Creates a new directory.

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

10.2.78 Month Function

Month(number)

Returns an integer between 1 and 12, inclusive, that represents the month of
the year.

Related Topics: Day, Hour, Weekday, 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

Runge Ltd May, 2006 Page 131


XCM Reference Guide Cypress Enable Commands

End Sub ' End Main Routine

10.2.79 MsgBox Function MsgBox Statement

MsgBox ( msg, [type] [, title])

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.

Symbolic constant Value Meaning

MB_OK 0 Display OK button only.


MB_OKCANCEL 1 Display OK and Cancel buttons.
MB_ABORTRETRYIGN 2 Display Abort, Retry, and Ignore buttons.
ORE
MB_YESNOCANCEL 3 Display Yes, No, and Cancel buttons.
MB_YESNO 4 Display Yes and No buttons.
MB_RETRYCANCEL 5 Display Retry and Cancel buttons.
MB_ICONSTOP 16 Display Stop Sign
MB_ICONQUESTION 32 Display Question Sign
MB_ICONEXCLAMATIO 48 Display Question Sign
N
MB_ICONINFORMATIO 64 Display Information sign
N
MB_DEFBUTTON1 0 First button is default.
MB_DEFBUTTON2 256 Second button is default.
MB_DEFBUTTON3 512 Third button is default.
MB_APPLMODAL 0 Application modal:The user must respond to the
message
MB_SYSTEMMODAL 4096 System modal: All applications are suspended until the
user responds to the message box

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.

Runge Ltd May, 2006 Page 132


XCM Reference Guide Cypress Enable Commands

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:

Symbolic constant Value Meaning

IDOK 1 OK button selected.


IDCANCEL 2 Cancel button selected.
IDABORT 3 Abort button selected.
IDRETRY 4 Retry button selected.
IDIGNORE 5 Ignore button selected.
IDYES 6 Yes button selected.
IDNO 7 No button selected.

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

Runge Ltd May, 2006 Page 133


XCM Reference Guide Cypress Enable Commands

MsgBox la,48,"OK button selected" ' Display return value


Dim lb As Long ' Declare return value
lb = MsgBox (dPrdRate, 1,"This is Code 1") ' Display OK and Cancel buttons
If (lb = 1) Then ' If ok pressed
MsgBox lb,48,"OK button selected" ' Display return value
Else ' canel pressed
MsgBox lb,48,"Cancel button selected" ' Display return value
End If ' End construct
Dim lc As Long ' Declare return value
lc = MsgBox (dPrdRate, 2,"This is Code 2") ' Display Abort,Retry,and Ignore
If lc = 3 Then MsgBox lc,48,"Abort selected" ' Display return value
If lc = 4 Then MsgBox lc,48,"Retry selected" ' Display return value
If lc = 5 Then MsgBox lc,48,"Ignore selected"' Display return value
Dim ld As Long ' Declare return value
ld = MsgBox (dPrdRate, 3,"This is Code 3") ' Display Yes, No, and Cancel
' buttons
If ld = 6 Then MsgBox ld,48,"Yes selected" ' Display return value
If ld = 7 Then MsgBox ld,48,"No selected" ' Display return value
If ld = 2 Then MsgBox ld,48,"Cancel selected"' Display return value
End Sub ' End Main Routine
' End of XCM

MsgBox Function, MsgBox Statement Example

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.

Related Topics: InputBox, InputBox$ Function

Example:

Sub Main

Dim DgDef, Msg, Response, Title ' Declare variables.


Title = "MsgBox Sample Question"
Msg = "This is a sample of Close Without Saving?."
Msg = Msg & " Do you want to continue?"
DgDef = MB_YESNOCANCEL + MB_ICONQUESTION + MB_DEFBUTTON3
Response = MsgBox(Msg, DgDef, Title) ' Get user response.
If Response = IDYES Then ' Evaluate response
Msg = "You chose Yes." ' and take appropriate

Runge Ltd May, 2006 Page 134


XCM Reference Guide Cypress Enable Commands

ElseIf Response = IDCANCEL Then


Msg = "You chose Cancel"
Else ' action.
Msg = "You chose No or pressed Enter."
End If
MsgBox Msg ' Display action taken.
End Sub

10.2.80 Name Statement

Name oldname As newname

Changes the name of a directory or a file.

The parameters oldname and newname are string that can optionally
contain a path.

Related Topics: Kill, ChDir

Example:
Sub Main

Name "testfile" As "newtest"

End Sub

10.2.81 Now Function

Now

Runge Ltd May, 2006 Page 135


XCM Reference Guide Cypress Enable Commands

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

10.2.82 Oct Function

Oct (num)

Returns the octal value of the decimal parameter

Oct returns a string

Related Topics: Hex

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

Runge Ltd May, 2006 Page 136


XCM Reference Guide Cypress Enable Commands

10.2.83 OKButton

OKBUTTON starting x position, starting y position, width, Height

For selecting options and closing dialog boxes

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

On Error { GoTo line | Resume Next | GoTo 0 }

Enables error-handling routine and specifies the line label of the error-
handling routine.

Related Topics: Resume

The line parameter refers to a label. That label must be present in the code or an error is generated.

Runge Ltd May, 2006 Page 137


XCM Reference Guide Cypress Enable Commands

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

Errors can be raised with the syntax:

Err.Raise x

The list below shows the corresponding descriptions for the defined values
of x.

3: "Return without GoSub";


5: "Invalid procedure call";
6: "Overflow";
7: "Out of memory";
9: "Subscript out of range";
10: "Array is fixed or temporarily locked";
11: "Division by zero";
13: "Type mismatch";
14: "Out of string space";
16: "Expression too complex";
17: "Can't perform requested operation";
18: "User interrupt occurred";
20: "Resume without error";
28: "Out of stack space";
35: "Sub, Function, or Property not defined";

Runge Ltd May, 2006 Page 138


XCM Reference Guide Cypress Enable Commands

47: "Too many DLL application clients";


48: "Error in loading DLL";
49: "Bad DLL calling convention";
51: "Internal error";
52: "Bad file name or number";
53: "File not found";
54: "Bad file mode";
55: "File already open";
57: "Device I/O error";
58: "File already exists";
59: "Bad record length";
60: "Disk full";
62: "Input past end of file";
63: "Bad record number";
67: "Too many files";
68: "Device unavailable";
70: "Permission denied";
71: "Disk not ready";
74: "Can't rename with different drive";
75: "Path/File access error";
76: "Path not found";
91: "Object variable or With block variable not set";
92: "For loop not initialised";
93: "Invalid pattern string";
94: "Invalid use of Null";
// OLE Automation Messages
429: "OLE Automation server cannot create object";
430: "Class doesn't support OLE Automation";
432: "File name or class name not found during OLE Automation operation";
438: "Object doesn't support this property or method";
440: "OLE Automation error";
443: "OLE Automation object does not have a default value";
445: "Object doesn't support this action";
446: "Object doesn't support named arguments";
447: "Object doesn't support current local setting";
448: "Named argument not found";
449: "Argument not optional";
450: "Wrong number of arguments";
451: "Object not a collection";
// Miscellaneous Messages

Runge Ltd May, 2006 Page 139


XCM Reference Guide Cypress Enable Commands

444: "Method not applicable in this context";


452: "Invalid ordinal";
453: "Specified DLL function not found";
457: "Duplicate Key";
460: "Invalid Clipboard format";
461: "Specified format doesn't match format of data";
480: "Can't create AutoRedraw image";
481: "Invalid picture";
482: "Printer error";
483: "Printer driver does not supported specified property";
484: "Problem getting printer information from the system.";
// Make sure the printer is set up correctly.
485: "invalid picture type";
520: "Can't empty Clipboard";
521: "Can't open Clipboard";

10.2.85 Open Statement

Open filename$ [For mode] [Access access] As [#]filenumber

Opens a file for input and output operations.

You must open a file before any I/O operation can be performed on it. The Open statement has
these parts:

Part Description

file File name or path.

mode Reserved word that specifies the file mode: Append, Binary
Input, Output

access Reserved word that specifies which operations are


permitted on the open file: Read, Write.

filenumber Integer expression with a value between 1 and 255, inclusive.


When an Open statement is executed, filenumber is associated
with the file as long as it is open. Other I/O statements can use the
number to refer to the file.

Runge Ltd May, 2006 Page 140


XCM Reference Guide Cypress Enable Commands

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.

Access type Description


Read Opens the file for reading only.
Write Opens the file for writing only.
Read Write Opens the file for both reading and writing.
This mode is valid only for Random and
Binary files and files opened for
Append
mode.

The following example writes data to a test file and reads it back.

Example :

Sub Main ()

Open "TESTFILE" For Output As #1 ' Open to write file.


userData1$ = InputBox ("Enter your own text here")
userData2$ = InputBox ("Enter more of your own text here")
Write #1, "This is a test of the Write # statement."
Write #1,userData1$, userData2
Close #1

Open "TESTFILE" for Input As #2 ' Open to read file.

Runge Ltd May, 2006 Page 141


XCM Reference Guide Cypress Enable Commands

Do While Not EOF(2)


Line Input #2, FileData ' Read a line of data.
PRint FileData ' Construct message.
Loop
Close #2 ' Close all open files.
MsgBox "Testing Print Statement" ' Display message.
Kill "TESTFILE" ' Remove file from disk.
End Sub

10.2.86 Option Base Statement

Option Base number


Declares the default lower bound for array subscripts.
The Option Base statement is never required. If used, it can appear only once in a module, can
occur only in the Declarations section, and must be used before you declare the dimensions of any
arrays.

The value of number must be either 0 or 1. The default base is 0.


The To clause in the Dim, Global, and Static statements provides a more flexible way to control the
range of an array's subscripts. However, if you don't explicitly set the lower bound with a To
clause, you can use Option Base to change the default lower bound to 1.

The example uses the Option Base statement to override the default base array subscript value of 0.

Related Topics: Dim, Global and Lbound Statements

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

Runge Ltd May, 2006 Page 142


XCM Reference Guide Cypress Enable Commands

Option Base 1 ' Module level statement.


Sub Main
Dim A(), Msg, NL ' Declare variables.
NL = Chr(10) ' Define newline.
ReDim A(20) ' Create an array.
Msg = "The lower bound of the A array is " & LBound(A) & "."
Msg = Msg & NL & "The upper bound is " & UBound(A) & "."
MsgBox Msg ' Display message.
End Sub

10.2.87 Option Explicit Statement

Option Explicit

Forces explicit declaration of all variables.

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.

Related Topics: Const and Global Statements

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.

10.2.88 Print Method

Runge Ltd May, 2006 Page 143


XCM Reference Guide Cypress Enable Commands

Print [expr, expr...] Print a string to an object.

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

Runge Ltd May, 2006 Page 144


XCM Reference Guide Cypress Enable Commands

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 :

Sub Main ' Start Main Routine


Dim lRepeat As Long ' Declare repeating variable
Dim lFNum As Long ' Declare File number
Dim lFName As Long ' Declare file name.
For lRepeat = 1 To 3 ' Loop three times
lFNum = FreeFile ' Determine next file number.
lFName = "TEST" & lFNum ' Construct message.
Open lFName For Output As lFNum ' Open file.
Print #lRepeat, "This is test #" & lRepeat ' Write string to file.
Print #lRepeat, "Here is another "; "line"; lRepeat
Next lRepeat ' Next in loop
Close ' Close all files.
End Sub ' End subroutine

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

Runge Ltd May, 2006 Page 145


XCM Reference Guide Cypress Enable Commands

Do While Not EOF(2)


Line Input #2, FileData ' Read a line of data.
Msg = Msg & FileData & NL ' Construct message.
MsgBox Msg ' Display message.
Loop
Close ' Close all open files.
MsgBox "Testing Print Statement" ' Display message.
Kill "TESTFILE" ' Remove file from disk.
End Sub

10.2.90 ReDim Statement

ReDim {Preserve}varname(subscripts)[As Type][,varname(subscripts)]

Used to declare dynamic arrays and reallocate storage space.

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:

'This XCM is an example of Re-dimension


Sub Main 'Start Main Routine
Dim lTestArray() As Long ' Declare as array aslong
Dim lRepeat As Long ' Declare increment as long
ReDim lTestArray(10) ' Redimension array to 10
For lRepeat = 1 To 10 ' Counter loop
lTestArray(lRepeat) = lRepeat + 10' Add 10 to lRepeat
Print lTestArray(lRepeat) ' Print Value
Next lRepeat ' Next increment
End Sub ' End of routine
' End of XCM

10.2.91 Rem Statement

Runge Ltd May, 2006 Page 146


XCM Reference Guide Cypress Enable Commands

Rem remark ‘remark


Used to include explanatory remarks in a program.
The parameter remark is the text of any comment you wish to include in the code.

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

10.2.92 Right Function

Right (stringexpression, n )

Returns the right most n characters of the string parameter.

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.

Related Topics: Len, Left, Mid Functions.

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

Runge Ltd May, 2006 Page 147


XCM Reference Guide Cypress Enable Commands

Msg = "You didn't enter two words." ' Generate Message


End If ' End space test
' construct
MsgBox Msg ' Display message.
End Sub ' End of Routine
'End of XCM

Runge Ltd May, 2006 Page 148


XCM Reference Guide Cypress Enable Commands

10.2.93 RmDir Statement

RmDir path

Removes an existing directory.

The parameter path is a string that is the name of the directory to be


removed.

Related Topics: ChDir, CurDir

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

10.2.94 Rnd Function

Rnd (number)

Returns a random number.

The parameter number must be a valid numeric expression.

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

Runge Ltd May, 2006 Page 149


XCM Reference Guide Cypress Enable Commands

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

10.2.95 Second Function

Second (number)

Returns an integer that is the second portion of the minute in the time
parameter.

The parameter number must be a valid numeric expression.

Related Topics: Day, Hour, Minute, Now.

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

Runge Ltd May, 2006 Page 150


XCM Reference Guide Cypress Enable Commands

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

10.2.96 Seek Function

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.

Related Topics: Open


Example:

Sub Main ' Start Main routine


Dim vMyChar As Variant ' Declare character
Open "TESTSEEKFILE.TXT" For Input As #1 ' Open file for reading.
Do While Not EOF(1) ' Loop until end of file.
vMyChar = Input(1, #1) ' Read next character of data.

Runge Ltd May, 2006 Page 151


XCM Reference Guide Cypress Enable Commands

Print Seek(1) ' Print byte position .


Loop ' Next character
Close #1 ' Close file.
End Sub ' End Main Routine

10.2.97 Seek Statement

Seek filenumber, position

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

Related Topics: Open


Example:
' This is an example of the seek function. In this example the
' XCM steps through a textfile in increments of 3 bytes.
' This Character is then printed to the screen
Sub Main ' Start Main Routine
Dim lRepeat As Long ' Declare repeating variable
Dim vMyChar As Variant ' Declare character variable
Open "TESTSEEKFILE.TXT" For Input As #1 ' Open file for reading.
For lRepeat = 1 To 24 Step 3 ' Loop until end of file.
Seek #1, lRepeat ' Seek to byte position
vMyChar = Input(1, #1) ' Read next character of data.
Print vMyChar ' Print character of data
Next lRepeat ' Next increment
Close #1 ' Close file.
End Sub ' End of routine
'End of XCM
' For example if the first line of the textfile read 123b
' Then the response would read 1 and b as the step interval
' is three bytes long.

10.2.98 Select Case Statement

Executes one of the statement blocks in the case based on the test variable
Select Case testvar
Case var1
Statement Block
Case var2

Runge Ltd May, 2006 Page 152


XCM Reference Guide Cypress Enable Commands

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

10.2.99 SendKeys Function

SendKeys (Keys, [wait])

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

Runge Ltd May, 2006 Page 153


XCM Reference Guide Cypress Enable Commands

Dim vMsg ' Declare variables.


vDummy = Shell("Calc.exe", 1) ' Shell Calculator.
For IRepeat = 1 To 5 ' Set up counting loop.
SendKeys IRepeat & "{+}", True ' Send keystrokes to Calculator
Next IRepeat ' to add each value of I.
vMsg = "Choose OK to close the Calculator."' Message
MsgBox vMsg ' Display OK prompt.
AppActivate "Calculator" ' Return focus to Calculator.
SendKeys "%{F4}", True ' Alt+F4 to close Calculator.
End Sub ' End routine
'End of XCM

10.2.100 Set Statement

Set Object = {[New] objectexpression | Nothing}

Assigns an object to an object variable.


Related Topics: Dim, Global, Static

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

Runge Ltd May, 2006 Page 154


XCM Reference Guide Cypress Enable Commands

10.2.101 SGN(Number)

Returns a Variant (Integer) indicating the sign of a number.


Syntax. The required number argument should be any valid numerical value.
Return The Following Values

If number is SGN returns


Greater than zero 1
Equal to zero 0
Less than zero -1

' Sign function


Sub Main ' Start Main Routine
Dim dSignE As Double ' Declare sign easting
Dim dSignN As Double ' Declare sign northing
Dim dSignZ As Double ' Declare sign elevation
Dim dEstA As Double ' Declare easting A
Dim dNthA As Double ' Declare Northing A
Dim dDthA As Double ' Declare Elevation A
Dim dEstB As Double ' Declare Easting B
Dim dNthB As Double ' Declare Northing B
Dim dDthB As Double ' Declare Elevation B
Dim dPartialE As Double ' Declare Partial Easting
Dim dPartialN As Double ' Declare Partial Northing
Dim dPartialZ As Double ' Declare Elevation Difference
Dim sGradient As String ' Declare Gradient String
Dim dLength As Double ' Declare Cord Length
Dim dGrad As Double ' Declare Gradient
' Coordinates of point A
dEstA = 3546.235 ' Assign Easting A
dNthA = 4545.258 ' Assign Northing A
dDthA = -435.459 ' Assign Elevation A
' Coordinates of point B
dEstB = 3942.235 ' Assign Easting B
dNthB = 5123.254 ' Assign Northing B
dDthB = -696.345 ' Assign Elevation B

Runge Ltd May, 2006 Page 155


XCM Reference Guide Cypress Enable Commands

' Difference between points


dPartialE = dEstA - dEstB ' Calc Partial Easting A
dPartialN = dNthA - dNthB ' Calc Partial Northing A
dPartialZ = dDthA - dDthB ' Calc Elevation Difference
' Sign value
dSignE = Sgn(dPartialE) ' Sign of Eastings
dSignN = Sgn(dPartialN) ' Sign of Northings
dSignZ = Sgn(dPartialZ) ' Sign of Northings
dLength = Sqr((dPartialE^2) + (dPartialN^2)) ' Cord Length
dGrad = dLength/dPartialZ ' Calculate Gradient
dGrad = Abs(dGrad) ' Calc Absolute value
If (dSignZ = 1) Then ' Gradient positive
sGradient = "Positive Grade" ' Assign string
Elseif dSignZ = -1 Then ' Gradient negative
sGradient = "Negative Grade" ' Assign String
End If ' End Construct
MsgBox dGrad,0,sGradient ' Display gradient
End Sub ' End MAIN Subroutine
'End of XCM

10.2.102 Shell Function

Shell ( app [, style])

Runs an executable program.

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

Return value: ID, the task ID of the started program.

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

Runge Ltd May, 2006 Page 156


XCM Reference Guide Cypress Enable Commands

Dim vDummy As Variant ' Declare dummy value


Dim vMsg ' Declare variables.
vDummy = Shell("Calc.exe", 1) ' Shell Calculator.
For IRepeat = 1 To 5 ' Set up counting loop.
SendKeys IRepeat & "{+}", True ' Send keystrokes to Calculator
Next IRepeat ' to add each value of I.
vMsg = "Choose OK to close the Calculator."' Message
MsgBox vMsg ' Display OK prompt.
AppActivate "Calculator" ' Return focus to Calculator.
SendKeys "%{F4}", True ' Alt+F4 to close Calculator.
End Sub ' End routine
'End of XCM

10.2.103 Sin Function

Sin (rad)

Returns the sine of an angle that is expressed in radians

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

10.2.104 Space Function

Space[$] (number )

Skips a specified number of spaces in a print# statement.

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

Runge Ltd May, 2006 Page 157


XCM Reference Guide Cypress Enable Commands

10.2.105 Sqr Function


Function

Sqr(num)

Returns the square root of a number.

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

Sub Main ' Start Main Routine


Route ' Call subroutine
End Sub ' End subroutine Route
'End of XCM

Runge Ltd May, 2006 Page 158


XCM Reference Guide Cypress Enable Commands

10.2.106 Static Statement

Static variable

Used to declare variables and allocate storage space. These variables will retain their value through
the program run

Related Topics: Dim, Function, Sub

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

Sub Joe( j As Integer ) ' Start Joe Subroutine


Static lRepeat ' Retain static value
Print lRepeat ' Display value
lRepeat = lRepeat + 5 ' Increment value by 5
Print lRepeat ' Display value
End Sub ' End of Subroutine joe
'End of XCM

10.2.107 Stop Statement

Stop

Ends execution of the program


The Stop statement can be placed anywhere in your code.

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

Runge Ltd May, 2006 Page 159


XCM Reference Guide Cypress Enable Commands

Next lRepeatz ' Next Increment


Next lRepeaty ' Next Increment
Stop ' Stop processing
Next lRepeatx ' Next Increment
End Sub ' End routine
'End of XCM

10.2.108 StrComp Function

StrComp( nstring1,string2, [compare] )

Returns a variant that is the result of the comparison of two strings

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

10.2.109 String Function

String ( numeric, charcode )

Runge Ltd May, 2006 Page 160


XCM Reference Guide Cypress Enable Commands

String returns a string.

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

10.2.110 Sub Statement

Sub SubName [(arguments)]


Dim [variable(s)]
[statementblock]
[Exit Function]
End Sub

Declares and defines a Sub procedures name, parameters and code.

When the optional argument list needs to be passed the format is as follows:

([ByVal] variable [As type] [,ByVal] variable [As type] ]…])

The optional ByVal parameter specifies that the variable is [passed by


value instead of by reference (see “ByRef and ByVal” in this manual).
The optional As type parameter is used to specify the data type. Valid
types are String, Integer, Double, Long, and Varaint (see “Variable Types”
in this manual).

Related Topics: Call, Dim, Function

Example:
Sub Main
Dim sDST As String

sDST = "t1"

Runge Ltd May, 2006 Page 161


XCM Reference Guide Cypress Enable Commands

mkdir sDST
mkdir "t2"
End Sub

10.2.111 Tan Function

Tan(angle)

Returns the tangent of an angle as a double.

The parameter angle must be a valid angle expressed in radians.

Related Topic: Atn, Cos, Sin


Example:
' This sample program show the use of the Tan function
' MsgBox ( msg, [type] [, title])
Sub Main ' Start Main Routine
Dim dTanValue As Double ' Declare Tan Value
Dim vMsg As Variant ' Declare Msg
Dim dPi As Double ' Declare variables.
dPi = 4 * Atn(1) ' Calculate Pi.
vMsg = "Pi is equal to " & dPi ' Combine string and reply
MsgBox vMsg,4096,"Calculation complete" ' Display results.
dTanValue = Tan(dPi/4) ' Calculate Tan value
MsgBox dTanValue & " is the tangent of Pi/4"' Combine Tan value and string
End Sub ' End of Routine
'End of XCM

10.2.112 Text Statement

Text Starting X position, Starting Y position, Width, Height, Label


Creates a text field for titles and labels.

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.

Runge Ltd May, 2006 Page 162


XCM Reference Guide Cypress Enable Commands

' 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

10.2.113 TextBox Statement

TextBox Starting X position, Starting Y position, Width, Height, Default String


Creates a Text Box for typing in numbers and text

Runge Ltd May, 2006 Page 163


XCM Reference Guide Cypress Enable Commands

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

Runge Ltd May, 2006 Page 164


XCM Reference Guide Cypress Enable Commands

10.2.114 Time Function


Time[()]
Returns the current system time.
Related topics: To set the time use the TIME$ statement.

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

Runge Ltd May, 2006 Page 165


XCM Reference Guide Cypress Enable Commands

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

10.2.115 Timer Event

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.

Related topics: DateSerial, DateValue, Hour Minute, Now, Second


TimeValue.

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

Runge Ltd May, 2006 Page 166


XCM Reference Guide Cypress Enable Commands

10.2.116 TimeSerial - Function

TimeSerial ( hour, minute, second )

Returns the time serial for the supplied parameters hour, minute, second.

Related topics: DateSerial, DateValue, Hour Minute, Now, Second


TimeValue.

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

Note: The serial time function should be limited to a maximum of 24 hours.

10.2.117 TimeValue - Function

TimeValue ( TimeString )

Returns a double precision serial number based of the supplied string


parameter.

Midnight = TimeValue(“23:59:59”)

Related topics: DateSerial, DateValue, Hour Minute, Now, Second


TimeSerial.

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

Runge Ltd May, 2006 Page 167


XCM Reference Guide Cypress Enable Commands

Print dMTime ' Display double value to screen


End Sub ' End of Routine
'End of XCM

10.2.118 Trim, LTrim, RTrim Functions

[L| R] Trim (String )

Ltrim, Rtrim and Trim all Return a copy of a string with leading, trailing or
both leading and trailing spaces removed.

Ltrim, Rtrim and Trim all return a string

Ltrim removes leading spaces.


Rtrim removes trailing spaces.
Trim removes leading and trailing spaces.

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

Runge Ltd May, 2006 Page 168


XCM Reference Guide Cypress Enable Commands

10.2.119 Type Statement

Type usertype elementname As typename


[ elementname As typename]
...
End Type

Defines a user-defined data type containing one or more elements.

The Type statement has these parts:

Part Description

Type Marks the beginning of a user-defined type.

usertype Name of a user-defined data type. It follows standard


variable naming conventions.

elementname Name of an element of the user-defined data type. It


follows standard variable-naming conventions.

subscripts Dimensions of an array element. You can declare


multiple dimensions. (not currently implemented)

typename One of these data types: Integer, Long, Single, Double,


String (for variable-length strings), String * length (for
fixed-length strings), Variant, or another user-defined
type. The argument typename can't be an object type.
End Type Marks the end of a user-defined type.

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

Runge Ltd May, 2006 Page 169


XCM Reference Guide Cypress Enable Commands

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

Runge Ltd May, 2006 Page 170


XCM Reference Guide Cypress Enable Commands

10.2.120 UBound Function

Ubound(arrayname[,dimension])

Returns the value of the largest usable subscript for the specified dimension of an
array.

Related Topics: Dim, Global, Lbound, and Option Base

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

10.2.121 UCase Function

Ucase (String )

Returns a copy of String is which all lowercase characters have been converted to
uppercase.

Related Topics: Lcase, Lcase$ Function

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

Runge Ltd May, 2006 Page 171


XCM Reference Guide Cypress Enable Commands

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

10.2.122 Val

Val(string)

Returns the numeric value of a string of characters.

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)

Returns a value that indicates how the parameter varname is stored


internally.

The parameter varname is a variant data type.

Runge Ltd May, 2006 Page 172


XCM Reference Guide Cypress Enable Commands

VarType Return values:

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

Related Topics: IsNull, IsNumeric

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

Runge Ltd May, 2006 Page 173


XCM Reference Guide Cypress Enable Commands

10.2.124 Weekday Function

Weekday(date,firstdayof week)

Returns an integer containing the whole number for the weekday it is representing.

Related Topics: Hour, Second, Minute, Day

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

10.2.125 While...Wend Statement

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.

Related Topics: Do...Loop Statement

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

Runge Ltd May, 2006 Page 174


XCM Reference Guide Cypress Enable Commands

sArray(2) = "XPAC -XCM's " ' Assign String 2


sArray(3) = "Mining Database"' Assign String 3
sArray(4) = "Scheduling" ' Assign String 4
sArray(5) = "Copper Mine" ' Assign String 5
bExchange = True ' Set exchange to true

While bExchange ' While true


bExchange = False ' Assign False
For lRepeat = 1 To lMAX ' Loop until lMAX
MsgBox sArray(lRepeat) ' Display Message from array
Next lRepeat ' Next increment
Wend ' End control structure
End Sub ' End routine
'End of XCM

10.2.126 With Statement

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.

Related Topics: While Statement and Do Loop

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

Sub Main ' Start Main routine


With type1a ' The type 1a

Runge Ltd May, 2006 Page 175


XCM Reference Guide Cypress Enable Commands

.a = 65 ' Assign 65 to long a


.d = 3.14 ' Assign 3.14 to double d
End With ' End with type 1a
With type2a ' The type 2a
.a = "Hello, world" ' Assign string a
With .o ' The type 1
.s = "Goodbye" ' Assign String s
End With ' End with type 1
End With ' End with type 2a
type1a.s = "YES" ' Assign type 1a string
MsgBox type1a.a ' Display message
MsgBox type1a.d ' Display message
MsgBox type1a.s ' Display message
MsgBox type2a.a ' Display message
MsgBox type2a.o.s ' Display message
End Sub ' End of routine

' 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

Runge Ltd May, 2006 Page 176


XCM Reference Guide Cypress Enable Commands

MsgBox type2a.o.s
End Sub

10.2.127 Write # - Statement


Write #filenumber [,parameterlist ]

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.

Related Topics: Open and Print # Statements

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

10.2.128 Year Function

Year(serial# )

Returns an integer representing a year between 1980 and 1999, inclusive.


The returned integer represents the year of the serial parameter.

The parameter serial# is a string that represents a date.

Runge Ltd May, 2006 Page 177


XCM Reference Guide Cypress Enable Commands

If serial is a Null, this function will return a Null.

Related Topics: Date, Date$ Function/Statement, Day, Hour, Month,


Minute, Now, Second.

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

Runge Ltd May, 2006 Page 178


XCM Reference Guide XPAC Functions and Subroutines

11 XPAC Functions and


Subroutines
This symbol after a function indicates it is a Report Writer Function.

Activity

Function Activity(ByVal Activity Number As Integer) As Boolean

Used to over-ride the productive activity associated with the main database data field in the result.

Abort

Function Abort(optional Message As Variant) As Boolean

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

Message This message is displayed as soon as the Abort function is encountered.


It is used to provide a message about why the XCM is being aborted. The
message is an optional argument and it is passed to the function by
reference as a variant data type.
An example of the window that is displayed is provided below. In this
example, the message passed to the function is “Warning: Negative
Volume Calculated”. If no message is passed into the function, this
window will not be displayed at all.

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.

Runge Ltd May, 2006 Page 179


XCM Reference Guide XPAC Functions and Subroutines

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

Sub AddDependencyToGroup (ByVal Group as Long, ByVal After as Long, ByVal


Before as Long , Optional ByVal ActAfter As Integer, Optional ByVal ActBefore As
Integer, Optional ByVal ReleaseProfileCurve As String)

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

Function CalendarHrs() As Double

Returns the accumulated calendar hours for all steps passed by the filter.

CalculateLineIntersection

Function CalculateLineIntersection ( ByRef Line1Start As Vertex, ByRef Line1End


As Vertex, ByRef Line2Start As Vertex, ByRef Line2End As Vertex, optional ByRef
Intersection As Vertex, optional ByVal ExtendLines As Boolean ) As Boolean

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

Runge Ltd May, 2006 Page 180


XCM Reference Guide XPAC Functions and Subroutines

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

Sub ChangeProductionRate ( ByVal sResourceName As String, ByVal lActivity as


long, ByVal sRate As String)

This function is used to change a resource’s production rate during a schedule.

ARGUMENTS

sResourceName The name of the resource that will have it’s production rate
changed

lActivity The activity of the resource that will be changed.

sRate The new production rate

Example:
call ChangeProductionRate(“Ore”, 1, “100”)

ChangeRoster

Sub ChangeRoster ( ByVal sResourceName As String, ByVal sRoster As String, ByVal


sRosterException As String )

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

sRoster The new roster.

sRosterException The new roster exception

REMARKS

Runge Ltd May, 2006 Page 181


XCM Reference Guide XPAC Functions and Subroutines

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.

Full Row Code Data Field Name Level Cleared


mProd Product 0
mProd_Rec Product Recovery 1

Runge Ltd May, 2006 Page 182


XCM Reference Guide XPAC Functions and Subroutines

mProd_Qty Product Quantity 1


mCost Costs 0 Yes
mCost_Wst Waste Operations 1 Yes
mCost_Wst_Clr Clearing & Topsoil 2 Yes
mCost_Wst_DB Waste Drill and Blast 2 Yes
mCost_Wst_Min Waste Mining 2 Yes
mCost_Cl Coal Mining 1 Yes
mCost_TotMin Total Mining Cost 1 Yes
mRev Revenue 0
mRev_PrdA Product A 1
mRev_PrdA_UnRev Unit Revenue 2
mRev_PrdA_Ton Tonnage 2

(1) Clear a selection of data fields.


Sub Main
'Clear a range of cost fields
ClearData mCost, mCost_Wst_Min
'Clear selected cost fields
ClearData mCost_Cl
ClearData mCost_TotMin
End Sub

(2) Clear a grouping of data fields.


Sub Main
'Clear all costing fields in one step
ClearData mCost
End Sub

RELATED FUNCTIONS
DbWriteValue, SetClass, SetNote

ClearGlobalObject

Sub ClearGlobalObject(Optional ByVal sObjectName As String)

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

Runge Ltd May, 2006 Page 183


XCM Reference Guide XPAC Functions and Subroutines

ClearInputPath

Function ClearInputPath(Input Path Name As String, optional First Step To Clear As


Long, optional Last Step to Clear As Long) As Long

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.

Runge Ltd May, 2006 Page 184


XCM Reference Guide XPAC Functions and Subroutines

• 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

Runge Ltd May, 2006 Page 185


XCM Reference Guide XPAC Functions and Subroutines

Function ClearUserFlag ( iFlagNo As Integer, lRecord As Long, iActivity As Integer,


Optional ByVal sResource As String ) As Boolean

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

Function CompletedTask() As Boolean

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

Function ClosingDumpCapacity(ByVal FieldNo As Integer) As Double

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

Function ClosingInv (ByVal FieldNo As Integer) As Double

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

Function ClosingInvSP (ByVal FieldNo As Integer) As Double

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

Runge Ltd May, 2006 Page 186


XCM Reference Guide XPAC Functions and Subroutines

Function CreateRecord(Level 1 Name As String, Level 1 Pil As Long, optional Level 2


Name As String, optional Level 2 Pil As Long, optional Level 3 Name As String, optional
Level 3 Pil As Long, optional Level 4 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 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. “”.

Runge Ltd May, 2006 Page 187


XCM Reference Guide XPAC Functions and Subroutines

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

(2) Add multiple records to a database.


Sub Main
Dim lNewRec As Long
Dim lBlock As Long
'Add 10 Blocks to Strip 9 in the HAK pit.
'Put this pit in the next available Pil.
'Use the Block Pil numbers as the Block names.
For lBlock = 1 To 10
lNewRec = CreateRecord("HAK", -1, "S09", 9, "", lBlock)
Next lBlock
'Confirm that the record has been created successfully.
If (lNewRec <= 0) Then Print "Record Creation Failed."
End Sub

Runge Ltd May, 2006 Page 188


XCM Reference Guide XPAC Functions and Subroutines

RELATED FUNCTIONS
SetRecName, GoRec, GetRecName, DbWriteValue, RemoveRecord

CreateRecordDB

Function CreateRecordDB(Database Name As Variant, Level 1 Name As String, Level


1 Pil As Long, optional Level 2 Name As String, optional Level 2 Pil As Long, optional
Level 3 Name As String, optional Level 3 Pil As Long, optional Level 4 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 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

Database Name The Database Name is an optional argument. It is passed by


reference as a variant data type.
The Database Name is used to specify a different database. If the
Database Name is not specified, then the current database will be
used.
The database name may be provided as a string (in double quotes)
or it may be one of the options below.

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

Runge Ltd May, 2006 Page 189


XCM Reference Guide XPAC Functions and Subroutines

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.

Database Name Options Description


ACTIVE_MAIN The main database.
ACTIVE_CALENDAR The active calendar database.
ACTIVE_RESULTS The active results database.

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

Function CreateRecord(Level 0 Name As String, Level 0 Pil As Long, Level 1 Name As


String, Level 1 Pil As Long, optional Level 2 Name As String, optional Level 2 Pil As
Long, optional Level 3 Name As String, optional Level 3 Pil As Long, optional Level 4

Runge Ltd May, 2006 Page 190


XCM Reference Guide XPAC Functions and Subroutines

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

Runge Ltd May, 2006 Page 191


XCM Reference Guide XPAC Functions and Subroutines

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

(2) Add multiple records to a database.


Sub Main
Dim lNewRec As Long
Dim lBlock As Long
'Add 10 Blocks to Strip 9 in the HAK pit.
'Put this pit in the next available Pil.
'Use the Block Pil numbers as the Block names.
For lBlock = 1 To 10

Runge Ltd May, 2006 Page 192


XCM Reference Guide XPAC Functions and Subroutines

lNewRec = CreateRecordEx("Deposit", 0, "HAK", -1, "S09", 9, "", lBlock)


Next lBlock
'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

Function CurveValue(Curve Name As String, x Value As Double, Curve Mode or y


Value As Double) As Double

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.

Curve Mode or This argument is passed by value as a double data type.


y Value
For two dimensional curves, this argument represents the Curve
Mode. It can be set to either True or False. Note that True and
False have predefined values that enable them to be passed into this
argument as a double data type.
To allow extrapolation in a two dimensional curve the Curve Mode
should be set to True.
To inhibit extrapolation in a two dimensional curve the Curve Mode
should be set to False. If extrapolation is inhibited and the x value is
outside the curve limits, then the y value with the closest x value in
the data range will be returned (ie. either the maximum or the
minimum y value).
For three dimensional curves, this argument represents the y value

Runge Ltd May, 2006 Page 193


XCM Reference Guide XPAC Functions and Subroutines

that is looked up on the y axis of the curve.

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

(2) 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) = CurveValue(sCurve, M(mEQP_WstFlat), M(mEQP_WstRamp))
End Sub

RELATED FUNCTIONS
Curve3DValue.

Curve3DValue

Function Curve3DValue(Curve Name As String, x Value As Double, y Value As


Double) As Double

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

Runge Ltd May, 2006 Page 194


XCM Reference Guide XPAC Functions and Subroutines

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

Function DbReadName(Database Name As Variant, Record Number As Long) As


String

Runge Ltd May, 2006 Page 195


XCM Reference Guide XPAC Functions and Subroutines

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)

Runge Ltd May, 2006 Page 196


XCM Reference Guide XPAC Functions and Subroutines

'Accumulate all of the ramp volumes.


If (DbReadName("Main", lRecNum) = "Ramp") Then
lCumRampVol = lCumRampVol + M(mTot_Vol)
End If
Print lCumRampVol
End Sub

(2) Find the record name for a record in a Parameters database.


Sub Main
Dim lAreaPil As Long
Dim lParamRec As Long
lAreaPil = GetApil(1)
lParamRec = GetRecFromPilDb("Area Parameters", lAreaPil)
'Read the Area name from the Parameters database.
Print DbReadName("Area Parameters", lParamRec)
End Sub

RELATED FUNCTIONS
GetRecName, GetRecNameAtLevel, GetPilFromPositionName

DbReadValue

Function DbReadValue(Database Name As Variant, Record Number As Long, Data


Field Number As Long) As Variant

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.

Runge Ltd May, 2006 Page 197


XCM Reference Guide XPAC Functions and Subroutines

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.

Record If the data field is a record field type, then the


function will return a long data type, containing the
record number.

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

(2) Read a value from a Parameters database.


Sub Main
'Apply the default insitu ore density from the Default Quality
'parameters database, if there is no imported value.
Dim lFldNumDefRD As Long
Dim lRecNumDef As Long
If (M(mIMP_Ore_RD) <= 0) Then
lFldNumDefRD = GetRowNumFromCode("Default Qly", "pIS_Ore_RD")
lRecNumDef = GetRecFromPilDB("Default Qly", 1)
M(mIS_Ore_RD) = DbReadValue("Default Qly", lRecNumDef, lFldNumDefRD)

Runge Ltd May, 2006 Page 198


XCM Reference Guide XPAC Functions and Subroutines

Else
M(mIS_Ore_RD) = M(mIMP_Ore_RD)
End If
End Sub

RELATED FUNCTIONS
DbReadName, DbWriteValue

DbWriteValue

Sub DbWriteValue(Database Name As Variant, Record Number As Long, Data Field


Number As Long, Value As Variant, optional Don’t Prompt As Boolean)

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.

Value The value to be written to the database is passed into this


argument. It is passed by value as a variant data type.
The data type of the value should match the data field type. For

Runge Ltd May, 2006 Page 199


XCM Reference Guide XPAC Functions and Subroutines

example, a string of text cannot be written to an additive field


type. There are no error messages generated or variables that can
be checked if this is not the case.

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

(2) 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

Runge Ltd May, 2006 Page 200


XCM Reference Guide XPAC Functions and Subroutines

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

Function DegToRad(Degrees As Double) As Double

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.

Runge Ltd May, 2006 Page 201


XCM Reference Guide XPAC Functions and Subroutines

Function DeletePolygon ( optional ByVal RecNum As Long, optional ByVal Activity As


Long, optional ByVal PolygonIndex As Long ) As Boolean

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.

Collection Type Name Comments


Activities Includes productive and non-
productive activities.

Runge Ltd May, 2006 Page 202


XCM Reference Guide XPAC Functions and Subroutines

Databases Includes the following:


• Field definitions
• Record structure
• Record values
• Level structure
Activity Schedules Mined Out Quantities and All
Preschedule Tables
Capacity Constraints
Curves
Dependency rule sets
Dumps
Dump Paths
Field selections
Feature layers
Gantt charts
Global options The settings stored under
Tools|Global Options.
Global variables
Input paths
Macros
Period constraints
Period delays
Polygon graphics plots
Polygon coordinate sets
Proximity constraints
Ranges
Resources
Reports
Rosters
Roster exceptions
Scenarios
Stockpiles

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

Runge Ltd May, 2006 Page 203


XCM Reference Guide XPAC Functions and Subroutines

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

Function FindDestinationInABL ( lRecord As Long, iActivity As Integer, Optional


ByRef iFlags As Integer, Optional ByVal sResource As String ) As Boolean

Runge Ltd May, 2006 Page 204


XCM Reference Guide XPAC Functions and Subroutines

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

lRecord The record number

iActivity The activity

iFlags An integer representing the current state of the flags for this item

sResource The resource name. If not specified or an empty string, the


current resource is used.

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

Function FindRecordInABL ( lRecord As Long, iActivity As Integer, Optional ByRef


iFlags As Integer, Optional ByVal sResource As String ) As Boolean

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

lRecord The record number

iActivity The activity

iFlags An integer representing the current state of the flags for this item

sResource The resource name. If not specified or an empty string, the


current resource is used.

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

Runge Ltd May, 2006 Page 205


XCM Reference Guide XPAC Functions and Subroutines

Function FindSourceInABL ( lRecord As Long, iActivity As Integer, Optional ByRef


iFlags As Integer, Optional ByVal sResource As String ) As Boolean

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

lRecord The record number

iActivity The activity

iFlags An integer representing the current state of the flags for this item

sResource The resource name. If not specified or an empty string, the


current resource is used.

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

Function FirstCompletedTask() As Boolean

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

Function FirstStartedTask() As Boolean

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.

Runge Ltd May, 2006 Page 206


XCM Reference Guide XPAC Functions and Subroutines

RELATED FUNCTIONS
LastCompletedTask, LastStartedTask, FirstCompletedTask, FirstTask, LastTask

FirstTask

Function FirstTask() As Boolean

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

Function GetActiveCalendarName() As Variant

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

Runge Ltd May, 2006 Page 207


XCM Reference Guide XPAC Functions and Subroutines

GetActiveScenarioName

Function GetActiveScenarioName() As Variant

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

Function GetActivityCount() As Long

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.

Runge Ltd May, 2006 Page 208


XCM Reference Guide XPAC Functions and Subroutines

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

(2) Store the productive activity names in an array.


Sub Main
Dim lNumActivities As Long
Dim lActivity As Long
Dim sActivity() As String
'Read the names of all productive activities and store them
'in a string array
lNumActivities = GetActivityCount()
ReDim sActivity(lNumActivities)
For lActivity = 1 to lNumActivities
sActivity(lActivity) = GetActivityName(lActivity)
Next lResource
End Sub

RELATED FUNCTIONS
GetActivityName, GetActivityNum

GetActivityName

Function GetActivityName(optional Activity Number As Long) As Variant

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.

Runge Ltd May, 2006 Page 209


XCM Reference Guide XPAC Functions and Subroutines

If the activity number is passed into the function as zero or as


DEFAULT_ACTIVITY, then the function will also return
“Default” as the activity name.

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

(2) Store the productive activity names in an array.


Sub Main
Dim lNumActivities As Long
Dim lActivity As Long
Dim sActivity() As String
'Read the names of all productive activities and store them
'in a string array
lNumActivities = GetActivityCount()
ReDim sActivity(lNumActivities)
For lActivity = 1 to lNumActivities
sActivity(lActivity) = GetActivityName(lActivity)
Next lResource
End Sub

RELATED FUNCTIONS
GetActivityCount, GetActivityNum

GetActivityNum

Function GetActivityNum(optional Activity Name As String) As Long

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

Runge Ltd May, 2006 Page 210


XCM Reference Guide XPAC Functions and Subroutines

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

Function GetApil(Level Number As Integer, Optional Record Number As Long, Optional


Database Name As Variant) As Long

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

Runge Ltd May, 2006 Page 211


XCM Reference Guide XPAC Functions and Subroutines

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.

Database Name The Database Name is an optional argument. It is passed by


reference as a variant data type.
The Database Name is used to specify a different database. If the
Database Name is not specified, then the current database will be
used.
The database name may be provided as a string (in double quotes)
or it may be one of the options below.

Database Name 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 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.

Runge Ltd May, 2006 Page 212


XCM Reference Guide XPAC Functions and Subroutines

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

Runge Ltd May, 2006 Page 213


XCM Reference Guide XPAC Functions and Subroutines

Dim lNextBlkPit As Long


lNextBlkRec = GetRecNum(NXT) 'Record number of next block
lNextBlkPit = GetApil(1, lNextBlkRec) 'Pit number that next block is in
Print lNextBlkPit
End Sub

RELATED FUNCTIONS
GetFeatureCount, GetFeatureName, GetLayerCount, GetEntityCount, GetEntity
GetLevelNum, GetRecNum, GetRecNumAtLevel, Predefined Database Level Variables.

GetASLCount

Function GetASLCount App ( Optional ByVal lActivity As Long, Optional ByVal


bAvailable As Boolean, Optional ByVal sResource As String ) As Integer"

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

Function GetCalendarNameFromScenario(optional Scenario Name As String) As


Variant

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

Runge Ltd May, 2006 Page 214


XCM Reference Guide XPAC Functions and Subroutines

Dim sScenarioCal As String


Const sSCENARIO = "5 Year Plan at 5Mtpa"
If (IsFirstInRange()) Then
sActiveCal = GetActiveCalendarName()
sScenarioCal = GetCalendarNameFromScenario(sSCENARIO)
If (sActiveCal<>sScenarioCal) Then
Print "The calendar for " & sSCENARIO & " scenario is not Active."
End If
End If
End Sub

RELATED FUNCTIONS
GetActiveCalendarName, GetFullModelName, GetPeriodFromRecNum

GetClass

Function GetClass(Data Field Number As Integer) As String

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)

Runge Ltd May, 2006 Page 215


XCM Reference Guide XPAC Functions and Subroutines

M(mROM_Clear_Ar) = 0
If (sTopsoil = "Exists") Then M(mROM_Clear_Ar) = M(mROM_Wst_Ar)
End Sub

(2) Read multiple values from adjacent classified fields.


Sub Main
Dim sDBFlag(4) As String
Dim lFlag As Long
Dim sWstPfCurve As String
Dim sWstDrlCurve As String
'Read the Drill & Blast flags for the current record.
For lFlag = 1 to 4
sDBFlag(lCount) = GetClass(mDB_Flag + lFlag)
Next lFlag
'Use the Drill & Blast flags to look up the relevant XPAC Curve
sWstPfCurve = "Waste pf - " & sDBFlag(1) & sDBFlag(2)
M(mDB_Wst_Blast_pf) = CurveValue(sWstPfCurve, M(mDB_Wst_Hard), FALSE)
sWstDrlCurve = "Waste Drill Prod - " & sDBFlag(3) & sDBFlag(4)
M(mDB_Wst_Drill_Prod) = CurveValue(sWstDrlCurve, M(mDB_Wst_Thk), FALSE)
End Sub

RELATED FUNCTIONS
SetClass, DbWriteValue, GetNote, GetFieldInfo

GetCurrentActivity

Function GetCurrentActivity ( ) As Long

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

Function GetCurrentCalendarTime() As Double


This function returns the time and date in calendar time.
It was added for user processing and can only be used with Pre / Post Period; TimeSlice; Block; and
Step events.
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

GetCurrentDirectory

Function GetCurrentDirectory() As Variant

DESCRIPTION
Returns the current directory. The current directory is that in which the system would open a file using
the Open command.

Runge Ltd May, 2006 Page 216


XCM Reference Guide XPAC Functions and Subroutines

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

Function GetCurrentOutputStep ( ByRef OutStep As OutputPathStep ) As Boolean

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()

Dim OutputStep As OutputPathStep


Dim lSteps As Long
'Get First Step
lSteps = GetCurrentOutputStep(OutputStep)
'If the are any steps print them out
If lSteps <> 0 Then
DisplayOutputStep OutputStep 'call sub routine to display step
End If
End Sub

Runge Ltd May, 2006 Page 217


XCM Reference Guide XPAC Functions and Subroutines

Sub DisplayOutputStep(ByRef OutStep As OutputPathStep)

Dim sLine As String


sLine = sLine + "StepNo " + CStr(OutStep.InputStepNo) + " "
sLine = sLine + "RecordNo " + CStr(OutStep.TaskId)+ " "
sLine = sLine + "Act " + CStr(OutStep.Activity)+ " "
sLine = sLine + "EntPct " + CStr(OutStep.EnteredPct)+ " "
sLine = sLine + "RelPct " + CStr(OutStep.ReleasedPct)+ " "
sLine = sLine + "ActPct " + CStr(OutStep.ActualPct)+ " "
sLine = sLine + "StDate " + CStr(OutStep.StartDate)+ " "
sLine = sLine + "EdDate " + CStr(OutStep.FinishDate)+ " "

Print sLine 'print the line to the event manager

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

Function GetCurrentPeriod ( ) As Long

Returns the Current Scheduling Period.

REMARKS
This function can only be called during a schedule via User Processing Scripts, it also cannot be called
during Pre Schedule events.

GetCurrentResource

Function GetCurrentResource ( ) As String

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

Function GetCurrentScheduleTime () As Double

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

Runge Ltd May, 2006 Page 218


XCM Reference Guide XPAC Functions and Subroutines

Function GetCurrentStepActivity () As Integer

Returns the activity for the current block being scheduled.

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

Function GetCurrentStepDetails ( ByRef dMined As Double, ByRef dReleased As


Double, ByRef dRemaining As Double ) As Boolean

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.

dMined The mined percent of the current step

dReleased The released percent of the current step

dRemaining The remaining percent of the current step

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

Function GetDatabaseName() As Variant

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.

Runge Ltd May, 2006 Page 219


XCM Reference Guide XPAC Functions and Subroutines

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

Function GetDependencies ( lRecord as Long ) As Boolean

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

Function Released (ByVal FieldNo As Integer) As Double

Returns the accumulated released value for the specified main database data field, for all steps passed
by the filter.
RemoveAllDependencies

GetDestApil

Function GetDestApil(ByVal lLevelNumber As Long) As Long

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.

Runge Ltd May, 2006 Page 220


XCM Reference Guide XPAC Functions and Subroutines

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

Function GetDestinationABLCount ( Optional ByVal lActivity As Long, Optional


ByVal bAvailable As Boolean, Optional ByVal sResource As String ) As Integer

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

Function GetEntity(Feature Layer Name As String, Layer Name As String, Entity


Index Number As Long, Vertex Coordinates() As Vertex, optional Entity Closed As
Boolean) As Long

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

Runge Ltd May, 2006 Page 221


XCM Reference Guide XPAC Functions and Subroutines

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.

Vertex This argument is an array which is passed to the function by


Coordinates() reference using an XPAC-defined data structure called Vertex.
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.
It is recommended that the Vertex Coordinates array be defined as
a re-sizeable array, so that it will be resized to accommodate as
many vertices as are present in the Entity being loaded. This is
done as follows.
Dim EntityVertex() As Vertex
In this example the array would be passed into the function as
follows.
EntityVertex()
If the Vertex Coordinates array has been defined as a fixed-sized
array, then GetEntity will load as many vertices as possible into
the array. For example:
Dim EntityVertex(2) As Vertex
In this example the array would still be passed into the GetEntity
function as follows.
EntityVertex()
The Vertex data structure has the following elements.

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.

Runge Ltd May, 2006 Page 222


XCM Reference Guide XPAC Functions and Subroutines

Entity Closed This argument is passed to the function by reference. It is a


boolean data type and it is optional.
If the Entity, specified by the Feature Layer name the Layer name
and the Entity Index number, is closed (ie. it has the dxf closed
flag set), then the variable passed in for this argument will be set
to True. Otherwise it will be set to False.

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()

Dim lFeatureCount As Long


Dim lLayerCount As Long
Dim lEntityCount As Long
Dim lVertexCount As Long

Dim sFeatureName As String


Dim sLayerName As String
Dim EntityPts()As Vertex
Dim sPrintMsg As String

Dim lFeatureIndex As Long


Dim lLayerIndex As Long
Dim lEntityIndex As Long

Runge Ltd May, 2006 Page 223


XCM Reference Guide XPAC Functions and Subroutines

Dim lVertexIndex As Long

If (IsFirstInRange()) Then Open "LeaseBoundary.csv" For Output As #1

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

Function GetEntityCount(Feature Layer Name As String, Layer Name As String) As


Long

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

Runge Ltd May, 2006 Page 224


XCM Reference Guide XPAC Functions and Subroutines

string data type.


The Layer name can be set to an empty string to get the total
number of Entities in 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.

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

Function GetFeatureCount() As Long

DESCRIPTION

Returns the number of Feature Layers in the current project.


Feature Layers are made up of Layers and Layers are made up of Entities. Entities may be text, lines,
polylines, lightweight polylines, etc.

ARGUMENTS
There are no arguments for this function.

VALUES RETURNED

Runge Ltd May, 2006 Page 225


XCM Reference Guide XPAC Functions and Subroutines

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()

Dim lFeatureCount As Long


Dim lLayerCount As Long
Dim lEntityCount As Long
Dim lVertexCount As Long

Dim sFeatureName As String


Dim sLayerName As String
Dim EntityPts()As Vertex
Dim sPrintMsg As String

Dim lFeatureIndex As Long


Dim lLayerIndex As Long
Dim lEntityIndex As Long
Dim lVertexIndex As Long

If (IsFirstInRange()) Then Open "LeaseBoundary.csv" For Output As #1

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

Function GetFeatureName(Feature Layer Index Number As Long) As String

Runge Ltd May, 2006 Page 226


XCM Reference Guide XPAC Functions and Subroutines

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

Function GetFeatureVertexCount (ByVal FeatureName As String ) As Long

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.

Returns the value –1 on failure.

Related function(s): GetFeatureVertexXYZ

GetFeatureVertexXYZ

Function GetFeatureVertexXYZ (ByVal VertexNum, ByVal FeatureName As String,


optional ByRef X As Double, optional ByRef Y As Double, optional ByRef Z As Double )
As Boolean

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.

Returns true if it successfully got the vertex. Returns false on an error.

Related function(s): GetFeatureVertexCount

Runge Ltd May, 2006 Page 227


XCM Reference Guide XPAC Functions and Subroutines

GetFieldInfo

Sub GetFieldInfo(Data Field Number As Integer, Data Field Information As FieldInfo,


Database Name As Variant)

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

Runge Ltd May, 2006 Page 228


XCM Reference Guide XPAC Functions and Subroutines

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.

One exception to the above rule is if the field type is set to


“Different type for each level”. In this case, the parameter may
return a valid data field number, representing the field type for an
upper level of the database.

If the field type is set to “Minimum of Self” or “Maximum of Self”,


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

Runge Ltd May, 2006 Page 229


XCM Reference Guide XPAC Functions and Subroutines

Script returns FPROT_SCRIPT


Both returns FPROT_ALL

When this subroutine 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.
After the function has been called, 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

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

(2) Export all Additive data field values from a database.


Sub Main

Runge Ltd May, 2006 Page 230


XCM Reference Guide XPAC Functions and Subroutines

Dim sRecData As String


Dim lFieldNum As Long
Dim FieldData As FieldInfo
'Open a file to export the data into
If (IsFirstInRange()) Then Open "Reserves.csv" For Output As #1
'Write the record name at each level to a string variable
sRecData = sDistrictName & "," & sPanelName & "," & sBlockName & ","
'Loop through the data fields
For lFieldNum = 1 to 500
Call GetFieldInfo(lFieldNum, FieldData, "Main")
If (FieldData.FieldType = FTYPE_ADDITIVE) Then
'Append the data field value to the string variable
sRecData = sRecData & CStr(M(lFieldNum)) & ","
End If
Next lFieldNum
'Write the record data string to the reserves file
Print #1, sRecData
If (IsLastInRange()) Then Close #1
End Sub

RELATED FUNCTIONS

RELATED FUNCTIONS

GetDependencies,
GetDependencies, GetPredecessor,
GetPredecessor, GetSuccessor,
GetSuccessor,
GetNumberOfPredecessors,, GetNumberOfSuccessors,
GetNumberOfPredecessors GetNumberOfSuccessors, Released

Function Released (ByVal FieldNo As Integer) As Double

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

Function GetFirstABLItem ( ByRef lRecord As Long, ByRef iActivity As Integer,


Optional ByRef bAvailable As Boolean, Optional ByVal sResource As String ) As
Integer

Returns the first 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.

ARGUMENTS

lRecord The record number

iActivity The activity

Runge Ltd May, 2006 Page 231


XCM Reference Guide XPAC Functions and Subroutines

bAvailable A Boolean true if available for selection

sResource The resource name. If not specified or an empty string, the


current resource is used.

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

Function GetFirstABLDestination ( ByRef lRecord As Long, ByRef iActivity As


Integer, Optional ByRef bAvailable As Boolean, Optional ByVal sResource As String )
As Integer

Returns the first 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.

ARGUMENTS

lRecord The record number

iActivity The activity

bAvailable A Boolean true if available for selection

sResource The resource name. If not specified or an empty string, the


current resource is used.

Available Flags
0 Available for Selection

Runge Ltd May, 2006 Page 232


XCM Reference Guide XPAC Functions and Subroutines

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
GetFirstABLDestination, GetNextABLDestination

GetFirstABLSource

Function GetFirstABLSource ( ByRef lRecord As Long, ByRef iActivity As Integer,


Optional ByRef bAvailable As Boolean, Optional ByVal sResource As String ) As
Integer

Returns the first 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.

ARGUMENTS

lRecord The record number

iActivity The activity

bAvailable A Boolean true if available for selection

sResource The resource name. If not specified or an empty string, the


current resource is used.

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

Runge Ltd May, 2006 Page 233


XCM Reference Guide XPAC Functions and Subroutines

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
GetFirstABLSource, GetNextABLSource

GetFirstInRange

Function GetFirstInRange(Database Range Name As String, optional Database Name


As String) As Long

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.

Return Value Reason

-1 The database range name is an empty string.

There are no records in the database range.

Abort If the specified database does not exist, then the function will return
an “Unspecified failure” and then Abort.

EXAMPLES

Runge Ltd May, 2006 Page 234


XCM Reference Guide XPAC Functions and Subroutines

(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

Function GetFirstOutputStep ( ByRef OutStep As OutputPathStep, ByVal


ScenarioName As String, ByVal ResourceName As String, Optional ByVal RangeName
As String ) As Long

Gets the First Output step from a Combined Output Path.


For Example
Long lSteps = GetFirstOutputStep(Step, “Production Scenario”, “DragLine
[SP],FEL [SP]”, PitARange)

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

Function GetFullModelName() As Variant

DESCRIPTION
Returns the full name of the XPAC model, including the drive, the directory path and the file name.

ARGUMENTS

Runge Ltd May, 2006 Page 235


XCM Reference Guide XPAC Functions and Subroutines

There are no arguments for this function.

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

Function GetGlobalArray(ByVal sObjectName As String, ByRef Object() As Variant)


As Boolean

DESCRIPTION
Returns the value of an array variable from the temporary store inside XPAC.

ARGUMENTS

sObjectName The name to use to reference this global object

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

Runge Ltd May, 2006 Page 236


XCM Reference Guide XPAC Functions and Subroutines

'Retrieve the global array from memory


GetGlobalArray "Gbl_sExitNames", g_sExitNames
GetGlobalObject "Gbl_lNumExit", g_lNumExit
Dim lEachExit As Long
Dim lExitIndex As Long
lExitIndex = 0
'Process each exit node in array
For lEachExit = 1 To g_lNumExit Step 1
'If exit node name is in array
If g_sExitNames(lEachExit) = "Exit One" Then
'Assign index of this exit node
lExitIndex = lEachExit
Exit For
End If
Next lEachExit
End Sub

RELATED FUNCTIONS
ClearGlobalObject, GetGlobalArray, GetGlobalObject, SetGlobalArray, SetGlobalObject

Runge Ltd May, 2006 Page 237


XCM Reference Guide XPAC Functions and Subroutines

GetGlobalObject

Function GetGlobalObject(ByVal sObjectName As String, ByRef Object As Variant) As


Boolean

DESCRIPTION
Returns the value of an object variable from the temporary store inside XPAC.

ARGUMENTS

sObjectName The name to use to reference this global object

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

Function GetInputPathName(Scenario Name As String, Resource Name As String) As


Variant

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.

Runge Ltd May, 2006 Page 238


XCM Reference Guide XPAC Functions and Subroutines

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

Function GetInputPathNoOfSteps(Input Path Name As String) As Long

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

Runge Ltd May, 2006 Page 239


XCM Reference Guide XPAC Functions and Subroutines

(1) Display the number of steps in an input path.


Sub Main
Const sINPUTPATH = "Large Waste Drill"
'Print the number of steps in the input path for the large waste drill.
Print sINPUTPATH & " No. of steps = " & GetInputPathNoOfSteps(sINPUTPATH)
End Sub

(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

Function GetInputStep(Input Path Name As String, Step Number As Long, Step


Information As InputPathStep) As Boolean

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.

Step Information This argument is passed to the function by reference using an


XPAC-defined data structure called InputPathStep.
A data structure is a data type that contains multiple elements.

Runge Ltd May, 2006 Page 240


XCM Reference Guide XPAC Functions and Subroutines

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 InputPathStep data structure has the following elements.

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

Runge Ltd May, 2006 Page 241


XCM Reference Guide XPAC Functions and Subroutines

step is being sent. It is returned as a string data type.


• For productive steps that have the destination set to a
stockpile, the destination SP will return the name of the
stockpile.
• For productive steps that have the destination set to a
classified data field or that have no destination, the destination
SP will return an empty string.
• For non-productive steps, the destination SP will return an
empty string.
ProdRate The production rate is a factor that is applied to the entered
production rate for the resource, to derate it or to increase it. It is
returned as a double data type.
• For productive steps, the production rate factor will be
greater than zero. It can also be greater than one if the
production rate needs to be increased.
• For non-productive steps, the production rate factor will
return a value of one.

When this function is used, a variable should be passed in for the


Step Information argument. That variable must be declared as an
InputPathStep type. For example:
Dim PathInfo As IputPathStep.
After the function has been called, the elements of the
InputPathStep structure can be referenced using the variable name,
followed by a full stop and then the relevant element name. For
example:
PathInfo.StepType
PathInfo.Activity
PathInfo.DestinationSP

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"

Runge Ltd May, 2006 Page 242


XCM Reference Guide XPAC Functions and Subroutines

Dim lTotSteps As Long


Dim lStep As Long
Dim StepInfo As InputPathStep
'Loop through all steps in the input path looking for a prod rate value.
lTotSteps = GetInputPathNoOfSteps(sINPUTPATH)
For lStep = 1 To lTotSteps
Call GetInputStep(sINPUTPATH, lStep, StepInfo)
If (StepInfo.StepType = PE_PROD And StepInfo.ProdRate <> 1) Then
Print "Production rate % assigned to Record " & StepInfo.TaskId
End If
Next lStep
End Sub

(2) Create a new input path from an existing input path.


Sub Main
Dim bStepFound As Boolean
Dim lOldStep As Long
Dim StepInfo As InputPathStep
Dim lNewStep As Long
'Read the first step details from the existing input path.
lOldStep = 1
bStepFound = GetInputStep("FEL Wst and Ore", lOldStep, StepInfo)
Do While (bStepFound = True)
'Insert the activity 1 steps into the new input path.
If (StepInfo.Activity = 1) Then
lNewStep = InsertIntoInputPath("FEL Wst", lNewStep + 1, StepInfo)
End If
'Read the next step from the existing input path.
lOldStep = lOldStep + 1
bStepFound = GetInputStep("FEL Wst and Ore", lOldStep, StepInfo)
Loop
End Sub

RELATED FUNCTIONS
Error! Reference source not found., GetInputPathNoOfSteps, ClearInputPath, InsertIntoInputPath

GetLastError

Function GetLastError() As Variant

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.

Runge Ltd May, 2006 Page 243


XCM Reference Guide XPAC Functions and Subroutines

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.

Return Value from Description and Format of Error Message


RunActiveScenario
Function
0 If the schedule is calculated successfully, then this function will
return an empty string.
1 If the user pushes the Cancel button while the schedule is
running, the schedule will not be completed for all periods and
this function will return:
“The Schedule has been cancelled”.
2 If there is a general error while the schedule is running (eg. an
invalid field code is encountered, no input path assigned to a
standard resource, etc), then this function will return an empty
string.
3 If an objective for a resource cannot be met, then this function
will return a message that describes the objective that failed.
The message has the following format, where x is the data for the
first error encountered.
“Resource=x,Period=x,PeriodName=x,Objective=x,Actual=x,
Lower=x,Upper=x,Target=x”
4 If there is a run-time error in a user processing script, then this
function will return an empty string.
If the user tries 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, then this function will return
an empty string.
5 Reserved for future use.
6 If a production target for a resource cannot be met, then this
function will return a message that describes the production
target that failed. The message has the following format, where x
is the data for the first error encountered.
“Resource=x,Period=x,PeriodName=x,Actual=x,Lower=x,
Upper=x,Target=x”

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")

Runge Ltd May, 2006 Page 244


XCM Reference Guide XPAC Functions and Subroutines

End If
End Sub

RELATED FUNCTIONS
RunActiveScenario.

GetLastOutputStep

Function GetLastOutputStep ( ByRef OutStep As OutputPathStep ) As Boolean

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()

Dim OutputStep As OutputPathStep


Dim lSteps As Long
'Get First Step
lSteps = GetLastOutputStep(OutputStep)
'If the are any steps print them out
If lSteps <> 0 Then
DisplayOutputStep OutputStep 'call sub routine to display step

Runge Ltd May, 2006 Page 245


XCM Reference Guide XPAC Functions and Subroutines

End If
End Sub

Sub DisplayOutputStep(ByRef OutStep As OutputPathStep)

Dim sLine As String


sLine = sLine + "StepNo " + CStr(OutStep.InputStepNo) + " "
sLine = sLine + "RecordNo " + CStr(OutStep.TaskId)+ " "
sLine = sLine + "Act " + CStr(OutStep.Activity)+ " "
sLine = sLine + "EntPct " + CStr(OutStep.EnteredPct)+ " "
sLine = sLine + "RelPct " + CStr(OutStep.ReleasedPct)+ " "
sLine = sLine + "ActPct " + CStr(OutStep.ActualPct)+ " "
sLine = sLine + "StDate " + CStr(OutStep.StartDate)+ " "
sLine = sLine + "EdDate " + CStr(OutStep.FinishDate)+ " "

Print sLine 'print the line to the event manager

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

Function GetLayerCount(Feature Layer Name As String) As Long

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.

Runge Ltd May, 2006 Page 246


XCM Reference Guide XPAC Functions and Subroutines

EXAMPLES
(1) Write the Feature Layer coordinates into a Text File.
Sub Main()

Dim lFeatureCount As Long


Dim lLayerCount As Long
Dim lEntityCount As Long
Dim lVertexCount As Long

Dim sFeatureName As String


Dim sLayerName As String
Dim EntityPts()As Vertex
Dim sPrintMsg As String

Dim lFeatureIndex As Long


Dim lLayerIndex As Long
Dim lEntityIndex As Long
Dim lVertexIndex As Long

If (IsFirstInRange()) Then Open "LeaseBoundary.csv" For Output As #1

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

Function GetLayerName(Feature Layer Name As String, Layer Index Number As


Long) As String

DESCRIPTION

Runge Ltd May, 2006 Page 247


XCM Reference Guide XPAC Functions and Subroutines

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

Function GetLevelNum(optional Record Number As Long] , Optional Database Name


As Variant) As Integer

DESCRIPTION
Returns the level number for the specified record.

ARGUMENTS

Record Number The record number is an optional argument. It is passed to the


function by value as a long data type.
If a record number is not supplied, then the level number will be
sought for the current record.
If a record number is supplied, then the level number will be sought
for that record in the current database. Note that the record pointers,
such as NXT, UP, etc, cannot be used in this argument.

Database Name The Database Name is an optional argument. It is passed by


reference as a variant data type.

Runge Ltd May, 2006 Page 248


XCM Reference Guide XPAC Functions and Subroutines

The Database Name is used to specify a different database. If the


Database Name is not specified, then the current database will be
used.
The database name may be provided as a string (in double quotes)
or it may be one of the options below.

Database Name Options Description


ACTIVE_MAIN The main database.
ACTIVE_CALENDAR The active calendar database.
ACTIVE_RESULTS The active results database.

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

Runge Ltd May, 2006 Page 249


XCM Reference Guide XPAC Functions and Subroutines

GetRecNameAtLevel, GetRecNumAtLevel, GetRecNum

GetMax

Function GetMax(First Value As Double, Second Value As Double) As Double

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

(2) Find the maximum of three values.


Sub Main
Dim dMaxBlkArea As Double 'Maximum Block Area
'Find the maximum of the overburden and parting areas
dMaxBlkArea = GetMax(M(mOverbdn_Area), M(mParting_Area))
'Find the maximum of the waste (from above) and coal areas
dMaxBlkArea = GetMax(dMaxBlkArea, M(mCoal_Area))
End Sub

RELATED FUNCTIONS
GetMin, Abs.

GetMin

Runge Ltd May, 2006 Page 250


XCM Reference Guide XPAC Functions and Subroutines

Function GetMin(First Value As Double, Second Value As Double) As Double

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

(2) Find the minimum of three values.


Sub Main
Dim dMinCost As Double 'Minimum Cost Mining Method
'Find the minimum cost for Electric Shovel versus Hydraulic Excavator
dMinCost = GetMin(M(mElecShv_Tot_Cost), M(mHydExc_Tot_Cost))
'Find the minimum cost for shovels (from above) versus FELs
dMinCost = GetMin(dMinCost, M(mFEL_Tot_Cost))
End Sub

RELATED FUNCTIONS
GetMax, Abs.

GetMineStatus

Function GetMineStatus(Record Number As Long, Activity Number As Long, Status


Type As Integer, Percentage As Double, optional Calculation Point As Integer) As
Boolean

DESCRIPTION

Runge Ltd May, 2006 Page 251


XCM Reference Guide XPAC Functions and Subroutines

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

Runge Ltd May, 2006 Page 252


XCM Reference Guide XPAC Functions and Subroutines

able to set 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 calculation of
the released percentage.
• 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.
For the scheduled records, the released percentages are
determined as follows:
• For standard scheduling resources, the released
percentages are set in the Input Paths.
• For AutoScheduler resources, the released percentages
are not supported.
MS_INVENTORY This is the percentage of the specified activity that is available
to be scheduled at the required point in time. It is equal to the
released percentage minus the mined percentage.

Percentage The percentage is passed to the function by reference as a


double data type. A variable should be passed into the function
for this argument and then the percentage value is returned in the
variable. Note that the value returned is between 0 and 1.
The variable could be a user-defined variable or a data field
variable, eg. dMinPct, M(mSch_Rem_Pct).

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.

Runge Ltd May, 2006 Page 253


XCM Reference Guide XPAC Functions and Subroutines

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)

Runge Ltd May, 2006 Page 254


XCM Reference Guide XPAC Functions and Subroutines

If (bStatusFound) Then
Print "Percent Inventory After Preschedule is " & dPct*100
End If
End Sub

RELATED FUNCTIONS
GetMOQItem, GetPSItem, GetInputStep, GetLastOutputStep

GetModelDirectory

Function GetModelDirectory() As String

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

Function GetMOQItem(Step Number As Long, Activity Number As Long, Item As


ItemRemoved) As Boolean

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.

Runge Ltd May, 2006 Page 255


XCM Reference Guide XPAC Functions and Subroutines

Item This argument is passed to the function by reference using an


XPAC-defined data structure called ItemRemoved.
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 ItemRemoved data structure has the following elements.

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.

When this function is used, a variable should be passed in for the


Item argument. That variable must be declared as an
ItemRemoved type. For example:
Dim MOQInfo As ItemRemoved.
After the function has been called, the elements of the
ItemRemoved structure can be referenced using the variable name,
followed by a full stop and then the relevant element name. For

Runge Ltd May, 2006 Page 256


XCM Reference Guide XPAC Functions and Subroutines

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

Runge Ltd May, 2006 Page 257


XCM Reference Guide XPAC Functions and Subroutines

(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

Function GetMOQItemCount() As Long

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

Runge Ltd May, 2006 Page 258


XCM Reference Guide XPAC Functions and Subroutines

(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

Function GetNextABLItem ( ByRef lRecord As Long, ByRef iActivity As Integer,


Optional ByRef bAvailable As Boolean, Optional ByVal sResource As String ) As
Integer

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 )

While iRetVal >= 0

Print "Record = " & lRecord & " Activity = " & iActivity & " Available = " & bAvailable

iRetVal = GetNextABLItem( lRecord, iActivity, bAvailable )

WEnd

GetNextABLDestination

Function GetNextABLDestination ( ByRef lRecord As Long, ByRef iActivity As


Integer, Optional ByRef bAvailable As Boolean, Optional ByVal sResource As String )
As Integer

Runge Ltd May, 2006 Page 259


XCM Reference Guide XPAC Functions and Subroutines

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 )

While iRetVal >= 0

Print "Record = " & lRecord & " Activity = " & iActivity & " Available = " & bAvailable

iRetVal = GetNextABLDestination( lRecord, iActivity, bAvailable )

WEnd

GetNextABLSource

Function GetNextABLSource ( ByRef lRecord As Long, ByRef iActivity As Integer,


Optional ByRef bAvailable As Boolean, Optional ByVal sResource As String ) As
Integer

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 )

While iRetVal >= 0

Print "Record = " & lRecord & " Activity = " & iActivity & " Available = " & bAvailable

iRetVal = GetNextABLSource( lRecord, iActivity, bAvailable )

WEnd

GetNextInRange

Function GetNextInRange(Record Number As Long, Database Range Name As String,


optional Database Name As String) As Long

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.

Runge Ltd May, 2006 Page 260


XCM Reference Guide XPAC Functions and Subroutines

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.

Return Value Reason

-1 The specified record number is at a different level to the scanning level


in the database range.
The specified record number is not within the database range.
The next record number is not within the database range.

The next record does not exist.

The database range name is an empty string.

There are no records in the database range.

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

Runge Ltd May, 2006 Page 261


XCM Reference Guide XPAC Functions and Subroutines

RELATED FUNCTIONS
GetFirstInRange, IsInRange, IsFirstInRange, IsLastInRange

GetNextOutputStep

Function GetNextOutputStep ( ByRef OutStep As OutputPathStep ) As Boolean

Gets the Next Output step from a Combined Output Path.


Returns True when successful.
For Example
' This subroutine Prints out All the outputs paths of the Scenario called Production Schedule

Sub Main()

Dim OutputStep As OutputPathStep


Dim lSteps As Long
'Get First Step
lSteps = GetFirstOutputStep(OutputStep, "Production Schedule", "All")
'If the are any steps print them out
If lSteps > 0 Then

Dim bNext As Boolean


bNext = true
While (bNext) ' keep getting next step until get to the end
DisplayOutputStep OutputStep 'call sub routine to display step
bNext = GetNextOutputStep(OutputStep) ' get next step
Wend

End If
End Sub

Sub DisplayOutputStep(ByRef OutStep As OutputPathStep)

Dim sLine As String


sLine = sLine + "StepNo " + CStr(OutStep.InputStepNo) + " "
sLine = sLine + "RecordNo " + CStr(OutStep.TaskId)+ " "
sLine = sLine + "Act " + CStr(OutStep.Activity)+ " "
sLine = sLine + "EntPct " + CStr(OutStep.EnteredPct)+ " "
sLine = sLine + "RelPct " + CStr(OutStep.ReleasedPct)+ " "
sLine = sLine + "ActPct " + CStr(OutStep.ActualPct)+ " "
sLine = sLine + "StDate " + CStr(OutStep.StartDate)+ " "
sLine = sLine + "EdDate " + CStr(OutStep.FinishDate)+ " "

Print sLine 'print the line to the event manager

End Sub

GetNote

Function GetNote(Data Field Number As Integer) As String

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

Runge Ltd May, 2006 Page 262


XCM Reference Guide XPAC Functions and Subroutines

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

Function GetNumberOfPredecessors () As Long

Returns the number of predecessors a record has.


Example
Dim lRecordPredecessor As Long
Dim iActivityOfPredecessor As Integer
Dim iFromActivity As Integer

Call GetDependencies( iRecord )


Dim iNumOfPredecessor As Integer
iNumOfPredecessor = GetNumberOfPredecessors()

Dim i As Integer
For i = 0 To iNumOfPredecessor -1

iFromActivity = GetPredecessor( i, lRecordPredecessor, iActivityOfPredecessor)


Next i

GetNumberOfSuccessors

Runge Ltd May, 2006 Page 263


XCM Reference Guide XPAC Functions and Subroutines

Function GetNumberOfSuccessors () As Long

Returns the number of successors a record has.


Example
Dim lRecordSuccessor As Long
Dim iActivityOfSuccessor As Integer
Dim iFromActivity As Integer

Call GetDependencies( iRecord )


Dim iNumOfSuccessor As Integer
iNumOfSuccessor = GetNumberOfSuccessors()

Dim i As Integer
For i = 0 To iNumOfSuccessor -1

iFromActivity = GetSuccessor( i, lRecordSuccessor, iActivityOfSuccessor)


Next i

GetNumChildren

Function GetNumChildren(Record Number As Long, Optional Database Name as


Variant) As Long

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.

Database Name The Database Name is an optional argument. It is passed by


reference as a variant data type.
The Database Name is used to specify a different database. If the
Database Name is not specified, then the current database will be
used.
The database name may be provided as a string (in double quotes)
or it may be one of the options below.

Record Number Description


Options
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

Runge Ltd May, 2006 Page 264


XCM Reference Guide XPAC Functions and Subroutines

NXTSIB The next sibling under the same parent


PRV The previous sibling regardless of parents
NXT The next sibling regardless of parents

Database Name 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 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

Runge Ltd May, 2006 Page 265


XCM Reference Guide XPAC Functions and Subroutines

Function GetNumFields(Database Name As String) As Long

DESCRIPTION
Returns the number of Fields in the specified database.

GetNumRecords

Function GetNumRecords(Type of Records As Long, Database Name As Variant,


optional Record Number As Long) As Long

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.

Runge Ltd May, 2006 Page 266


XCM Reference Guide XPAC Functions and Subroutines

ACTIVE_RESULTS The active results database.

Record Number This is an optional argument that is passed to the function by


value as a long data type.
If the type of records (the first argument) is set to zero or two, the
record number will be ignored.
If the type of records (the first argument) is set to one, the function
returns the number of lowest level records underneath the
specified record number.
If the type of records (the first argument) is set to three, the
function returns the number of records at the same level as the
specified record number, regardless of their parents.

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)

Runge Ltd May, 2006 Page 267


XCM Reference Guide XPAC Functions and Subroutines

lNumBlks = GetNumRecords(1, "Main", lAreaRecNum)


Print "Area " & lArea & " has " & lNumBlks & " blocks."
Next lArea
End Sub

(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

Function GetOutputPathNoOfSteps(Scenario Name As String, Resource Name As


String, optional Range Name As String) As Long

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;

Runge Ltd May, 2006 Page 268


XCM Reference Guide XPAC Functions and Subroutines

• end of period markers; and


• end of schedule markers.
If a range name is passed to the function, then each step in the
specified output path is tested to determine whether it is in the
database range. The function then returns the sum of:
• the number of productive steps from the output path that are
within the database range;
• the end of period markers; and
• the end of schedule markers.
Non-productive steps are not included in the step count when a
range name is passed to the function. This rule applies even if the
range called “All” is passed in. For this reason, specifying the range
called “All” is different to not specifying a database range.

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

Runge Ltd May, 2006 Page 269


XCM Reference Guide XPAC Functions and Subroutines

(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

Function GetOutputRange ( ByVal ScenarioName As String, ByVal ResourceName As


String, ByVal InputStep As Long, optional ByRef FirstOutputStep As Long, optional
ByRef LastOutputStep As Long ) As Long

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.

StepType Number Title Uses

PE_PROD 1 Productive Step Percentage


PE_NONPROD 2 Non Productive Step TimeSpan
PE_ZEROPROD 3 Zero Production Step TimeSpan
PE_ROFF_NOP 4 Rostered Off Time TimeSpan
PE_ROFF_OP 6 Rostered Off Time TimeSpan
PE_EXTOP 5 Extended Operation Percentage
PE_EOP 98 End of Period
PE_EOS 99 End of Schedule
TBU_CALENDAR_TIME 0 Calendar time (Default)
TBU_ROSTER_TIME 1 Roster/Working time
TBU_OPERATING_TIME 2 Operating Time

' An Example of Getoutputrange


Sub Main ' Start Main Routine

Runge Ltd May, 2006 Page 270


XCM Reference Guide XPAC Functions and Subroutines

Dim sActScen As String ' Declare scenario


Dim lOutputRange As Long ' Declare Range
Dim sResourceName As String ' Declare Resource
Dim lNumRes As Long ' Declare number of resources
Dim lResNo As Long ' Declare repeating variable
Dim lStep As Long ' Declare repeating variable
Dim lStepNo As Long ' Declare number of steps
Dim sPthName As String ' Declare pathname
Dim bInputStep ' Declare input step
Dim vPath As InputPathStep ' Declare vPath
Dim lStepTypex As Long ' Declare Steptype
Dim lTaskid As Long ' Declare Task identification
Dim iActivity As Integer ' Declare activity number
Dim dDelay As Double ' Declare entered delay
Dim iDelayUnits As Integer ' Declare entered delay units
Dim dEntPct As Double ' Declare entered percentage
Dim dReleaseP As Double ' Declare release percentage
Dim sDestin As String ' Declare destination
If (IsFirstinRange())Then ' Only process once
sActScen = GetActiveScenarioName () ' Return active scenario
MsgBox sActScen,64,"Active Scenario" ' Display Answer
lNumRes = GetResourceCount( sActScen ) ' Count number of resources
If (lNumRes <= 0) Then ' Test if resources exist
MsgBox "No Resources in Scenario." ' Exit Sub
Else ' Resources exist
For lResNo = 1 To lNumRes ' Loop through all resources
' Retrieve resource name
sResourceName = GetResourceName(lResNo,sActScen)
' Retrieve inputpath name
sPthName = GetInputPathName(sActScen,sResourceName)
lStepNo = GetInputPathNoofSteps(sPthName)' Return no of input path steps
For lStep = 1 To lStepNo ' Loop through all steps
bInputStep =GetInputStep(sPthName,lStep,vPath)
' This section show the components of the steptype
lStepTypex= vPath.steptype ' Return Step type(SEE Table)
MsgBox lStepTypex,1,"StepType" ' Display Steptype
lTaskid = vPath.TaskID ' Return Productive Record number
MsgBox lTaskid,1,"TaskID" ' Display Productive Rec number
iActivity = vPath.Activity ' Return Productive activity
MsgBox iActivity,1,"Activity" ' Display Productive activity
dDelay = vPath.EnteredDelay ' Return Entered delay
MsgBox dDelay,1,"Entered Delay" ' Display Entered delay
iDelayUnits =vPath.EnteredDElayTimeBaseUnits
MsgBox iDelayUnits,1,"Time Units" ' Display delay time units
dEntPct = vPath.EnteredPct ' Return entered percentage
MsgBox dEntPct,1,"Entered Percent" ' Display entered percentage

Runge Ltd May, 2006 Page 271


XCM Reference Guide XPAC Functions and Subroutines

dReleaseP = vPath.ReleasedPct ' Return Released percentage


MsgBox dReleaseP,1,"Released Percent" ' Display Released percentage
sDestin = vPath.DestinationSP ' Return Destination
MsgBox lDestin,1,"Destination" ' Display Destination
' Getoutputrange function
lOutputRange = GetOutputRange(sActScen,sResourceName,bInputStep)
MsgBox lOutputRange,1,"outputrange"' Display message
Next lStep ' Next step
Next lResNo ' Next Resource
End If ' End resource construct
End If ' End is first in range Construct
End Sub ' End main routine
' End of XCM

RELATED FUNCTIONS
GetInputPathNoOfSteps, GetOutputPathNoOfSteps, GetInputStep, GetOutputStep,
GetOutputRangeForRecord

GetOutputRangeForPeriod

Function GetOutputRangeForPeriod ( ByVal ScenarioName As String, ByVal


ResourceName As String, ByVal Period As Long, optional ByRef FirstOutputStep As
Long, optional ByRef LastOutputStep As Long ) As Long

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

Function GetOutputRangeForRecord (ScenarioName As String, ResourceName As


String, lRecord As Long, iActivity As Integer, ByRef FirstOutputStep As Long, ByRef
LastOutputStep As Long ) As Boolean

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

Runge Ltd May, 2006 Page 272


XCM Reference Guide XPAC Functions and Subroutines

Function GetOutputStep ( ByVal ScenarioName As String, ByVal ResourceName As


String, ByVal Step As Long, ByRef OutStep As OutputPathStep ) As Boolean

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

StepType Number Title Uses


PE_PROD 1 Productive Step Percentage
PE_NONPROD 2 Non Productive Step TimeSpan
PE_ZEROPROD 3 Zero Production Step TimeSpan
PE_ROFF_NOP 4 Rostered Off Time TimeSpan
PE_ROFF_OP 6 Rostered Off Time TimeSpan
PE_EXTOP 5 Extended Operation Percentage
PE_EOP 98 End of Period
PE_EOS 99 End of Schedule
TBU_CALENDAR_TIME 0 Calendar time (Default)
TBU_ROSTER_TIME 1 Roster/Working time
TBU_OPERATING_TIME 2 Operating Time

Runge Ltd May, 2006 Page 273


XCM Reference Guide XPAC Functions and Subroutines

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

Function GetParam(Data Field Number As Integer, Record Number As Long) As


Double

DESCRIPTION

Runge Ltd May, 2006 Page 274


XCM Reference Guide XPAC Functions and Subroutines

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

Runge Ltd May, 2006 Page 275


XCM Reference Guide XPAC Functions and Subroutines

GetParamFromPil

Function GetParamFromPil(Data Field Number As Integer, Level 1 Pil As Integer,


optional Level 2 Pil As Integer, optional Level 3 Pil As Integer, optional Level 4 Pil As
Integer, optional Level 5 Pil As Integer, optional Level 6 Pil As Integer, optional Level 7
Pil As Integer, optional Level 8 Pil As Integer, optional Level 9 Pil As Integer, optional
Level 10 Pil As Integer) As Double

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.

Runge Ltd May, 2006 Page 276


XCM Reference Guide XPAC Functions and Subroutines

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

Function GetPctThroughPeriod ( ) As Double

Returns the progress of the current period as a percentage.

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

GetPeriodDuration(optional Period Number As Long, optional Calendar Database


Name As String, optional Start Date Field Number As Integer) As Double

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

Runge Ltd May, 2006 Page 277


XCM Reference Guide XPAC Functions and Subroutines

Database Name number. It is passed by value as a string data type.


The calendar database name is an optional argument. If it is not passed
into the function or it is passed in as an empty string, then it is assumed to
be the active calendar database.

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

Runge Ltd May, 2006 Page 278


XCM Reference Guide XPAC Functions and Subroutines

GetPeriodFromRecNum

Function GetPeriodFromRecNum(Record Number As Long, optional Calendar


Database Name As String) As Long

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.

Calendar The calendar database name is an optional argument. It is passed


Database Name by value as a string data type.
If the calendar database name is not passed in, then the function
will look for the specified record number in the active calendar
database.

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

Runge Ltd May, 2006 Page 279


XCM Reference Guide XPAC Functions and Subroutines

Dim lNumSteps As Long


'Find out how many schedule steps there are in each calendar period
For lYear = 2000 to 2020
sCalName = GetCalendarNameFromScenario("LOM Plan")
lPerRec = GetRecFromPilDB(sCalName, lYear)
lPerNum = GetPeriodFromRecNum(lPerRec, sCalName)
lNumSteps = GetOutputRangeForPeriod("LOM Plan", "Wst Miner", lPerNum)
Print lYear & " has " & lNumSteps & "schedule steps."
Next lYear
End Sub

RELATED FUNCTIONS
GetRecNumFromPeriod, GetRecNameFromPeriod, GetCalendarNameFromScenario,
GetOutputRangeForPeriod

GetPeriodRangeForResource

Function GetPeriodRangeForResource (ScenarioName As String, ResourceName As


String, ByRef FirstPeriod As Long, ByRef LastPeriod As Long ) As Boolean

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

Function GetPeriodRangeForScenario (ScenarioName As String, ByRef FirstPeriod


As Long, ByRef LastPeriod As Long) As Boolean

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

Runge Ltd May, 2006 Page 280


XCM Reference Guide XPAC Functions and Subroutines

Function GetPilFromPositionName(Optional Position Name As String, Optional Level


Number As Long, Optional Database Name As Variant, Optional Section Name As
String) As Long

DESCRIPTION
Returns the Position In Level (Pil) number for the specified position name by looking up the level in
the position table.

ARGUMENTS

Position Name The Position Name is an optional argument. It is passed by value as


a string data type. It represents the record name at the specified
level.
If no Position Name is specified, or if the position name is an empty
string, then the Position Name of the current record will be assumed.

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.

Database Name The Database Name is an optional argument. It can only be


specified if both the Position Name and the Level Number are
specified. The Database Name is passed by reference as a variant
data type.
If no Database Name is specified, or it is an empty string, then the
function will use the database over which the XCM is being run.
If a Database Name is specified, then the function will use that
database. The options listed below can also be passed into the
function as the Database Name.

SectionName The Section Name is an optional argument. It can only be specified


if the Position Name, the Level Number and the Database Name are
specified. The Section Name is passed by reference as a string data
type.
For the Main database, the section names are “Deposit”,
“Stockpiles” and “Dumps”. For other databases, this argument
should be omitted.

Options Description
ACTIVE_MAIN The main database.
ACTIVE_CALENDAR The active calendar database.
ACTIVE_RESULTS The active results database.

VALUES RETURNED

Runge Ltd May, 2006 Page 281


XCM Reference Guide XPAC Functions and Subroutines

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

(3) Find the pil number for the current material


Sub Main
Dim lMatPil As String
'Find the pil number for the current Material
lMatPil = GetPilFromPositionName("", THISLEVEL)
Print lMatPil
End Sub

RELATED FUNCTIONS
GetPositionNameFromPil, GetRecName, GetApil

GetPilFromPositionNameEx

Function GetPilFromPositionNameEx(optional Position Name As String, optional


Level Number As Long, optional Database Name As Variant, Optional Section Name As
String) As Long

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

Runge Ltd May, 2006 Page 282


XCM Reference Guide XPAC Functions and Subroutines

Position Name The Position Name is an optional argument. It is passed by value as


a string data type. It represents the record name at the specified
level.
If no Position Name is specified, or if the position name is an empty
string, then the Position Name of the current record will be assumed.

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.

Database Name The Database Name is an optional argument. It can only be


specified if both the Position Name and the Level Number are
specified. The Database Name is passed by reference as a variant
data type.
If no Database Name is specified, or it is an empty string, then the
function will use the database over which the XCM is being run.
If a Database Name is specified, then the function will use that
database. The options listed below can also be passed into the
function as the Database Name.

SectionName The Section Name is an optional argument. It can only be specified


if the Position Name, the Level Number and the Database Name are
specified. The Section Name is passed by reference as a string data
type.
For the Main database, the section names are “Deposit”,
“Stockpiles” and “Dumps”. For other databases, this argument
should be omitted.

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")

Runge Ltd May, 2006 Page 283


XCM Reference Guide XPAC Functions and Subroutines

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

Function GetPolygonArea ( ByRef Poly() As Vertex ) As Double

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.

Function GetPolygonAreaXY(Optional ByVal RecNum As Long, Optional ByVal


Activity As Long, Optional ByVal PolygonIndex As Long) As Double

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

Runge Ltd May, 2006 Page 284


XCM Reference Guide XPAC Functions and Subroutines

GetPolygonCentroid

Sub GetPolygonCentroid ( ByRef Poly() As Vertex, ByRef Centre As Vertex )

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.

Function GetPolygonCentroidXY(ByRef dX As Double, ByRef dY As Double, Optional


ByVal RecNum As Long, Optional ByVal Activity As Long, Optional ByVal
PolygonIndex As Long) As Boolean

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

Function GetPolygonCount ( optional ByVal RecNum As Long, optional ByVal Activity


As Long) As Long

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.

Runge Ltd May, 2006 Page 285


XCM Reference Guide XPAC Functions and Subroutines

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

Function GetPolygonVertexCount ( optional ByVal RecNum As Long, optional ByVal


Activity As Long, optional ByVal PolygonIndex As Long ) As Long

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.

Function GetPolygonVertexXYZ ( ByVal VertexNum As Long, optional ByRef X As


Double, optional ByRef Y As Double, optional ByRef Z As Double, optional ByVal
RecNum As Long, optional ByVal Activity As Long, optional ByVal PolygonIndex As
Long ) As Boolean

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

Function GetPositionNameFromPil(optional Pil Number As Long, optional Level


Number As Long, optional Database Name As Variant, Optional Section Name As
String) As String

Runge Ltd May, 2006 Page 286


XCM Reference Guide XPAC Functions and Subroutines

DESCRIPTION
Returns the position name for the specified Position In Level (Pil) number by looking up the level in
the position table.

ARGUMENTS

Pil Number The Pil Number is an optional argument. It is passed by value as a


long data type.
If no Pil Number is specified, or if the pre-defined value THISAPIL
is used, then the Pil Number of the current record will be assumed.
If a Database Name is specified, then THISAPIL should not be
used for the Pil Number as the function will return an empty string.

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.

Database Name The Database Name is an optional argument. It can only be


specified if both the Pil Number and the Level Number are
specified. The Database Name is passed by reference as a variant
data type.
If no Database Name is specified, or it is an empty string, then the
function will use the database over which the XCM is being run.
If a Database Name is specified, then the function will use that
database. The options listed below can also be passed into the
function as the Database Name.

SectionName The Section Name is an optional argument. It can only be specified


if the Position Name, the Level Number and the Database Name are
specified. The Section Name is passed by reference as a string data
type.
For the Main database, the section names are “Deposit”,
“Stockpiles” and “Dumps”. For other databases, this argument
should be omitted.

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.

Runge Ltd May, 2006 Page 287


XCM Reference Guide XPAC Functions and Subroutines

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

(3) Find the name of the current material.


Sub Main
Dim sMatName As String
'Find the name of the current Material
sMatName = GetPositionNameFromPil(THISAPIL, THISLEVEL)
Print sMatName
End Sub

RELATED FUNCTIONS
GetPilFromPositionName, GetRecName, GetApil

GetPositionNameFromPilEx

Function GetPositionNameFromPilEx(optional Pil Number As Long, optional Level


Number As Long, optional Database Name As Variant, Optional Section Name As
String) As String

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.

Runge Ltd May, 2006 Page 288


XCM Reference Guide XPAC Functions and Subroutines

ARGUMENTS

Pil Number The Pil Number is an optional argument. It is passed by value as a


long data type.
If no Pil Number is specified, or if the pre-defined value THISAPIL
is used, then the Pil Number of the current record will be assumed.
If a Database Name is specified, then THISAPIL should not be
used for the Pil Number as the function will return an empty string.

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.

Database Name The Database Name is an optional argument. It can only be


specified if both the Pil Number and the Level Number are
specified. The Database Name is passed by reference as a variant
data type.
If no Database Name is specified, or it is an empty string, then the
function will use the database over which the XCM is being run.
If a Database Name is specified, then the function will use that
database. The options listed below can also be passed into the
function as the Database Name.

SectionName The Section Name is an optional argument. It can only be specified


if the Position Name, the Level Number and the Database Name are
specified. The Section Name is passed by reference as a string data
type.
For the Main database, the section names are “Deposit”,
“Stockpiles” and “Dumps”. For other databases, this argument
should be omitted.

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.

Runge Ltd May, 2006 Page 289


XCM Reference Guide XPAC Functions and Subroutines

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

Function GetPredecessor (Pos as Integer, ByRef Record as Long, ByRef Act as


Integer) As Integer

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

Call GetDependencies( iRecord )


Dim iNumOfPredecessor As Integer
iNumOfPredecessor = GetNumberOfPredecessors()

Dim i As Integer
For i = 0 To iNumOfPredecessor -1
iFromActivity = GetPredecessor( i, lRecordPredecessor, iActivityOfPredecessor)

Next i

GetPSItem

Function GetPSItem(Scenario Name As String, Step Number As Long, Activity Number


As Long, Item As ItemRemoved) As Boolean

DESCRIPTION

Runge Ltd May, 2006 Page 290


XCM Reference Guide XPAC Functions and Subroutines

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.

Item This argument is passed to the function by reference using an


XPAC-defined data structure called ItemRemoved.
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 ItemRemoved data structure has the following elements.

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.

Runge Ltd May, 2006 Page 291


XCM Reference Guide XPAC Functions and Subroutines

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.

When this function is used, a variable should be passed in for the


Item argument. That variable must be declared as an
ItemRemoved type. For example:
Dim PSInfo As ItemRemoved.
After the function has been called, the elements of the
ItemRemoved structure can be referenced using the variable name,
followed by a full stop and then the relevant element name. For
example:
PSInfo.TaskID
PSInfo.ReleasedPct
PSInfo.MinedPct
Note: The inventory percentage for the specified activity and
record can be calculated at the end of the Preschedule as follows:
Inventory Percent = Released Percent – Mined Percent

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

Runge Ltd May, 2006 Page 292


XCM Reference Guide XPAC Functions and Subroutines

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

Runge Ltd May, 2006 Page 293


XCM Reference Guide XPAC Functions and Subroutines

GetPSItemCount
GetPSItemCount

Function GetPSItemCount(Scenario Name As String) As Long

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

(2) Find out whether each record is in the Preschedule table.


Sub Main
Const sACTNAME = "Development"
Dim lActNum As Long
Dim sActiveScenario As String
Dim lStepNum As Long
Dim dPSInfo As ItemRemoved
Dim sCurrentRec As String
'Find out how many steps there are in the Preschedule table and then
'loop through the steps from the first to the last.
lActNum = GetActivityNum(sACTNAME)

Runge Ltd May, 2006 Page 294


XCM Reference Guide XPAC Functions and Subroutines

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

Function GetRecFromName(Level 1 Name As String, optional Level 2 Name As String,


optional Level 3 Name As String, optional Level 4 Name As String, optional Level 5
Name As String, optional Level 6 Name As String, optional Level 7 Name As String,
optional Level 8 Name As String, optional Level 9 Name As String, optional Level 10
Name As String) As Long

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")

Runge Ltd May, 2006 Page 295


XCM Reference Guide XPAC Functions and Subroutines

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

Function GetRecFromNameDB(Database Name As Variant, Level 1 Name As String,


optional Level 2 Name As String, optional Level 3 Name As String, optional Level 4
Name As String, optional Level 5 Name As String, optional Level 6 Name As String,
optional Level 7 Name As String, optional Level 8 Name As String, optional Level 9
Name As String, optional Level 10 Name As String) As Long

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

Database Name The Database Name is an optional argument. It is passed


by reference as a variant data type.
The Database Name is used to specify a different database. If
the Database Name is not specified, then the current database
will be used.
The database name may be provided as a string (in double
quotes) or it may be one of the options below.

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.

Runge Ltd May, 2006 Page 296


XCM Reference Guide XPAC Functions and Subroutines

Database Name 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 requested record does not exist, then the function will return –1, but the XCM will not abort.

GetRecFromNameDBEx
GetRecFromNameDBEx

Function GetRecFromNameDBEx(Database Name As Variant, Level 0 Name As


String, optional Level 1 Name As String, optional Level 2 Name As String, optional
Level 3 Name As String, optional Level 4 Name As String, optional Level 5 Name As
String, optional Level 6 Name As String, optional Level 7 Name As String, optional
Level 8 Name As String, optional Level 9 Name As String, optional Level 10 Name As
String) As Long

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

Database Name The Database Name is an optional argument. It is passed


by reference as a variant data type.
The Database Name is used to specify a different database. If
the Database Name is not specified, then the current database
will be used.
The database name may be provided as a string (in double
quotes) or it may be one of the options below.

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.

Database Name Options Description


ACTIVE_MAIN The main database.

Runge Ltd May, 2006 Page 297


XCM Reference Guide XPAC Functions and Subroutines

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 requested record does not exist, then the function will return –1, but the XCM will not abort.

GetRecFromNameEx

Function GetRecFromNameEx(Level 0 Name As String, Level 1 Name As String,


optional Level 2 Name As String, optional Level 3 Name As String, optional Level 4
Name As String, optional Level 5 Name As String, optional Level 6 Name As String,
optional Level 7 Name As String, optional Level 8 Name As String, optional Level 9
Name As String, optional Level 10 Name As String) As Long

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.

Runge Ltd May, 2006 Page 298


XCM Reference Guide XPAC Functions and Subroutines

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

Function GetRecFromPil(Level 1 Pil As Long, optional Level 2 Pil As Long, optional


Level 3 Pil As Long, optional Level 4 Pil As Long, optional Level 5 Pil As Long, optional
Level 6 Pil As Long, optional Level 7 Pil As Long, optional Level 8 Pil As Long, optional
Level 9 Pil As Long, optional Level 10 Pil As Long) As Long

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)

Runge Ltd May, 2006 Page 299


XCM Reference Guide XPAC Functions and Subroutines

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

Function GetRecFromPilDB(Database Name As Variant, (Level 1 Pil As Long, optional


Level 2 Pil As Long, optional Level 3 Pil As Long, optional Level 4 Pil As Long, optional
Level 5 Pil As Long, optional Level 6 Pil As Long, optional Level 7 Pil As Long, optional
Level 8 Pil As Long, optional Level 9 Pil As Long, optional Level 10 Pil As Long) As Long

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.

Runge Ltd May, 2006 Page 300


XCM Reference Guide XPAC Functions and Subroutines

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

Function GetRecFromPilEx(Level 0 Pil As Long, Level 1 Pil As Long, optional Level 2


Pil As Long, optional Level 3 Pil As Long, optional Level 4 Pil As Long, optional Level 5
Pil As Long, optional Level 6 Pil As Long, optional Level 7 Pil As Long, optional Level 8
Pil As Long, optional Level 9 Pil As Long, optional Level 10 Pil As Long) As Long

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.

Runge Ltd May, 2006 Page 301


XCM Reference Guide XPAC Functions and Subroutines

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

Function GetRecName(Record Number As Long, Name Type As Integer, Optional


Database Name As Variant) As String

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

Runge Ltd May, 2006 Page 302


XCM Reference Guide XPAC Functions and Subroutines

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

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:

Name Type Options Description


RECORDNAME The name of the record at that level. For example, RL550.
PATHNAME The name of the record at each level, separated by forward
slashes. For example, Pit8\9\RL550.
FULLNAME The record number followed by the path name of the record.
For example, 256: Pit8\9\RL550.

Database The Database Name is an optional argument. It is passed by


Name reference as a variant data type.
The Database Name is used to specify a different database. If the
Database Name is not specified, then the current database will be used.
The database name may be provided as a string (in double quotes) or it
may be one of the options below.

Database Name 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 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.

Runge Ltd May, 2006 Page 303


XCM Reference Guide XPAC Functions and Subroutines

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

(2) Print the path name for the current record.


Sub Main
'Print the path name for the current record.
Print GetRecName(CURRENT, PATHNAME)
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

Function GetRecNameAtLevel(Level Number As Integer, optional Starting Record As


Long, Optional Database Name As Variant) As String

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.

Runge Ltd May, 2006 Page 304


XCM Reference Guide XPAC Functions and Subroutines

Starting Record The starting record is defined as a record number and it is an


optional argument. It is passed into the function by value as
a long data type.
The starting record is used to define the record number at, or
above, which level the record name will be returned. If it is
not specified, then it is assumed to be the current record.

Database Name The Database Name is an optional argument. It is passed


by reference as a variant data type.
The Database Name is used to specify a different database. If
the Database Name is not specified, then the current database
will be used.
The database name may be provided as a string (in double
quotes) or it may be one of the options below.

Database Name 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 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

Runge Ltd May, 2006 Page 305


XCM Reference Guide XPAC Functions and Subroutines

Dim lNextRec As Long


Dim sBnchNameNextRec As String
sBnchNameThisRec = GetRecNameAtLevel(lBENCH)
lNextRec = GetRecNum(NXT)
sBnchNameNextRec = GetRecNameAtLevel(lBENCH, lNextRec)
If (sBnchNameThisRec <> sBnchNameNextRec) Then
Call MsgBox("New Bench Encountered")
End If
End Sub

RELATED FUNCTIONS
GetRecName, GetRecFromName, GetRecNumAtLevel

GetRecNameFromPeriod

Function GetRecNameFromPeriod(Period Number As Long, optional Name Type As


Integer, optional Calendar Database Name As String) As Variant

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.

Runge Ltd May, 2006 Page 306


XCM Reference Guide XPAC Functions and Subroutines

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

Function GetRecNum(Optional Record Pointer As Long, Optional Starting Record As


Long, Optional Database Name As String) As Long

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)

Runge Ltd May, 2006 Page 307


XCM Reference Guide XPAC Functions and Subroutines

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

Runge Ltd May, 2006 Page 308


XCM Reference Guide XPAC Functions and Subroutines

(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

Function GetRecNumAtLevel(Level Number As Integer, Optional Starting Record As


Long, Optional Database Name As Variant) As Long

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.

Starting Record The starting record is defined as a record number and it is an


optional argument. It is passed into the function by value as
a long data type.
The starting record is used to define the record number at, or
above, which level the record number will be returned. If it
is not specified, then it is assumed to be the current record.

Database Name The Database Name is an optional argument. It is passed


by reference as a variant data type.
The Database Name is used to specify a different database. If
the Database Name is not specified, then the current database
will be used.
The database name may be provided as a string (in double
quotes) or it may be one of the options below.

Database Name Options Description


ACTIVE_MAIN The main database.
ACTIVE_CALENDAR The active calendar database.
ACTIVE_RESULTS The active results database.

Runge Ltd May, 2006 Page 309


XCM Reference Guide XPAC Functions and Subroutines

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

Function GetRecNumFromPath(Path Name As String, optional Database Name As


Variant) As Long

Runge Ltd May, 2006 Page 310


XCM Reference Guide XPAC Functions and Subroutines

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. “”.

Database Name The Database Name is an optional argument. It is passed by


reference as a variant data type.
The Database Name is used to specify a different database. If the
Database Name is not specified, then the current database will be
used.
The database name may be provided as a string (in double quotes) or
it may be one of the following options.

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

(2) Get the record number for a record in a different database.


Sub Main
'Get the record number for the next drive in the same panel, from
'the Panel\Drive Parameters database.
Dim sNextDriveName As String
Dim sParamDbPath As String
sNextDriveName = "Drv" & CStr(lDriveNum + 1)
sParamDbPath = sPanelName & "\" & sNextDriveName
Print GetRecNumFromPath(sParamDbPath, "Panel\Drive Parameters")

Runge Ltd May, 2006 Page 311


XCM Reference Guide XPAC Functions and Subroutines

End Sub

RELATED FUNCTIONS
GetRecNum, GetRecNumAtLevel, GetRecName

GetRecNumFromPeriod

Function GetRecNumFromPeriod(Period Number As Long, optional Calendar


Database Name As String) As Long

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

Runge Ltd May, 2006 Page 312


XCM Reference Guide XPAC Functions and Subroutines

'The period targets could then be compared to the scheduled quantities


End Sub

RELATED FUNCTIONS
GetPeriodFromRecNum, GetRecNameFromPeriod, GetCalendarNameFromScenario,
GetOutputRangeForPeriod

GetResourceCount

Function GetResourceCount(optional Scenario Name As String) As Long

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

(2) Loop through the resources in a scenario.


Sub Main
Const sSCENARIO = "Three Year Schedule"
Dim lNumResources As Long
Dim lResource As Long
Dim sResource() As String
'Read the names of the resources and then store them in a string array
lNumResources = GetResourceCount(sSCENARIO)
ReDim sResource(lNumResources)
For lResource = 1 to lNumResources

Runge Ltd May, 2006 Page 313


XCM Reference Guide XPAC Functions and Subroutines

sResource(lResource) = GetResourceName(lResource, sSCENARIO)


Next lResource
End Sub

RELATED FUNCTIONS
GetResourceName, Error! Reference source not found., GetOutputStep

GetResourceLocation

Sub GetResourceLocation ( ByVal sResourceName As String, ByRef lRecord As Long,


ByRef iActivity As Integer)

This function can only be used in User Processing Scripts it returns the location of a resource.

ARGUMENTS

sResourceName The name of the resource

lRecord The resources current location

iActivity The resources current activity

Example:
Dim lRecord as Long
Dim iActivity as Integer
call GetResouceLocation(“Ore”, lRecord, iActivity)

GetResourceName

Function GetResourceName(Resource Number As Long, optional Scenario Name As


String) As Variant

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.

Runge Ltd May, 2006 Page 314


XCM Reference Guide XPAC Functions and Subroutines

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

(2) Read the names of all resources in the specified scenario.


Sub Main
Const sSCENARIO = "Three Year Schedule"
Dim lNumResources As Long
Dim lResource As Long
Dim sResource() As String
'Read the names of the resources and then store them in a string array
lNumResources = GetResourceCount(sSCENARIO)
ReDim sResource(lNumResources)
For lResource = 1 to lNumResources
sResource(lResource) = GetResourceName(lResource, sSCENARIO)
Next lResource
End Sub

RELATED FUNCTIONS
GetResourceCount, Error! Reference source not found., GetOutputStep

GetResourceRoster

Function GetResourceRoster ( ByVal ScenarioName As String, ByVal ResourceName


As String, ByRef RosterName as Variant, ByRef RosterExceptionName as Variant) As
Boolean

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.

Runge Ltd May, 2006 Page 315


XCM Reference Guide XPAC Functions and Subroutines

EXAMPLES

Dim sRoster As String


Dim sRosterEx As String
Dim sScenario As String
Dim sResource As String
Dim sMsg As String

sScenario = "Production Schedule"


sResource = "Dragline"

' Get the Resource Roster and Display it in a Msg Box


If GetResourceRoster(sScenario, sResource, sRoster, sRosterEx) Then
' sRoster and sRosterEx contain the Roster and Roster Exception for
' sScenario/sResource
Dim sMsg1 As String
Dim sMsg2 As String
sMsg1 = sScenario + " " + sResource
sMsg2 = "Roster: "+ sRoster + ", Roster Exception: " + sRosterEx
sMsg = sMsg1 + sMsg2
MsgBox sMsg
Else
sMsg = "For " + sScenario + ", " + sResource + " : Lookup Failed"
MsgBox sMsg
End If

GetRosterHrs

Function GetRosterHrs ( ByVal RosterName As String, ByVal RosterExceptionName


As String, ByVal StartDate as Double, ByVal EndDate as Double ) As Double

DESCRIPTION
Returns the number of rostered hours performed within the two supplied dates for the specified roster
and roster exception.

' Calculate the Rostered Hours for the Roster “Roster”


‘ and the roster exception “RosterEx”
Dim StartDate As Date
Dim EndDate As Date
Dim Hours as Double
StartDate = CDate ("September 17, 2001 9:00 am")
EndDate = CDate ("October 1,2001 9:00 am")

' "Roster" is a standard 8 hr roster


' "RosterEx" is a public holiday on 19 September 2001
Hours = GetRosterHours("Roster","RosterEx",StartDate,EndDate)

Runge Ltd May, 2006 Page 316


XCM Reference Guide XPAC Functions and Subroutines

‘ Hours should be 72.

GetRowCodeFromNum

Function GetRowCodeFromNum(Database Name As String, Row Number As Long) As


Variant

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

Function GetRowNumFromCode(Database Name As String, Data Field Full Row Code


As String) As Long

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.

Runge Ltd May, 2006 Page 317


XCM Reference Guide XPAC Functions and Subroutines

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

Function GetScheduleStartPeriod ( ) As Long

Returns the Schedule Start Period.


REMARKS
This function is available only in the User Processing Scripts.

GetScriptExecutionRange

Function GetScriptExecutionRange() As Variant

DESCRIPTION

Runge Ltd May, 2006 Page 318


XCM Reference Guide XPAC Functions and Subroutines

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

Function GetScriptName() As Variant

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

Runge Ltd May, 2006 Page 319


XCM Reference Guide XPAC Functions and Subroutines

RELATED FUNCTIONS
GetCurrentDirectory, GetDatabaseName, GetFullModelName, GetRecName

GetScriptsDirectory

Function GetScriptsDirectory() As String

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

Function GetSourceABLCount App ( Optional ByVal lActivity As Long, Optional


ByVal bAvailable As Boolean, Optional ByVal sResource As String ) As Integer"

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

Function GetSPCreationDate ( ByRef dCreated As Double, ByRef dFinished As


Double) As Boolean

This function can only be called from a Stockpile Creation Script.


Refer to the stockpile settings in schedule setup.
Returns True if successful.
Example:
Dim dStart as Double
Dim dEnd As Double
‘Get Creation Date
GetSPCreationDate dStart, dEnd
‘Store Creation Date and Period Number in Stockpile Record
M(mStartDt) = dStart

Runge Ltd May, 2006 Page 320


XCM Reference Guide XPAC Functions and Subroutines

M(mEndDt) = dEnd
M(mPeriodNo) = GetCurrentPeriod

GetSuccessor

Function GetSuccessor (Pos as Long, Record as Long, Act as Integer) As Long

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

Call GetDependencies( iRecord )


Dim iNumOfSuccessor As Integer
iNumOfSuccessor = GetNumberOfSuccessors()

Dim i As Integer
For i = 0 To iNumOfSuccessor -1

iFromActivity = GetSuccessor( i, lRecordSuccessor, iActivityOfSuccessor)


Next i

GetTrackingField

Function GetTrackingField (ByVal FieldNo as Long, Optional ByVal ActivityNum As


Long, Optional ByVal sRangeName As String, Optional ByVal sResourceName As
String) As Double

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

FieldNo Field Number you want to track.

ActivityNum The Activity Number you want to track. To track All Activities,
specify 0 here.

RangeName The Range to Track In.

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.

Runge Ltd May, 2006 Page 321


XCM Reference Guide XPAC Functions and Subroutines

RELATED FUNCTIONS
InitTrackingField

GetValue

Function GetValue (ByVal iFieldNo As Integer, ByVal iPeriod As Integer) As Double

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

Function GetVertexEOS ( ByRef V As Vertex ) As Boolean

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

Function GetVertexEOSA ( ByRef Poly() As Vertex, ByVal Index As Long ) As Boolean

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

Function GoRec(Record Pointer As Long) As Boolean

DESCRIPTION
Returns a True value if the requested record is made the current record.

ARGUMENT

Runge Ltd May, 2006 Page 322


XCM Reference Guide XPAC Functions and Subroutines

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

(2) Find the next record that contains ore.


Remember that GoRec returns a False value if the record does not exist.
Sub Main
Dim lNextRecNum As Long

Runge Ltd May, 2006 Page 323


XCM Reference Guide XPAC Functions and Subroutines

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

Function IIf(Expression As Boolean, True Value As Variant, False Value As Variant) As


Variant

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

Runge Ltd May, 2006 Page 324


XCM Reference Guide XPAC Functions and Subroutines

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

Function Import(FileName As String, CollectionType as String) As Boolean

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.

Runge Ltd May, 2006 Page 325


XCM Reference Guide XPAC Functions and Subroutines

Collection Type Name Comments


Activities Includes productive and non-
productive activities.
Databases Includes the following:
• Field definitions
• Record structure
• Record values
• Level structure
Activity Schedules
Capacity Constraints
Curves
Dependency Rule Sets
Dumps
Dump Paths
Field Selections
Feature Layers
Gantt Charts
Global Options
Global Variables
Input Paths
Macros
Period Constraints
Period Delays
Polygon Graphics Plots
Polygon Coordinate Sets
Proximity Constraints
Ranges
Resources
Reports
Rosters
Roster Exceptions
Scenarios
Stockpiles

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.

Runge Ltd May, 2006 Page 326


XCM Reference Guide XPAC Functions and Subroutines

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

Function InitTrackingField (ByVal FieldNo as Long, Optional ByVal ActivityNum As


Long, Optional ByVal sRangeName As String, Optional ByVal sResourceName As
String) As Boolean

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

Runge Ltd May, 2006 Page 327


XCM Reference Guide XPAC Functions and Subroutines

supported in XPAC 2003 onwards. Every time a Record is mined the Progress Tracking Field(s) will
be updated.

ARGUMENTS

FieldNo Field Number you want to track.

ActivityNum The Activity Number you want to track. To track All Activities,
specify 0 here.

RangeName The Range to Track In.

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.

Function InPoly(ByVal dX As Double, ByVal dY As Double, ByRef adXArray() As


Double, ByRef adYArray() As Double, Optional ByVal dEdgeWidth As Double, Optional
ByVal lMode As Long) As Boolean

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

Runge Ltd May, 2006 Page 328


XCM Reference Guide XPAC Functions and Subroutines

Dim iCrkRow As Integer ' Creek row number


Dim bInside As Boolean ' Flag variable
Dim iNumPts As Integer ' Points in record polygon
Dim iEachPnt As Integer ' Loop Value
Dim dTest As Double ' Variable for vertex array
Dim lCurrRec As Long ' Record number
Dim dDummy As Double ' Dummy variable
Dim lOBRec As Long ' Overburden Record Number
Dim bDoneInit As Boolean ' Boolean Initiation variable
Sub Main ' Start main Routine
ClearData mCrk ' Clear Data Row
If bDoneInit = false Then ' Check for initialisation
Init ' Read in array from Init subroutine
bDoneInit=true ' set flag so array is not read twice
End If ' End Construct
lCurrRec= GetRecNum(Current) ' Current Record Number
dEast = m(mEasting) ' Easting Of Blocks Centroid
dNorth = m(mNorthing) ' Northing Of Blocks Centroid
iCrkRow = mCrk ' Row used As Creek Zone Flag
' Initially test if the centroid of the block is in the polygon
bInside = InPoly(dEast,dNorth,dEPnt,dNPnt)
' Returns a value of one if is true
' Then test to see if any point within the block is inside the polygon.
If (bInside = 0) Then ' If Centoid Is Not In Creek Zone
Test ' Call test subroutine
End If ' End Point Query construct
m(mCrk) = Abs(bInside) ' Set Creek Zone Flag
End Sub ' End Main Subroutine
Sub Test() ' Start test subRoutine
' Find number of Points from polygon information
iNumPts = GetPolygonVertexCount(lCurrRec)
' But are any of the points within the exclusion polygon
For iEachPnt = 1 To iNumPts Step 1
' Repeat for Each Point In Polygon
dDummy = GetPolygonVertexXYZ(iEachPnt,dEast,dNorth)
' Return Coordinate Variable
bInside = InPoly(dEast,dNorth,dEPnt,dNPnt)
' Calculate if the block is within
If (bInside =-1) Then
Exit Sub
End If
Next iEachPnt ' Process Next Point In Blocks Polygon
End Sub ' End Main Subroutine
Sub Init() ' Polygon Array with 9 points
dEPnt(1) = 92871 ' Assign X Coordinate Of Point
dEPnt(2) = 92867 ' Assign X Coordinate Of Point

Runge Ltd May, 2006 Page 329


XCM Reference Guide XPAC Functions and Subroutines

dEPnt(3) = 92880 ' Assign X Coordinate Of Point


dEPnt(4) = 92885 ' Assign X Coordinate Of Point
dEPnt(5) = 92846 ' Assign X Coordinate Of Point
dEPnt(6) = 92837 ' Assign X Coordinate Of Point
dEPnt(7) = 92805 ' Assign X Coordinate Of Point
dEPnt(8) = 92789 ' Assign X Coordinate Of Point
dEPnt(9) = 92810 ' Assign X Coordinate Of Point
dEPnt(10) = 92871 ' Assign X Coordinate Of Point
dNPnt(1) = 79249 ' Assign Y Coordinate Of Point
dNPnt(2) = 79328 ' Assign Y Coordinate Of Point
dNPnt(3) = 79422 ' Assign Y Coordinate Of Point
dNPnt(4) = 79471 ' Assign Y Coordinate Of Point
dNPnt(5) = 79550 ' Assign Y Coordinate Of Point
dNPnt(6) = 79626 ' Assign Y Coordinate Of Point
dNPnt(7) = 79729 ' Assign Y Coordinate Of Point
dNPnt(8) = 79818 ' Assign Y Coordinate Of Point
dNPnt(9) = 79941 ' Assign Y Coordinate Of Point
dNPnt(10) = 79249 ' Assign Y Coordinate Of Point
End Sub

RELATED FUNCTIONS
GetPolygonVertexCount, GetPolygonVertexXYZ, GetPolygonCentroidXY, InPoly, InPolyRec

InPolyRec
Note – This function has been superseded by the PointInPolygon function.

Function InPolyRec(ByVal dX As Double, ByVal dY As Double, Optional ByVal


RecNum As Long, Optional ByVal Activity As Long, Optional ByVal PolygonIndex As
Long, Optional ByVal dEdgeWidth As Double, Optional ByVal lMode As Long) As
Boolean

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

Runge Ltd May, 2006 Page 330


XCM Reference Guide XPAC Functions and Subroutines

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

Alternate (Even-odd) Winding

InsertIntoInputPath

Function InsertIntoInputPath(Input Path Name As String, Step Number As Long,


Step Information As InputPathStep) As Long

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

Runge Ltd May, 2006 Page 331


XCM Reference Guide XPAC Functions and Subroutines

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.

Step Information This argument is passed to the function by reference using an


XPAC-defined data structure called InputPathStep.
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 InputPathStep data structure has the following elements.

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.

Runge Ltd May, 2006 Page 332


XCM Reference Guide XPAC Functions and Subroutines

• 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.
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 passed to the function
as a double data type.
• For productive steps, the released percent should be
between 0 and 1.
• For non-productive steps, the released percent is ignored.
DestinationSP The destination stockpile is the name of the stockpile to which this
step is being sent. It is passed in as a string data type.
• For productive steps the destination stockpile should be the
name of the stockpile or an empty string. It is not possible to
set the destination stockpile to a classified field using this
function.
• For non-productive steps, the destination stockpile is
ignored.
ProdRate The production rate is a factor that is applied to the entered
production rate for the resource, to derate it or to increase it. It is
passed to the function as a double data type.
• For productive steps, the production rate factor should be
greater than zero. It can also be greater than one if the
production rate needs to be increased.
• For non-productive steps, the production rate factor is
ignored.

When this function is used, a variable should be passed in for the


Step Information argument. That variable must be declared as an
InputPathStep type. For example:
Dim NewPathInfo As IputPathStep.
Before the function is called, the elements of the InputPathStep
structure should be assigned using the variable name, followed by
a full stop and then the relevant element name. For example:
NewPathInfo.StepType
NewPathInfo.Activity
NewPathInfo.DestinationSP

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

Runge Ltd May, 2006 Page 333


XCM Reference Guide XPAC Functions and Subroutines

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

(2) Create a new input path from an existing input path.


Sub Main
Dim bStepFound As Boolean
Dim lOldStep As Long
Dim StepInfo As InputPathStep
Dim lNewStep As Long
'Read the first step details from the existing input path.
lOldStep = 1
bStepFound = GetInputStep("FEL Wst and Ore", lOldStep, StepInfo)
Do While (bStepFound = True)
'Insert the activity 1 steps into the new input path.
If (StepInfo.Activity = 1) Then
lNewStep = InsertIntoInputPath("FEL Wst", lNewStep + 1, StepInfo)
End If
'Read the next step from the existing input path.
lOldStep = lOldStep + 1
bStepFound = GetInputStep("FEL Wst and Ore", lOldStep, StepInfo)
Loop
End Sub

RELATED FUNCTIONS
GetInputStep, Error! Reference source not found., GetInputPathNoOfSteps, ClearInputPath

InsertResourceDelay

Function InsertResourceDelay(Duration as Double[, NonProductiveActivity as


Integer][, EnteredDelayTimeBase Units as Integer][, [Resource Name as String])

Runge Ltd May, 2006 Page 334


XCM Reference Guide XPAC Functions and Subroutines

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

Duration The duration of the delay in days or parts of days.

NonProductive This parameter describes the non-productive activity which will be


Activity inserted as the delay.

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.

' THIS USER PROCESSING SCRIPT IS A PRE BLOCK SCRIPT

' 4 shifts = 32 hours = 1.333 day


' Panel extension is non-productive activity 106
' TBU - rostered time

Call InsertResourceDelay(1.333, 106, 1)

(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.

Runge Ltd May, 2006 Page 335


XCM Reference Guide XPAC Functions and Subroutines

' THIS USER PROCESSING SCRIPT IS A PRE BLOCK SCRIPT

If (lBlockNum = 3) Then

' Drivehead installation is non-productive activity 104


' TBU - calendar time

Call InsertResourceDelay(14.0, 104, 0, "CM1 [SP]")

End If

RELATED FUNCTIONS
ChangeProductionRate, ChangeRoster

IsCombinationConstrained
IsCombinationConstrained

Function IsCombinationConstrained(ByVal lSourceRecord As Long, ByVal iActivity


As Integer, ByVal lDestinationRecord As Long, Optional ByVal sResources As String,
Optional ByRef sConstraintDetails As String) As Boolean

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

lSourceRecord The record number of the source task to query.

iActivity The activity of the source task to query.

lDestinationRecord The record number of the destination to query.

sResources The name of the resource for which to evaluate the


constraints. If not specified or an empty string, the
current resource is used.

sConstraintDetails If specified, the names of the capacity and period


constraints that are constraining the specified task for the
specified resource will be returned.

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

Runge Ltd May, 2006 Page 336


XCM Reference Guide XPAC Functions and Subroutines

Function IsFirst() As Boolean

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

(2) Use IsFirst to clear an accumulation variable.


'Declare a script variable to accumulate the drill metres within a Panel.
Dim dCumDrillMtr As Double

Runge Ltd May, 2006 Page 337


XCM Reference Guide XPAC Functions and Subroutines

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

Function IsFirstInRange() As Boolean

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

(2) Display a message at the beginning of an XCM.


Sub Main
If (IsFirstInRange()) Then
'Display a warning message at the start of the XCM.
Dim lResponse As Long
Const sMSG = "This XCM Clears the ROM Reserves."

Runge Ltd May, 2006 Page 338


XCM Reference Guide XPAC Functions and Subroutines

lResponse = MsgBox(sMSG, MB_OKCANCEL, "WARNING")


If (lResponse = IDCANCEL) Then Abort "The XCM was not Processed."
End If
End Sub

RELATED FUNCTIONS
IsLastInRange, IsFirst, GetFirstInRange

IsInRange

Function IsInRange (sRange As String) As Boolean

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

Function IsLast() As Boolean

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.

Runge Ltd May, 2006 Page 339


XCM Reference Guide XPAC Functions and Subroutines

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

Function IsLastInRange() As Boolean

Runge Ltd May, 2006 Page 340


XCM Reference Guide XPAC Functions and Subroutines

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

(2) Display a message at the end of an XCM.


'Declare the Cumulative Low Grade Ore as a Script Variable.
Dim dCumLGOre As Double
Sub Main
'Accumulate the Low Grade Ore.
dCumLGOre = dCumLGOre + M(mOre_LG_Ton)
If (IsLastInRange()) Then
'Display a message if there is any Low Grade Ore in the deposit.
If (dCumLGOre > 0) Then
Dim sMsg As String
sMsg = "Deposit Contains " & CStr(dCumLGOre) & "t Low Grade Ore"
Call MsgBox(sMsg, MB_OK, "Attention.")
End If
End If
End Sub

RELATED FUNCTIONS
IsLast, IsFirstInRange, GetNextInRange

IsTaskConstrained

Runge Ltd May, 2006 Page 341


XCM Reference Guide XPAC Functions and Subroutines

Function IsTaskConstrained(ByVal lRecord As Long, ByVal iActivity As Integer,


Optional ByVal sResources As String, Optional ByRef sConstraintDetails As String) As
Boolean

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

lRecord The record number of the task to query.

iActivity The activity of the task to query.

sResources The name of the resource for which to evaluate the


constraints. If not specified or an empty string, the
current resource is used.

sConstraintDetails If specified, the names of the capacity and period


constraints that are constraining the specified task for the
specified resource will be returned.

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

Function IsTaskReserved(ByVal lRecord As Long, ByVal iActivity As Integer, Optional


ByRef dTotalReservedPct As Double, Optional ByRef sResources As String) As Boolean

DESCRIPTION
Returns True if the specified task (record number and activity) is currently reserved to be mined by one
or more resources.

ARGUMENTS

lRecord The record number of the task to query.

iActivity The activity of the task to query.

sResources If specified, upon return will contain the total percentage


of the block (0 – 100) that has been reserved by
resources.

sConstraintDetails If specified, upon return will contain the resource(s) that


have reserved part or all of the specified task.

VALUES RETURNED
The function returns a boolean data type.

Runge Ltd May, 2006 Page 342


XCM Reference Guide XPAC Functions and Subroutines

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

Function IsValidRecNum(Record Number As Long, Optional Database Name As


Variant) As Boolean

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.

Database Name The Database Name is an optional argument. It is passed


by reference as a variant data type.
The Database Name is used to specify a different database. If
the Database Name is not specified, then the current database
will be used.
The database name may be provided as a string (in double
quotes) or it may be one of the options below.

Database Name Options Description


ACTIVE_MAIN The main database.
ACTIVE_CALENDAR The active calendar database.
ACTIVE_RESULTS The active results database.

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

Runge Ltd May, 2006 Page 343


XCM Reference Guide XPAC Functions and Subroutines

(2) Find out whether the adjacent records exist.


Sub Main
Dim lDrivePlus1Rec As Long
Dim lDriveMinus1Rec As Long
'Use the current Drive and Block numbers to look up the same
'Block in the adjacent Drives.
lDrivePlus1Rec = GetRecFromPil(lPanelNum, lDriveNum+1, lBlockNum)
lDriveMinus1Rec = GetRecFromPil(lPanelNum, lDriveNum-1, lBlockNum)
'If either of the adjacent Blocks exist, then set a data field
If (IsValidRecNum(lDrivePlus1Rec) Or IsValidRecNum(lDriveMinus1Rec)) Then
Call SetClass(mAdj_Blk_Exist, "Yes")
End If
End Sub

RELATED FUNCTIONS
GetRecNum, GetRecNumFromPath, GetRecFromPil

LastCompletedTask

Function LastCompletedTask() As Boolean

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

Function LastStartedTask() As Boolean

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

Runge Ltd May, 2006 Page 344


XCM Reference Guide XPAC Functions and Subroutines

LastCompletedTask, FirstCompletedTask, FirstStartedTask, FirstTask, LastTask

LastTask

Function LastTask() As Boolean

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

Function LoadPolygon ( ByRef Poly() As Vertex, optional ByVal RecNum As Long,


optional ByVal Activity As Long, optional ByVal PolygonIndex As Long ) As Long

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

Runge Ltd May, 2006 Page 345


XCM Reference Guide XPAC Functions and Subroutines

Dim M(1 to Field Count) As Double

Dim C(1 to Field Count) As Double

Dim P(1 to Field Count) As Double

Dim R(1 to Field Count) As Double

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.

Record If the data field is a record field type, then the


accessor will return the record number.

MakeRGB

Function MakeRGB(Red Value As Integer, Green Value As Integer, Blue Value As


Integer) As Long

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.

Runge Ltd May, 2006 Page 346


XCM Reference Guide XPAC Functions and Subroutines

Colour Red Value Green Value Blue Value


Black 0 0 0
Blue 0 0 255
Green 0 255 0
Cyan 0 255 255
Red 255 0 0
Magenta 255 0 255
Yellow 255 255 0
White 255 255 255
Grey 127 127 127

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

Sub OffsetPolygon ( ByRef Poly() As Vertex, ByVal X As Double, ByVal Y As Double,


ByVal Z As Double )

Offsets the specified polygon by the distance specified in X, Y and Z.

RELATED FUNCTIONS
LoadPolygon, SavePolygon, GetPolygonCount, GetPolygonVertexCount, ScalePolygon

Runge Ltd May, 2006 Page 347


XCM Reference Guide XPAC Functions and Subroutines

OpeningDumpCapacity

Function OpeningDumpCapacity (ByVal FieldNo As Integer) As Double

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

Function OpeningInv (ByVal FieldNo As Integer) As Double

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

Function OpeningInvSP (ByVal FieldNo As Integer) As Double

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

Function OperatingHrs () As Double

Returns the accumulated productive and non-productive operating hours for all steps passed by the
filter.

OriginalValue

Function OriginalValue (ByVal FieldNo As Integer, ByVal L0 as Long, Optional ByVal


L1 as Long, Optional ByVal L2 as Long, Optional ByVal L3 as Long, Optional ByVal L4
as Long, Optional ByVal L5 as Long, Optional ByVal L6 as Long, Optional ByVal L7 as
Long, Optional ByVal L8 as Long, Optional ByVal L9 as Long, Optional ByVal L10 as
Long) As Variant

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

Function PeriodEnd () As Double

Returns the period end date.

PeriodStart

Function PeriodStart () As Double

Returns the period start date.

Runge Ltd May, 2006 Page 348


XCM Reference Guide XPAC Functions and Subroutines

Pil

Function Pil (ByVal Level As Integer, ByVal Pos As Integer) As Boolean

Used to only pass record that have the specified position in level number at the specified database level.

PointInPolygon

Function PointInPolygon ( ByRef Poly() As Vertex, ByRef Point As Vertex, optional


ByVal EdgeWidth As Double, optional ByVal Mode As Long ) As Boolean

Determines if the given point is inside the polygon.


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.

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

Function PolygonArithmetic (ByRef ResultPoly() As Vertex, ByRef Poly1() As Vertex,


ByVal Operation As Long, ByRef Poly2() As Vertex ) As Long

Runge Ltd May, 2006 Page 349


XCM Reference Guide XPAC Functions and Subroutines

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

LoadPolygon Poly1, CURRENT, 1


LoadPolygon Poly1, CURRENT, 2

PolygonArithmetic Result, Poly1, PA_INTERSECTION, Poly2

SavePolygon Result, CURRENT, 3

End Sub

RELATED FUNCTIONS
LoadPolygon, SavePolygon, GetPolygonCount, GetPolygonVertexCount

Example 1 Example 2 Example 3

Polygon 1

Polygon2

Operation

PA_UNION

Runge Ltd May, 2006 Page 350


XCM Reference Guide XPAC Functions and Subroutines

PA_INTERSECTION

PA_REMAINDER

Runge Ltd May, 2006 Page 351


XCM Reference Guide XPAC Functions and Subroutines

QBColor

Function QBColor(Standard Colour Number As Integer) As Long

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.

Standard Description Standard Description


Colour Colour Number
Number

0 Black 8 Grey

1 Blue 9 Light Blue

2 Green 10 Light Green

3 Cyan 11 Light Cyan

4 Red 12 Light Red

5 Magenta 13 Light Magenta

6 Yellow 14 Light Yellow

7 White 15 Bright White

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

Runge Ltd May, 2006 Page 352


XCM Reference Guide XPAC Functions and Subroutines

If (M(mBlk_RL)> 200) Then lStdColNum = 1 'Blue


If (M(mBlk_RL)> 250) Then lStdColNum = 2 'Green
If (M(mBlk_RL)> 300) Then lStdColNum = 3 'Cyan
'Convert the standard colour number to its RGB number
M(mBlk_Colour) = QBColor(lStdColNum)
'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(mBlk_Colour).
End Sub

RELATED FUNCTIONS

M, C, P, R Accessors

Dim M(1 to Field Count) As Double

Dim C(1 to Field Count) As Double

Dim P(1 to Field Count) As Double

Dim R(1 to Field Count) As Double

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.

Record If the data field is a record field type, then the


accessor will return the record number.

MakeRGB

RadToDeg

Function RadToDeg(Radians As Double) As Double

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

Runge Ltd May, 2006 Page 353


XCM Reference Guide XPAC Functions and Subroutines

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

Function ReadBaseValue(Database Name As Variant, Record Number As Long, Data


Field Number As Long) As Variant

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

Runge Ltd May, 2006 Page 354


XCM Reference Guide XPAC Functions and Subroutines

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.

Record If the data field is a record field type, then the


function will return a long data type, containing the
record number.

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

Runge Ltd May, 2006 Page 355


XCM Reference Guide XPAC Functions and Subroutines

ReadValue

Function ReadValue(Database Name As Variant, Full Row Code As String, Lvl0 As


Variant, Lvl1 As Variant, Lvl2 As Variant, Lvl3 As Variant, Lvl4 As Variant, Lvl5 As
Variant, Lvl6 As Variant, Lvl7 As Variant, Lvl8 As Variant, Lvl9 As Variant, Lvl10 As
Variant) As Variant

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 If the data field is a record field type, then the


function will return a long data type, containing the

Runge Ltd May, 2006 Page 356


XCM Reference Guide XPAC Functions and Subroutines

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

Sub RecalculateDatabase(ByVal bFullRecalc As Boolean, Optional ByVal DbName


As String)

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

Sub ReducePolygonComplexity(ByRef Poly() As Vertex, Optional ByVal dTolerance


As Double)

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

Function Released (ByVal FieldNo As Integer) As Double

Returns the accumulated released value for the specified main database data field, for all steps passed
by the filter.

RemoveAllDependencies

Runge Ltd May, 2006 Page 357


XCM Reference Guide XPAC Functions and Subroutines

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

Sub RemoveDependency ( lSuccessor as Long, lPredecessor as Long , Optional


ActSuccessor As Integer, Optional ActPredecessor As Integer)

Removes a dependency between two records.


Example :
Call RemoveDependency(1,2,0,0)
Will remove a dependency between record number 1 and record number 2 (all activities) .
Call RemoveDependency (1,2,1,3)
Will remove a dependency between record number 1 and record number 2 between the activities 1 and
3
Call RemoveDependency ( CURRENT, PRVSIB, 1, 3 )

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

Function Released (ByVal FieldNo As Integer) As Double

Returns the accumulated released value for the specified main database data field, for all steps passed
by the filter.
RemoveAllDependencies

RemoveRecord

Function RemoveRecord(Record Number As Long, Optional Database Name As


Variant) As Boolean

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

Runge Ltd May, 2006 Page 358


XCM Reference Guide XPAC Functions and Subroutines

database over which the XCM is running.


The record may be a lowest level record or an upper level record.
If it is an upper level record then the upper level record and all of
its children will be removed from the database.
The record number is passed to the function by value and is 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:

Database Name The Database Name is an optional argument. It is passed by


reference as a variant data type.
The Database Name is used to specify a different database. If the
Database Name is not specified, then the current database will be
used.
The database name may be provided as a string (in double quotes)
or it may be one of the options below.

Record 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

Database Name Options Description


ACTIVE_MAIN The main database.
ACTIVE_CALENDAR The active calendar database.
ACTIVE_RESULTS The active results database.

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.

Runge Ltd May, 2006 Page 359


XCM Reference Guide XPAC Functions and Subroutines

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

Function ClosingInv (ByVal FieldNo As Integer) As Double

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

Function ClosingInvSP (ByVal FieldNo As Integer) As Double

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

Function RemoveTask(ByVal lRecord As Long, ByVal iAct As Integer, ByVal


sResourceName As String) As Boolean

DESCRIPTION

Runge Ltd May, 2006 Page 360


XCM Reference Guide XPAC Functions and Subroutines

This function will remove the specified task from the Available Block List.

ARGUMENTS

lRecord The record number of the task

iAct The activity number of the task

sResourceName The name of the resource from whose ABL to remove the task

REMARKS
This function is available only in User Processing Scripts.

ResetMaxCapacity

Sub ResetMaxCapacity ( ByRef lRecord As Long )

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

Function Resource (ByVal ResourceName As String) As Boolean

Used to only pass steps that were scheduled by the specified resource.

RNOEXDB

Runge Ltd May, 2006 Page 361


XCM Reference Guide XPAC Functions and Subroutines

Function RNOEXDB(Project Name As Variant, Database Name As Variant, Record


Path Name As String) As Long

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"

Runge Ltd May, 2006 Page 362


XCM Reference Guide XPAC Functions and Subroutines

sRecPath = GetRecName(CURRENT, PATHNAME)


M(mRecNum_Old) = RNOEXDB(sProjPath & sProjName, sDBName, sRecPath)
End Sub

RELATED FUNCTIONS
GetRecNum, GetRecNumFromPath, DbReadName

RosterHrs

Function RosterHrs( ByVal sRosterName As String, ByVal sRosterExceptionName As


String ) As Double
This function is only available for use within the report writer.

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

Function RosterHrsResource(ByVal sResourceName As String, Optional ByVal


bIncludeRosterExceptions As Boolean) As Double
This function is only available for use within the report writer.
This function returns the number of rostered hours performed within the current reporting period (in the
report writer) by the specified resource. It takes into account the roster and the roster exceptions
assigned to that resource in each reporting period. Note that this function will take into account
changing of rosters when the schedule runs.

' 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

Function RunActiveScenario(Start Period Number As Long, Finish Period Number As


Long, Display Progress Bar As Boolean) As Integer

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.

Runge Ltd May, 2006 Page 363


XCM Reference Guide XPAC Functions and Subroutines

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.

Runge Ltd May, 2006 Page 364


XCM Reference Guide XPAC Functions and Subroutines

6 A production target could not be achieved for one of the resources.

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

Function RunMacro(Macro Name As String, optional Macro Location As Integer) As


Integer

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.

Return Value Description

Runge Ltd May, 2006 Page 365


XCM Reference Guide XPAC Functions and Subroutines

The macro has been run successfully. No error messages will be


0
displayed.
An error message was encountered when the macro was compiled. A
message will be displayed explaining the error.
An error message was encountered while the macro was running. A
message will be displayed explaining the error.

1 This value is not currently returned (Error_Macro).

2 This value is not currently returned (Error_Compiling_Macro).

3 This value is not currently returned (Error_General).

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

Function RunScheduleReport (ByVal sReportName As String, ByVal iStartPeriod As


Integer, ByVal iEndPeriod As Integer, Optional ByVal bInteractive As Boolean) As
Boolean

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

Runge Ltd May, 2006 Page 366


XCM Reference Guide XPAC Functions and Subroutines

Function RunScript(Database Name As Variant, Script Name As String, optional


Database Range Name As String) As Integer

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.

1 The function returns these values under these circumstances:


No script name was specified.

Runge Ltd May, 2006 Page 367


XCM Reference Guide XPAC Functions and Subroutines

The requested script name is the same as the running script name.
The requested script doesn’t exist.

2 The script being called was unable to be compiled.

3 The function returns these values under these circumstances:


An Invalid database name was specified.
An unexpected error occurred whilst running the script.

4 The script being called was cancelled by the user.

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

Function SafeDivide(Numerator As Double, Denominator As Double) As Double

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

Runge Ltd May, 2006 Page 368


XCM Reference Guide XPAC Functions and Subroutines

Dim dBlkVol As Double 'Block Volume


Dim dBlkArea As Double 'Block Area
Dim dBlkThk As Double 'Block Thickness
dBlkVol = 35000
dBlkArea = 0
'Calculate the Block Thickness and then Print it’s value
dBlkThk = SafeDivide(dBlkVol, dBlkArea)
Print dBlkThk
End Sub

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

Runge Ltd May, 2006 Page 369


XCM Reference Guide XPAC Functions and Subroutines

ScanCircleReference

Function ScanCircleReference ( ) As Boolean

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

Function ScanCircleReferenceFrom (ByVal lRecord As Long) As Boolean

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

Function SetActivePolygonSet ( SetName As String ) As Boolean

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

Function SetActiveScenario(Scenario Name As String) As Boolean

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.

Runge Ltd May, 2006 Page 370


XCM Reference Guide XPAC Functions and Subroutines

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

Function SetClass(Data Field Number As Integer, Classification As String, optional


Don’t Prompt As Boolean) As Boolean

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.

Classification The classification is the value that is assigned to the classified


data field in the current record. It is passed by value as a string
data type.
The classification does not have to already exist for the classified
data field, but it can already exist.

Don’t Prompt This argument 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

Runge Ltd May, 2006 Page 371


XCM Reference Guide XPAC Functions and Subroutines

create that new classification.


If the argument is missing, then the function will behave as if the
argument were set to False.

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

(2) Ask for confirmation before creating new classifications.


Sub Main
'Categorise Waste as Drill/Blast or Free Dig
If (GetClass(mWst_Hrd) = "Competent" And M(mWst_Thk) > 1.2) Then
Call SetClass(mWst_Frag, "Drill/Blast")
ElseIf (GetClass(mWst_Hrd) = "Fractured" And M(mWst_Thk) > 2.5) Then
Call SetClass(mWst_Frag, "Drill/Blast")
Else
Call SetClass(mWst_Frag, "Free Dig")
End If
End Sub

RELATED FUNCTIONS
GetClass, DbWriteValue, GetNote, GetFieldInfo

SetDependency

Function SetDependency ( lSuccessor as Long, lPredecessor as Long , Optional


ActSuccessor As Integer, Optional ActPredecessor As Integer) As Boolean

Sets a Dependency between two Records.


If the dependency cannot be added the function returns false.
Example :

Runge Ltd May, 2006 Page 372


XCM Reference Guide XPAC Functions and Subroutines

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

Function Released (ByVal FieldNo As Integer) As Double

Returns the accumulated released value for the specified main database data field, for all steps passed
by the filter.
RemoveAllDependencies, SetDependencyOnRange

SetDependencyEx

Function SetDependencyEx (ByVal lSuccessor as Long, ByVal lPredecessor as Long ,


Optional ByVal ActSuccessor As Integer, Optional ByVal ActPredecessor As Integer,
Optional ByVal OR As Boolean, Optional ByVal ReleaseProfileCurve As String,
Optional ByVal LagDuration As Double) As Long

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

Function SetDependencyOnRange (ByVal lSuccessor as Long, ByVal


sSuccessorRange as String, ByVal lPredecessor as Long, ByVal sPredecessorRange as
String, Optional ByVal ActSuccessor As Integer, Optional ByVal ActPredecessor As
Integer) As Boolean

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

Runge Ltd May, 2006 Page 373


XCM Reference Guide XPAC Functions and Subroutines

GetDependencies,
GetDependencies, GetPredecessor,
GetPredecessor, GetSuccessor,
GetSuccessor,
GetNumberOfPredecessors,
GetNumberOfPredecessors, GetNumberOfSuccessors,
GetNumberOfSuccessors, Released

Function Released (ByVal FieldNo As Integer) As Double

Returns the accumulated released value for the specified main database data field, for all steps passed
by the filter.
RemoveAllDependencies, SetDependency

SetFieldInfo

Function SetFieldInfo(Data Field Number As Integer, Data Field Information As


FieldInfo, Database Name As Variant) As Boolean

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

Runge Ltd May, 2006 Page 374


XCM Reference Guide XPAC Functions and Subroutines

FTYPE_TITLE sets it to Title


FTYPE_NOTE sets it to Note
FTYPE_CLASS sets it to Class
FTYPE_DATEMIN sets it to Date (Min)
FTYPE_DATEMAX sets it to Date (Max)
FTYPE_RECORD sets it to Record
FTYPE_MIN sets it to Min
FTYPE_MAX sets it to Max
FTYPE_RATIO sets it to Ratio
FTYPE_PRODUCT sets it to Product
FTYPE_SUM sets it to Sum
FTYPE_DIFF sets it to Difference
FTYPE_NOAGG sets it to No Aggregate

Note that FieldType cannot set a “Different type for each


level”. All levels will be assigned the same FieldType.

Param1 This parameter accepts a data field number as a long data


type. What this data field number sets is dependent on the
field type, as follows.
Weight Average sets the Weighting Field
Minimum sets the Minimum Of
Maximum sets the Maximum Of
Difference sets Difference1
Ratio sets Ratio1
Product sets Product1
Sum sets Sum1

If the data field is not one of the above field types, then
Param1 should be set to –1.

To assign the data field as “Minimum of Self” or “Maximum


of Self”, Param1 should be set to –1.

Param2 This parameter accepts a data field number as a long data


type. What this data field number sets is dependent on the
field type, as follows.
Difference sets Difference2
Ratio sets Ratio2
Product sets Product2
Sum sets Sum2

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

Runge Ltd May, 2006 Page 375


XCM Reference Guide XPAC Functions and Subroutines

data field as a long data type.


The activity should be set to zero for “No Activity”.
Protection Sets 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 set.
These constants are listed below.
FPROT_NONE sets it to None
FPROT_EDIT sets it to Edit
FPROT_SCRIPT sets it to Script
FPROT_ALL sets it to Both

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

Runge Ltd May, 2006 Page 376


XCM Reference Guide XPAC Functions and Subroutines

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

(2) Change the field type for a data field.


Sub Main
Dim FieldData As FieldInfo
Dim bFieldUpdated As Boolean
'Read the current data field information
Call GetFieldInfo(mIS_Wst_Thk, FieldData, "Main")
'Change the field type to be weight averaged against area
'and include zeros
FieldData.FieldType = FTYPE_WTAVG
FieldData.Param1 = mIS_Wst_Ar
FieldData.Param2 = -1
FieldData.IncludeZeros = True
bFieldUpdated = SetFieldInfo(mIS_Wst_Thk, FieldData, "Main")
If (bFieldUpodated = False) Then Print "Unsuccessful Data Field Update"
End Sub

RELATED FUNCTIONS
GetFieldInfo, DbReadValue, DbWriteValue

SetGlobalArray

Sub SetGlobalArray(ByVal sObjectName As String, ByRef Object() As Variant)

DESCRIPTION
Saves the value of an array variable to the temporary store inside XPAC.

ARGUMENTS

sObjectName The name to use to reference this global object

Object The object to save. The object must be of the type that the global
array was declared.

Runge Ltd May, 2006 Page 377


XCM Reference Guide XPAC Functions and Subroutines

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

Runge Ltd May, 2006 Page 378


XCM Reference Guide XPAC Functions and Subroutines

SetGlobalObject

Sub SetGlobalObject(ByVal sObjectName As String, ByRef Object As Variant)

DESCRIPTION
Saves the value of a variable to the temporary store inside XPAC.

ARGUMENTS

sObjectName The name to use to reference this global object

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

Function SetMOQItem(Record Number As Long, Activity Number As Long, Released


Percent As Double, Mined Percent As Double) As Boolean

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.

Runge Ltd May, 2006 Page 379


XCM Reference Guide XPAC Functions and Subroutines

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

Function SetNote(Data Field Number As Integer, Note As String) As Boolean

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

Runge Ltd May, 2006 Page 380


XCM Reference Guide XPAC Functions and Subroutines

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

Sub SetParam(Data Field Number As Integer, Value As Double, Record Number As


Long)

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

Runge Ltd May, 2006 Page 381


XCM Reference Guide XPAC Functions and Subroutines

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

Sub SetParamFromPil(Data Field Number As Integer, Value As Double, Level 1 Pil As


Integer, optional Level 2 Pil As Integer, optional Level 3 Pil As Integer, optional Level 4
Pil As Integer, optional Level 5 Pil As Integer, optional Level 6 Pil As Integer, optional
Level 7 Pil As Integer, optional Level 8 Pil As Integer, optional Level 9 Pil As Integer,
optional Level 10 Pil As Integer)

DESCRIPTION

Runge Ltd May, 2006 Page 382


XCM Reference Guide XPAC Functions and Subroutines

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

Runge Ltd May, 2006 Page 383


XCM Reference Guide XPAC Functions and Subroutines

'from a curve (which is a function of the bench RL).


If (IsFirst()) Then
dWstTrkProd = CurveValue("WstTrkProd-" & sPitName, lBenchNum)
'Write the waste truck productivity into the "Pit Bench
'Parameters" database
lParFld = GetRowNumFromCode("Pit Bench Parameters", "pWst_Trk_Prod")
Call SetParamFromPil(lParFld, dWstTrkProd, lPitNum, lBenchNum)
End If
End Sub

RELATED FUNCTIONS
GetParamFromPil, SetParam, GetParam, DbWriteValue

SetProgressBar

Sub SetProgressBar(Bar Progress As Integer, Message As String)

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

Runge Ltd May, 2006 Page 384


XCM Reference Guide XPAC Functions and Subroutines

SetProgressBar is a subroutine, so it does not return a value.


An example of the progress window that is generated by this subroutine is shown below. In this
example, the bar progress has a value of 38 and the message is “Processing Year 2005”. The name of
the XCM is also displayed on the top line of the window.

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

Function SetPSItem(Scenario Name As String, Record Number As Long, Activity


Number As Long, Released Percent As Double, Mined Percent As Double) As Boolean

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

Runge Ltd May, 2006 Page 385


XCM Reference Guide XPAC Functions and Subroutines

be changed for all.

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

Runge Ltd May, 2006 Page 386


XCM Reference Guide XPAC Functions and Subroutines

Function SetRecName(Record Number As Long, New Record Name As String) As


Boolean

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

Runge Ltd May, 2006 Page 387


XCM Reference Guide XPAC Functions and Subroutines

(1) Rename a lowest level record.


Sub Main
'Rename the last block record in each panel.
If (IsLast()) Then Call SetRecName(CURRENT, "Last")
End Sub

(2) Change a level name to include its Pil number.


'Declare the previous Panel record number as a script variable.
Dim lPrevPanelRec As Long
Sub Main
Dim lResult As Long
Dim lPanelRec As Long
lPanelRec = GetRecNumAtLevel(2)
'Only update the Panel name when a new Panel is reached.
If (lPrevPanelRec <> lPanelRec) Then
'Change the Panel name to include the Panel number.
lResult = SetRecName(lPanelRec, "Panel" & CStr(lPanelNum))
'Display an error message if the Panel name could not be changed.
If (lResult = False) Then Print "Panel Rename Failed."
End If
lPrevPanelRec = lPanelRec
End Sub

RELATED FUNCTIONS
GoRec, GetRecName, GetRecNameAtLevel, DbReadName

SetUserFlag

Function SetUserFlag ( iFlagNo As Integer, lRecord As Long, iActivity As Integer,


Optional ByVal sResource As String ) As Boolean

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

iFlagNo Flag number 1 or 2

lRecord The record in the available block list

iActivity The activity to switch off

sResource Optional resource name. If 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.

Runge Ltd May, 2006 Page 388


XCM Reference Guide XPAC Functions and Subroutines

REMARKS
This function is available only in the User Processing Scripts.

RELATED FUNCTIONS
ClearUserFlag

SetVertex

Sub SetVertex ( ByRef V As Vertex, 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.

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.

Runge Ltd May, 2006 Page 389


XCM Reference Guide XPAC Functions and Subroutines

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

Sub SetVertexEOS ( ByRef V As Vertex )

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

Sub SetVertexEOSA ( ByRef Poly() As Vertex, ByVal Index As Long )

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

Function StartedTask() As Boolean

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

Function StepType (ByVal x As Long) As Boolean

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

Function StockpileInventory(ByRef sStockpileName As String) As Boolean

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.

Runge Ltd May, 2006 Page 390


XCM Reference Guide XPAC Functions and Subroutines

WorkHrs

Function StepType () As Double

Returns the accumulated productive operating hours for all steps passed by the filter.

WriteABLToFile

Function WriteABLToFile( sFileName As String, optional ByVal bAppend as Boolean,


optional ByVal sComment As String ) As Boolean

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

Sub WriteBaseValue(Database Name As Variant, Record Number As Long, Data


Field Number As Long, Value As Variant, optional Don’t Prompt As Boolean)

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.

Runge Ltd May, 2006 Page 391


XCM Reference Guide XPAC Functions and Subroutines

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.

Value The value to be written to the database is passed into this


argument. It is passed by value as a variant data type.
The data type of the value should match the data field type. For
example, a string of text cannot be written to an additive field
type. There are no error messages generated or variables that can
be checked if this is not the case.

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)

Runge Ltd May, 2006 Page 392


XCM Reference Guide XPAC Functions and Subroutines

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

Function WriteDestinationABLToFile( sFileName As String, optional ByVal bAppend


as Boolean, optional ByVal sComment As String ) As Boolean

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

Function WriteSourceABLToFile( sFileName As String, optional ByVal bAppend as


Boolean, optional ByVal sComment As String ) As Boolean

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

Function WriteValue(Database Name As Variant, Full Row Code As String, Value As


Variant, Lvl0 As Variant, Lvl1 As Variant, Lvl2 As Variant, Lvl3 As Variant, Lvl4 As
Variant, Lvl5 As Variant, Lvl6 As Variant, Lvl7 As Variant, Lvl8 As Variant, Lvl9 As
Variant, Lvl10 As Variant) As Variant

DESCRIPTION
Writes a value to the specified data field, record and database. Values may be written to any field type.
ARGUMENTS

Runge Ltd May, 2006 Page 393


XCM Reference Guide XPAC Functions and Subroutines

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.

Value The value to be written to the database is passed into this


argument. It is passed by value as a variant data type.
The data type of the value should match the data field type. For
example, a string of text cannot be written to an additive field
type. There are no error messages generated or variables that can
be checked if this is not the case.

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

Runge Ltd May, 2006 Page 394

You might also like