Download - 48784209 Microstation Basic

Transcript
Page 1: 48784209 Microstation Basic

600macro.bk : 600_TITL.FRM Page 1 Friday, October 15, 1999 1:27 PM

MicroStation®

BASIC Guide

DAA010290-1/0002

Page 2: 48784209 Microstation Basic

600macro.bk : 600_TITL.FRM Page 2 Friday, October 15, 1999 1:27 PM

Page 3: 48784209 Microstation Basic

600macro.bk : 600_TRDK.FRM Page i Friday, October 15, 1999 1:27 PM

TrademarksAccuDraw, MicroStation, MicroStation Modeler, MicroStation PowerDraft, MicroStation Review, MicroStation Vault and SmartLine are registered trademarks of Bentley Systems, Incorporated. Bentley, the “B” Bentley logo, MDL, PowerScope, QuickVision, TeamMate and MasterPiece are trademarks of Bentley Systems, Incorporated.

Bentley SELECT is a service mark of Bentley Systems, Incorporated.

Adobe, the Adobe logo, Acrobat, the Acrobat logo, Distiller, Exchange, and PostScript are trademarks of Adobe Systems Incorporated.

Windows is a registered trademark and Win32s is a trademark of Microsoft Corporation.

Other brands and product names are the trademarks of their respective owners.

Copyrights 1997 Bentley Systems, Incorporated.

MicroStation® 95 1995 Bentley Systems, Incorporated.

IGDS file formats 1987-1994 Intergraph Corporation.

Intergraph Raster File Formats 1994 Intergraph Corporation Used with permission.

Portions 1992-1994 Summit Software Company.

Unpublished – rights reserved under the copyright laws of the United States.

MicroStation BASIC Guide i

Page 4: 48784209 Microstation Basic

600macro.bk : 600_TRDK.FRM Page ii Friday, October 15, 1999 1:27 PM

ii MicroStation BASIC Guide

Page 5: 48784209 Microstation Basic

600macro.bk : 600MACRO.TOC Page iii Friday, October 15, 1999 1:27 PM

Table of Contents

Part 1: Concepts and Procedures

1. Introduction to MacrosCreating Macros ______________________________________________ 1-1

Guidelines for creating a macro_____________________________ 1-2Advanced macro programming _____________________________ 1-3

Running Macros _____________________________________________ 1-5Creating and Managing Macros ________________________________ 1-6

Generating macros________________________________________ 1-6Managing macros_________________________________________ 1-7Adding macros to MicroStation’s user interface ________________ 1-8

2. Prototyping, Editing, and Debugging MacrosPrototyping__________________________________________________ 2-1

Starting conditions ________________________________________ 2-1The Create Macro dialog box_______________________________ 2-1Stopping the macro generator ______________________________ 2-2The form of a prototype macro _____________________________ 2-3BASIC extensions commonly used by the macro generator _____ 2-4

The BASIC Editor ____________________________________________ 2-6Text editing area and scrolling______________________________ 2-7Status message field_______________________________________ 2-8Line number and column number fields _____________________ 2-8File menu _______________________________________________ 2-8Edit menu _______________________________________________ 2-9Run menu _______________________________________________ 2-10Debugger icons __________________________________________ 2-11Working with variables ____________________________________ 2-12

3. Macro Language OverviewComments___________________________________________________ 3-1Naming Rules________________________________________________ 3-1Built-in Data Types ___________________________________________ 3-2

Integers _________________________________________________ 3-2Long integers ____________________________________________ 3-2Strings __________________________________________________ 3-2Singles __________________________________________________ 3-3Doubles_________________________________________________ 3-3

MicroStation BASIC Guide iii

Page 6: 48784209 Microstation Basic

Table Of Contents: Macro Language Overview

iv Micro

600macro.bk : 600MACRO.TOC Page iv Friday, October 15, 1999 1:27 PM

Variable Declarations __________________________________________3-3Declaring integer variables _________________________________3-4Declaring long variables ___________________________________3-4Declaring string variables___________________________________3-4Declaring single variables __________________________________3-5Declaring double variables _________________________________3-5

Arrays of Variables ____________________________________________3-5Fixed-length arrays ________________________________________3-6Variable-length arrays______________________________________3-7

User-defined Data Type Variables _______________________________3-8Creating a user-defined data type____________________________3-8Declaring user-defined data type variables ____________________3-9Working with user-defined data type variables ________________3-9

Variable Scope _______________________________________________3-9Local variables____________________________________________3-10Private variables __________________________________________3-10Public variables ___________________________________________3-10

Initial Variable Values _________________________________________3-11Symbolic Constants ___________________________________________3-11Expressions __________________________________________________3-11

Assignment operator_______________________________________3-11Arithmetic operators _______________________________________3-12String concatenation operators ______________________________3-13Relational operators _______________________________________3-13Logical operators__________________________________________3-14Operator precedence ______________________________________3-15

Statements and the Line Continuation Character ___________________3-15Controlling Execution _________________________________________3-16

If...Then...Else ____________________________________________3-16Select...Case ______________________________________________3-18Do...Loop ________________________________________________3-19While...Wend_____________________________________________3-22For...Next ________________________________________________3-22Labels and the Goto statement ______________________________3-24GoSub and Return statements _______________________________3-24

Program Structure_____________________________________________3-25Subroutine procedures _____________________________________3-26Calling subroutine procedures ______________________________3-27Function procedures_______________________________________3-28Calling function procedures ________________________________3-30Passing arguments to procedures ____________________________3-30Declaring procedures ______________________________________3-32

Objects in BASIC _____________________________________________3-32Declaring an object variable ________________________________3-33Object variable operations__________________________________3-34Creating an object instance _________________________________3-35

Station BASIC Guide

Page 7: 48784209 Microstation Basic

Table Of Contents: Macro Interactions With MicroStation

600macro.bk : 600MACRO.TOC Page v Friday, October 15, 1999 1:27 PM

Accessing object properties ________________________________ 3-36Accessing object methods__________________________________ 3-36Object collections ________________________________________ 3-37Constant objects __________________________________________ 3-37

Error Handling _______________________________________________ 3-38

4. Macro Interactions With MicroStationMicroStation BASIC Extension conventions _______________________ 4-1Sequencing MicroStation Commands ____________________________ 4-1Macro Coordinate System______________________________________ 4-2Querying and Manipulating Graphic Elements ____________________ 4-3

Modifying graphic elements ________________________________ 4-8Using selection sets and fences _____________________________ 4-9Graphic element location __________________________________ 4-11Accessing design file information ___________________________ 4-12Accessing MicroStation settings _____________________________ 4-13Accessing MicroStation state information _____________________ 4-13Accessing design file view information_______________________ 4-14Accessing reference file information _________________________ 4-14Accessing MicroStation session information ___________________ 4-15Database features of MicroStation BASIC extensions ___________ 4-15

Using Macros to Specify Pen Table Output Actions ________________ 4-18Overview of macro operation in pen tables___________________ 4-18The Main subroutine is optional in plotting___________________ 4-19Working with element priorities in macros ___________________ 4-19Pen Table Plot Element Hook function return values___________ 4-20A macro plot function example _____________________________ 4-21Pen table program entry points _____________________________ 4-22The different program entry points and their function__________ 4-24Optimizing the macro for plotting___________________________ 4-25

Using Macros to Perform DWG Import/Export ____________________ 4-26Objects for specifying import and export settings______________ 4-26Object for specifying font cross-reference information__________ 4-27Objects for specifying cell/block cross-reference information____ 4-28Editing and compiling “dwg.bas”____________________________ 4-29

MicroStation BASIC Guide v

Page 8: 48784209 Microstation Basic

Table Of Contents: Adding Dialog Boxes to Macros

vi Micro

600macro.bk : 600MACRO.TOC Page vi Friday, October 15, 1999 1:27 PM

5. Adding Dialog Boxes to MacrosStandard Dialog Boxes_________________________________________5-1Custom Dialog Boxes__________________________________________5-2Dialog Builder________________________________________________5-3

Dialog menu _____________________________________________5-4Edit menu________________________________________________5-6Options menu ____________________________________________5-8Common item attributes____________________________________5-10Text Editor dialog box _____________________________________5-11Label Editor dialog box ____________________________________5-11Toggle Button Editor dialog box ____________________________5-12Option Button Editor dialog box ____________________________5-12Push Button Editor ________________________________________5-13Color Picker dialog box ____________________________________5-14Level Map Editor dialog box ________________________________5-15Scale Editor dialog box ____________________________________5-15Alignment menu __________________________________________5-18Tool box_________________________________________________5-19Exiting Builder____________________________________________5-20

6. The MDL AlternativeMicroStation Development Environment__________________________6-1

MicroStation Development Language_________________________6-2MDL built-in functions _____________________________________6-2When to use MDL instead of BASIC__________________________6-3

Part 1: Macro Language Reference

7. Standard BASIC ReferenceBASIC Command Overview ____________________________________7-1

Operators ________________________________________________7-1Constants and special keywords_____________________________7-2Math and numerical operators ______________________________7-2Array handling____________________________________________7-3System __________________________________________________7-4Miscellaneous ____________________________________________7-4Program control __________________________________________7-4Variable control___________________________________________7-5

Station BASIC Guide

Page 9: 48784209 Microstation Basic

Table Of Contents: Standard BASIC Reference

600macro.bk : 600MACRO.TOC Page vii Friday, October 15, 1999 1:27 PM

Character and string manipulation___________________________ 7-6File handling_____________________________________________ 7-7Date and time____________________________________________ 7-8Business calculations______________________________________ 7-9Dynamic Data Exchange (DDE), Windows platforms only ______ 7-10

A to Z Reference ____________________________________________ 7-11& ______________________________________________________ 7-11' _______________________________________________________ 7-12* _______________________________________________________ 7-12+_______________________________________________________ 7-12- _______________________________________________________ 7-13/ _______________________________________________________ 7-13<_______________________________________________________ 7-13<=______________________________________________________ 7-14<>______________________________________________________ 7-14=_______________________________________________________ 7-15>_______________________________________________________ 7-15>=______________________________________________________ 7-16\ _______________________________________________________ 7-16^_______________________________________________________ 7-17_ _______________________________________________________ 7-17Abs_____________________________________________________ 7-18And ____________________________________________________ 7-19ArrayDims _______________________________________________ 7-19ArraySort ________________________________________________ 7-20Asc _____________________________________________________ 7-20Atn _____________________________________________________ 7-21Basic.Capability%_________________________________________ 7-21Basic.Eoln$ ______________________________________________ 7-22Basic.FreeMemory ________________________________________ 7-22Basic.OS ________________________________________________ 7-22Basic.PathSeparator$ ______________________________________ 7-23Beep ___________________________________________________ 7-24Call_____________________________________________________ 7-24CDbl ___________________________________________________ 7-24Chr$ ____________________________________________________ 7-25CInt ____________________________________________________ 7-25CLng ___________________________________________________ 7-26Close ___________________________________________________ 7-27Command$ ______________________________________________ 7-27Const ___________________________________________________ 7-28Cos_____________________________________________________ 7-28CSng ___________________________________________________ 7-28CStr ____________________________________________________ 7-29Date$ ___________________________________________________ 7-29DateAdd ________________________________________________ 7-30

MicroStation BASIC Guide vii

Page 10: 48784209 Microstation Basic

Table Of Contents: Standard BASIC Reference

viii Micro

600macro.bk : 600MACRO.TOC Page viii Friday, October 15, 1999 1:27 PM

DateDiff _________________________________________________7-31DatePart _________________________________________________7-33DateSerial________________________________________________7-34DateValue _______________________________________________7-34Day _____________________________________________________7-34DDB ____________________________________________________7-35DDEExecute______________________________________________7-36DDEInitiate ______________________________________________7-36DDEPoke ________________________________________________7-37DDERequest______________________________________________7-38DDESend ________________________________________________7-38DDETerminate____________________________________________7-39DDETerminateAll _________________________________________7-39DDETimeOut_____________________________________________7-40Declare __________________________________________________7-40DEF…___________________________________________________7-41Dim_____________________________________________________7-42Dir$_____________________________________________________7-44Do...Loop ________________________________________________7-45ebArchive________________________________________________7-47ebDirectory ______________________________________________7-47ebHidden ________________________________________________7-47ebNone__________________________________________________7-48ebNormal ________________________________________________7-48ebReadOnly ______________________________________________7-49ebSystem ________________________________________________7-49ebVolume________________________________________________7-49End _____________________________________________________7-50Environ$_________________________________________________7-50Eof______________________________________________________7-50Eqv _____________________________________________________7-51Erase ____________________________________________________7-52Erl ______________________________________________________7-53Err (function)_____________________________________________7-53Err (statement)____________________________________________7-54Error ____________________________________________________7-54Error$ ___________________________________________________7-55Exit Do __________________________________________________7-56Exit For__________________________________________________7-56Exit Function _____________________________________________7-57Exit Sub _________________________________________________7-57Exp _____________________________________________________7-58False ____________________________________________________7-58FileAttr __________________________________________________7-58FileCopy_________________________________________________7-59FileDateTime _____________________________________________7-60

Station BASIC Guide

Page 11: 48784209 Microstation Basic

Table Of Contents: Standard BASIC Reference

600macro.bk : 600MACRO.TOC Page ix Friday, October 15, 1999 1:27 PM

FileDirs _________________________________________________ 7-61FileExists ________________________________________________ 7-61FileLen__________________________________________________ 7-62FileList __________________________________________________ 7-62FileParse$ _______________________________________________ 7-64Fix _____________________________________________________ 7-65For...Next _______________________________________________ 7-65Format$ _________________________________________________ 7-66FreeFile _________________________________________________ 7-73Function...End Function ___________________________________ 7-73Fv ______________________________________________________ 7-75Get _____________________________________________________ 7-76GetAttr__________________________________________________ 7-78Global __________________________________________________ 7-79GoSub __________________________________________________ 7-79Goto____________________________________________________ 7-80Hex$ ___________________________________________________ 7-80Hour ___________________________________________________ 7-81If...Then...Else____________________________________________ 7-81Imp ____________________________________________________ 7-83Input #__________________________________________________ 7-84Input$ __________________________________________________ 7-85InStr ____________________________________________________ 7-85Int______________________________________________________ 7-86IPmt ____________________________________________________ 7-87IRR _____________________________________________________ 7-88Is ______________________________________________________ 7-90Item$ ___________________________________________________ 7-90ItemCount _______________________________________________ 7-91Kill _____________________________________________________ 7-91LBound _________________________________________________ 7-92LCase$ __________________________________________________ 7-93Left$____________________________________________________ 7-93Len_____________________________________________________ 7-94Let _____________________________________________________ 7-95Like ____________________________________________________ 7-95Line Input # _____________________________________________ 7-96Line$ ___________________________________________________ 7-97LineCount _______________________________________________ 7-98Loc _____________________________________________________ 7-98Lock____________________________________________________ 7-99Lof _____________________________________________________ 7-101Log_____________________________________________________ 7-101LSet ____________________________________________________ 7-102LTrim$ __________________________________________________ 7-102Main____________________________________________________ 7-103

MicroStation BASIC Guide ix

Page 12: 48784209 Microstation Basic

Table Of Contents: Standard BASIC Reference

x Micro

600macro.bk : 600MACRO.TOC Page x Friday, October 15, 1999 1:27 PM

Mid$ ____________________________________________________7-103Minute __________________________________________________7-104MIRR____________________________________________________7-104MkDir ___________________________________________________7-105Mod_____________________________________________________7-106Month ___________________________________________________7-106Name ___________________________________________________7-107Not _____________________________________________________7-107Now ____________________________________________________7-108NPer ____________________________________________________7-108Npv _____________________________________________________7-110Null _____________________________________________________7-111Oct$ ____________________________________________________7-111On Error_________________________________________________7-112Open____________________________________________________7-114Option Base______________________________________________7-116Option Compare __________________________________________7-116Or ______________________________________________________7-117PI_______________________________________________________7-118Pmt _____________________________________________________7-118PPmt ____________________________________________________7-119Print ____________________________________________________7-121Print# ___________________________________________________7-122Private___________________________________________________7-123Public ___________________________________________________7-124Put______________________________________________________7-125Pv ______________________________________________________7-127Random _________________________________________________7-128Randomize_______________________________________________7-128Rate_____________________________________________________7-129ReDim___________________________________________________7-130REM ____________________________________________________7-131Reset ____________________________________________________7-131Resume__________________________________________________7-131Return___________________________________________________7-133Right$ ___________________________________________________7-133RmDir ___________________________________________________7-133Rnd _____________________________________________________7-134RSet_____________________________________________________7-134RTrim$ __________________________________________________7-135Second __________________________________________________7-135Seek (function) ___________________________________________7-135Seek (statement) __________________________________________7-136Select...Case ______________________________________________7-137Set ______________________________________________________7-139SetAttr ___________________________________________________7-140

Station BASIC Guide

Page 13: 48784209 Microstation Basic

Table Of Contents: MicroStation Extensions to BASIC

600macro.bk : 600MACRO.TOC Page xi Friday, October 15, 1999 1:27 PM

Sgn_____________________________________________________ 7-141Sin _____________________________________________________ 7-141Sleep ___________________________________________________ 7-141Sln _____________________________________________________ 7-142Space$ __________________________________________________ 7-142Spc _____________________________________________________ 7-143Sqr _____________________________________________________ 7-143Stop ____________________________________________________ 7-144Str$_____________________________________________________ 7-144StrComp ________________________________________________ 7-145String$ __________________________________________________ 7-146Sub...End Sub ____________________________________________ 7-146SYD ____________________________________________________ 7-147Tab_____________________________________________________ 7-148Tan_____________________________________________________ 7-148Time$___________________________________________________ 7-149Timer ___________________________________________________ 7-149TimeSerial _______________________________________________ 7-150TimeValue_______________________________________________ 7-150Trim$ ___________________________________________________ 7-151True ____________________________________________________ 7-151Type____________________________________________________ 7-151UBound_________________________________________________ 7-152UCase$ _________________________________________________ 7-153UnLock _________________________________________________ 7-153Val _____________________________________________________ 7-154Weekday ________________________________________________ 7-155While...Wend ____________________________________________ 7-156Width#__________________________________________________ 7-156Word$ __________________________________________________ 7-157WordCount ______________________________________________ 7-157Write #__________________________________________________ 7-158Xor_____________________________________________________ 7-158Year ____________________________________________________ 7-159

8. MicroStation Extensions to BASICState Object _________________________________________________ 8-2

MbeState.inputType_______________________________________ 8-3MbeState.getInputCommand________________________________ 8-3MbeState.getInputDataPoint ________________________________ 8-4MbeState.getInputKeyin ___________________________________ 8-4MbeState.cmdResult_______________________________________ 8-5MbeState.errorMessages, MbeState.messages __________________ 8-6MbeState.noElementDisplay ________________________________ 8-6

MicroStation BASIC Guide xi

Page 14: 48784209 Microstation Basic

Table Of Contents: MicroStation Extensions to BASIC

xii Micro

600macro.bk : 600MACRO.TOC Page xii Friday, October 15, 1999 1:27 PM

MbeState.parseAll _________________________________________8-7MbeState.measureResult1, MbeState.measureResult2 ____________8-7MbeState.locateTolerance___________________________________8-8MbeState.locateFileNum____________________________________8-9MbeState.locateHeaderFilePos_______________________________8-10MbeState.locateComponentFilePos ___________________________8-10MbeState.setLocateFileMask, MbeState.getLocateFileMask________8-10MbeState.setLocateTypeMask, MbeState.getLocateTypeMask _____8-11MbeState.locatePropMask, MbeState.locatePropVal _____________8-13MbeState.locateClassMask __________________________________8-14

Element Object ______________________________________________8-15MbeElement.attachActiveEntity ______________________________8-18MbeElement.reviewDBAttributes ____________________________8-18MbeElement.reportDBLinkages______________________________8-19MbeElement.loadDAttributes________________________________8-19MbeElement.foundDBLinkages ______________________________8-19MbeElement.extractDBLinkages _____________________________8-20MbeElement.appendDBLinkage _____________________________8-21MbeElement.deleteDBLinkage_______________________________8-21MbeElement.firstElement ___________________________________8-22MbeElement.nextElement __________________________________8-22MbeElement.nextComponent _______________________________8-24MbeElement.headerElement ________________________________8-26MbeElement.thisComponent ________________________________8-27MbeElement.isHeader______________________________________8-28MbeElement.isComponent__________________________________8-29MbeElement.isGraphics ____________________________________8-29MbeElement.type _________________________________________8-29MbeElement.fileSize _______________________________________8-30MbeElement.internalSize ___________________________________8-30MbeElement.fromFile ______________________________________8-31MbeElement.fromLocate____________________________________8-32MbeElement.filePos _______________________________________8-33MbeElement.componentFilePos _____________________________8-33MbeElement.fileNum ______________________________________8-33MbeElement.changeAll_____________________________________8-34MbeElement.level _________________________________________8-34MbeElement.color _________________________________________8-35MbeElement.style _________________________________________8-35MbeElement.weight _______________________________________8-36MbeElement.class _________________________________________8-36MbeElement.properties ____________________________________8-37MbeElement.getOrigin _____________________________________8-38MbeElement.getPoints _____________________________________8-39MbeElement.setPoints______________________________________8-40MbeElement.getEndPoints __________________________________8-41

Station BASIC Guide

Page 15: 48784209 Microstation Basic

Table Of Contents: MicroStation Extensions to BASIC

600macro.bk : 600MACRO.TOC Page xiii Friday, October 15, 1999 1:27 PM

MbeElement.getRange_____________________________________ 8-41MbeElement.move ________________________________________ 8-42MbeElement.rotate________________________________________ 8-42MbeElement.scale ________________________________________ 8-43MbeElement.rewrite_______________________________________ 8-44MbeElement.addToFile ____________________________________ 8-45MbeElement.display_______________________________________ 8-45MbeElement.area _________________________________________ 8-46MbeElement.perimeter ____________________________________ 8-46MbeElement.volume ______________________________________ 8-47MbeElement.getCentroid___________________________________ 8-47MbeElement.cellName_____________________________________ 8-47MbeElement.getCellLevels _________________________________ 8-48MbeElement.getCellBox ___________________________________ 8-48MbeElement.getRotation ___________________________________ 8-49MbeElement.font _________________________________________ 8-49MbeElement.fontName ____________________________________ 8-49MbeElement.charHeight, MbeElement.charWidth ______________ 8-50MbeElement.lineSpacing ___________________________________ 8-51MbeElement.justification ___________________________________ 8-51MbeElement.getString _____________________________________ 8-52MbeElement.setString _____________________________________ 8-53MbeElement.primaryAxis __________________________________ 8-53MbeElement.secondaryAxis ________________________________ 8-54MbeElement.startAngle ____________________________________ 8-54MbeElement.sweepAngle __________________________________ 8-55MbeElement.topRadius, MbeElement.bottomRadius ____________ 8-55MbeElement.getTopOrigin _________________________________ 8-55MbeElement.publish ______________________________________ 8-56MbeElement.group________________________________________ 8-57MbeElement.isTagged _____________________________________ 8-57MbeElement.tagId ________________________________________ 8-57MbeElement.numTags_____________________________________ 8-58MbeElement.extractTags ___________________________________ 8-58MbeElement.getMbeTag ___________________________________ 8-58MbeElement.attachTag ____________________________________ 8-59MbeElement.getNumLinkages ______________________________ 8-59MbeElement.extractLinkage ________________________________ 8-59MbeElement.appendLinkage _______________________________ 8-60MbeElement.deleteLinkage_________________________________ 8-61

Element Set Object ___________________________________________ 8-62MbeElementSet.fromSelectionSet ____________________________ 8-62MbeElementSet.fromFence _________________________________ 8-63MbeElementSet.getFirst ____________________________________ 8-64MbeElementSet.getNext____________________________________ 8-64MbeElementSet.clear ______________________________________ 8-65

MicroStation BASIC Guide xiii

Page 16: 48784209 Microstation Basic

Table Of Contents: MicroStation Extensions to BASIC

xiv Micro

600macro.bk : 600MACRO.TOC Page xiv Friday, October 15, 1999 1:27 PM

Settings Object _______________________________________________8-66MbeSettings.angle _________________________________________8-67MbeSettings.areaMode _____________________________________8-68MbeSettings.axisAngle _____________________________________8-68MbeSettings.axisOrigin _____________________________________8-68MbeSettings.capMode______________________________________8-69MbeSettings.cell___________________________________________8-69MbeSettings.class__________________________________________8-69MbeSettings.color _________________________________________8-70MbeSettings.colorName ____________________________________8-70MbeSettings.currentGraphicGroup ___________________________8-71MbeSettings.fillColor_______________________________________8-71MbeSettings.fillMode_______________________________________8-71MbeSettings.font __________________________________________8-72MbeSettings.fontName _____________________________________8-72MbeSettings.gridReferences _________________________________8-72MbeSettings.gridUnits ______________________________________8-73MbeSettings.level__________________________________________8-73MbeSettings.lineStyle ______________________________________8-74MbeSettings.lineStyleName _________________________________8-74MbeSettings.lineTerminator _________________________________8-74MbeSettings.nodeJustification _______________________________8-75MbeSettings.patternAngle1__________________________________8-75MbeSettings.patternAngle2__________________________________8-75MbeSettings.patternCell ____________________________________8-76MbeSettings.setPatternDelta_________________________________8-76MbeSettings.getPatternDelta ________________________________8-77MbeSettings.patternScale ___________________________________8-77MbeSettings.point _________________________________________8-77MbeSettings.setScale _______________________________________8-78MbeSettings.getScale_______________________________________8-78MbeSettings.tagIncrement __________________________________8-78MbeSettings.terminatorScale ________________________________8-79MbeSettings.textHeight_____________________________________8-79MbeSettings.textWidth _____________________________________8-79MbeSettings.textLineLength _________________________________8-80MbeSettings.textLineSpacing ________________________________8-80MbeSettings.textJustification ________________________________8-80MbeSettings.weight________________________________________8-81MbeSettings.associationLock ________________________________8-81MbeSettings.axisLock ______________________________________8-82MbeSettings.boresiteLock___________________________________8-82MbeSettings.cellStretchLock_________________________________8-82MbeSettings.constructionPlaneLock __________________________8-83MbeSettings.depthLock_____________________________________8-83MbeSettings.graphGroupLock _______________________________8-83

Station BASIC Guide

Page 17: 48784209 Microstation Basic

Table Of Contents: MicroStation Extensions to BASIC

600macro.bk : 600MACRO.TOC Page xv Friday, October 15, 1999 1:27 PM

MbeSettings.gridLock______________________________________ 8-84MbeSettings.fenceClip _____________________________________ 8-84MbeSettings.fenceOverlap__________________________________ 8-84MbeSettings.fenceVoid ____________________________________ 8-85MbeSettings.levelLock _____________________________________ 8-85MbeSettings.selectionSetLock _______________________________ 8-85MbeSettings.snapLock _____________________________________ 8-86MbeSettings.textNodeLock _________________________________ 8-86MbeSettings.settingErr _____________________________________ 8-86

Design File Information Object ________________________________ 8-87MbeDgnInfo.dgnFileName _________________________________ 8-87MbeDgnInfo.dgn3D_______________________________________ 8-88MbeDgnInfo.dgnFileReadOnly______________________________ 8-88MbeDgnInfo.endOfFile ____________________________________ 8-88MbeDgnInfo.masterUnitName ______________________________ 8-88MbeDgnInfo.subUnitName _________________________________ 8-89MbeDgnInfo.uorPerSub____________________________________ 8-89MbeDgnInfo.subPerMaster _________________________________ 8-90MbeDgnInfo.getGlobalOrigin_______________________________ 8-90MbeDgnInfo.graphicGroup_________________________________ 8-90MbeDgnInfo.nextGraphicGroup ____________________________ 8-91MbeDgnInfo.cellFileName _________________________________ 8-91MbeDgnInfo.cell3D _______________________________________ 8-91MbeDgnInfo.cellFileReadOnly ______________________________ 8-92

Current Transformation Object _________________________________ 8-93MbeCurrentTransform.masterUnits __________________________ 8-93MbeCurrentTransform.dgnUnits _____________________________ 8-95MbeCurrentTransform.moveOrigin __________________________ 8-96MbeCurrentTransform.moveOriginWorld _____________________ 8-96MbeCurrentTransform.rotate________________________________ 8-96MbeCurrentTransform.fromView ____________________________ 8-97MbeCurrentTransform.scale ________________________________ 8-97MbeCurrentTransform.scalarToUors _________________________ 8-97MbeCurrentTransform.scalarFromUors _______________________ 8-98MbeCurrentTransform.pointToUors__________________________ 8-98MbeCurrentTransform.pointFromUors _______________________ 8-98

View Object ________________________________________________ 8-99MbeViews(index)_________________________________________ 8-99MbeView.active __________________________________________ 8-100MbeView.screenNum______________________________________ 8-101MbeView.fastCurve _______________________________________ 8-101MbeView.noText _________________________________________ 8-101MbeView.slowFont _______________________________________ 8-102MbeView.lineWeight ______________________________________ 8-102MbeView.pattern _________________________________________ 8-102MbeView.textNode _______________________________________ 8-103

MicroStation BASIC Guide xv

Page 18: 48784209 Microstation Basic

Table Of Contents: MicroStation Extensions to BASIC

xvi Micro

600macro.bk : 600MACRO.TOC Page xvi Friday, October 15, 1999 1:27 PM

MbeView.enterDataField ___________________________________8-103MbeView.grid ____________________________________________8-103MbeView.levelSymbology __________________________________8-103MbeView.construction _____________________________________8-104MbeView.dimension _______________________________________8-104MbeView.areaFill__________________________________________8-105MbeView.refBoundary _____________________________________8-105MbeView.fastRefClip_______________________________________8-105MbeView.deferApply ______________________________________8-105MbeView.update __________________________________________8-106MbeView.getLevels ________________________________________8-106MbeView.levelsOn, MbeView.levelsOff _______________________8-107

Reference File Object _________________________________________8-108MbeRefFiles.maxRefFiles ___________________________________8-109MbeRefFiles(index)________________________________________8-109MbeRefFile.active _________________________________________8-109MbeRefFile.notFound ______________________________________8-110MbeRefFile.display ________________________________________8-110MbeRefFile.locate _________________________________________8-110MbeRefFile.snap __________________________________________8-111MbeRefFile.plot ___________________________________________8-111MbeRefFile.scaleLineStyle __________________________________8-111MbeRefFile.fileName_______________________________________8-112MbeRefFile.attachName ____________________________________8-112MbeRefFile.logical_________________________________________8-113MbeRefFile.description_____________________________________8-113MbeRefFile.scale __________________________________________8-113MbeRefFile.getLevels ______________________________________8-114MbeRefFile.levelsOn, MbeRefFile.levelsOff ____________________8-114MbeRefFile.saveSettings ____________________________________8-115

Session Object _______________________________________________8-116MbeSession.msProduct_____________________________________8-116MbeSession.msPlatform ____________________________________8-117MbeSession.msVersion _____________________________________8-117MbeSession.language ______________________________________8-118MbeSession.numScreens ___________________________________8-118MbeSession.canSwapScreen ________________________________8-119MbeSession.elapsedTime ___________________________________8-119

C Expression Statements ______________________________________8-120MbeCExpressionLong______________________________________8-120MbeCExpressionDouble____________________________________8-120MbeCExpressionString _____________________________________8-121

CAD Input Operations ________________________________________8-123MbeGetInput _____________________________________________8-124MbePoint ________________________________________________8-125MbeSendAppMessage______________________________________8-125

Station BASIC Guide

Page 19: 48784209 Microstation Basic

Table Of Contents: MicroStation Extensions to BASIC

600macro.bk : 600MACRO.TOC Page xvii Friday, October 15, 1999 1:27 PM

MbeSetAppVariable _______________________________________ 8-125MbeSetScaledAppVar______________________________________ 8-126MbeSendCommand _______________________________________ 8-127MbeSendDataPoint________________________________________ 8-127MbeSendDragPoints_______________________________________ 8-128MbeSendLastInput ________________________________________ 8-129MbeSendKeyin ___________________________________________ 8-129MbeSendReset ___________________________________________ 8-129MbeSendTentPoint________________________________________ 8-129MbeWriteCommand_______________________________________ 8-130MbeWriteError ___________________________________________ 8-130MbeWriteMessage ________________________________________ 8-131MbeWritePrompt _________________________________________ 8-131MbeWriteStatus___________________________________________ 8-131MbeRelocate _____________________________________________ 8-131MbeStartLocate ___________________________________________ 8-132Example of element location techniques _____________________ 8-133MbeLocateElement________________________________________ 8-139MbeScalarFromString______________________________________ 8-141MbePointFromString ______________________________________ 8-141MbeAngleFromString ______________________________________ 8-141MbeStringFromScalar ______________________________________ 8-142MbeStringFromPoint ______________________________________ 8-142MbeStringFromAngle ______________________________________ 8-143MbeGetConfigVar_________________________________________ 8-143MbeFindFile _____________________________________________ 8-143MbeStartDefaultCommand _________________________________ 8-144

Dialog Box Statements _______________________________________ 8-145MbeFileOpen, MbeFileCreate _______________________________ 8-145MbeMessageBox _________________________________________ 8-146MbeInputBox ____________________________________________ 8-147MbeSelectBox____________________________________________ 8-147MbeOpenModalDialog ____________________________________ 8-148

MbeSqlda Object ____________________________________________ 8-150MbeSqlda.numColumns ___________________________________ 8-150MbeSqlda.column ________________________________________ 8-150MbeSqlda.value __________________________________________ 8-150MbeSqlda.type ___________________________________________ 8-151MbeSqlda.length__________________________________________ 8-151MbeSqlda.isNull __________________________________________ 8-151MbeSqlda.scale___________________________________________ 8-152MbeSqlda.precision _______________________________________ 8-152MbeSqlda.getIndex _______________________________________ 8-152

MbeTable Object ____________________________________________ 8-153MbeTable.name __________________________________________ 8-153MbeTable.criteria _________________________________________ 8-153

MicroStation BASIC Guide xvii

Page 20: 48784209 Microstation Basic

Table Of Contents: MicroStation Extensions to BASIC

xviii Micro

600macro.bk : 600MACRO.TOC Page xviii Friday, October 15, 1999 1:27 PM

MbeTable.largestMslink ____________________________________8-154MbeTable.entityNumber____________________________________8-154MbeTable.activeReview ____________________________________8-154MbeTable.reportTable _____________________________________8-155MbeTable.fenceFilter ______________________________________8-155MbeTable.describe ________________________________________8-156MbeTable.recordFirst ______________________________________8-156MbeTable.recordLast_______________________________________8-157MbeTable.recordNext ______________________________________8-157MbeTable.recordInsert _____________________________________8-158MbeTable.recordUpdate____________________________________8-158MbeTable.recordDelete ____________________________________8-159MbeTable.copy ___________________________________________8-159MbeTable.create __________________________________________8-159MbeTable.drop ___________________________________________8-160

MbeDatabase Object __________________________________________8-161MbeDatabase.name________________________________________8-161MbeDatabase.activeEntity __________________________________8-162MbeDatabase.mslink_______________________________________8-162MbeDatabase.errorText ____________________________________8-162MbeDatabase.describe _____________________________________8-163MbeDatabase.connect______________________________________8-163MbeDatabase.disconnect ___________________________________8-163MbeDatabase.defineActiveEntity_____________________________8-164MbeDatabase.showActiveEntity______________________________8-164MbeDatabase.editActiveEntity _______________________________8-164MbeDatabase.modeCommit_________________________________8-165MbeDatabase.modeConfirm ________________________________8-165MbeDatabase.modeDelete __________________________________8-165MbeDatabase.modeForms __________________________________8-166MbeDatabase.modeLinkage_________________________________8-166MbeDatabase.dAType______________________________________8-167MbeDatabase.reportOpen __________________________________8-167MbeDatabase.reportClose __________________________________8-167

MbeDatabaseLink Object ______________________________________8-168MbeDatabaseLink.dAType __________________________________8-169MbeDatabaseLink.entityNumber _____________________________8-169MbeDatabaseLink.isInformation _____________________________8-169MbeDatabaseLink.isModified________________________________8-169MbeDatabaseLink.isRemote _________________________________8-169MbeDatabaseLink.isUserLink________________________________8-170MbeDatabaseLink.linkClass _________________________________8-170MbeDatabaseLink.linkSize __________________________________8-170MbeDatabaseLink.linkType _________________________________8-170MbeDatabaseLink.mslink ___________________________________8-171MbeDatabaseLink.tableName _______________________________8-171

Station BASIC Guide

Page 21: 48784209 Microstation Basic

Table Of Contents: MicroStation Extensions to BASIC

600macro.bk : 600MACRO.TOC Page xix Friday, October 15, 1999 1:27 PM

MbeDgnLevels Object ________________________________________ 8-172MbeDgnLevels.rootGroup__________________________________ 8-172MbeDgnLevels.numGroups ________________________________ 8-172MbeDgnLevels.numNamedLevels ___________________________ 8-173MbeDgnLevels.getGroup___________________________________ 8-173MbeDgnLevels.getLevel____________________________________ 8-173MbeDgnLevels.freeGroups _________________________________ 8-173MbeDgnLevels.freeLevels __________________________________ 8-174MbeDgnLevels.freeAll _____________________________________ 8-174MbeDgnLevels.loadGroupsFromFile _________________________ 8-174MbeDgnLevels.loadLevelsFromFile __________________________ 8-174MbeDgnLevels.loadAllFromFile _____________________________ 8-175MbeDgnLevels.saveGroupsToFile ___________________________ 8-175MbeDgnLevels.saveLevelsToFile ____________________________ 8-175MbeDgnLevels.saveAllToFile _______________________________ 8-176

MbeLevelGroup Object _______________________________________ 8-177MbeLevelGroup.groupName _______________________________ 8-177MbeLevelGroup.getLevels__________________________________ 8-177MbeLevelGroup.getDescendentLevels________________________ 8-178MbeLevelGroup.getDescendentGroups ______________________ 8-178MbeLevelGroup.getParentGroup ____________________________ 8-179MbeLevelGroup.getLevelMask ______________________________ 8-179MbeLevelGroup.deleteGroup_______________________________ 8-180MbeLevelGroup.addGroup_________________________________ 8-180MbeLevelGroup.addLevel __________________________________ 8-180

MbeNamedLevel Object _______________________________________ 8-181MbeNamedLevel.levelNumber ______________________________ 8-181MbeNamedLevel.levelName ________________________________ 8-181MbeNamedLevel.levelComment_____________________________ 8-182MbeNamedLevel.getParentGroup ___________________________ 8-182MbeNamedLevel.getLevelMask _____________________________ 8-182MbeNamedLevel.deleteLevel _______________________________ 8-183

Tag BASIC Extensions ________________________________________ 8-184MbeNumberOfTagSets_____________________________________ 8-184MbeGetTagSetNames______________________________________ 8-184

MbeTagSet Object ___________________________________________ 8-186MbeTagSet.name _________________________________________ 8-186MbeTagSet.reportName____________________________________ 8-186MbeTagSet.fileNum _______________________________________ 8-187MbeTagSet.numTagDefs ___________________________________ 8-187MbeTagSet.getTagDefNames _______________________________ 8-187MbeTagSet.add___________________________________________ 8-188MbeTagSet.update ________________________________________ 8-188MbeTagSet.delete_________________________________________ 8-188MbeTagSet.getTagDef _____________________________________ 8-189MbeTagSet.generateReport _________________________________ 8-189

MicroStation BASIC Guide xix

Page 22: 48784209 Microstation Basic

Table of Contents: MicroStation Extensions to BASIC

600macro.bk : 600MACRO.TOC Page xx Friday, October 15, 1999 1:27 PM

MbeTagSet.deleteInstances_________________________________ 8-190MbeTagDef Object ___________________________________________ 8-191

MbeTagDef.name ________________________________________ 8-191MbeTagDef.setName______________________________________ 8-192MbeTagDef.prompt _______________________________________ 8-192MbeTagDef.style _________________________________________ 8-192MbeTagDef.tagType ______________________________________ 8-193MbeTagDef.defaultValue __________________________________ 8-193MbeTagDef.isHidden _____________________________________ 8-194MbeTagDef.isConstant ____________________________________ 8-194MbeTagDef.tagId _________________________________________ 8-194MbeTagDef.add __________________________________________ 8-195MbeTagDef.update _______________________________________ 8-195MbeTagDef.delete ________________________________________ 8-196

MbeTag Object ______________________________________________ 8-197MbeTag.setName _________________________________________ 8-197MbeTag.name____________________________________________ 8-198MbeTag.fileNum _________________________________________ 8-198MbeTag.id_______________________________________________ 8-198MbeTag.targetId__________________________________________ 8-199MbeTag.type_____________________________________________ 8-199MbeTag.value____________________________________________ 8-199MbeTag.size _____________________________________________ 8-200MbeTag.version __________________________________________ 8-200MbeTag.isHidden_________________________________________ 8-200MbeTag.setOffset_________________________________________ 8-201MbeTag.getOffset_________________________________________ 8-201MbeTag.getMbeElement ___________________________________ 8-201MbeTag.getTaggedElement ________________________________ 8-202MbeTag.getTextElement ___________________________________ 8-202

MbeMacro Object ____________________________________________ 8-203MbeMacro.suspend _______________________________________ 8-203

Topology Objects ____________________________________________ 8-204GbeTLayerPoint.type, GbeTLayerLine.type,

GbeTLayerPolygon.typeGbeTLayerMixed.type ____________ 8-205GbeTLayerPoint.sqlStatement, GbeTLayerLine.sqlStatement,

GbeTLayerPolygon.sqlStatement, GbeTLayerMixed.sqlStatement __________________________ 8-205

GbeTLayerPoint.name, GbeTLayerLine.name, GbeTLayerPolygon.name, GbeTLayerMixed.name _________ 8-205

GbeTLayerPoint.queryList, GbeTLayerLine.queryList, GbeTLayerPolygon.queryList, GbeTLayerMixed.queryList ___ 8-206

GbeTLayerPoint.holes, GbeTLayerLine.holes, GbeTLayerPolygon.holes, GbeTLayerMixed.holes _________ 8-206

GbeTLayerPoint.shapesAsAreas, GbeTLayerLine.shapesAsAreas, GbeTLayerPolygon.shapesAsAreas,

xx MicroStation BASIC Guide

Page 23: 48784209 Microstation Basic

Table of Contents: MicroStation Extensions to BASIC

600macro.bk : 600MACRO.TOC Page xxi Friday, October 15, 1999 1:27 PM

GbeTLayerMixed.shapesAsAreas ________________________ 8-206GbeTLayerPoint.load, GbeTLayerLine.load,

GbeTLayerPolygon.load, GbeTLayerMixed.load ___________ 8-206GbeTLayerPoint.add, GbeTLayerLine.add,

GbeTLayerPolygon.add, GbeTLayerMixed.add ____________ 8-207GbeTLayerPoint.display, GbeTLayerLine.display,

GbeTLayerPolygon.display, GbeTLayerMixed.display_______ 8-207GbeTLayerPoint Object _______________________________________ 8-208

GbeTLayerPoint.color _____________________________________ 8-208GbeTLayerPoint.level _____________________________________ 8-208GbeTLayerPoint.weight____________________________________ 8-208GbeTLayerPoint.nodeType_________________________________ 8-208GbeTLayerPoint.pointPolyOverlay __________________________ 8-209

GbeTLayerLine Object ________________________________________ 8-210GbeTLayerLine.color ______________________________________ 8-210GbeTLayerLine.level ______________________________________ 8-210GbeTLayerLine.style ______________________________________ 8-210GbeTLayerLine.weight ____________________________________ 8-210GbeTLayerLine.linePolyOverlay_____________________________ 8-210

GbeTLayerPolygon Object ____________________________________ 8-212GbeTLayerPolygon.color __________________________________ 8-212GbeTLayerPolygon.level ___________________________________ 8-212GbeTLayerPolygon.style ___________________________________ 8-212GbeTLayerPolygon.weight _________________________________ 8-212GbeTLayerPolygon.fillColor ________________________________ 8-213GbeTLayerPolygon.doFill __________________________________ 8-213GbeTLayerPolygon.polyPolyOverlay_________________________ 8-213GbeTLayerPolygon.pointPolyOverlay ________________________ 8-213GbeTLayerPolygon.linePolyOverlay _________________________ 8-214

GbeTLayerMixed Object ______________________________________ 8-215GbeTLayerMixed.pointPolyOverlay__________________________ 8-215GbeTLayerMixed.linePolyOverlay ___________________________ 8-215Topology Error Codes_____________________________________ 8-216

Category Object _____________________________________________ 8-217GbeCategories.maxCategories ______________________________ 8-217GbeCategories.listByMslink ________________________________ 8-217GbeCategories(index) _____________________________________ 8-218GbeCategories.indexFromMslink____________________________ 8-218GbeCategory.attachMaps __________________________________ 8-218GbeCategory.cellLibrary ___________________________________ 8-218GbeCategory.detachMaps __________________________________ 8-218GbeCategory.fileExt_______________________________________ 8-219GbeCategory.listFeaturesByMslink___________________________ 8-219GbeCategory.listMapsByMslink _____________________________ 8-219GbeCategory.mslink ______________________________________ 8-219GbeCategory.name _______________________________________ 8-219

MicroStation BASIC Guide xxi

Page 24: 48784209 Microstation Basic

Table of Contents: MicroStation Extensions to BASIC

600macro.bk : 600MACRO.TOC Page xxii Friday, October 15, 1999 1:27 PM

Category Error Codes _____________________________________ 8-220Feature Object ______________________________________________ 8-221

GbeFeatures.maxFeatures__________________________________ 8-221GbeFeatures.listByMslink __________________________________ 8-221GbeFeatures(index)_______________________________________ 8-222GbeFeatures.indexFromMslink _____________________________ 8-222GbeFeature.categoryMslink ________________________________ 8-222GbeFeature.color _________________________________________ 8-222GbeFeature.description____________________________________ 8-222GbeFeature.display _______________________________________ 8-223GbeFeature.level _________________________________________ 8-223GbeFeature.mslink _______________________________________ 8-223GbeFeature.name ________________________________________ 8-223GbeFeature.style _________________________________________ 8-223GbeFeature.type _________________________________________ 8-223GbeFeature.weight _______________________________________ 8-224Feature Error Codes ______________________________________ 8-224

Map Object _________________________________________________ 8-225GbeMaps.maxMaps _______________________________________ 8-225GbeMaps.listByMslink_____________________________________ 8-225GbeMaps.attachByView ___________________________________ 8-226GbeMaps(index) _________________________________________ 8-226GbeMaps.indexFromMslink ________________________________ 8-226GbeMap.mslink __________________________________________ 8-226GbeMap.name ___________________________________________ 8-226GbeMap.description ______________________________________ 8-227GbeMap.directory ________________________________________ 8-227GbeMap.attach___________________________________________ 8-227GbeMap.detach __________________________________________ 8-227GbeMap.isAttached _______________________________________ 8-227GbeMap.categoryMslink ___________________________________ 8-227Map Error Codes _________________________________________ 8-228

Project Object _______________________________________________ 8-229GbeProject.DBconnect ____________________________________ 8-229GbeProject.DBload _______________________________________ 8-229GbeProject.directory ______________________________________ 8-229GbeProject.exportFile _____________________________________ 8-230GbeProject.keyMap _______________________________________ 8-230GbeProject.loginName ____________________________________ 8-230GbeProject.mapManager___________________________________ 8-230GbeProject.workMap______________________________________ 8-230GbeProject.open _________________________________________ 8-230GbeProject.close _________________________________________ 8-231Project Error Codes _______________________________________ 8-231

xxii MicroStation BASIC Guide

Page 25: 48784209 Microstation Basic

Table of Contents: Error Codes

600macro.bk : 600MACRO.TOC Page xxiii Friday, October 15, 1999 1:27 PM

9. Error CodesRuntime Error Messages _______________________________________ 9-1

Visual Basic Compatible Error Messages _____________________ 9-2MicroStation Error Messages________________________________ 9-4

Compiler Error Messages ______________________________________ 9-5Run-time error codes _________________________________________ 9-8Topology Error Codes ________________________________________ 9-8Category Error Codes _________________________________________ 9-9Feature Error Codes __________________________________________ 9-9Map Error Codes _____________________________________________ 9-10Project Error Codes ___________________________________________ 9-10

Appendix: OLE AutomationDifferences Between MicroStation BASIC and OLE Automation______ A-2

The Application object ____________________________________ A-2MicroStation-defined constants _____________________________ A-3Dim statements __________________________________________ A-3MicroStation-defined “User-Defined Types”___________________ A-4

MicroStation Application methods ______________________________ A-6OLE Automation-specific methods and objects ________________ A-7Examples________________________________________________ A-9

Appendix: MicroStation BASIC Constants

MicroStation BASIC Guide xxiii

Page 26: 48784209 Microstation Basic

Table of Contents: MicroStation BASIC Constants

600macro.bk : 600MACRO.TOC Page xxiv Friday, October 15, 1999 1:27 PM

xxiv MicroStation BASIC Guide

Page 27: 48784209 Microstation Basic

600macro.bk : 601P_PT1 Page 39 Friday, October 15, 1999 1:27 PM

Part I: Concepts and Procedures

Page 28: 48784209 Microstation Basic

600macro.bk : 601P_PT1 Page 40 Friday, October 15, 1999 1:27 PM

Page 29: 48784209 Microstation Basic

600macro.bk : 601_MINT.FRA Page 1 Friday, October 15, 1999 1:27 PM

1 Introduction to Macros

Macros are BASIC programs that automate often-used, usually short sequences of operations. Many MicroStation-specific extensions have been added to the BASIC language to customize it for the MicroStation environment.

In its simplest form, a macro “drives” MicroStation in much the same way a human user does. Macros select tools and view controls, send key-ins, manipulate dialog boxes, modify elements, and more, using many of the tools documented in this guide. The obvious advantage of writing a macro to perform a task that could otherwise be done manually is automating mechanical and repetitive tasks. Several sample macros are supplied with MicroStation.

✍ This guide covers the entire functionality of MicroStation BASIC. Some of the MicroStation BASIC extensions documented cannot be used to develop macros for some products, since those products do not have the same functionality as MicroStation 95 and other Bentley engineering products. Subject to these limitations, references in this guide to “MicroStation” also apply to MicroStation-based products, such as MicroStation PowerDraft and MicroStation PowerScope.

Creating MacrosWriting macros for MicroStation was designed to be as simple as possible.

First, we chose the BASIC language because of its ease-of-use and rich functionality.

Second, we extended the BASIC language to include many statements that closely resemble familiar MicroStation commands and actions. In this way, the macro facility capitalizes on your knowledge about the MicroStation interface. For example, the macro command MbeSendDataPoint sends a data point to MicroStation. All BASIC language extensions are easily recognized by their Mbe prefix.

Third, MicroStation has a built-in macro generator that allows users to write macro prototypes by recording the task as it is

MicroStation BASIC Guide 1-1

Page 30: 48784209 Microstation Basic

Creating Macros

600macro.bk : 601_MINT.FRA Page 2 Friday, October 15, 1999 1:27 PM

manually performed. This feature also serves as a learning aid for macro writing. (To learn how to write a macro that performs a particular MicroStation task, execute the task manually with the macro generator running and then review the generated macro program.)

✍ For more flexible and powerful macro programming, many other BASIC language extensions are available in MicroStation. These include commands to interactively accept CAD input (data points, resets, etc.) as well as display standard and custom dialogs to collect additional information during the execution of a macro. There are also “object” extensions representing different types of data in MicroStation, like elements and current session information. The combination of standard BASIC language functionality and all MicroStation extensions makes for a rich programming environment.

Guidelines for creating a macroCreating a macro involves running the macro generator, adding BASIC language constructs, and making the program more interactive.

Running the macro generator

In most cases, use MicroStation’s Macro Generator to generate a rough prototype of the program. Start the macro generator, perform the general task to be echoed by the macro, and then stop the macro generator. Afterwards, a small macro program reflects the actions performed during the generation.

Adding BASIC language constructs

The newly generated macro consists almost entirely of MicroStation BASIC language extensions because MicroStation activity cannot be expressed in terms of standard BASIC. At this point, the macro writer may wish to make the program more useful by replacing hard-coded coordinates with BASIC variables or adding looping commands so the task can be performed multiple times. In general, edit the program to take advantage of the features of the BASIC language to make the macro more useful.

Making the program more interactive

An additional level of flexibility can be gained with a macro by querying the user for additional information during its execution. For example, instead of always playing back a macro with the

1-2 MicroStation BASIC Guide

Page 31: 48784209 Microstation Basic

Creating Macros

Intr

oduc

tion

to M

acro

s 1

600macro.bk : 601_MINT.FRA Page 3 Friday, October 15, 1999 1:27 PM

fixed coordinates of its original generation, the macro could ask the user to enter a data point interactively. This is accomplished using the MbeGetInput extension.

It may also be necessary for the macro to collect more general information such as string, integer, or floating point values. Several utility dialogs are available as extensions to the macro language for this purpose. Some standard dialogs in MicroStation, such as the File Open and File Create dialogs, are also available. Custom dialogs can also be displayed by macros to collect more specialized information. Such dialogs are designed using the BASIC Editor window.

Advanced macro programmingIn many cases, you will need access to detailed information about the graphics environment while writing a macro. Many extensions to the BASIC language have been provided to answer this need. Where possible, the MicroStation graphics environment is presented to a macro programmer in the form of well developed objects with properties and methods. This organization makes data management easier and isolates the macro writer from file update logic.

Here is an overview of the different types of BASIC programming extensions available:

• Element Object Extensions — MbeElement organizes design file elements into objects with sets of properties and functions. A macro using these objects can manipulate elements without knowing all the details of element formats.

• Element Set Object Extensions — MbeElementSet extension simplifies processing of multiple MbeElement elements selected by the user with either a selection set or fence.

• Element Location Extensions — Allow you to generate element selection/location information for one or more elements and feed this information into standard MicroStation tools.

• Design File Information Object Extensions — MbeDgnInfo organizes design file information into properties and methods of the current design file.

• Settings Object Extensions — MbeSettings organizes overall session information, such as active settings and locks, into a system object with property and method extensions.

• State Object Extensions — An MbeState object is used to encapsulate information about the current state of MicroStation.

MicroStation BASIC Guide 1-3

Page 32: 48784209 Microstation Basic

Creating Macros

600macro.bk : 601_MINT.FRA Page 4 Friday, October 15, 1999 1:27 PM

For example, “What input is available from the user?” and “What were the results of the last command sequenced by my macro?”.

• Design View Information Object Extensions — An array of MbeView objects is provided as a way of reading and writing MicroStation design view information.

• Reference File Object Extensions — Reference file attributes such as file name, description, scale and many others are encapsulated in MbeRefFile objects.

✍ It is possible to provide command line arguments to the macro from the Key-in window. The macro accesses these arguments, if any, through the Command$ BASIC statement.

1-4 MicroStation BASIC Guide

Page 33: 48784209 Microstation Basic

Running Macros

Intr

oduc

tion

to M

acro

s 1

600macro.bk : 601_MINT.FRA Page 5 Friday, October 15, 1999 1:27 PM

Running MacrosYou can load and run a macro using the Macros settings box or a key-in.

➤ To load and run a macro

1. From the Utilities menu, choose Macros.

The Macros settings box opens.

2. In the Macro Name list box, select the macro.

3. Click the Run button.

OR

1. From the Utilities menu, choose Macros.

The Macros settings box opens.

2. Click the Browse button.

The Select Macro dialog box opens.

3. Key in or select the desired macro, and click the OK button.

The Start Macro dialog box opens.

4. Click the Run button.

OR

◆ In the Key-in window, key in:

MACRO <macro_name> [arg1 arg2 ... argn]

MbeSendKeyin “<macro_name> [arg1 arg2 ... argn]”

Macros settings box

MicroStation BASIC Guide 1-5

Page 34: 48784209 Microstation Basic

Creating and Managing Macros

600macro.bk : 601_MINT.FRA Page 6 Friday, October 15, 1999 1:27 PM

Creating and Managing MacrosYou can create and manage your macros using the Create Macro dialog box and the Macros dialog box. You can also use the Customize dialog box to create a tool or menu item that runs a macro.

Generating macrosCreate Macro is used to generate a macro based on your actions in MicroStation.

➤ To generate a macro

1. From the Utilities menu, select Create Macro …

The Create Macro dialog box opens.

2. Key in the name and description of the macro to be generated.

3. Click the OK button to start the macro generation session.

The macro begins and a small dialog box opens.

4. Control your macro session by choosing the dialog buttons as follows:

Play — When this button is clicked, your actions are captured and written to the macro. When the dialog box is initially displayed, the Play button is automatically selected.

Pause — When this button is clicked your actions are not written to the macro. Pausing is useful when actions should not be captured before the macro is finished. Click the Play button to resume generating the macro.

Create Macro dialog box

Dialog box with controls formacro session, Play (left),

Pause (middle), andEnd (right)

1-6 MicroStation BASIC Guide

Page 35: 48784209 Microstation Basic

Creating and Managing Macros

Intr

oduc

tion

to M

acro

s 1

600macro.bk : 601_MINT.FRA Page 7 Friday, October 15, 1999 1:27 PM

End — Clicking this button has the same effect as choosing End Macro from the Utilities menu: the dialog box closes.

Managing macrosThe Macros settings box is used to display a list of available macros and optionally to run, edit, or debug a given macro.

BASIC Editor

The BASIC Editor window is used to display, edit and debug macros.

➤ To open the BASIC Editor window

1. From the Utilities menu, choose Macros.

The Macros dialog box opens.

2. Select a macro name from the list box.

3. Click the Edit… button.

OR

◆ Key in:

macro debug <macroname> [arg1 arg2 ... argn]

MicroStation BASIC Guide 1-7

Page 36: 48784209 Microstation Basic

600macro.bk : 601_MINT.FRA Page 8 Friday, October 15, 1999 1:27 PM

where macroname can have either no extension or a .bas extension. If no extension is given, .bas is assumed.

The large multiline text field is a limited functionality ASCII editor. The icons above this edit window allow for single stepping through macro commands, stepping into macro subroutines, viewing and changing the values of variables, setting breakpoints, running the macro to completion and stopping the debugger.

Adding macros to MicroStation’s user interfaceThe Customize dialog box (Workspace menu/Customize) is used to customize MicroStation’s graphical user-interface. Since any key-in may be assigned to a customized tool box icon, macro key-ins can be assigned to icons for starting macros with a single click.

The key-in to run a macro is:

macro debug <macroname> [arg1 arg2 ... argn]

where macroname can have either the .ba or .bas extension.

BASIC Editor window

1-8 MicroStation BASIC Guide

Page 37: 48784209 Microstation Basic

Creating and Managing Macros

Intr

oduc

tion

to M

acro

s 1

600macro.bk : 601_MINT.FRA Page 9 Friday, October 15, 1999 1:27 PM

MicroStation BASIC Guide 1-9

Page 38: 48784209 Microstation Basic

Creating and Managing Macros

600macro.bk : 601_MINT.FRA Page 10 Friday, October 15, 1999 1:27 PM

1-10 MicroStation BASIC Guide

Page 39: 48784209 Microstation Basic

600macro.bk : 602_PRO.FRA Page 1 Friday, October 15, 1999 1:27 PM

2 Prototyping, Editing, and Debugging Macros

Planning, prototyping, editing, and debugging a macro is usually performed in one large, often continuous, step. Even though you may carefully plan your macro, you may make changes to this plan during the editing and debugging phases.

PrototypingUsually, the first step in writing a macro is to generate a prototype program with the macro generator. The macro generator “watches” user actions in MicroStation and tries to generate an approximate macro command, or series of commands, that duplicate the actions. A user can “sketch” a rough program by manually performing the task while the macro generator translates the actions into a series of macro commands.

A small dialog appears on the screen containing three buttons. This is a control dialog for the macro generator, used for pausing, resuming, and stopping the macro generator.

Starting conditionsIn some cases, the generated macro program may require certain conditions before starting. If this case, generate the original prototype with similar starting conditions. So, before starting the prototype session, you may wish to “set the stage” for the macro. For example, you may design a macro program that operates on selection sets and expects a selection set to exist before the macro starts. In that case, create a selection set that is representative of those to be operated on by the finished macro. A selection set is one example of a pre-condition. Other examples of pre-conditions are: the presence on the screen of a particular view window or dialog box or activation of a particular design file.

The Create Macro dialog boxThe Create Macro dialog box is used to supply three pieces of information about the new macro: the macro name, a description of the macro, and optionally, a location other than the default macro directory where the generated macro file will be stored.

MicroStation BASIC Guide 2-1

Page 40: 48784209 Microstation Basic

Prototyping

600macro.bk : 602_PRO.FRA Page 2 Friday, October 15, 1999 1:27 PM

The first text field in the dialog, labeled “Name”, assigns a name to the macro. The name of the macro has an 8 character limitation and is used as the base filename of the generated macro program.

The second text field is labeled “Description”. The user can enter a free-form description of the macro and the actions it performs. This description becomes part of the program in the form of a comment block.

For the most part, you do not need to know that a macro program is stored as a file. In some cases, however, you may wish to save the macro to an alternate location from the default directory. The Location option menu at the bottom of the Create Macro dialog is supplied for this reason. This option menu shows all the directory names listed in the MS_MACRO configuration variable. To save the macro in one of the alternate directories, choose the appropriate directory from the option menu. If more directory names need to be added to the option menu, you must change the MS_MACRO configuration variable to contain the new directory names, then display the Create Macro dialog again.

This somewhat structured control over the location of macros is a deliberate measure to de-emphasize a macro’s location as a file and to instead focus attention on its name and description.

The remaining controls in the Create Macro dialog box are the OK and Cancel buttons. If Cancel is clicked, the entire session is ignored and the macro generator will not start. If OK is clicked, the Create Macro dialog is dismissed and a small control dialog for the macro generator becomes active and “watches” for user actions to translate and save as macro statements.

Stopping the macro generatorTo stop the macro generator, click the stop button in the control dialog or choose End Macro from the Utilities menu. This menu item replaces the Create Macro... menu item when the macro generator starts. Likewise, when the macro generator is stopped, the End Macro menu item is replaced by Create Macro.

Once the macro generator is stopped, the generation of the prototype macro program is finished and the control dialog is closed. At this point, the user will typically go to the BASIC Editor window to shape the macro into final form. Before beginning our discussion of the BASIC Editor, let’s look at some commands that are commonly generated by the macro generator.

2-2 MicroStation BASIC Guide

Page 41: 48784209 Microstation Basic

Prototyping

Prot

otyp

ing

, Ed

iting

, and

Deb

ugg

ing

Mac

ros

2

600macro.bk : 602_PRO.FRA Page 3 Friday, October 15, 1999 1:27 PM

The form of a prototype macroHere is an example of a prototype macro created by the macro generator. In this example, the macro generator captured the placement of a circle and a block.

' Place circle and block

Sub main

Dim startPoint As MbePointDim Point As MbePoint, point2 As MbePoint

' Start a commandMbeSendCommand “PLACE CIRCLE ICON”

' Coordinates are in master unitsstartPoint.x = 214704.345000#startPoint.y = 214775.629900#startPoint.z = 268473.667900#

' Send a data point to the current commandpoint.x = startPoint.xpoint.y = startPoint.ypoint.z = startPoint.zMbeSendDataPoint point, 5%

point.x = startPoint.x - 4.674700#point.y = startPoint.y + 1.775400#point.z = startPoint.z + 0.393900#MbeSendDataPoint point, 5%

MbeSendCommand "PLACE BLOCK ICON"

point.x = startPoint.x - 8.006900#point.y = startPoint.y + 4.023000#point.z = startPoint.z + 5.908800#MbeSendDataPoint point, 5%

point.x = startPoint.x - 6.943600#point.y = startPoint.y + 3.728400#point.z = startPoint.z + 6.401300#MbeSendDataPoint point, 5%

MbeSendResetEnd Sub

MicroStation BASIC Guide 2-3

Page 42: 48784209 Microstation Basic

Prototyping

600macro.bk : 602_PRO.FRA Page 4 Friday, October 15, 1999 1:27 PM

The macro has two major parts. The macro description, which appears first in the file, can be edited but must always appear at the top of the macro program.

The remaining part of the macro is the program itself. The macro generator will always generate one flat subroutine called main. The subroutine is flat because it does not call any other subroutines.

Because the BASIC language was not designed for CAD environments, new BASIC language elements had to be added to the MicroStation BASIC interpreter. These new language elements will hereafter be referred to as “BASIC extensions” or just “extensions.”

To make the BASIC extensions for MicroStation easy to distinguish from standard BASIC, we follow one naming convention: all MicroStation BASIC extensions begin with the letters “Mbe.”

In the example, three unique extension calls were generated: MbeSendCommand, MbeSendDataPoint and MbeSendReset. Although the BASIC interpreter is not case-sensitive, initial capitalization makes the extensions easier to read. The first use of each extension is preceded by a comment describing its purpose. Also, parameters to functions are shown with datatype suffixes to be clear about the type of data being passed.

Although a simple review of the program created by the macro generator is informative, users should review documentation for all MicroStation extensions. Some generated macros do not show all the ways extensions can be called. For example, some extensions take optional arguments which may, or may not, be used by the macro generator. Also, some extension functions have “overloaded” argument lists, meaning they can take different types of arguments depending on the goal.

BASIC extensions commonly used by the macro generatorThe following list highlights the extensions used by the macro generator to approximate the user’s actions in MicroStation:

Command Used to

MbeSendCommand Issues a MicroStation command

MbeSendDataPoint Issues a data point

MbeSendTentPoint Issues a tentative point

2-4 MicroStation BASIC Guide

Page 43: 48784209 Microstation Basic

Prototyping

Prot

otyp

ing

, Ed

iting

, and

Deb

ugg

ing

Mac

ros

2

600macro.bk : 602_PRO.FRA Page 5 Friday, October 15, 1999 1:27 PM

MbeSendReset Issues a Reset

MbeSendKeyin Sends a key-in string to MicroStation

MbeSendDragPoints Simulates a drag of the pointing device

MbeSetAppVariable Sets the state of a dialog box application variable

MbeSetScaledAppVar Sets the state of a dialog box application variable; the values represent distances or coordinates in Master Units.

MbeSendAppMessage Initiate an application-defined event.

Command Used to

MicroStation BASIC Guide 2-5

Page 44: 48784209 Microstation Basic

The BASIC Editor

600macro.bk : 602_PRO.FRA Page 6 Friday, October 15, 1999 1:27 PM

The BASIC EditorAfter generating a macro prototype, you can edit the macro to refine its behavior and extend its usefulness. Since macro source files (.bas extension) are text, you can edit them outside the MicroStation Macro graphics environment using any text editor then return to the MicroStation environment to run the macro. Another option is to use MicroStation’s BASIC Editor window to edit Macros. The built-in editor provides debugging capabilities for testing changes during editing.

➤ To edit an existing macro

1. From the Utilities Menu, choose Macros.

2. In the list box, select the macro to be edited.

or

Click the Browse button and use the select Macro dialog box to select the Macro.

3. Click the Edit button.

Macros dialog box

2-6 MicroStation BASIC Guide

Page 45: 48784209 Microstation Basic

The BASIC Editor

Prot

otyp

ing

, Ed

iting

, and

Deb

ugg

ing

Mac

ros

2

600macro.bk : 602_PRO.FRA Page 7 Friday, October 15, 1999 1:27 PM

The BASIC Editor window opens.

4. Make the desired edits.

5. Save the changes to disk.

✍ As an alternate to steps 1-3, you can open the BASIC Editor window by keying MACRO DEBUG <macroname>.

Text editing area and scrollingThe text editing area is the large rectangle that spans most of the BASIC Editor window is resized, so is the editing area. Thus, users can increase or decrease the number of visible rows and columns in the editing area. The editing area allows text strings to be entered and edited and supports vertical scrolling.

Press the <Return> key to enter a line break. The standard cut, copy, and paste operations are supported. Select multiple characters by dragging the cursor through text ranges and by performing keyboard navigation while holding down the <Shift> key.

Horizontal scrolling is also supported. Control horizontal scrolling by moving the pointer to the left or right. As the pointer moves

MicroStation BASIC Guide 2-7

Page 46: 48784209 Microstation Basic

The BASIC Editor

600macro.bk : 602_PRO.FRA Page 8 Friday, October 15, 1999 1:27 PM

out of the editing area, MicroStation scrolls the text so the cursor remains in the editing area.

Status message fieldThe status message field is a read-only, text field used to display debugger status messages. It is located directly beneath the text editing area on the left side of the window. Stretch the width of the window to expand the field size.

Line number and column number fieldsThe line number and column number fields are read-only, text fields that show the macro program line and column numbers where the cursor is currently positioned. These fields are always synchronized with cursor movement, either from a user key-in (for example, Up arrow or <Pg Dn>) or from a macro error during debugging.

File menu

New

Discards the current macro file being edited and clears the text editing area. The new (empty) buffer will be untitled. Use “Save As” before debugging the new macro.

Open

Displays the Open BASIC Source file dialog box to select a new macro file for editing. If a new macro file is already selected, the macro file currently being edited is discarded and the new macro file is loaded into the text editing area.

Save

Saves the text updates to the macro file on disk.

Save As…

Allows the user to save the current text editing area contents to a new macro file name. The Save Source To dialog box displays so that the user may choose the new macro file name.

2-8 MicroStation BASIC Guide

Page 47: 48784209 Microstation Basic

The BASIC Editor

Prot

otyp

ing

, Ed

iting

, and

Deb

ugg

ing

Mac

ros

2

600macro.bk : 602_PRO.FRA Page 9 Friday, October 15, 1999 1:27 PM

Exit

Causes the Macro Editor to be unloaded. If the contents of the text editing area have been modified but not yet saved, the user is warned and given an opportunity to save the updates to the macro file at this time.

Edit menu

Undo

Undo negates the last modification to the text by the user. After you undo an operation, the preceding operation cannot be undone. You can undo a series of operations by repeatedly choosing this option.

Redo

This is effective after an undo command has been executed. It negates the undo, changing the text to its original format before the undo took place.

Find

Opens the Find Text dialog box. Type in the text to find. To make the search case-sensitive, enable the Match Case toggle button. Then, start the search by clicking the OK button. MicroStation highlights the first match moving forward from the pointer position.

Find Next

Searches for the next occurrence of the text you entered in the Find text dialog box.

Cut

Copies the currently selected text in the text editing area to the clipboard, deleting the text from the text editor window afterwards.

Copy

Copies the currently selected text in the text editing area to the clipboard. The existing text editing area contents remain intact.

Paste

Copies text from the clipboard into the text editing area at the location of the cursor.

MicroStation BASIC Guide 2-9

Page 48: 48784209 Microstation Basic

The BASIC Editor

600macro.bk : 602_PRO.FRA Page 10 Friday, October 15, 1999 1:27 PM

Variables

Opens the Variables window. For more on variables and the Variables window, refer to the section “Working with variables” on page 2-12.

Custom Dialog > Edit…

Opens the Builder dialog box, which is used to create custom dialog boxes. All custom dialogs created will be saved as resources in the compiled version of the macro (the.BA file).

Custom Dialog > Insert…

Displays a list of custom dialogs defined for the current macro. Selecting an entry in the list enters a line of source code in the macro at the current cursor position:

actionbutton = MbeOpenModalDialog (<chosen dialogId>)

Program Entry Point

Allows the programmer to designate BASIC functions to be called for use in the plotting process. The BASIC functions defined by program entry points provide customization for the final plot when standard pen tables are not sufficient.

Run menu

Execute

Compiles the current macro and runs it from the beginning. If the debugger is active when Execute is chosen, the debugger is stopped before the compilation starts.

Break

Causes a breakpoint to be toggled (set or reset) at the current line position in the text editing area indicated by the cursor position.

Step Into

Causes the debugger to execute the currently highlighted line in the macro. If the currently highlighted line is a subprocedure call, the debugger traces execution “down and into” the subprocedure then stops and highlights the first executable line in the subprocedure.

2-10 MicroStation BASIC Guide

Page 49: 48784209 Microstation Basic

The BASIC Editor

Prot

otyp

ing

, Ed

iting

, and

Deb

ugg

ing

Mac

ros

2

600macro.bk : 602_PRO.FRA Page 11 Friday, October 15, 1999 1:27 PM

Step Over

Causes the debugger to execute the currently highlighted line in the macro. If the currently highlighted line is a subprocedure call, the debugger runs all statements in the subprocedure before stopping and highlighting the first executable line after the subprocedure call.

Go

Causes the debugger to continue executing the macro from the current statement forward until completion or until a breakpoint is encountered. If a breakpoint is encountered, the debugger suspends the macro and highlights the current line.

Stop Debug

Causes the debugger to abort the current debugging session for the macro. Breakpoint information remains intact.

Debugger iconsThe following icons appear at the top of the BASIC Editor window:

To Click

Continue execution of macro.Go

Halt execution of macro.Stop

Toggle a breakpoint.Toggle Breakpoint

Execute one line of source and trace execution into a subroutine if necessary.

Step Into

Execute one line of source without tracing execution into subroutines.

Step Over

Opens the Variables dialog for viewing and modifying BASIC variables.

Edit Variables

MicroStation BASIC Guide 2-11

Page 50: 48784209 Microstation Basic

The BASIC Editor

600macro.bk : 602_PRO.FRA Page 12 Friday, October 15, 1999 1:27 PM

Working with variablesUse the Variables window to view and change the values of BASIC variables of a macro running in the debugger. All simple BASIC data types are supported: integer (%), long integer (&), string ($), single (!) and double (#). In addition, members of user-defined types and arrays may also be viewed and changed. Objects defined by the macro are shown by name, but constituent properties cannot be accessed.

To display the Variables, choose Edit > Variable or click the Edit Variable icon in the BASIC Editor window.

Public, private and local variables

As you step through a macro in the debugger, the Variables window updates automatically to show all variables in use by the macro at each stage of your debugging session. Public, private and local variables are color-coded for easy identification. (See “Variable Scope” on page 3-9 for a discussion on public, private and local variables.) Color is also used to highlight changed values of variables as the user steps through a macro in the debugger. By default, updated values are displayed in red.

As you step into a subroutine in the debugger, the calling subroutine’s local variables go “out of scope” and therefore are automatically removed from the list. Likewise, once the first executable statement in the new subroutine is highlighted, the variables that are local to that subroutine are automatically added

Variables window

2-12 MicroStation BASIC Guide

Page 51: 48784209 Microstation Basic

The BASIC Editor

Prot

otyp

ing

, Ed

iting

, and

Deb

ugg

ing

Mac

ros

2

600macro.bk : 602_PRO.FRA Page 13 Friday, October 15, 1999 1:27 PM

to the list. Public and private variables always remain in the list while the macro is being debugged.

Expanding and collapsing complex variables

Expand user-defined types (UDT) and arrays to show their constituent members by double-clicking on the respective entry in the list. To expand a UDT or array from the keyboard, use the cursor keys to highlight the entry in the list, then press the <Return> key. In the same manner, an expanded UDT or array can be collapsed down again by double-clicking on its entry in the list.

Changing values

You can change the value of a BASIC variable in the list if it is one of these data types: integer, long integer, string, single-precision floating point or double-precision floating point. Change the value of one of these data types using a procedure identical to expanding or collapsing UDTs and arrays. Double-click on the appropriate entry or press the <Return> key after the entry is highlighted. The value displays for editing in the Change Variable Value dialog box.

Change Variable Valuedialog box

MicroStation BASIC Guide 2-13

Page 52: 48784209 Microstation Basic

The BASIC Editor

600macro.bk : 602_PRO.FRA Page 14 Friday, October 15, 1999 1:27 PM

2-14 MicroStation BASIC Guide

Page 53: 48784209 Microstation Basic

600macro.bk : 603_LNO.FRA Page 1 Friday, October 15, 1999 1:27 PM

3 Macro Language Overview

The MicroStation macro language is BASIC with MicroStation-specific extensions.

This chapter is intended as an overview of BASIC. If you need more information about BASIC than provided here, refer to a BASIC reference book. For information about the macro language’s MicroStation-specific extensions, see “Macro Interactions With MicroStation” on page 4-1.

CommentsYou can put comments in a macro to explain what it does, how it does it, why it does it, and for any other reason you choose. In fact, the text you entered as the description when you created the macro is inserted as comments on the first lines of the macro.

A single quote ( ' ) anywhere on a line indicates the beginning of a comment.

Example ' This is a comment beginning at the left edge of the screen.Print "Hello, world!" ' The comment extends to the end of the line

The entire line is treated as a comment when it begins with the Rem statement

Example Rem Both lines in this exampleRem are treated as comments.

The examples in this chapter will include comments to tell you more about them.

Naming RulesAll names in macros, such as the names of variables, procedures, labels, and object properties, must follow the same naming rules:

• Names are composed of alphabetic characters, digits 0 to 9, and the underbar (_).

• Names must begin with an alphabetic character.

MicroStation BASIC Guide 3-1

Page 54: 48784209 Microstation Basic

Built-in Data Types

600macro.bk : 603_LNO.FRA Page 2 Friday, October 15, 1999 1:27 PM

• Names cannot be longer than 40 characters.

• Names are not case-sensitive. Capitalization is used only to make a macro easier to read.

The following names are valid:

Dim origin, point2, cell_origin ' Names of variablesDim viewNumber ' Another variable name

The following names are invalid:

Dim 1view ' Names cannot begin with a digit.Dim point@start ' Illegal character in the name.

Built-in Data TypesAll variables and literal constants (hard-coded values) in a macro are associated with a specific data type.

IntegersAn integer is a whole number like 0, 2048, or -13. Integer variables can contain positive or negative numbers in the range from -32768 to 32767.

Long integersLong integers are like integers, but the range of values is much larger. Long variables can contain whole numbers in the range from -2,147,483,648 to 2,147,483,647.

StringsA string variable contains a group of ASCII characters, i.e., the characters “Hello, world!” or “Area = 20411.2 SQ FT”. A string variable can hold up to 32,767 characters.

A string literal constant is a double quoted group of characters. If double quotes are needed in the constant, use two double quote characters.

Example Print "John said ""Hello"" to Jane and Mary."

The maximum number of characters in a string literal constant is 255.

3-2 MicroStation BASIC Guide

Page 55: 48784209 Microstation Basic

Variable Declarations

Mac

ro L

ang

uage

Ove

rvie

w 3

600macro.bk : 603_LNO.FRA Page 3 Friday, October 15, 1999 1:27 PM

SinglesA single-precision floating point value is a real number like 0.5 or -414.75. Single variables have seven significant digits and contain negative values from -3.402823E38 to -1.401298E-45 and positive values from 1.401298E-45 to 3.402823E38.

A single literal constant is a number with a decimal point. If the value is very large, very small, or very close to 0, it should be expressed as nnnnEeee where nnnn is the mantissa and eee is the exponent.

The single-precision float is formatted according to IEEE standards.

DoublesDouble-precision floating point numbers are like single-precision floating point numbers, but more digits are significant and the ranges of possible values are much larger. Double variables have 15 significant digits and contain negative values from -1.797693134862315E308 to -4.94066E-324 and positive values from 4.94066E-324 to 1.797693134862315E308.

A double literal constant is a number with a decimal point. If the value is very large, very small, or very close to 0, it should be expressed using the same nnnnEeee format, as for a single literal constant.

The double-precision float is formatted according to IEEE standards.

Variable DeclarationsYou specify, or declare, the data type of a variable in one of two ways:

• Explicitly when the variable is dimensioned at the beginning of the macro or procedure.

• Implicitly when the variable is used the first time by appending a type character to the name.

✍ Declaring variables explicitly is recommended because it makes it easier for you to read and debug your macros.

MicroStation BASIC Guide 3-3

Page 56: 48784209 Microstation Basic

Variable Declarations

600macro.bk : 603_LNO.FRA Page 4 Friday, October 15, 1999 1:27 PM

Declaring integer variablesInteger variables are declared explicitly in a Dim (dimension) statement by appending an As Integer clause or by appending a percent sign (%) to the variable name.

Example Dim count As Integer ' Explicit integer declarationsDim viewNumber%

Integer variables are declared implicitly by appending a percent sign to the variable name the first time it is used.

Example previousView% = viewNumber ' Implicit declaration of previousView

When a variable is used without being declared either explicitly or implicitly, it is an integer variable.

Declaring long variablesLong integer variables are declared explicitly in a Dim statement by appending an As Long clause or by appending an ampersand (&) to the variable name.

Example Dim filePosition As Long ' Explicit long integer declarationsDim elemLength&

Long variables are declared implicitly by appending an ampersand to the variable name the first time is it used.

Example newLength& = elemLength + 10 ' Implicit declaration of newLength

Declaring string variablesString variables are declared explicitly in a Dim statement by appending an As String clause or by appending a dollar sign ($) to the variable name.

Example Dim textBuffer As String ' Explicit string declarationsDim commandName$

String variables are declared implicitly by appending a dollar sign to the variable name the first time it is used.

Example title$ = "First Floor Plan" ' Implicit declaration of title

String variables do not have a fixed length. Longer or shorter groups of characters can be assigned to a string variable without losing characters or padding the value with spaces.

3-4 MicroStation BASIC Guide

Page 57: 48784209 Microstation Basic

Arrays of Variables

Mac

ro L

ang

uage

Ove

rvie

w 3

600macro.bk : 603_LNO.FRA Page 5 Friday, October 15, 1999 1:27 PM

Declaring single variablesSingle-precision floating point variables are declared explicitly in a Dim statement by appending an As Single clause or by appending an exclamation point (!) to the variable name.

Example Dim tempF As Single ' Explicit single declarationsDim fraction!

Single variables are declared implicitly by appending an exclamation point to the variable name the first time it is used.

Example tempC! = 5 * (tempF - 32) / 9 ' Implicit declaration of tempC

✍ Using double variables to store floating point values is recommended over using single variables. Calculations on doubles are faster than calculations on singles.

Declaring double variablesDouble-precision floating point variables are declared explicitly in a Dim statement by appending an As Double clause or by appending a pound sign (#) to the variable name.

Example Dim scale As Double ' Explicit double declarationsDim origin#

Double variables are declared implicitly by appending a pound sign to the variable name the first time it is used.

Example endPoint# = origin + origin / 2 ' Implicit declaration of endPoint

Arrays of VariablesAn array is a group of related variables of the same data type. With arrays, you can refer to a series of variables by using a single name and then use a number (an index) to refer to a particular variable within the array. Arrays have both a lower and an upper bound, and the elements of the array are contiguous.

Example ' Declare an array of 32 file names. Indices are from 0 to 31Dim refFiles(31) As StringrefFiles(0) = "city.dgn" ' Set the first member...message$ = "Reference File: " + refFiles(31) ' Use the last member

MicroStation BASIC Guide 3-5

Page 58: 48784209 Microstation Basic

Arrays of Variables

600macro.bk : 603_LNO.FRA Page 6 Friday, October 15, 1999 1:27 PM

The array in the above example is a one dimensional array. You can also work with multi-dimensional arrays of up to 60 dimensions. When you refer to a member of a multi-dimensional array, you must specify the index in each dimension.

Example Dim vertex#(1,2) ' Declare 2x3 array of coordinatesvertex(0,0) = 0.0 ' X, Y, Z coordinates of first vertexvertex(0,1) = -0.5vertex(0,2) = 1000.0vertex(1,0) = vertex(0,0) ' Coordinates of second vertexvertex(1,1) = vertex(0,1) + 203.5vertex(1,2) = vertex(0,2)

✍ Array members are rarely set using literal constant indices as in the examples above. Instead, arrays are often referenced within loops. For more information see “Do...Loop” on page 3-19 and “For...Next” on page 3-22.

Fixed-length arraysWhen the number of dimensions and the lower and upper bounds of each dimension are known ahead of time, declare a fixed-length array with the Dim statement.

Only the upper bound in each dimension must be specified when declaring a fixed-length array. The default lower bound is 0.

Example Dim referenceFile$(31) ' Array of 32 character stringsDim vertex(1,2) As Double ' 2x3 array of doubles

You can change the default lower bound to 1 by putting an Option Base 1 statement outside of any subroutines and functions.

Example Option Base 1...' Declaring the arrays when Option Base 1 is specified.Dim referenceFile$(32) ' Indices from 1 to 32Dim vertex(2,3) As Double ' First member is (1,1), last is (2,3)

You also can set the lower bound in an array dimension explicitly using the To keyword. One or both of the bounds may be negative integers. The range for array bounds is from -32,768 to 32,767.

Example Dim viewFlags%(1 To 8) ' Explicitly set lower bound to 1Dim points#(100, -1 To 1) ' Second dimension indices are -1, 0, 1

3-6 MicroStation BASIC Guide

Page 59: 48784209 Microstation Basic

Arrays of Variables

Mac

ro L

ang

uage

Ove

rvie

w 3

600macro.bk : 603_LNO.FRA Page 7 Friday, October 15, 1999 1:27 PM

Variable-length arraysWhen the number of dimensions or the bounds in a dimension are not known ahead of time or will change, declare a variable-length array with the Dim statement. Declaring a variable-length array differs from declaring a fixed-length array in that you do not specify the array bounds.

Example Dim attachedFiles() As String ' Number of attached files is unknownDim points#() ' Number of points will change

The dimensions of the array are defined at runtime by using the ReDim (redimension) statement. The bounds are specified much as they are in the Dim statement.

Example numRefFiles% = 10 ' 10 reference files are attachedReDim attachedFiles(1 To numRefFiles)numPoints% = 5 ' Shape is a pentagonReDim points(numPoints, -1 To 1)

You can change the size of an array with the ReDim statement many times when running a macro. If the contents of the array should be saved when it is resized, add the Preserve option to the ReDim statement. You may not change the number of array dimensions if you are preserving the contents of the array while resizing it.

Example Dim textBuffer$() ' Declare variable array of stringsnumLines% = 10 ' Start with 10 linesReDim textBuffer(numLines)numLines = numLines + 10 ' Add 10 lines and preserve contentsReDim Preserve textBuffer(numLines)numLine = numLines - 5 ' Remove last 5 lines from textBufferReDim Preserve textBuffer(numLines)

You can use the ArrayDims function to query the number of dimensions in an array and the LBound and UBound functions to find out the lower and upper bounds, respectively, of a dimension.

MicroStation BASIC Guide 3-7

Page 60: 48784209 Microstation Basic

User-defined Data Type Variables

600macro.bk : 603_LNO.FRA Page 8 Friday, October 15, 1999 1:27 PM

User-defined Data Type VariablesA user-defined data type is a data structure, or record, that contains more than one variable. The variables, or fields, in the record, represent related pieces of information and can be different data types. When you declare a variable of a user-defined data type, the pieces of information are grouped together and can be accessed through the same variable.

Creating a user-defined data typeA user-defined data type is created with a Type...End Type statement outside of all the subroutines and functions in the macro. The general format is:

Type usernamevariable1 As type1variable2 As type2...variableN As typeN

End Type

The name of the user-defined data type is username. Each field in the user-defined data type is defined with a variable name and a corresponding data type. The data type of a field can be any built-in data type or a user-defined data type created earlier in the macro. A field can also be a fixed-length array.

Example Type Point2d ' Create a 2D point data typex As Doubley As Double

End Type

Example Type TableDescription ' Create a table description data typetitle As Stringorigin As Point2dextent As Point2dname(1 To 32) As String

End Type

3-8 MicroStation BASIC Guide

Page 61: 48784209 Microstation Basic

Variable Scope

Mac

ro L

ang

uage

Ove

rvie

w 3

600macro.bk : 603_LNO.FRA Page 9 Friday, October 15, 1999 1:27 PM

Declaring user-defined data type variablesOnce a user-defined data type is defined, variables of that type must be declared explicitly in a Dim statement by using the As type clause where type is the user-defined data type name.

Example Dim plotView As TableDescription ' Table description for reference filesDim vertices(100) As Point2d ' Array of 101 2D points (Option Base 0)

User-defined type variables cannot be declared implicitly by appending a type definition character to the variable name the first time it is used.

Working with user-defined data type variablesA field in a user-defined data type variable is accessed with the “dot” operator and is treated like any other variable of the same data type.

Example refFileTable.table = "Reference Files" ' Title for ref. file table

refFileTable.extent.x = refFileTable.origin.x + 2.0 ' Add table sizerefFileTable.extent.y = refFileTable.origin.y + 16.0 ' to origin

refFileTable.name(1) = "border.dgn" ' Names ofrefFileTable.name(2) = "details.dgn" ' reference filesrefFileTable.name(3) = refFileTable.name(2)

points(0).x = 0.0 ' Coordinates of the first pointpoints(0).y = 532.6points(49).x = points(0).x ' Coordinates of the 50th pointpoints(49).y = points(0).y / 2

You can assign user-defined data type variables of the same type to each other. The contents of all fields of one variable are copied to the other.

Example Dim origin As Point2d, extent As Point2dextent = origin ' Set the extent equal to the origin

Dim origin As Point2d, block(4) As Point2dblock(0) = block(4) ' Copy last point to firstorigin = block(0) ' Copy first point to origin

Variable ScopeThe statement with which you declare a variable controls the parts of the macro in which the variable name is valid.

MicroStation BASIC Guide 3-9

Page 62: 48784209 Microstation Basic

Variable Scope

600macro.bk : 603_LNO.FRA Page 10 Friday, October 15, 1999 1:27 PM

Local variablesLocal variables, either declared explicitly with the Dim statement or implicitly using a type character, are recognized only within the subroutine or function in which they are declared. Once the subroutine or function exits, the variables no longer exist and the names are not valid. If a subroutine or function is called recursively, a new set of variables is created on each call.

Private variablesPrivate variables are recognized within all subroutines and functions within a macro and exist as long as the macro is executing. Private variables are a way for subroutines and functions to share data.

Declare private variables with the Private statement. The syntax of the Private statement is like the Dim statement, but it must be placed before all the subroutines and functions in the macro.

Example Private designFile As String ' Declared with As <Type> clausePrivate elementCount% ' Declared with type characterPrivate lastPoint As Point2d ' User-defined data type variablePrivate pointBuffer(100) As Point2d ' Fixed-length arrayPrivate elementList() As Long ' Variable-length array

Public variablesPublic variables are recognized within all subroutines and functions in all the macros that are currently loaded. Public variables are a way for macros to share data.

Declare public variables with the Public statement. The syntax of the Public statement is like the Dim statement, but it must be placed before all the subroutines and functions in the macro.

Example Public designFile As String ' Declared with As <Type> clausePublic numberOfElements% ' Declared with type characterPublic acceptPoint As Point2d ' User-defined data type variablePublic levelFlags(63) As Integer ' Fixed-length arrayPublic referenceNames$() ' Variable-length array

Use public variables only if necessary. If two macros use the same variable name for public variables of different data types; you will not be able to run the second macro.

3-10 MicroStation BASIC Guide

Page 63: 48784209 Microstation Basic

Initial Variable Values

Mac

ro L

ang

uage

Ove

rvie

w 3

600macro.bk : 603_LNO.FRA Page 11 Friday, October 15, 1999 1:27 PM

Initial Variable ValuesAll declared numeric variables are given an initial value of 0. All declared string variables are initialized with the empty string (“”).

Symbolic ConstantsYour macro may contain many literal constants. If the same constants appear over and over and are difficult to remember or, in and of themselves, are meaningless, symbolic constants can make your macro easier to read and maintain.

Declare symbolic constants, either numeric or string, with the Const statement. These statements must be placed outside of all the subroutines and functions in the macro.

Example Const MaxReferenceFiles% = 255 ' Integer constantConst AcceptReject$ = "Accept/Reject" ' String constantConst OneThird# = 1 / 3 ' Derived from an expression

Once a symbolic constant is defined, its value cannot be changed.

ExpressionsAn expression is any combination of literal constants and variables, functions, and operators that can be evaluated. An expression can be a simple “3,” a complicated mathematical formula, or the comparison of a string variable and the string returned by a function procedure.

Assignment operatorThe result of an expression is assigned to a variable with the equal sign (=). The expression is on the right side of the equal sign; the variable, on the left. Most of the code examples in this chapter include assignment statements.

You can freely assign numeric values to numeric variables without explicitly converting the data type. However, an overflow error will occur at runtime if the numeric value is larger than can be represented by the data type of the variable.

MicroStation BASIC Guide 3-11

Page 64: 48784209 Microstation Basic

Expressions

600macro.bk : 603_LNO.FRA Page 12 Friday, October 15, 1999 1:27 PM

Example dValue# = 45207 ' Assign integer value to double variableiValue% = dValue ' Overflow—Maximum integer value 32,767

When a floating point value (single or double) is converted to an integer value (integer or long), it is rounded to the nearest integer using Baker’s rounding rules:

• If the fractional part is larger than 0.5, the number is rounded.

• If the fractional part is smaller than 0.5, the number is truncated.

• If the fractional part is equal to 0.5, the number is rounded if it is odd and truncated if it is even.

For example, 2.1 is rounded to 2, 4.6 is rounded to 5, 2.5 is truncated to 2, and 3.5 is rounded to 4.

Arithmetic operatorsArithmetic operators work with numeric operands and yield a numeric result. The operands can be numeric literal constants, simple variables, or more complex expressions that evaluate to numeric results.

The operands in an arithmetic expression need not be the same numeric data type. When they differ, the operand with the “smaller” data type is promoted to the “larger” data type before the operation is performed. Longs are larger than integers, doubles are larger than singles, and floating point data types are larger than whole number data types.

Operator Used to # of arguments

- Negate the expression 1

+ Add the expressions 2

- Subtract the second expression from the first

2

* Multiply the two expressions 2

/ Divide the first expression by the second

2

\ Integer divide the first expression by the second

2

Mod Calculate the remainder in an integer division of the expressions

2

^ Raise the first expression to the power specified by the second

2

3-12 MicroStation BASIC Guide

Page 65: 48784209 Microstation Basic

Expressions

Mac

ro L

ang

uage

Ove

rvie

w 3

600macro.bk : 603_LNO.FRA Page 13 Friday, October 15, 1999 1:27 PM

If an expression that includes an arithmetic operator is part of an assignment statement, the data type of the result is also considered before performing the operation. The operands will be promoted to the “largest” of the two operands and the result variable before performing the operation. For example:

Example dValue# = 10 / 4 ' dValue = 2.5; operands promoted to Doubles.

String concatenation operatorsThe operators that work with string operands and yield a string result are solely for string concatenation.

Other string manipulations, for example, extracting the first six characters, are performed by calling BASIC functions. See the on-line help topic Macro Language Reference: in the “MicroStation BASIC” help file for a complete list.

Relational operatorsThe relational operators are used to compare expressions and yield a Boolean result, True (-1) or False (0).

When you use the relational operators to compare string expressions, the comparisons are case-sensitive; in other words, “a” is not the same as “A”. Also, upper case letters in a string sort lower than lower case letters so that comparing “a” and “A” would show that “A” is less than “a.” You can turn off case sensitivity in string comparisons by placing an Option Compare Text statement outside of the subroutines and functions in the macro.

+ Concatenate two string expressions

& Concatenate two string expressions

= Are the expressions equal?

<> Are the expressions not equal?

> Is the first expression greater than the second?

< Is the first expression less than the second?

>= Is the first expression greater than or equal to the second?

<= Is the first expression less than or equal to the second?

MicroStation BASIC Guide 3-13

Page 66: 48784209 Microstation Basic

Expressions

600macro.bk : 603_LNO.FRA Page 14 Friday, October 15, 1999 1:27 PM

Logical operatorsThe logical operators work with Boolean operands, expressions yielding a Boolean result, and yield a Boolean result, True (-1) or False (0).

The logical operators also work with numeric operands. The logical operation is performed bitwise—in other words—on each bit of the two numeric operands, and yields a numeric result.

Example Dim a As Long, b As Long, c As Longa = 3855 ' In binary, a is 0000 1111 0000 1111b = 255 ' In binary, b is 0000 0000 1111 1111c = Not a ' c = 1111 0000 1111 0000, 61,680 in decimalc = a Or b ' c = 0000 1111 1111 1111, 4095 in decimalc = a And b ' c = 0000 0000 0000 1111, 15 in decimalc = a Xor b ' c = 0000 1111 1111 0000, 4080 in decimalc = a Eqv b ' c = 1111 0000 0000 1111, 61,455 in decimalc = a Imp b ' c = 1111 0000 1111 1111, 61,695 in decimal

Logical operator

Used to Operands

Not Reverse the Boolean result. 1

Or Is either expression True? 2

And Are both expressions True? 2

Xor Is one expression True and the other False?

2

Eqv Are both expressions True or are both False?

2

Imp Is the second expression implied by the first?

2

3-14 MicroStation BASIC Guide

Page 67: 48784209 Microstation Basic

Statements and the Line Continuation Character

Mac

ro L

ang

uage

Ove

rvie

w 3

600macro.bk : 603_LNO.FRA Page 15 Friday, October 15, 1999 1:27 PM

Operator precedenceAn expression can include more than one operator. The order in which the operations are performed is called the operator precedence. From highest to lowest precedence:

The order in which operations are performed always can be forced by parenthesizing. You can also use parentheses in expressions even when they are not necessary in order to make your macros easier to read and debug.

When an expression contains more than one operator of the same precedence, evaluation proceeds from left to right.

Statements and the Line Continuation CharacterUsually, a line in a BASIC program is a complete statement. However, if the statement is very long, it can span several lines by using line continuation characters. The line continuation character, the underbar (_), must be the last character on the line and be preceded by a space.

Example message$ = "Cannot create MS_DEF:plan.dgn because a " + _"design file with that name is already open."

The line continuation character cannot be used within strings.

( ) Parentheses

^ Exponentiation

- Unary minus

*, / Multiplication and division

\ Integer division

Mod Modulo

+, - Addition and subtraction

=, <>, >, <, >=, <=, Like

Relational and pattern matching

Not Logical negation

And And

Or Or

Xor, Eqv, Imp Exclusive or, equivalence, and implication

Is Object references

MicroStation BASIC Guide 3-15

Page 68: 48784209 Microstation Basic

Controlling Execution

600macro.bk : 603_LNO.FRA Page 16 Friday, October 15, 1999 1:27 PM

Controlling ExecutionThe prototype macros generated by the Create Macro and End Macro commands are very simple in that each statement in the Main subroutine is executed in order and exactly once. The BASIC language includes several constructs to control the path of execution. For example, you can make a block of statements execute only if a condition is True or make a block of statements execute multiple times.

If...Then...ElseAn If...Then...Else structure executes a block of statements conditionally. The general format is:

If condition1 Then[statementblock1]

[ElseIf condition2 Then[statementblock2]]

[Else[statementblockN]]

End If

Usually, each condition is a Boolean expression, an expression that evaluates to True or False. However, a condition may also be any expression that evaluates to a numeric value. The result is converted to an integer before the condition is tested. A zero numeric value is False and any nonzero numeric value is True. Each statement block is the one or more statements to be executed when the condition is True.

Execution of an If...Then...Else construct begins with evaluating the first conditional expression. If it is False, the next conditional expression is evaluated and, so on, until a True condition is found. When the True condition is found, the corresponding statement block is executed followed by the statement after the End If. The ElseIf blocks are optional and depend on how many conditions are to be checked. The Else block is also optional and is executed if all of the conditional expressions evaluate to False.

The structure of an If...Then...Else block varies widely. Here are some examples:

Example ' Simple If-Then-Else structureIf numPoints < 3 Then

3-16 MicroStation BASIC Guide

Page 69: 48784209 Microstation Basic

Controlling Execution

Mac

ro L

ang

uage

Ove

rvie

w 3

600macro.bk : 603_LNO.FRA Page 17 Friday, October 15, 1999 1:27 PM

Print "Shape needs at least three points."End If

Example ' Name in drawing title block depends on the design file nameIf designFile$ = "untitled.dgn" Then

titleBlock$ = ""Else

titleBlock$ = designFile$End If

Example ' Examine points in a buffer. Note use of ElseIf and AndIf numPoints < 2 Then

Print "At least two points are needed to define a line string."ElseIf (p(1).x = p(numPoints).x) And (p(1).y = p(numPoints).y) Then

numVertices% = numPoints - 1Print "Shape contains "; numVertices; " vertices."

ElsePrint "Line string contains "; numPoints; " points."

End If

An If...Then statement that is contained to one line does not require the EndIf statement:

Example ' Special If...Then syntax for single condition with single statementIf numPoints < 3 Then Print "Shape needs at least three points."

Another way to perform multiple comparisons in an If...Then block is to “nest” the If statements. For example:

Example ' Alternate coincident point checkIf points(1).x = points(numPoints).x Then

If points(1).y = points(numPoints).y ThenPrint "End points are coincident."

EndIfEndIf

MicroStation BASIC Guide 3-17

Page 70: 48784209 Microstation Basic

Controlling Execution

600macro.bk : 603_LNO.FRA Page 18 Friday, October 15, 1999 1:27 PM

Select...CaseThe Select...Case structure is an alternative to If...Then...Else for selectively executing one block of statements from among several blocks of statements. A single test expression is evaluated once at the top of structure. The result is compared with the values in each Case in the construct, and when a match is found, the block of statements associated with the Case is executed. The general format is:

Select Case testexpression[Case expressionlist1

[statementblock1]][Case expressionlist2

[statementblock2]][Case Else

[statementblockN]]End Select

Each expressionlist is a list of one or more expressions that evaluate to the same type as the testexpression. When expressionlist contains more than one expression, the expressions are separated by commas. The expressions can be specific values or ranges of values. Each statementblock contains the zero or more statements to be executed when the expressions match.

After the test expression is evaluated, the expressionlists in the Case statements are evaluated in order, and the statements associated with the first matching Case statement are executed followed by the statement after the End Select. The statements in the optional Case Else block are executed when a match is not found in any of the expressionlists.

Example Select Case textJustificationCase Is < 0 'All negative values

Print "Invalid justification"Case 0 To 2, 15, 16 '0, 1, 2, 15, 16

Print "Left justification"Case 6 To 8, 19, 20 '6, 7, 8, 19, 20

Print "Center justification"Case 12 To 14, 23, 24 '12, 13, 15, 23, 24

Print "Right justification"Case Is < 6, 17, 18 '3, 4, 5, 17, 18

Print "Left Margin justification"Case Is < 12, 21, 22 '9, 10, 11, 21, 22

Print "Right Margin justification"Case Is < 127 'Values between 25 and 126

Print "Undefined justification"

3-18 MicroStation BASIC Guide

Page 71: 48784209 Microstation Basic

Controlling Execution

Mac

ro L

ang

uage

Ove

rvie

w 3

600macro.bk : 603_LNO.FRA Page 19 Friday, October 15, 1999 1:27 PM

Case 127 '127Print "No justification"

Case Else 'Anything greater than 127Print "Invalid justification"

End Select

Do...LoopA Do loop executes a block of statements an indefinite number of times. Each variation of the Do...Loop evaluates a condition to determine whether to execute the block of statements again.

In the first variation of the Do...Loop, the statements are executed as long as the condition is True:

Do While conditionstatements

Loop

The condition is evaluated first. If it evaluates to False, the statements are skipped and execution continues after the Loop statement. If the condition evaluates to True, the statements are executed. Execution returns to the Do While statement and condition is evaluated again. This loop executes zero or more times.

Example ' Using Do While...Loop, get design files in current directoryDim dgnFile$(1 To 100) ' Array for 100 DGN namesDim numFiles As IntegernumFiles = 1dgnFile(numFiles) = Dir$("*.dgn") ' Get first design file nameDo While dgnFile(numFiles) <> ""

numFiles = numFiles + 1dgnFile(numFiles) = Dir$() ' Get next design file name

Loop

The second variation of the Do...Loop is one in which the condition is evaluated after the statements are executed.

Dostatements

Loop While condition

The statements are executed and then condition is evaluated. If the condition evaluates to False, execution continues with the statement after the Loop While statement. If the condition evaluates to True, the statements are executed again. In this

MicroStation BASIC Guide 3-19

Page 72: 48784209 Microstation Basic

Controlling Execution

600macro.bk : 603_LNO.FRA Page 20 Friday, October 15, 1999 1:27 PM

variation of the Do...Loop, the statements are executed at least once.

Example ' Using Do...Loop While, get design files in current directoryDim dgnFile$(1 To 100) ' Array for 100 DGN namesDim numFiles As IntegernumFiles = 0Do

numFiles = numFiles + 1If numFiles = 1 Then ' Get first design file name

dgnFile(numFiles) = Dir$("*.dgn")Else ' Get next design file name

dgnFile(numFiles) = Dir$()End If

Loop While dgnFile(numFiles) <> ""

The third variation of the Do...Loop is like the first except the loop is repeated as long as condition is False.

Do Until conditionstatements

Loop

This loop is executed zero or more times. Notice that the Do Until condition is equivalent to Do While Not condition.

Example ' Using Do Until...Loop, get design files in current directoryDim dgnFile$(1 To 100) ' Array for 100 DGN namesDim numFiles As IntegernumFiles = 1dgnFile(numFiles) = Dir$("*.dgn") ' Get first design file nameDo Until dgnFile(numFiles) = ""

numFiles = numFiles + 1dgnFile(numFiles) = Dir$() ' Get next design file name

Loop

The fourth variation of the Do...Loop is like the second variation except the loop is repeated as long as condition is False.

Dostatements

Loop Until condition

The statements are executed at least once. Notice again that the Do...Until condition is equivalent to the Do...While Not condition.

Example ' Using Do...Loop Until, get design files in current directoryDim dgnFile$(1 To 100) ' Array for 100 DGN names

3-20 MicroStation BASIC Guide

Page 73: 48784209 Microstation Basic

Controlling Execution

Mac

ro L

ang

uage

Ove

rvie

w 3

600macro.bk : 603_LNO.FRA Page 21 Friday, October 15, 1999 1:27 PM

Dim numFiles As IntegernumFiles = 0Do

numFiles = numFiles + 1If (numFiles = 1) Then ' Get first design file name

dgnFile(numFiles) = Dir$("*.dgn")Else ' Get next design file name

dgnFile(numFiles) = Dir$()End If

Loop Until dgnFile(numFiles) = ""

The fifth variation of the Do...Loop is the endless Do loop. A condition is not specified so the statements repeat until an End statement exits the macro or some type of Exit statement is encountered.

Dostatements

Loop

Sometimes you will find it convenient to exit a Do...Loop without waiting for the condition test at the top or the bottom of the loop. The Exit Do statement, which generally appears in an If statement or a Select...Case statement, immediately transfers execution to the statement after the Loop statement. The Exit Do statement is also an appropriate way to exit an endless loop.

Example ' Using Do...Loop and Exit Do, get design files in current directoryDim dgnFile$(1 To 100) ' Array for 100 DGN namesDim numFiles As IntegernumFiles = 0Do

numFiles = numFiles + 1If numFiles = 1 Then ' Get first design file name

dgnFile(numFiles) = Dir$("*.dgn")Else ' Get next design file name

dgnFile(numFiles) = Dir$()End IfIf dgnFile(numFiles) = "" Then

Exit Do ' Exit the loopWhile

MicroStation BASIC Guide 3-21

Page 74: 48784209 Microstation Basic

Controlling Execution

600macro.bk : 603_LNO.FRA Page 22 Friday, October 15, 1999 1:27 PM

While...WendThe While...Wend structure is another way to execute a block of statements an indefinite number of times. It is identical to the first variation of the Do...Loop in functionality; the statements are executed as long as the condition is True.

While conditionstatements

Wend

This loop executes zero or more times.

Example ' Using While...Wend, get design files in current directoryDim dgnFile$(1 To 100) ' Array for 100 DGN namesnumFiles% = 1dgnFile(numFiles) = Dir$("*.dgn") ' Get first design file nameWhile dgnFile(numFiles) <> ""

numFiles = numFiles + 1dgnFile(numFiles) = Dir$() ' Get next design file name

Wend

For...NextDo loops are effective when the block of statements is to be executed an unknown number of times. When the statements must be executed a specific number of times, a For...Next structure is more efficient. The general format is:

For counter = start To end [Step increment]statements

Next [counter]

Counter is a numeric variable and start, end, and increment are numeric expressions that are evaluated once at the beginning of the loop. If increment evaluates to a positive value, start should be less than or equal to end; otherwise, the statements will not be executed. If increment evaluates to a negative value, start must be greater than or equal to end for the statements to be executed. If the Step clause is not included, increment defaults to 1.

The For...Next structure is executed as follows:

1. Initialize counter to start.

2. Compare counter to end. If counter is greater than end when increment is positive or is less than end when increment is negative, exit the loop and continue with statement after Next.

3. Execute the statements.

3-22 MicroStation BASIC Guide

Page 75: 48784209 Microstation Basic

Controlling Execution

Mac

ro L

ang

uage

Ove

rvie

w 3

600macro.bk : 603_LNO.FRA Page 23 Friday, October 15, 1999 1:27 PM

4. Add increment to counter.

5. Go back to the second step.

Example ' Scale points in dynamic array about the origin.For num% = LBound(points) To UBound(points)

points(num).x = points(num).x * scalepoints(num).y = points(num).y * scale

Next num

For...Next structures can be nested to perform loops within loops.

Example ' Rotate points in a dynamic array. r is 2x2 rotation matrixDim p#(1 To 2) ' Temporary coordinate bufferDim num%, row%For num = LBound(points) To UBound(points)

For row = 1 To 2p(row) = r(row,1) * points(num).x + r(row,2) * points(num).y

Next rowpoints(num).x = p(1)points(num).y = p(2)

Next num

Sometimes you will find it convenient to exit a For...Next loop without completing the specified number of iterations. The Exit For statement immediately transfers execution to the statement after the Next statement.

Example ' Using For...Next and Exit For, get design files in current directory' The example handles a directory containing more than 100 design files.Dim dgnFile$(1 To 100) ' Array for 100 DGN namesDim numFiles As IntegerFor numFiles = 1 To 100

If numFiles = 1 Then ' Get first design file namedgnFiles(numFiles) = Dir$("*.dgn")

Else ' Get next design file namedgnFiles(numFiles) = Dir$()

End IfIf dgnFiles(numFiles) = ""Then ' Got last design file name

Exit For ' Exit the loopEnd If

Next numFiles

MicroStation BASIC Guide 3-23

Page 76: 48784209 Microstation Basic

Controlling Execution

600macro.bk : 603_LNO.FRA Page 24 Friday, October 15, 1999 1:27 PM

Labels and the Goto statementYou can label groups of statements in a macro. A label is a name ending with a colon (:) and it must be the first item in a line.

Example setPoint: point.x = 356.2 ' Labeled with "setPoint"point.y = 1.7

copyPoint: origin = point ' Labeled with "copyPoint"

The Goto statement unconditionally transfers execution to a labeled statement. The labeled statement must be in the same procedure as the Goto statement.

Example ' Calculate the sum of the first 10 powers of 2Sub Main

Dim maxExponent%, total&, exponent%maxExponent = 10total = 0exponent = 0

repeat: ' Label at top of the loopexponent = exponent + 1total = total + 2 ^ exponentIf exponent < maxExponent Then

Goto repeat ' Jump to repeat:Else

Goto done ' Jump to done:End If

done: ' Label after the loopprint "Sum is "; total

End Sub

✍ Use Goto statements sparingly for they make macros difficult to read and debug. The calculation in the previous example can be done more clearly with a For...Next loop.

GoSub and Return statementsThe GoSub statement is similar to the Goto statement in that execution unconditionally jumps to a labeled statement in the same procedure. GoSub differs from Goto in that execution returns to the statement after the GoSub when a Return statement is encountered.

Example ' Calculate the sum of the first 10 powers of 2Sub Main

Dim maxExponent%, total&, exponent%

3-24 MicroStation BASIC Guide

Page 77: 48784209 Microstation Basic

Program Structure

Mac

ro L

ang

uage

Ove

rvie

w 3

600macro.bk : 603_LNO.FRA Page 25 Friday, October 15, 1999 1:27 PM

maxExponent = 10total = 0GoSub calculate ' Jump to calculate:Print "Sum of "; maxExponent; "is "; totalExit Sub ' Exits the subroutine

calculate: ' calculate subprocedureFor exponent = 1 To maxExponent

total = total + 2 ^ exponentNext exponentReturn ' Return to Print statement

End Sub

✍ The GoSub and Return statements should be used sparingly if at all. Instead, the statements in a labeled subprocedure block should be moved into a procedure and the procedure called in place of the GoSub statement. Procedures are discussed in the next section.

Program StructureAs the Main procedures in your macros get larger and more complex, break them up into procedures that each do a single task. Procedures make macros easier to read and to maintain, and procedures can be reused.

Procedures can be implemented as either subroutines or functions.

• Subroutine procedures do not return a value. Calling the subroutine is the entire statement.

• Function procedures do return a value so the function call must be part of an expression.

Procedures are either intrinsic or user-defined.

• Intrinsic procedures are subroutines and functions implemented as part of the BASIC language and the MicroStation BASIC extension. An intrinsic procedure can be called from any subroutine or function in any macro.

• User-defined procedures are the subroutines and functions you define within the macro. A user-defined procedure can be called from any subroutine or function in the same macro.

User-defined procedures can be implemented as recursive subroutines or functions. A recursive procedure is one that calls itself directly or indirectly.

MicroStation BASIC Guide 3-25

Page 78: 48784209 Microstation Basic

Program Structure

600macro.bk : 603_LNO.FRA Page 26 Friday, October 15, 1999 1:27 PM

Subroutine proceduresSubroutine procedures, those that do not return a value, are defined by the Sub...End Sub structure. The Main procedure in a macro is a predefined subroutine with no parameters. The general format is:

Sub procedurename [(paramlist)]statements

End Sub

Procedurename is the name of the subroutine. The paramlist is the list of the subroutine’s parameters, if any. When the list contains more than one parameter, the parameters are separated by commas. The statements make up the body of the subroutine and perform the task delegated to the subroutine.

Each parameter in the paramlist looks like a variable declaration and acts like a variable in the subroutine. The syntax is:

[ByVal] variablename[( )] [As type]

Variablename is the name the parameter will use in the subroutine. The data type of the parameter is specified either by using the As type clause or, if it is a built-in data type, a type declaration character at the end of variablename. If a type is not specified, the parameter is given the integer type. The parameter can be an array variable; however, the dimensions and bounds of the array are not specified.

When the optional ByVal keyword is included in a parameter declaration, changes in the parameter value are not reflected back to the procedure that called the subroutine.

✍ The ByVal keyword is incompatible with user-defined data type and array parameters; changes in member values are always reflected back in the procedure that called the subroutine.

Example ' Print the sum of the first N powers of M' Parameters are integersSub PrintPowerSum (baseNum As Integer, maxExponent%)

Dim total&, exponent%total = 0For exponent = 1 To maxExponent

total = total + baseNum ^ exponentNext exponentPrint "Sum of the powers = "; total

End Sub

Example ' Print the distance between two 2D points' Parameter is an array of the Point2d user-defined data type

3-26 MicroStation BASIC Guide

Page 79: 48784209 Microstation Basic

Program Structure

Mac

ro L

ang

uage

Ove

rvie

w 3

600macro.bk : 603_LNO.FRA Page 27 Friday, October 15, 1999 1:27 PM

Sub PrintDistance (points() As Point2d)Dim xDistance#, yDistance#xDistance = points(2).x - points(1).xyDistance = points(2).y - points(1).ydistance = Sqr(xDistance * xDistance + yDistance * yDistance)Print "Distance is "; distance

End Sub

Sometimes you will find it necessary to exit a subroutine before the End Sub statement at the end of the subroutine. The Exit Sub statement immediately exits the subroutine, and execution continues in the calling procedure with the statement following the subroutine call. Any number of Exit Sub statements can appear anywhere in a subroutine.

Example ' Get design files in current directory (one last time)' Subroutine has no parametersPrivate dgnFiles$(1 To 100) ' Macro-wide array for 100 DGN namesSub GetDesignFiles

Dim numFiles As IntegernumFiles = 1dgnFiles(numFiles) = Dir$("*.dgn") ' Get first design file nameWhile dgnFiles(numFiles) <> ""

numFiles = numFiles + 1if (numFiles >= 100) Then ' Array is full

Exit Sub ' Exit GetDesignFilesdgnFiles(numFiles) = Dir$() ' Get next design file name

WendEnd Sub

Calling subroutine proceduresThe statement for calling a subroutine is the name of the subroutine followed by a comma separated list of expressions that match the subroutine’s parameter list. If a subroutine has no parameters, the statement is just the subroutine name. The general format is:

subroutinename [arglist]

The Call statement is a second way call a subroutine. The general format is:

Call subroutinename [(arglist)]

Again, the arglist is not included when the subroutine has no parameters.

Example ' Print the sum of the first 10 powers of 2 and 3Sub Main

MicroStation BASIC Guide 3-27

Page 80: 48784209 Microstation Basic

Program Structure

600macro.bk : 603_LNO.FRA Page 28 Friday, October 15, 1999 1:27 PM

Dim maxExponent As IntegermaxExponent = 10PrintPowerSum 2, maxExponentCall PrintPowerSum (3, maxExponent)

End Sub

Example ' Print distances between some 2D pointsSub Main

Dim points(1 To 2) As Point2dpoints(1).x = 356.2 ' Initialize point coordinatespoints(1).y = 1.7points(2).x = 501.5points(2).y = -16.8PrintDistance pointspoints(2).x = points(1).x ' Change second point's coordinatespoints(2).y = 299.0Call PrintDistance (points)

End Sub

Function proceduresFunction procedures, procedures that return a value, are defined by the Function...End Function structure. The general format is:

Function procedurename [(paramlist)] [As type]statements

End Function

Procedurename is the name of the function. Because a function returns a value, the data type of the function is specified either by using the As type clause or a type declaration character at the end of procedurename. Only built-in data types are valid; functions cannot return an array or a user-defined data type. If a type is not specified, the function is given the integer type.

The paramlist is the list of the function’s parameters, if any. When the list contains more than one parameter, the parameters are separated by commas. Each parameter in paramlist looks like a variable declaration and acts like a variable in the function. The syntax is identical to that described for subroutine procedures.

The statements make up the body of the function and perform the task delegated to it. At least one of the statements should assign a value to procedurename. If a function exits without setting procedurename, the function returns a 0 if it is a numeric data type or an empty string (“”) if it is a string data type.

3-28 MicroStation BASIC Guide

Page 81: 48784209 Microstation Basic

Program Structure

Mac

ro L

ang

uage

Ove

rvie

w 3

600macro.bk : 603_LNO.FRA Page 29 Friday, October 15, 1999 1:27 PM

Example ' Calculate the sum of the first N powers of M' Parameters are integers' Function returns a long integerFunction PowerSum (baseNum As Integer, maxExponent%) As Long

Dim total&, exponent%total = 0For exponent = 1 To maxExponent

total = total + baseNum ^ exponentNext exponentPowerSum = total

End Function

Example ' Calculate the distance between two 2D points' Parameter is an array of the Point2d user-defined data type' Function returns a doubleFunction Distance# (points() As Point2d)

Dim xDistance#, yDistance#xDistance = points(2).x - points(1).xyDistance = points(2).y - points(1).yDistance = Sqr(xDistance * xDistance + yDistance * yDistance)

End Function

Sometimes you will find it necessary to exit a function before the End Function statement at the end of the function. The Exit Function statement immediately exits the function, and execution continues in the calling procedure with the statement following the function call. Any number of Exit Function statements can appear in a function.

Example ' Count the design files in the array. Array is already filled.' Function has no parameters. It returns an integer.Private dgnFiles$(1 To 100) ' Macro-wide array for 100 DGN namesFunction CountDesignFiles%

Dim numFiles As IntegerCountDesignFiles = 0 ' Initialize return valuenumFiles = 1While dgnFiles(numFiles) <> ""

CountDesignFiles = numFiles ' Update return valueif (numFiles >= 100) Then ' At the end of the array

Exit Function ' Exit CountDesignFilesnumFiles = numFiles + 1

WendEnd Function

MicroStation BASIC Guide 3-29

Page 82: 48784209 Microstation Basic

Program Structure

600macro.bk : 603_LNO.FRA Page 30 Friday, October 15, 1999 1:27 PM

Calling function proceduresBecause a function procedure returns a value, a function must be called in an expression. A function call expression is the name of the function followed by its arguments which are enclosed in parentheses. The general format is:

... functionname ([arglist])...

The argument list, arglist, is a comma-separated list of expressions that match the function’s parameter list.

Example ' Print the sum of the first 10 powers of 2, 4, 6, and 8Sub Main

Dim total&, baseNum%For baseNum = 2 To 8 Step 2

total = PowerSum(baseNum, 10)Print "Sum of the first 10 powers of"; baseNum; "is"; total

Next baseNumEnd Sub

Example ' Print distances between some 2D pointsSub Main

Dim points(1 To 2) As Point2dpoints(1).x = 356.2 ' Initialize point coordinatespoints(1).y = 1.7points(2).x = 501.5points(2).y = -16.8Print "First distance is"; Distance(points)points(2).x = points(1).x ' Change second point's coordinatespoints(2).y = 299.0Print "Second distance is"; Distance(points)

End Sub

Passing arguments to proceduresBy default, arguments are passed to subroutine and function procedures by reference. When a variable is passed to a procedure by reference, any changes made to the corresponding parameter’s value in the procedure are also made to the variable’s value in the calling procedure.

If a variable’s value must not be changed by a called procedure, enclose the argument in parentheses. The argument is then passed by value, and any changes made to the corresponding parameter’s value in the procedure are not made to the variable’s value in the calling procedure.

3-30 MicroStation BASIC Guide

Page 83: 48784209 Microstation Basic

Program Structure

Mac

ro L

ang

uage

Ove

rvie

w 3

600macro.bk : 603_LNO.FRA Page 31 Friday, October 15, 1999 1:27 PM

When the argument being passed to a procedure is an expression rather than a variable, the expression is evaluated, and the result is passed to the procedure by value.

Example Sub ScaleValue (scale#, value#)value = value * scale

End Sub

Sub MainDim dValue#dValue = 100ScaleValue 2.0, dValue ' Pass dValue by referencePrint dValue ' Prints "200"ScaleValue 0.5, (dValue) ' Pass dValue by valuePrint dValue ' Prints "200", not "100"ScaleValue 1.5, Sqr(dValue) ' Pass square root of 200 by value

End Sub

✓ Be careful when a procedure takes a single argument. For example:

Example mySubroutine theArg 'Pass theArg by reference. Value may change.mySubroutine (theArg) 'Pass theArg by value. Value will not change.sTs = myFunction(theArg) 'Pass theArg by reference. Value may change.sTs = myFunction((theArg)) 'Pass theArg by value. Value will not change.

The parameter declarations in the subroutine and function procedures also affect the way the arguments are passed. When a parameter declaration includes the ByVal keyword, the corresponding argument is always passed by value, and any changes made to the parameter’s value are not made to the variable in the calling procedure.

Example Sub ScaleValue (scale#, ByVal value#)value = value * scalePrint value

End SubSub Main

Dim dValue#dValue = 100 ' dValue does not changeScaleValue 2.0, dValue ' ScaleValue prints "200"ScaleValue 0.5, (dValue) ' ScaleValue prints "50"ScaleValue 1.5, Sqr(dValue) ' ScaleValue prints "15"

End Sub

Arrays of variables and user-defined data type variables are always passed by reference to subroutine and function procedures. The ByVal keyword cannot be used when declaring parameters that are arrays or user-defined data types in the

MicroStation BASIC Guide 3-31

Page 84: 48784209 Microstation Basic

Objects in BASIC

600macro.bk : 603_LNO.FRA Page 32 Friday, October 15, 1999 1:27 PM

procedure. Changes made to member values are also made to the variable members in the calling procedure.

Declaring proceduresIt is good programming practice to place subroutine and function procedure definitions in the macro source before the procedures that call them. Then, any calls to a procedure can be checked against the procedure definition for the number and the data type of the arguments, and, if it is a function, the returned data type. When you follow this practice, the Main subroutine is the last procedure in the macro.

When circumstances prevent this arrangement, use the Declare statement to receive the benefits of syntax checking. The formats for declaring subroutine function procedures are:

Declare Sub procedurename [(paramlist)]

Declare Function procedurename [(paramlist)] [As type]

Procedurename, the optional paramlist, and in the function declaration, the definition of the returned data type, are identical to their counterparts in the Sub and Function procedure definition statements.

Example ' Declare statements for subroutine examplesDeclare Sub PrintPowerSum (baseNum As Integer, maxExponent%)Declare Sub PrintDistance (points() As Point2d)Declare Sub GetDesignFiles

' Declare statements for function examplesDeclare Function PowerSum (baseNum As Integer, maxExponent%) As LongDeclare Function Distance# (points() As Point2d)Declare Function CountDesignFiles%

Objects in BASICAn object is an encapsulation of data and routines into a single unit. Objects in the BASIC language are used to group together procedures and data items that are meant to be used together.

For example, a MicroStation graphics element has attributes such as color, size and location, as well as directions that specify how to display it using those attributes. When the attributes and directions are combined, they form an object.

3-32 MicroStation BASIC Guide

Page 85: 48784209 Microstation Basic

Objects in BASIC

Mac

ro L

ang

uage

Ove

rvie

w 3

600macro.bk : 603_LNO.FRA Page 33 Friday, October 15, 1999 1:27 PM

Not all of the information about the data of an object and how the procedures manipulate that data is accessible outside of the object. Only a simple and refined interface is exposed.

• Certain data items in objects are made available for programmability. Such data items are known as properties. For example, an element object could expose an integer called color. Usually, you can both retrieve (Get) and modify (Set) properties.

• Certain internal procedures in objects are also made available for programmability. Such procedures are called methods. A method is implemented either as a subroutine or a function that may or may not have arguments. For example, the element object may expose a Move method to translate the element based on an argument that specifies the distances in the x, y and z directions.

Only object types that have been predefined are available to a macro. A new object type cannot be defined by a macro. Basic is the only non-MicroStation-specific object that is available.

Declaring an object variableAn object variable, a variable that refers to an object, is declared explicitly in a Dim statement, a Private statement, or a Public statement. The As type clauses in the statements specify the object type.

Example Dim element As MbeElement ' An MbeElement object variablePrivate elemSet As MbeElementSet ' Macro-wide object variable

Object Type Description

Basic Operating system information

MbeCurrentTransform Macro coordinate system

MbeDgnInfo Design file information

MbeElement Graphic element

MbeElementSet Elements in selection set or fence

MbeRefFile Reference file

MbeRefFiles The collection of reference files

MbeSession MicroStation session information

MbeSettings Active settings and locks

MbeState MicroStation state information

MbeView View or window

MbeViews The collection of views

MicroStation BASIC Guide 3-33

Page 86: 48784209 Microstation Basic

Objects in BASIC

600macro.bk : 603_LNO.FRA Page 34 Friday, October 15, 1999 1:27 PM

An object variable is given an initial value of Nothing (0) when it is declared because the variable is not yet associated with a physical object or an underlying application object.

Object variable operationsObject variables are assigned with the Set statement. The format is:

Set objectvariable = objectexpression

This statement is similar to the assignment statement for other data types; objectexpression is evaluated and the result is assigned to objectvariable. The difference is that objectexpression must evaluate to the object type of objectvariable. The expression can be as simple as another object variable or it can be a function that returns an object variable.

This first format of the Set statement does not duplicate the object referred to by objectexpression. A reference to the object is copied to objectvariable so that the physical object or underlying application object can be accessed through it.

An object variable can also be assigned to Nothing with the Set statement. The second format for the Set statement is:

Set objectvariable = Nothing

Assigning objectvariable to Nothing breaks the association the variable had with an object. The physical object or the underlying application object can no longer be accessed through objectvariable.

Example ' Declare two object variables. Initial values are NothingDim element1 as MbeElement, element2 As MbeElementSet element1 = FirstSetElement() ' Function returns an MbeElement objectSet element2 = element1 ' Both variables refer to same object...Set element1 = Nothing ' Break element1's associationSet element2 = Nothing ' Break element2’s association

The value contained in an object variable is meaningless to the macro except in the following situations:

• Object variables can be compared to each other to determine if they refer to the same object.

• An object variable can be compared to Nothing to determine if it refers to any object.

Object variables are compared by using the Is operator.

3-34 MicroStation BASIC Guide

Page 87: 48784209 Microstation Basic

Objects in BASIC

Mac

ro L

ang

uage

Ove

rvie

w 3

600macro.bk : 603_LNO.FRA Page 35 Friday, October 15, 1999 1:27 PM

Example Dim selectionSet As MbeElementSet, fence As MbeElementSet...If selectionSet Is Nothing Then

Print "selectionSet is not associated with an element set object"End IfIf fence Is Not Nothing Then Print "fence is in use"If selectionSet Is fence Then

Print "selectionSet and fence refer to the same element set object"Print "(or Nothing)"

End If

Creating an object instanceAn object variable must be associated with a physical object or an underlying application object before you can access object properties or call object methods

You can create an object instance at the same time an object variable is declared with the Dim statement by using the As New objecttype clause.

Example ' Declare object variables and create underlying objectsDim element As New MbeElementDim selectionSet As New MbeElementSet

When the New keyword is included in the Dim statement, the initial object variable value is not Nothing, but a value that refers to the physical object or the underlying application object.

You also can create an object instance with the Set statement. The third format for the Set statement is:

Set objectvariable = New objecttype

A new instance of objecttype is created and objectvariable is set to the value that refers to the physical object or the underlying application objects.

Example ' Declare object variables. Initial values are Nothing.Dim element As MbeElementDim selectionSet As MbeElementSet' Create underlying objects. Set variables to refer them.Set element = New MbeElementSet selectionSet = New MbeElementSet

MicroStation BASIC Guide 3-35

Page 88: 48784209 Microstation Basic

Objects in BASIC

600macro.bk : 603_LNO.FRA Page 36 Friday, October 15, 1999 1:27 PM

Accessing object propertiesOnce you have declared an object variable and associated it with a physical object or an underlying application object, you can retrieve and modify the object’s properties. The properties of an object are accessed with the “dot” operator:

objectvariable.property

When a property is writable, you can modify it with the assignment operator.

Example element.color = 4 ' Set the element color

When a property is readable, you can use it in expressions like any other variable of the same type.

Example If element.type = MBE_CellHeader Then ' Retrieve the element typePrint "Cell : "; element.cellName ' Retrieve the cell name

End If

Accessing object methodsOnce an object variable is associated with a physical object or an underlying application object, you can manipulate the object by calling its methods. An object’s methods are accessed with the “dot” operator just like an object’s properties.

An object method that does not return a value is called in a standalone statement. The format is similar to calling a subroutine procedure:

objectvariable.method [arglist]

The arglist is a comma-separated list of expressions that match the method’s parameter list. If the method has no parameters, the statement is just objectvariable.method.

Example element.display MBE_Hilite ' Highlight the elementelement.firstElement ' Set component in complex element

An object method that returns a value is called as part of an expression. The format is similar to a function call expression:

...objectvariable.method([arglist])...

The argument list, arglist, is a comma separated list of expressions that match the method’s parameter list. The arguments are enclosed in parentheses.

Example Dim origin As MbePointIf element.getOrigin (origin) <> MBE_Success Then ' Relational expr.

3-36 MicroStation BASIC Guide

Page 89: 48784209 Microstation Basic

Objects in BASIC

Mac

ro L

ang

uage

Ove

rvie

w 3

600macro.bk : 603_LNO.FRA Page 37 Friday, October 15, 1999 1:27 PM

Print "Element doesn't have an origin"Else

Print "Element origin :"; origin.x; origin.y; origin.zEnd If

Example Dim distance As MbePoint, status%distance.x = -10.5distance.y = 15.25distance.z = 1 / 3status = element.move (distance) ' Assignment statement

Object collectionsAn object collection is a grouping of objects. Each object in the grouping is accessed individually by using an index that is either a number or a string. In some ways, an object collection is like a one-dimensional array of objects.

Example ' MbeViews is a collection of MbeView objectsDim currentView As MbeViewSet currentView = MbeViews(7) ' Assign MbeView object variablecurrentView.pattern = True ' Set pattern display in view 7currentView.update ' Update view 7For num% = 1 To 8

If MbeViews(num).active <> 0 Then ' Retrieve MbeView propertyPrint "View "; num; " is active."

End IfNext num

An object collection can itself have properties that expose information about the collection and methods to navigate the collection.

Example ' MbeRefFiles is a collection of MbeRefFile objectsnumFiles% = MbeRefFiles.maxRefFiles ' Collection property

Constant objectsBecause objects are a convenient way to group related data items and procedures, both the BASIC language and the MicroStation BASIC extensions expose system data and procedures that manipulate the environment through constant objects. A constant object is a pre-instantiated object of a reserved type. A symbolic constant that refers to that object is declared for you.

MicroStation BASIC Guide 3-37

Page 90: 48784209 Microstation Basic

Error Handling

600macro.bk : 603_LNO.FRA Page 38 Friday, October 15, 1999 1:27 PM

Only the properties and methods of a constant object can be accessed. You cannot use the symbolic constant in Set statements or in logical expressions using the Is operator. You also cannot declare additional object variables of the reserved object type or create new objects of the object type.

The properties of a constant object are accessed with the “dot” operator. The format is:

constantname.property

If the property is writable, you can modify it with the assignment operator. If the property is readable, you can use it in expressions like any other variable of the same type.

Example MbeDgnInfo.masterUnitName = "km" ' Set MbeDgnInfo masterUnitNamePrint "BASIC version "; Basic.Version ' Retrieve Basic version

A constant object’s methods are accessed with the “dot” operator. Call a method that does not return a value in a standalone statement. The format is similar to calling a subroutine procedure:

constantname.method [arglist]

A method that does return a value is called as part of an expression. The format is similar to calling a function in an expression:

...constantname.method ([arglistI])...

Example ' Set transformation to master units in MbeCurrentTransform objectMbeCurrentTransform.masterUnits True

Example ' Get the coordinates of the user's data point. Query MbeState object.Dim point As MbePoint, view%If MbeState.getInputDataPoint (point, view) = MBESuccess Then

Print "Point in view "; view; " : "; point.x; point.yEnd If

Error HandlingEven after syntax errors and program logic problems have been corrected, errors may still occur when running a macro. For example, the floppy drive may not be ready or bad input could cause a value to be too large for a variable. These runtime errors can be dealt with through error handlers.

3-38 MicroStation BASIC Guide

Page 91: 48784209 Microstation Basic

Error Handling

Mac

ro L

ang

uage

Ove

rvie

w 3

600macro.bk : 603_LNO.FRA Page 39 Friday, October 15, 1999 1:27 PM

You set an error handler for a procedure with the On Error statement. The format is:

On Error Goto label

If an error occurs at runtime, execution will jump to the statement at label, which must be in the same procedure, for appropriate action.

Within the error handler, you can retrieve the error number with the Err function and a corresponding message string with the Error function.

After you handle the error (such as by displaying the error message to the user), use a Resume statement to return to executing statements in the procedure. The format of the Resume statement determines the statement with which execution resumes.

Resume

Use this format to repeat the statement that invoked the error handler. Repeating the statement is most commonly used when the user can correct the error.

Resume Next

Use this format to return to the statement after the one that invoked the error handler. Resuming on the next statement is most commonly used when the code needs correction.

Resume label

Use this format to resume execution at a labeled statement. This format should be used infrequently, if at all. Like the Goto and GoSub statements, this form of the Resume statement makes a macro difficult to read and debug.

MicroStation BASIC Guide 3-39

Page 92: 48784209 Microstation Basic

600macro.bk : 603_LNO.FRA Page 40 Friday, October 15, 1999 1:27 PM

Example ' Check existence of a design fileFunction DesignFileExists% (dgnName$)

On Error Goto handleErrorDesignFileExists = Dir$(dgnName) <> ""Exit Function

handleError:errNum% = Err()If errNum = 71 Then ' Disk is not ready

Print "Insert floppy or CD"Sleep(2000) ' Pause for 2 secondsResume ' Repeat Dir statement

ElseIf errNum = 53 Or errNum = 76 Then ' File/path not foundDesignFileExists = FalseResume Next ' Resume after Dir statement

Else ' Other, unexpected errorError errNum ' Trigger error in calling procedure

End IfEnd Function

If a runtime error occurs and an error handler is not enabled for the procedure, the error handler in the calling procedure is invoked. If an error handler is not enabled in the calling procedure, the error handler in its calling procedure is invoked. The search continues back through the calling procedures until either an enabled error handler is found or there are no more procedures. If an enabled error handler is not found, the macro terminates with an error.

When an enabled error handler is found among the calling procedures, execution jumps to that handler as if the error were generated in that procedure. The Resume and Resume Next statements return execution to the statements in the procedure with the enabled handler, not the statements in the procedure in which the error occurred.

A similar search for enabled error handlers in calling procedures happens when a runtime error occurs within an error handler. Once an error handler is invoked, it is disabled and is no longer the active error handler. The Error statement in the previous example takes advantage of this search for enabled error handlers.

Example Function DesignFileExists% (dgnName$)DesignFileExists = Dir(dgnName) <> "" ' No handler enabled

End Function

3-40 MicroStation BASIC Guide

Page 93: 48784209 Microstation Basic

Error Handling

Mac

ro L

ang

uage

Ove

rvie

w 3

600macro.bk : 603_LNO.FRA Page 41 Friday, October 15, 1999 1:27 PM

Function ValidDesignFile% (dgnName$)On Error Goto fileFailureIf DesignFileExists(dgnName) <> 0 Then

' Open the file with Open statement' Read the first four bytes with Get statement' Compare values with design file numbers' Set ValidDesignFile accordingly' Close the file with Close statement

ElseValidDesignFile = False

End IfExit Function

fileFailure:' This handler deals with all errors from DesignFileExists() as' well as any generated by the Open, Get, and Close statements.ValidDesignFile = False ' Not a valid design fileExit Function ' Clears error condition

End Function

You can use the On Error statement to ignore runtime errors altogether in a procedure. The format is:

On Error Resume Next

If an error occurs at runtime, execution continues with the next statement. Use this type of error handling only in controlled situations.

Example ' Check existence of a design file' If a runtime error occurs, execution continues with the next' statement--exiting the function. DesignFileExists, because it has not' been assigned, defaults to 0 (False), which is the desired result.Function DesignFileExists% (dgnName$)

On Error Resume NextDesignFileExists = Dir$(dgnName) <> ""

End Function

If you no longer need an error handler, you can disable it with the third form of the On Error statement:

On Error Goto 0

After this statement is executed, error handling is no longer enabled for the procedure. Disabling an error handler is useful when the handler does not apply to all the statements in a procedure.

MicroStation BASIC Guide 3-41

Page 94: 48784209 Microstation Basic

Error Handling

600macro.bk : 603_LNO.FRA Page 42 Friday, October 15, 1999 1:27 PM

Example Sub CreateDesignFile (dgnName$)On Error Goto handleErrorIf DesignFileExists(dgnName) <> 0 Then

On Error Goto 0 ' Disable handlerKill dgnName ' Delete old fileOn Error Goto handleError ' Enable handler again

End If' Create the design fileExit Sub

handleError:' Deal with runtime errors

End Sub

You can generate runtime errors in a procedure with the Error statement. The format is:

Error errornumber

The errornumber is either a built-in error number or a user-defined error number.

The Error statement is most commonly used to trigger an unexpected error again from within an error handler. During testing, you can use Error to simulate a system error to debug an error handler. Also, if you write the error handlers to deal with them, you can use the Error statement to generate macro-specific runtime errors.

3-42 MicroStation BASIC Guide

Page 95: 48784209 Microstation Basic

600macro.bk : 604_ITCT.FRA Page 1 Friday, October 15, 1999 1:27 PM

4 Macro Interactions With MicroStation

This section discusses extensions to BASIC that give the macro programmer access to the inner workings of MicroStation. The MicroStation-specific extensions include predefined constants, data types, functions, objects and collections. The concepts behind the extensions are also described in this section. Details of the implementation of the individual functions, objects, and methods are documented in “MicroStation Extensions to BASIC” on page 8-1.

The aim of the BASIC extensions is to remain simple. For example, the element extensions provide access to the geometry and display attributes of MicroStation’s graphic elements, as well as methods for simple manipulations to them. For more difficult element manipulations (for example, chamfer or fillet), the macro programmer steps MicroStation through commands rather than directly manipulating elements.

MicroStation BASIC Extension conventionsMicroStation-specific extensions to BASIC are distinguished from other BASIC language features and user-written functions in that they always start with a signature of MBE_ or Mbe. Pre-defined MicroStation-specific constants start with the MBE_ signature. All MicroStation-specific functions, types, and predefined objects or collections start with the Mbe signature.

Many extension functions return an integer that indicates whether the function was successful. All such functions return MBE_Success (which is predefined as 0) if successful or a non-zero error code that identifies the error if unsuccessful.

Sequencing MicroStation CommandsOften the easiest way to accomplish a macro’s objectives is to use the MicroStation commands and provide the inputs. When recording a macro, MicroStation generates a macro that consists of calls to the extension functions that correspond to the user’s inputs. These functions include MbeSendCommand, MbeSendKeyin,

MicroStation BASIC Guide 4-1

Page 96: 48784209 Microstation Basic

Macro Coordinate System

600macro.bk : 604_ITCT.FRA Page 2 Friday, October 15, 1999 1:27 PM

MbeSendDataPoint, MbeSendTentPoint, MbeSendLastInput and MbeSendReset.

Sometimes the macro generated by recording user input can be run unmodified, but more often the recording serves as a starting point in the programming process. Frequently, you need to modify the macro. Use the MbeGetInput extension to get user input. Use the predefined MbeState State Object to retrieve the type and details of the user’s input. Use the MbeWriteMessage, MbeWriteError, MbeWriteStatus, MbeWriteCommand and MbeWritePrompt extensions to guide and prompt the user.

Macro Coordinate SystemThe macro programmer need not be concerned with how the design file working units are set up. All coordinates that are returned to macros from the MicroStation-specific extensions are returned in double precision variables. When coordinates are provided by the macro to the extensions, they are provided in double precision. (The BASIC rules for promotion to double precision values are used if coordinates are not provided in double precision variables.)

Additionally, macro programmers need not worry whether the current design file is 2D or 3D. Points are passed to and from the MicroStation extension procedures as type MbePoint, which is predefined as if the following statements were included in every macro:

Type MbePointx as Doubley as Doublez as Double

End Type

If the active design file is 2D, the z member is zero when returned from an extension function and is ignored when an MbePoint is passed as an argument to an extension function.

By default, macros work in the “master units” of the active design file. The coordinate system can be changed by the macro programmer using the MbeCurrentTransform Current Transformation Object. The MbeCurrentTransform dgnUnits method sets the coordinate system to design file coordinates; the masterUnits method sets it back to the default of master units. The fromView method sets the coordinate system to match the

4-2 MicroStation BASIC Guide

Page 97: 48784209 Microstation Basic

Querying and Manipulating Graphic Elements

Mac

ro In

tera

ctio

ns W

ith M

icro

Stat

ion

4

600macro.bk : 604_ITCT.FRA Page 3 Friday, October 15, 1999 1:27 PM

orientation of a particular view. Use the moveOrigin, moveOriginWorld, rotate and scale methods to make other coordinate system transformations. A macro can transform points and distances back and forth between its current coordinate system and the fixed design file coordinate system by using the scalarToUors, scalarFromUors, distanceToUors, and distanceFromUors methods.

All angles passed to and from the MicroStation extension functions are in radians. Since angle key-ins to MicroStation (for example, setting the active angle) are expected in degrees, macros that generate key-ins from angles must convert from radians to degrees, which is easily accomplished by multiplying by 180.0/PI.

Querying and Manipulating Graphic ElementsMost macros affect graphic elements in the design file. Manipulating or creating elements by sequencing MicroStation commands is often all that is needed but sometimes macros need information about graphic elements to determine how to process them or what inputs to supply to MicroStation commands. Also, it is sometimes more convenient to directly perform simple manipulations than to sequence MicroStation commands. The MbeElement object extensions meet these needs.

The implementation of the MbeElement object minimizes the knowledge of the graphic element format that is required of the macro programmer. All data is retrieved using object properties or functions. All manipulations are performed with object functions. However, it is still necessary to understand some graphic elements concepts.

MicroStation design files are composed of control elements and graphic elements. Control elements save design file settings, view configuration, attach reference files, etc. The information stored in control elements is not directly accessible to the macro programmer through the MbeElement object.

Graphic elements are categorized as “simple” or “complex” graphic elements. Simple graphic elements represent their entire geometry in one data item in the design file, such as lines, arcs, ellipses, text, line strings, shapes, cones and cylinders.

MicroStation BASIC Guide 4-3

Page 98: 48784209 Microstation Basic

Querying and Manipulating Graphic Elements

600macro.bk : 604_ITCT.FRA Page 4 Friday, October 15, 1999 1:27 PM

Complex graphic elements require more than one data item in the design file. These more complicated graphic elements include surfaces of projection or revolution, B-spline curves and B-spline surfaces, and groupings of simple graphic elements like cells, text nodes, and complex shapes and chains. Each complex element is made up of a “header” element followed by one or more “component” elements. Cells can group together other complex elements like text nodes and other cells.

To the macro programmer both simple and complex elements are represented by a single MbeElement object. This is desirable because many modifications to individual component elements of a complex element require modifications to the header element. The MbeElement object allows the macro programmer to modify component elements without worrying about consequential modifications required to the header element because the object implementation takes care of them. In fact, the MbeElement object implementation simplifies the task of modifying component elements and makes it difficult for a macro programmer to corrupt a design file.

Using the MbeElement Object

As explained in “Macro Language Overview” on page 3-1, objects in BASIC are used to encapsulate the data representing an entity and to group the functions or methods that can be used to manipulate that data. The first step in using an MbeElement object is to declare the object and allocate space for it using either of the following BASIC constructs:

Dim element as New MbeElement

or

Dim element as MbeElement

Set element = New MbeElement

You can call the MbeElement object variable anything you want in your program. In this example we use element as the variable name.

Either of these constructs establishes a name for an element object and allocates memory for the object. The next step is to associate an actual graphic element with the object. There are two MbeElement methods that provide means for obtaining a graphical element. Use the fromFile element to obtain a graphic element from either the active design file or one of the attached reference files given its file position. Use the fromLocate method to obtain the element that the user (or a macro emulating a user) last interactively located in the design file.

4-4 MicroStation BASIC Guide

Page 99: 48784209 Microstation Basic

Querying and Manipulating Graphic Elements

Mac

ro In

tera

ctio

ns W

ith M

icro

Stat

ion

4

600macro.bk : 604_ITCT.FRA Page 5 Friday, October 15, 1999 1:27 PM

Once you have associated a graphic element with your MbeElement object, you can query its properties and manipulate it using the methods of the MbeElement object.

Often, the first step is determining the type of graphic element and whether it is a simple or complex graphic element. The type and isHeader read-only properties are used for these two tasks.

The techniques used to query and manipulate element objects are similar for simple graphic elements and complex graphic elements, but there are some differences.

Simple Graphic Elements

If the graphic element represented by the MbeElement object is a simple graphic element, queries and manipulations are straightforward. You can query (and change) the display attributes using the color, weight, style, level and class properties. For many element types, you can determine geometric properties using the getRange, getOrigin, getEndPoints and getPoints object methods.

Use font, justification, charWidth, charHeight and getString methods for text.

Use primaryAxis, secondaryAxis, startAngle and sweepAngle methods for ellipses (including circular ellipses) and arcs.

Complex Graphic Elements

It is more complicated when a complex graphic element is represented by the MbeElement object.

Picture a complex element as a tree with branches. The simplest complex element has one header element (the trunk) and one or more component elements (the branches), as illustrated below.

In the case where one complex element is contained within another, the component element branch that is itself a header element has its own branches. This nesting can go up to ten

Component Elements

Header Element

Complex Element

MicroStation BASIC Guide 4-5

Page 100: 48784209 Microstation Basic

Querying and Manipulating Graphic Elements

600macro.bk : 604_ITCT.FRA Page 6 Friday, October 15, 1999 1:27 PM

levels deep. A nested cell complex element is illustrated below. In this case a cell contains a single nested cell.

To effectively deal with complex elements, the macro programmer needs a way of querying the component elements individually and a way of navigating through each branch of the tree.

Querying individual components of a complex element is done by using “current position.” The current position points to one of the graphic elements that makes up a complex element; either a header element or a component element. When the methods mentioned above for simple elements are applied to an MbeElement object representing a complex element, they apply to the graphic element that is at the current position in the complex element. There are a number of element methods that are used to move the current position within a complex element, including nextElement, nextComponent and firstElement.

The nextElement and nextComponent methods differ in their behavior when the element at the “current position” is a header element. The nextComponent method moves the current position to the first component element of the complex element (that is, to the first “branch”). The nextElement method moves the current position to the element following the complex header, at the same nesting level as the complex header. The effect of nextElement and nextComponent is illustrated below:

The most efficient way to process each component element of a complex element is to use a recursive subroutine (or function). A recursive subroutine is a subroutine that calls itself. A subroutine is written to process all component elements of the complex

Cell Header

Cell Header

Nested Cell Complex Element

Next Next

Current

Effect of NextElement, Next Component

4-6 MicroStation BASIC Guide

Page 101: 48784209 Microstation Basic

Querying and Manipulating Graphic Elements

Mac

ro In

tera

ctio

ns W

ith M

icro

Stat

ion

4

600macro.bk : 604_ITCT.FRA Page 7 Friday, October 15, 1999 1:27 PM

element. When that subroutine encounters a component element that is a complex header, it calls itself to process the components of that complex element. Here is an example of a simple macro that uses a recursive subroutine to print the nesting level, element type, and file position of each graphic element in a file, including every component element of the complex graphic elements:

'-----------------------------------------------------------------''Subroutine that shows element type, nesting level and file position''-----------------------------------------------------------------Sub ShowElemInfo (nestLevel as integer, inElem as MbeElement) If nestLevel > 0 Then print Spc(nestLevel*2); "(";nestLevel;") Type "; inElem.type; Else print "Type "; inElem.type; End If print " Filepos "; inElem.componentFilePosEnd Sub

'-----------------------------------------------------------------'' Recursive subroutine that processes a simple or complex element''-----------------------------------------------------------------Sub ProcessElement (nestLevel as integer, inElem as MbeElement) Dim gotNext as integer

Do ' call function that shows info for element at current position Call ShowElemInfo (nestLevel, inELem)

If inElem.isHeader <> 0 Then ' if any components in complex, process them recursively If inElem.nextComponent = MBE_Success Then Call ProcessElement (nestLevel+1, inElem) End If gotNext = inElem.nextElement Else gotNext = inElem.nextComponent End If Loop While gotNext = MBE_SuccessEnd Sub

'-----------------------------------------------------------------'' Main entry point''-----------------------------------------------------------------Sub main

MicroStation BASIC Guide 4-7

Page 102: 48784209 Microstation Basic

Querying and Manipulating Graphic Elements

600macro.bk : 604_ITCT.FRA Page 8 Friday, October 15, 1999 1:27 PM

Dim element as New MbeElement Dim filePos as Long

' read the first element filePos = element.fromFile (0)

Do While filePos >= 0 Call ProcessElement (0, element) filePos = element.fromFile (filePos + element.fileSize) Loop End Sub

The ProcessElement function can be easily modified for use in other situations where the task involves processing components of complex elements. The elemshow.bas examples uses this exact technique.

Modifying graphic elementsSome of the MbeElement properties are read-only, meaning they can be used like variables in BASIC statements, such as:

elemType = element.type

but cannot be used as the target of an assignment:

element.type = MbeCellHeader ' This will result in a “not method” error

The type property in this example is read-only since the data format for each element type is different. It corrupts the element to simply change its type so the MbeElement object does not allow this.

In contrast a number of properties can be read and written. In this case those properties can be used in expressions and as the target of an assignment:

oldColor = element.colorelement.color = newColor

The color property is one such read/write property. Others that apply to all graphic elements include level, weight, style, class and group.

When these properties are assigned, by default they are assigned to the component element at the current position. However, if the changeAll property of an MbeElement is set to TRUE, then when the property is assigned it affects all component elements of the MbeElement object. This makes it easy to change, for example, the level of every text element in a text node or every element in a cell. Since changeAll makes sweeping changes to all component elements, set it with caution.

4-8 MicroStation BASIC Guide

Page 103: 48784209 Microstation Basic

Querying and Manipulating Graphic Elements

Mac

ro In

tera

ctio

ns W

ith M

icro

Stat

ion

4

600macro.bk : 604_ITCT.FRA Page 9 Friday, October 15, 1999 1:27 PM

Refer to the MbeElement reference section for information on other MbeElement object methods.

Using selection sets and fencesThe MbeElementSet object provides a means for macros to operate on multiple elements selected by the user with either a selection set or a fence. The first step in using an MbeElementSet object is to declare the object and allocate space for it using either of the following BASIC constructs:

Dim elemSet as New MbeElementSet

or

Dim elemSet as MbeElementSet

Set elemSet = New MbeElementSet

This allocates memory for the MbeElementSet object which is now an empty set. There are two object methods for getting elements into the MbeElementSet object: fromSelectionSet and fromFence.

To operate on elements in the MbeElementSet, retrieve them sequentially using the getFirst and getNext object functions. Each member of the set is returned as type MbeSetMember, which is predefined as if the following statements were included in every macro:

Type MbeSetMemberfilePos as LongfileNum as Integer

End Type

When done retrieving and processing the elements of an MbeElementSet object, the set is discarded using the clear object method.

The following macro example uses the same technique as the previous example to show information about graphic elements. Instead of showing every element in the design file, it shows only those elements selected using MicroStation’s element selection tool. If no element is selected, it shows elements in the fence. If there are no elements selected and the fence is not placed, the macro does nothing.

'-----------------------------------------------------------------''Subroutine that shows element type, nesting level and file position'

MicroStation BASIC Guide 4-9

Page 104: 48784209 Microstation Basic

Querying and Manipulating Graphic Elements

600macro.bk : 604_ITCT.FRA Page 10 Friday, October 15, 1999 1:27 PM

'-----------------------------------------------------------------Sub ShowElemInfo (nestLevel as integer, inElem as MbeElement) If nestLevel > 0 Then print Spc(nestLevel*2); "(";nestLevel;") Type "; inElem.type; Else print "Type "; inElem.type; End If print " Filepos "; inElem.componentFilePosEnd Sub

'-----------------------------------------------------------------'' Recursive subroutine that processes a simple or complex element''-----------------------------------------------------------------Sub ProcessElement (nestLevel as integer, inElem as MbeElement) Dim gotNext as integer

Do ' call function that shows info for element at current position Call ShowElemInfo (nestLevel, inELem)

If inElem.isHeader <> 0 Then ' if any components in complex, process them recursively If inElem.nextComponent = MBE_Success Then Call ProcessElement (nestLevel+1, inElem) End If gotNext = inElem.nextElement Else gotNext = inElem.nextComponent End If Loop While gotNext = MBE_SuccessEnd Sub

'-----------------------------------------------------------------'' Main entry point''-----------------------------------------------------------------Sub main Dim elemSet as New MbeElementSet Dim element as New MbeElement dim setMember as MbeSetMember Dim gotElement as Integer dim filePos as long

If elemSet.fromSelectionSet (1) <> MBE_Success Then print "No Selection Set - trying fence" If elemSet.fromFence () <> MBE_Success Then print "No fence - giving up" Exit Sub

4-10 MicroStation BASIC Guide

Page 105: 48784209 Microstation Basic

Querying and Manipulating Graphic Elements

Mac

ro In

tera

ctio

ns W

ith M

icro

Stat

ion

4

600macro.bk : 604_ITCT.FRA Page 11 Friday, October 15, 1999 1:27 PM

Else print "Processing Fence"

End If Else print "Processing Selection Set" End If

gotElement = elemSet.getFirst (setMember) Do While gotElement = MBE_Success filePos = element.fromFile (setMember.filePos, setMember.fileNum) Call ProcessElement (0, element) gotElement = elemSet.getNext (setMember) LoopEnd Sub

See the MbeElementSet object reference section for details.

Graphic element locationQuite often a macro operates on a graphic element selected by the user. One way of doing this task is to set up the macro to work on an element set from a selection set. The user selects the element(s) to work on and then invokes the macro or the macro guides the user by sequencing the MicroStation CHOOSE ELEMENT command.

While this is a good approach there are a few drawbacks. Because information about the location of the data point used to select each element in a selection set is not available, this method is appropriate for operations that make changes independent of geometry (for example, changing symbology). However, it is also generally unsuitable for operations dependent on geometry (for example, rotate element) unless the required geometry can be calculated from information extracted from the graphic element.

A second drawback is that a macro cannot affect the elements that the user puts into the selection set. Of course, the macro can ignore the elements when it processes the set, but sometimes it is preferable to have control over the selection process.

There are several different types of element location problems that macro programmers encounter:

1. The macro will operate on the located element using the methods provided for the MbeElement object. For this case, use the MbeStartLocate function. User inputs are received by the BASIC program and forwarded to MicroStation. When an element is located, the macro can use the

MicroStation BASIC Guide 4-11

Page 106: 48784209 Microstation Basic

Querying and Manipulating Graphic Elements

600macro.bk : 604_ITCT.FRA Page 12 Friday, October 15, 1999 1:27 PM

MbeElement.fromLocate object method to retrieve the located element. The macro can check to see if it matches a criteria of its own before operating on it using MbeElement object methods.

2. The macro wants to apply its own criteria, as in 1 above, so it uses the MbeStartLocate function. But when the graphic element is located, it wants to sequence a MicroStation command to do the actual element manipulation. In this case the macro locates the element as in 1 and then starts the MicroStation command (using the MbeSendCommand function). When the command asks the user to identify an element, the macro calls MbeRelocate. To the active command, this has the same effect as the user selecting the element located by the MbeStartLocate function by entering a data point at exactly the location that was sent to MicroStation during the location interaction.

3. The macro wants to find elements to work on using either the fence or a selection set or by stepping through the design file and finding them. But it wants to sequence a MicroStation command that requires element location to perform the actual task. In this case, the macro starts the MicroStation command for each element on which it wants to operate. When the command asks the user to identify an element, the macro calls MbeLocateElement. To the active command, this has the same effect as the user entering a data point at a location specified as an argument to MbeLocateElement and selecting the element specified as an argument.

Accessing design file informationInformation about the active design file is encapsulated in the MbeDgnInfo object. In contrast to MbeElement and MbeElementSet objects, MbeDgnInfo is pre-defined for each macro. This means you cannot declare an MbeDgnInfo object in a Dim statement. The object is automatically defined for you and you access its properties and methods using the construct MbeDgnInfo.method.

The MbeDgnInfo object includes the following read-only properties: dgnFileName, cellFileName, dgn3d, cell3d, dgnFileReadOnly, cellFileReadOnly, endOfFile, graphicGroup and nextGraphicGroup.

The following read/write properties are supported: masterUnitName, subUnitName, uorPerSub and subPerMaster.

4-12 MicroStation BASIC Guide

Page 107: 48784209 Microstation Basic

Querying and Manipulating Graphic Elements

Mac

ro In

tera

ctio

ns W

ith M

icro

Stat

ion

4

600macro.bk : 604_ITCT.FRA Page 13 Friday, October 15, 1999 1:27 PM

Accessing MicroStation settingsAccess the active settings and locks that MicroStation uses while placing and manipulating elements through the MbeSettings object. Like the MbeDgnInfo object, the MbeSettings object is pre-defined, so the object is automatically defined. Access its properties and methods using the construct MbeSettings.method.

The object methods that retrieve or change settings include: color, colorName, lineStyle, lineStyleName, weight, level, class, angle, font, fontName, gridUnits, gridReference, textHeight, textWidth, textJustification, nodeJustification, textLineLength, textLineSpacing, cell, lineTerminator, tagIncrement, point, setPatternDelta, getPatternDelta, patternAngle1, patternAngle2, patternScale, patternCell, areaMode, axisAngle, axisOrigin, capMode, fillMode, fillColor, setScale, getScale, terminatorScale and currentGraphicGroup.

The object methods that retrieve or change lock state include: snapLock, gridLock, associationLock, boresiteLock, axisLock, angleLock, textNodeLock, scaleLock, graphGroupLock, levelLock, fenceOverlap, fenceClip, fenceVoid, cellStretchLock, selectionSetLock, contructionPlaneLock, isometricLock and depthLock.

The “table” BASIC example illustrates using a number of MbeSettings properties.

Accessing MicroStation state informationInformation about the current state of MicroStation is encapsulated in the MbeState object. This includes the inputType read-only property, which reveals the type of input entered by users, and the getInputCommand, getInputDataPoint and getInputKeyin properties, which retrieve the actual input.

When input is directed to MicroStation using the MbeSendCommand and MbeSendDataPoint statements, determine the success or error status of the commands sequenced by the macro by examining the cmdResult read-only property. Determine the file number and file position of a located element using the locateFileNum, locateHeaderFilePos and locateComponentFilePos read-only properties.

The MbeState object also includes read/write properties that allow a macro to control whether MicroStation informational and

MicroStation BASIC Guide 4-13

Page 108: 48784209 Microstation Basic

Querying and Manipulating Graphic Elements

600macro.bk : 604_ITCT.FRA Page 14 Friday, October 15, 1999 1:27 PM

error messages are displayed to the user (messages, errorMessages) and whether graphic element are drawn to the views (noElementDisplay).

The results of measure commands are available through the measureResult1 and measureResult2 read-only properties.

And finally, the MbeState object provides several methods for controlling the element location process. Use the locateTolerance property to read or modify the element location tolerance. Control the elements eligible for modification by manipulation and fence commands through the locateClassMask, locatePropMask, locatePropVal, setLocateTypeMask and setLocateFileMask methods.

Accessing design file view informationMicroStation views are represented to the macro programmer as a predefined BASIC collection of MbeView objects called MbeViews. Syntactically, accessing views is similar to subscripting an array. For example, to tell if view 1 is active, query the read-only property active using the expression MbeViews(1).active. Alternatively, a macro can declare a variable of type MbeView, assign a view to it using the BASIC Set operator, and access the object property through the MbeView object:

Dim view as MbeView

Set view = MbeViews(1)active = view.active

View attributes that affect the way graphic elements are displayed can be queried and changed using the read/write properties fastCurve, slowFont, noText, lineWeight, pattern, textNode, enterDataFields, grid, levelSymbology, construction, dimension, areaFill, refBoundary and fastRefClip. If the read/write property deferApply is FALSE (the default) the changes take place immediately by updating the view. If deferApply is set to TRUE, the changes take place on the next update. Use the update method to update a view. Use the levelsOn and levelsOff methods to turn master file levels on and off. Use the getLevels method to retrieve the levels currently turned on.

Accessing reference file informationReference files are represented as a BASIC collection of MbeRefFile objects called MbeRefFiles. The maximum number of reference files that can be attached is accessible as

4-14 MicroStation BASIC Guide

Page 109: 48784209 Microstation Basic

Querying and Manipulating Graphic Elements

Mac

ro In

tera

ctio

ns W

ith M

icro

Stat

ion

4

600macro.bk : 604_ITCT.FRA Page 15 Friday, October 15, 1999 1:27 PM

MbeRefFiles.maxRefFiles. As with views, you can either access an individual reference file in a syntax similar to an array reference, for example, MbeRefFiles(refNum).property, or you can declare an MbeRefFile object and use the Set operator to assign it to access a particular reference file.

MbeRefFile methods include active, fileName, logical, description, attachName, notFound, display, snap, locate, display, plot, scaleLineStyle, scale, getLevels, levelsOn and levelsOff. Use the saveSettings method to write the changes back to attachment control element in the design file.

Accessing MicroStation session informationInformation about the MicroStation session is encapsulated in the MbeSession object. The MbeSession object is predefined. Access its properties and methods using the construct MbeSession.method.

The MbeSession properties (all of which are read-only) include msProduct, msVersion, msPlatform, language, numScreens and canSwapScreen. The elapsed time since the start of the MicroStation session can also be obtained with MbeSession.elapsedTime.

Database features of MicroStation BASIC extensionsThe database features of MicroStation BASIC are implemented over these main objects:

• MbeSqlda

• MbeTable

• MbeDatabase

• MbeDatabaseLink

MbeSqlda object

The MbeSqlda object helps the user extract results after a query or a describe table operation. The MbeSqlda object is similar to the concept of records in a database table.

Using the MbeSqlda object

The first step in using an MbeSqlda object is to declare the object and allocate space for it using either of the following BASIC constructs:

Dim sqlda as New MbeSqlda

MicroStation BASIC Guide 4-15

Page 110: 48784209 Microstation Basic

Querying and Manipulating Graphic Elements

600macro.bk : 604_ITCT.FRA Page 16 Friday, October 15, 1999 1:27 PM

or

Dim sqlda as MbeSqlda

Set sqlda = New MbeSqlda

You can call the MbeSqlda object variable anything you want in your macro. In this example, sqlda is used as the variable name. Both constructs establish a name for a sqlda object and allocates memory for that object.

The next step is to associate a record with the MbeSqlda object. The following methods provides the means for obtaining a valid MbeSqlda object.

MbeTable.describe

MbeTable.recordFirst

MbeTable.recordLast

MbeTable.recordNext

Once you have obtained a valid MbeSqlda object, you can query its properties using the methods of the MbeSqlda object.

MbeTable object

The MbeTable object represents a table in a database.

Using the MbeTable object

The first step in using an MbeTable object is to declare the object and allocate space for it using either of the following BASIC constructs:

Dim tb as New MbeTable

or

Dim tb as MbeTable

Set tb = New MbeTable

You can call the MbeTable object variable anything you want in the program. In this example, tb is used as the variable name. Either of the constructs establishes a name for an MbeTable object and allocates memory.

The next step is to associate an MbeTable object with a valid table in the database. MbeTable.name provides the means for making a valid MbeTable object.

Once you have a valid MbeTable object, you can query and manipulate its properties using the various methods of the MbeTable object.

4-16 MicroStation BASIC Guide

Page 111: 48784209 Microstation Basic

Querying and Manipulating Graphic Elements

Mac

ro In

tera

ctio

ns W

ith M

icro

Stat

ion

4

600macro.bk : 604_ITCT.FRA Page 17 Friday, October 15, 1999 1:27 PM

MbeDatabase object

MbeDatabase object represents a database or schema.

Using the MbeDatabase object

The first step in using an MbeDatabase object is to declare the object and allocate space for it using either of the following BASIC constructs:

Dim db as New MbeDatabase

or

Dim db as MbeDatabase

Set db = New MbeDatabase

You can call the MbeDatabase object variable anything you want in your program. In this example, db is used as the variable name. Either of these constructs establishes a name for an MbeDatabase object and allocates memory.

The next step is to associate an MbeDatabase object with a valid database name. MbeDatabase.name provides means for making a valid MbeDatabase object.

Once you have a valid MbeDatabase object, you can query and manipulate its properties using the various methods of the MbeDatabase object.

MbeDatabaseLink object

MbeDatabaseLink object represents the linkage between graphics and database.

Using the MbeDatabaseLink object

The first step in using an MbeDatabaseLink object is to declare the object and allocate space for it using either of the following BASIC constructs:

Dim link as New MbeDatabaseLink

or

Dim link as MbeDatabaseLink

Set link = New MbeDatabaseLink

You can call the MbeDatabaseLink object variable anything you want in your program. In this example we use link as the variable name. Either of these constructs establishes a name for an MbeDatabaseLink object and allocates memory.

MicroStation BASIC Guide 4-17

Page 112: 48784209 Microstation Basic

Using Macros to Specify Pen Table Output Actions

600macro.bk : 604_ITCT.FRA Page 18 Friday, October 15, 1999 1:27 PM

Using Macros to Specify Pen Table Output ActionsA BASIC macro can be assigned as part of a pen table output action for plotting. For example, in BASIC you can edit text and text node element strings in any imaginable way.

This flexibility does not come without a cost. Compared to the core pen table features, using macros is slow. It is most efficient to implement as many element manipulations as possible using core pen table features, resorting to macros only when necessary.

Overview of macro operation in pen tablesWhen you specify a BASIC function as part of the output action in a pen table section, it affects the entire plotting process. The following steps show how the plotting process utilizes any BASIC macros defined as part of a pen table’s section definitions:

1. When the pen table is loaded, any MicroStation BASIC macros specified as part in the pen table sections are automatically loaded. If the BASIC macro contains a Main subroutine it is executed.

2. The actual plotting process is started by clicking the OK button of the Plot settings box or choosing the Preview option. When the actual plotting process is started, initial plot data (plot border and comment) is outputted. This is followed by the loading of any Pre-Plot Hook entry point function defined in each macro from the pen table section.

3. Each element is processed through the section element criteria and when a match is found, all output actions except priority are applied to the element.

4. The Pen Table Plot Element Hook entry point function associated with the current pen table section is executed. If this function returns with MBE_ElemPrioritize, then the element is set aside with the priority level assigned by the called function. The element will be reprocessed as part of the next step.

5. If the Pen Table Plot Element Hook entry point function returns with an MBE_Ignore, the element is ignored and dropped from the plot output.

6. Once all non-prioritized elements have been processed, the prioritized elements are re-processed through the macro functions, again in order of their priority value. At this point any element manipulations performed in the macro will be passed on as plot output.

4-18 MicroStation BASIC Guide

Page 113: 48784209 Microstation Basic

Using Macros to Specify Pen Table Output Actions

Mac

ro In

tera

ctio

ns W

ith M

icro

Stat

ion

4

600macro.bk : 604_ITCT.FRA Page 19 Friday, October 15, 1999 1:27 PM

7. Once all elements have been processed, the macros’ post-plot hook functions will be executed.

8. The plot termination commands are sent to the output file or device from the plotting program.

9. The macros’ Plot Finished hook entry point function in each section is finally executed.

10.The plotting process concludes.

As you can see, the macro can be accessed at a number of steps in the plotting process. Because of this intimate involvement in the plotting process, it is imperative the macro is optimized to minimize unnecessary or duplicate processing.

The Main subroutine is optional in plottingA macro that uses the entry points below may, or may not, have a Main subroutine. If it is present, it will be executed upon macro load.

General Procedure for Creating a Macro for Pen Table Use1. Activate the BASIC Editor window (Utilities menu/Macros) and

open or create the BASIC macro.

2. (Optional) Create the Main subroutine section which is automatically executed when the plotting process invokes the macro.

3. Create at least one Function code segment containing the operations to be performed during the macro’s execution.

4. Set the program entry point (Edit menu/Program Entry Point) to one of the four standard plotting related settings.

5. Save the macro file (creates .bas and .ba files).

Working with element priorities in macrosOne of the common features a pen table is called upon to perform is the reordering of elements in the plot sequence. Known as prioritization, this feature is commonly performed as part of the output action definition in each section.

Although you can use a macro to perform the prioritization function, for the best output performance, this function should be left to the core output action operation of the same name.

MicroStation BASIC Guide 4-19

Page 114: 48784209 Microstation Basic

Using Macros to Specify Pen Table Output Actions

600macro.bk : 604_ITCT.FRA Page 20 Friday, October 15, 1999 1:27 PM

However, due to the complex nature of particular element selection criteria, you may have to prioritize an element using a macro. When this becomes necessary you should organize your function so that the priority is determined before any other processing is done.

As noted in the plotting steps, a BASIC function that prioritizes an element will have that element passed to it again later. This occurs after other unprioritized elements and elements with a lower priority have already been completely processed. The first time the function receives the element object its priority will always be 0. If by convention you never assign a priority of 0 to an element, your function can tell that an element is being passed to your BASIC function for the first time by testing the priority for a value of 0. The priority of 0 would tell your function to make the decisions necessary to determine the desired priority for the element, and then exit without performing any element manipulations.

Later, when the element is passed to your function for the second time, your function will find that the element has a non-zero priority (it will have whatever priority that was assigned to it before). Your function can then proceed to perform any desired element manipulations.

Pen Table Plot Element Hook function return valuesTo differentiate between the various results possible with a macro used in plotting, all Pen Table Plot Element Hook functions return

4-20 MicroStation BASIC Guide

Page 115: 48784209 Microstation Basic

Using Macros to Specify Pen Table Output Actions

Mac

ro In

tera

ctio

ns W

ith M

icro

Stat

ion

4

600macro.bk : 604_ITCT.FRA Page 21 Friday, October 15, 1999 1:27 PM

a value to the plot process as part of their operation. There are three such values:

The function must specifically set the output of the function to the appropriate value:

basicUpdateHook_element = MBE_ElemNormal

A macro plot function exampleThe following is an example BASIC function that does three things: it prioritizes text elements so that they are always drawn last, it causes all text and text-node elements in reference file 4 to be ignored (not plotted), and it performs certain font substitutions. In each case, the function sets the appropriate return value of MBE_ElemPrioritize, MBE_ElemIgnore or MBE_ElemNormal as just described:

Function floatTextAndUsePlottingFonts (elm as MbeElement) As Long dim ts$ as String If elm.type = MBE_Text Or elm.type = MBE_TextNode Then' Check if this is first pass on the element If elm.displayPriority = 0 Then elm.displayPriority = 10000 floatTextAndUsePlottingFonts = MBE_ElemPrioritize Exit Function

MBE_ElemNormal This is the most benign value your function can return. After the function has returned this value the element will be plotted. Any manipulations performed on the element will be reflected in the plot. The element remains unprioritized—it will plot prior to any prioritized elements. Any value that may have been assigned to elm.displayPriority has no effect when this return value is used.

MBE_ElemIgnore This return value tells the system to exclude the element from the plot. It is therefore wasted effort to perform manipulations on an element if you return this value.

MBE_ElemPrioritize When this value is returned the plotting order of the element is determined by elm.displayPriority, which will probably be set by the function just prior to returning.

MicroStation BASIC Guide 4-21

Page 116: 48784209 Microstation Basic

Using Macros to Specify Pen Table Output Actions

600macro.bk : 604_ITCT.FRA Page 22 Friday, October 15, 1999 1:27 PM

End If' Check if this text is part of reference file 4 If elm.fileNum = 4 Then floatTextAndUsePlottingFonts = MBE_ElemIgnore Exit Function End If' Check if font associated with this text is CHAR_FAST_FONT If elm.fontName = "CHAR_FAST_FONT" Then elm.fontName = "BLOCK_OUTLINE" Else elm.fontName = "ARCHITECTURAL" End If End If floatTextAndUsePlottingFonts = MBE_ElemNormal End Function

Pen table program entry pointsAs part of the preparation of a macro for use with the plotting process, program entry points must be defined. There are four such entry points described below. To set a function as an entry point requires the use of the BASIC Editor window.

➤ To designate pen table program entry points

1. From the Utilities menu, choose Macros.

The Macros settings box opens.

2. Select the macro that is to contain pen table program entry points, and click the Edit button.

The BASIC Editor dialog box will appear with the contents of the selected macro in its editing area.

3. From the Edit menu, choose Program Entry Point.

4-22 MicroStation BASIC Guide

Page 117: 48784209 Microstation Basic

Using Macros to Specify Pen Table Output Actions

Mac

ro In

tera

ctio

ns W

ith M

icro

Stat

ion

4

600macro.bk : 604_ITCT.FRA Page 23 Friday, October 15, 1999 1:27 PM

The Select Entry Point dialog box opens. If any of the functions were previously defined they will appear in the listing portion of this dialog box.

4. Click the New button to add a new entry point.

The Edit BASIC Macro Entry Point dialog box opens.

5. Select the Entry Point type from the list on the left side of this dialog box.

For most functions, this will be the first entry, Pen Table PlotElement Hook.

6. In the Name field, key in the BASIC function name. This is the name as found on the Function line in your macros. Example (name shown in bold):

Function floatTextAndUsePlottingFonts (elm as MbeElement) As Long

7. Click the OK button to add the new entry point to the list.

Select Entry Point dialog box

Edit BASIC Macro EntryPoint dialog box

MicroStation BASIC Guide 4-23

Page 118: 48784209 Microstation Basic

Using Macros to Specify Pen Table Output Actions

600macro.bk : 604_ITCT.FRA Page 24 Friday, October 15, 1999 1:27 PM

The different program entry points and their functionThere are currently four different types of entry points that are unique to plotting. Depending on the entry point type, the function definition changes slightly. Below are the descriptions of these entry points and an example of the function line format required for each.

Pen Table Plot Element Hook

This is the entry point type you must create for a function that is associated with a pen table section. There may be multiple entry points of this type in a single macro. The function declaration must be of the form:

Function userPlot_element (elm as MbeElement) As Long

This is the most commonly used program entry point. Unlike the other entry points that get called only once per plotting operation, the Pen Table Plot Element Hook gets called for each element being processed for plotting.

Pre-Plot Hook

At the time that this entry point is called, MicroStation has written initialization commands to the plotfile, possibly drawn border and raster components but has yet to produce any other plot output. A macro can use this entry point to add graphic to the plot that do not exist in the design. Returning any value other than MBE_Success will cause the plot to be aborted. Only one entry point of this type may be defined per macro. The function declaration must be of the form:

Function userPlot_pre As Long

Post-Plot Hook

At the time that this entry point is called, MicroStation has completed writing drawing commands to the plotfile but has not yet written termination commands and the plotfile is open. As with the Pre-Plot Hook, the plot method of an MbeElement object can be used here to add its graphic to the plot. This function should always return MBE_Success. Only one entry point of this type may be defined per macro. The function declaration must be of the form:

Function userPlot_post As Long

4-24 MicroStation BASIC Guide

Page 119: 48784209 Microstation Basic

Using Macros to Specify Pen Table Output Actions

Mac

ro In

tera

ctio

ns W

ith M

icro

Stat

ion

4

600macro.bk : 604_ITCT.FRA Page 25 Friday, October 15, 1999 1:27 PM

Plot Finished Hook

At the time that this entry point is called, the plot has been completed and the plotfile is closed. This function should always return MBE_Success. Only one entry point of this type may be defined per macro. The function declaration must be of the form:

Function userPlot_finished As Long

The function names shown in the examples above (userPlot_…) are for illustration only. The actual names used are up to the developer.

Optimizing the macro for plottingIn the example given earlier, the structure shown was very straightforward and was provided for illustration purposes. In reality, this macro contains an unnecessary processing step which, if used with a large design, could waste a significant amount of time.

In the example, a test is made to see if the element has been prioritized. This was done with the If conditional check:

If elm.displayPriority = 0 Thenelm.displayPriority = 10000floatTextAndUsePlottingFonts = MBE_ElemPrioritizeExit Function

End If

Once the priority of the element is changed, the program returned control to the plotting process. Note, however, that the check for the reference file and the subsequent non-output is cycled through in a separate loop.

If elm.fileNum = 4 ThenfloatTextAndUsePlottingFonts = MBE_ElemIgnoreExit Function

End If

In reality, you would combine the check for the priority and the reference file into one conditional If/then evaluation like this:

Example If elm.displayPriority = 0 ThenIf elm.fileNum = 4 Then

floatTextAndUsePlottingFonts = MBE_ElemIgnoreElse

elm.displayPriority = 10000floatTextAndUsePlottingFonts = MBE_ElemPrioritize

End If

MicroStation BASIC Guide 4-25

Page 120: 48784209 Microstation Basic

Using Macros to Perform DWG Import/Export

600macro.bk : 604_ITCT.FRA Page 26 Friday, October 15, 1999 1:27 PM

Exit FunctionEnd If

This would result in only one pass on any elements that are not destined for the plotfile.

Using Macros to Perform DWG Import/ExportA number of DWG import and export settings are accessible only through the dwg.bas macro or a user specified macro.

Objects for specifying import and export settingsThere are two objects for DWG import and export settings: MbeDWGImportSettings and MbeDWGExportSettings. Following is a list of properties for each of these objects.

Object Settings Values Description

MbeDWGImportSettings

.polylineWidthAs MBE_Linestyle, MBE_Shape

Width to weight mapping support has been dropped.

.ignoreEmptyLayers MBE_ON, MBE_OFF If the layer is never used, ignore it.

MbeDWGExportSettings

.DXFPrecision Integer in the range 1-20

Sets how many digits after decimal point in DXF file.

.ltScale Any reasonable positive floating point

This value is placed in the DWG/DXF header for line type scale. It overrides the Line Terminator Scale value in the seed file if one is specified.

.refNameInLayer MBE_ON, MBE_OFF If on, the reference file logical name is placed in layer name preceding a hyphen; the level name or number follows the hyphen — for example, “REFLOGNAME-LEVEL5”.

4-26 MicroStation BASIC Guide

Page 121: 48784209 Microstation Basic

Using Macros to Perform DWG Import/Export

Mac

ro In

tera

ctio

ns W

ith M

icro

Stat

ion

4

600macro.bk : 604_ITCT.FRA Page 27 Friday, October 15, 1999 1:27 PM

Object for specifying font cross-reference informationA macro-driven interface utilizes six macro objects to input font cross reference information.

Each object/method ending in “Entry” takes as required arguments the AutoCAD font name followed by the MicroStation font number.

MbeFontNameTable.addImportEntry "romanc", 3

This last statement is important, as the order of “AutoCAD fontname”, MicroStation font number is the same regardless of whether import or export is the intended operation. The AutoCAD font names must be enclosed in quotation marks.

There are two additional optional arguments associated with exporting a MicroStation font to AutoCAD: width factor and oblique angle. Both are used to place additional information in the output DWG/DXF file for these AutoCAD related font attributes. Note there is no equivalent to these arguments in the Import DWG/DXF operation.

MbeFontNameTable.addExportEntry "romanc", 3, 2.0, 30.0

MbeFontNameTable methods Used to

addExportEntry add a single AutoCAD to MicroStation font entry into the export font translation table.

addImportEntry add a single AutoCAD to MicroStation font entry into the import font translation table.

addImportExportEntry add a single AutoCAD to MicroStation font entry into both the import and export font translation table.

addImportEntryFromFile read in a list of AutoCAD / MicroStation font entries from a specified ASCII text file and place them into the import font translation table.

addExportEntryFromFile read in a list of AutoCAD / MicroStation font entries from a specified ASCII text file and place them into the export font translation table.

addImportExportEntryFromFile read in a list of AutoCAD / MicroStation font entries from a specified ASCII text file and place them into both the import and export translation tables.

MicroStation BASIC Guide 4-27

Page 122: 48784209 Microstation Basic

Using Macros to Perform DWG Import/Export

600macro.bk : 604_ITCT.FRA Page 28 Friday, October 15, 1999 1:27 PM

✍ You must specify a value for the width factor in order to specify the optional oblique angle.

Using an ASCII file as input

To maintain compatibility with the existing table-driven interface, there are three additional methods associated with using an ASCII list file for the font names translation table. The MBE font objects ending in FromFile process a list of AutoCAD font names and MicroStation font numbers from the file defined by the first and required argument, the file-name. By default, this file will be sought in the directory defined by the environment variable, MS_DWGTABLES. An optional argument provides an environment variable name that points to a specific subdirectory where the file can be found.

That is, the ASCII input file is invoked as follows, with the second argument optional:

...FromFile “Filename”, “MS_DWGTABLES”

The internal format of the input file is as follows:

AutoCADfontname MicroStationFontNumber WidthFactor ObliqueAngle

As with the .addExportEntry method, the WidthFactor and ObliqueAngle arguments are optional.

It should be noted that one of the features of using the macro interface is future expandability. Should additional parameters be needed in manipulating fonts, all that is required is additional parameters in the input ASCII file and a modification to the macro.

Objects for specifying cell/block cross-reference informationWhen the export DWG/DXF process encounters a cell, it attempts to find a match in its table as loaded from the dwg.bas macro. If a match is found, the equivalent AutoCAD block name is used instead of the cell name. MicroStation still generates a block definition based on the cell contents.

When the import DWG/DXF process encounters a block name, it attempts to find a match in the import table loaded from the dwg.bas macro. The contents of the cell is created from the block definition found in the DWG/DXF source file.

4-28 MicroStation BASIC Guide

Page 123: 48784209 Microstation Basic

Using Macros to Perform DWG Import/Export

Mac

ro In

tera

ctio

ns W

ith M

icro

Stat

ion

4

600macro.bk : 604_ITCT.FRA Page 29 Friday, October 15, 1999 1:27 PM

To load the import and export block/cell table the following MBE objects and methods are used:

Each object.method ending in Entry takes as required arguments the AutoCAD block name followed by the cell name. This last statement is important, as the order of AutoCAD and MicroStation arguments is the same regardless of whether import or export is the intended operation. The block and cell names must be enclosed in quotation marks, as in the following example:

MbeBlockNameTable.addImportEntry “callout”, “symbol1”

Editing and compiling “dwg.bas”As a BASIC macro, dwg.bas can be edited using the BASIC Editor window (Utilities menu/Macros). Once the file is highlighted, click the Edit button. Do not double-click the filename or click the Run button. The DWG extensions in this macro source file will only compile when one of the DWG import or export applications is loaded.

In order to compile and run dwg.bas, one of the DWG translators must have been run at least once. This allows the DWG translator

MbeBlockNameTable methods Used to

addExportEntry add a single AutoCAD-to-MicroStation block entry into the export block translation table.

addImportEntry add a single AutoCAD-to-MicroStation block entry into the import block translation table.

addImportExportEntry add a single AutoCAD-to-MicroStation block entry into both the import and export block translation tables.

addImportEntryFromFile read in a list of AutoCAD / MicroStation block entries from a specified ASCII text file and place them into the import block translation table.

addExportEntryFromFile read in a list of AutoCAD / MicroStation block entries from a specified ASCII text file and place them into the export block translation table.

addImportExportEntryFromFile read in a list of AutoCAD / MicroStation block entries from a specified ASCII text file and place them into both the import and export block translation tables.

MicroStation BASIC Guide 4-29

Page 124: 48784209 Microstation Basic

Using Macros to Perform DWG Import/Export

600macro.bk : 604_ITCT.FRA Page 30 Friday, October 15, 1999 1:27 PM

to register the DWG macro extensions. Once this is done, the file can be compiled and run as any other macro.

If there is a compile error, the error and line number are provided. If a run-time error occurs, an error number is returned. These error numbers are defined below.

It is not necessary to edit the macro file before each translation. The translator will automatically load the macro file for each translation. If a compile or run-time error occurs, an alert box displays containing the error and line number after which the translation halts. In this case, just bring up the editor as described above and go the line number to fix the problem. Then save the change and restart the translator.

Error numbers

The following table shows the defined run-time error codes.

Error number Meaning

1901 Invalid Block name

1902 Invalid Cell Name

1903 Cannot open table file

1904 Invalid font file name

1905 Invalid font number

1906 Invalid settings value

4-30 MicroStation BASIC Guide

Page 125: 48784209 Microstation Basic

600macro.bk : 605_BLDR.FRA Page 1 Friday, October 15, 1999 1:27 PM

5 Adding Dialog Boxes to Macros

There are several ways a macro may need to interact with a user. For example, allowing a user to enter a datapoint while in the process of locating an element. However, a user’s interaction is not limited to generating datapoints and selecting elements. You may need to collect more general information like “Please provide a file name.” or “Would you like to continue?” Several general purpose dialog boxes allow a macro to collect information of this nature.

Standard Dialog BoxesIn many instances the Standard Dialog extensions described here eliminate the need to design custom dialogs in a macro. For detailed information on these extensions, see “Dialog Box Statements” on page 8-145. The descriptions of the standard dialog extensions below are only meant to highlight their functionality.

Use the MbeFileOpen and MbeFileCreate extensions to help create and open files. These functions invoke the standard MicroStation File Open and File Create dialogs. When calling these functions, the macro may supply default values for filename, file filter, and description.

Another extension, MbeMessageBox, allows a macro to display a general purpose message dialog in a variety of push-button and information icon configurations. A macro can display a message in a dialog box with an OK button, OK and Cancel buttons, Yes and No buttons, and so on, depending on the type of response needed from the user. At the same time, you can display one of several icons (or no icon at all) in the same dialog. Examples include the STOP, warning (!), question (?), or information icons (i).

The MbeInputBox extension allows a macro to display a general purpose dialog with a message prompt, a text field in which the user may enter free-form string data, and an OK button. After the user enters an answer in the text field and clicks the OK button, the reply is immediately stored in a string variable supplied by the macro.

MicroStation BASIC Guide 5-1

Page 126: 48784209 Microstation Basic

Custom Dialog Boxes

600macro.bk : 605_BLDR.FRA Page 2 Friday, October 15, 1999 1:27 PM

The MbeSelectBox is a general purpose dialog used for displaying a list of items. The user selects one item from the list and clicks the OK button. The index of the selected item is returned to the macro.

Custom Dialog BoxesThe five standard dialogs described above will satisfy most data collection requirements of macros. However, in cases where the collected data is too complex for these standard dialogs, you may wish to define a custom dialog.

Custom dialogs for BASIC macros are similar to dialog boxes used throughout MicroStation with the following exceptions:

1. Custom dialog boxes in macros are always modal. That means a macro displaying a custom dialog box is suspended until the user dismisses the dialog box. Then control is returned to the macro. This implies that all custom dialogs must have at least one push-button defined to dismiss the dialog (for example, OK).

2. BASIC custom dialog boxes do not have hook functions. The macro relies on access strings to set BASIC variables while the dialog is displayed. When the dialog is dismissed, the macro can reference the associated BASIC variables to see what information was provided by the user in the dialog box.

3. Data type characteristics are dynamically assigned to text items in BASIC custom dialogs. The type of information accepted by the text item is determined by the data type of the BASIC variable associated with the text item. For example, if the access string for a text item specifies a string variable, then the text item takes on the characteristics of a string text field. If the access string specifies a Double variable, the text field treats information provided by the user as double-precision floating point. This is also true for integer and long integer values.

The facility to define custom dialog boxes is called the Dialog Builder, which is invoked from the BASIC Editor window by choosing Edit > Custom Dialog > Edit. All dialogs and dialog items for macros are defined graphically and stored as binary information in the macro’s .ba file. There is no textual dialog box definition for a Custom Dialog box in MicroStation BASIC.

After a custom dialog has been defined using the Dialog Builder window, a macro can display the dialog box by calling the

5-2 MicroStation BASIC Guide

Page 127: 48784209 Microstation Basic

Dialog Builder

Ad

din

g D

ialo

g B

oxes

to

Mac

ros

5

600macro.bk : 605_BLDR.FRA Page 3 Friday, October 15, 1999 1:27 PM

MbeOpenModalDialog function. An automated way of generating this function call is to use the Edit > Custom Dialog > Insert… menu to bring up a list of all custom dialogs defined for a macro. Choosing a dialog from this list causes a line of text to be automatically inserted into the macro. This line is a call to the MbeOpenModalDialog function.

W Deleting a compiled macro file (.ba) will permanently destroy all the dialog box definitions for the macro. They cannot be recovered except to completely reconstruct them using the Dialog Box Builder.

Dialog BuilderThe Dialog Builder window allows you to create and modify dialog resources and save the changes or new resource items to a binary .ba file. Any item in a standard dialog can be placed and manipulated and the dialog itself can be resized. All created dialog boxes are saved to the default file. When you launch Builder from the Basic Editor, the default file is specified by the path where the file is located and by the name of the user-defined macro <macro name>.ba. The .ba extension file contains the dialog box resources for the macro. So, the dialog boxes of a macro named Table would be stored in the file table.ba.

The main dialog box contains two list boxes. The top list box contains a list of currently opened dialog boxes and provides details of the status, name, ID number, and resource file to which they belong. Status is a one-character field preceding the Title field with the following flags: “ “-blank, “M”odified, “N”ew and “R”ead only. Newly opened dialogs, or dialogs opened as copies of the original, are given the “N” flag. This flag is retained until

Builder dialog box andmacro Tools tool box

MicroStation BASIC Guide 5-3

Page 128: 48784209 Microstation Basic

Dialog Builder

600macro.bk : 605_BLDR.FRA Page 4 Friday, October 15, 1999 1:27 PM

the dialog is saved, when the flag is cleared. The bottom list box contains a list of all the items in the currently selected dialog box.

Dialog menuThe Dialog menu contains selections for creating and loading dialog boxes to be edited and for deleting and saving dialogs in a file. During an editing session, use Dialog > Load… to open many dialogs at one time. This allows you to compare dialog layouts for consistency and to cut and paste items between dialogs to ensure that they are identical.

New

Creates a new, untitled dialog box. The new dialog is associated with the default file. If no default file exists, the dialog is not associated with any file until you choose “Save Dialog” or “Save Dialog To New.”

Load…

Opens the Load Dialog dialog box. This dialog lets you select the file from which to open the dialog box, the dialog within the file to open, and the mode in which the dialog will be opened. If the

To Choose from the Dialog menu

Create a new dialog box in the default file. New

Open an existing dialog resource in the current file. Load…

Close an existing dialog box. Close

Save a created dialog box to a file. Save

Save a dialog box to an existing resource file (.ba). Save to Existing

Save a dialog box to a new file. Save to New…

Delete a dialog box from a file. Delete

5-4 MicroStation BASIC Guide

Page 129: 48784209 Microstation Basic

Dialog Builder

Ad

din

g D

ialo

g B

oxes

to

Mac

ros

5

600macro.bk : 605_BLDR.FRA Page 5 Friday, October 15, 1999 1:27 PM

user opens a dialog box with a dialog ID that is already open, the dialog box is opened as a copy.

Load Dialog Box As Read Only

Open a dialog box for editing or reviewing. If on, users cannot modify the dialog box, items cannot be dragged, the dialog box cannot be resized, the OK button in change dialogs is disabled, and none of the “Save …” menu options can be chosen from the File menu.

Load Dialog Box As A Copy Of Original

If on, a copy of the selected dialog box with no associated file is made. This dialog box is treated as a new dialog and any changes made are not applied to the original dialog.

Close

Closes the currently selected dialog box. When a modified dialog box is closed, an alert box is displayed. You are given the option of saving the dialog before closing (Yes), closing without saving (No), and cancelling the close operation (Cancel).

Save …

Saves the dialog to the assigned file destination. If no destination exists, the dialog can be saved to the file of your choosing.

Save Dialog… is disabled if no changes have been made to the dialog box or if the dialog was opened as read-only.

Load Dialog dialog box

MicroStation BASIC Guide 5-5

Page 130: 48784209 Microstation Basic

Dialog Builder

600macro.bk : 605_BLDR.FRA Page 6 Friday, October 15, 1999 1:27 PM

Save To New…

Saves the dialog to a newly created file of your choosing. This becomes the default file to which newly opened dialog boxes are saved. This item is disabled if the file has been opened as read-only.

Save To Existing…

Saves the dialog to an already existing resource file that you choose. This item is disabled if the file has been opened as read-only.

Delete

Deletes the currently selected dialog box from the file to which it belongs. This item is disabled if the dialog box does not belong to a file.

✍ The push-buttons in the Builder window (New, Load and Save…) operate the same as their menu counterparts in the File menu.

Edit menuThe Edit menu contains selections for moving, copying, deleting, selecting and arranging dialog items. Use Cut, Copy and Paste between multiple dialog boxes for accelerated dialog box creation.

Cut

Cuts the selected item(s) from the dialog and places the items in the clipboard, from which you can paste them into any open dialog. Associated attributes are cut with the items. Cut items are removed from the dialog item list.

To Choose from the Edit menu

Cut the selected dialog item(s) to the clipboard. Cut

Copy the selected dialog item(s) to the clipboard. Copy

Paste dialog item(s) from the clipboard into the current dialog.

Paste

Delete the selected dialog item(s). Delete

Select all the items in the current dialog. Select All

Bring the selected dialog item(s) to the front. Bring To Front

Send the selected dialog item(s) behind any other dialog items in the same area.

Send To Back

5-6 MicroStation BASIC Guide

Page 131: 48784209 Microstation Basic

Dialog Builder

Ad

din

g D

ialo

g B

oxes

to

Mac

ros

5

600macro.bk : 605_BLDR.FRA Page 7 Friday, October 15, 1999 1:27 PM

Copy

Copies the selected item(s) to the clipboard without affecting the original items. You can paste copies of the clipboard items into any open dialog. Associated attributes are copied with the item.

Paste

Pastes the item(s) in the clipboard into the dialog that has the input focus. Associated attributes are pasted with the item. Pasted items are added to the end of the dialog item list.

Delete

Deletes the selected item(s) from the dialog.

Select All

Selects all the items in the current dialog. This function is the same as individually selecting each item while holding down the <Shift> key or drawing a selection box around all the items.

Bring To Front

Brings the selected item(s) in front of all other items in the dialog. Use this command to control which items are selected first when you click an area occupied by more than one item. An item’s front or back location affects its selectability when the dialog is edited and used.

Send To Back

Positions the selected item(s) behind all other overlapping items. Use this command, to control which items are selected first when you click an area occupied by more than one item. An item’s front or back location affects its selectability when the dialog is edited and used.

MicroStation BASIC Guide 5-7

Page 132: 48784209 Microstation Basic

Dialog Builder

600macro.bk : 605_BLDR.FRA Page 8 Friday, October 15, 1999 1:27 PM

Options menu

Test Dialog

Toggles the dialog between edit and test modes. Edit mode is Builder’s normal mode in which dialogs and the items in them can be added, deleted, and modified. In test mode, the dialog behaves as it would in a macro; option buttons can be changed, toggle buttons toggled, text in text items can be edited, color pickers selected, and level maps changed. Test mode allows the dialog box designer to test the “usability” of the dialog box’s layout.

✍ All linkages to the macro’s BASIC variables are not connected and do not function in Builder’s test mode.

Preferences

Toggles the display of the Preferences dialog box. By default the dialog box is hidden. At present the only user-definable preference is Vertical Spacing, which controls the amount of space inserted between dialog items when Space Vertically is chosen from the Alignment menu. Spacing is measured in dialog units and 1.25 is the default setting.

Tools

Toggles the display of the tools box. By default the tools box is displayed. Use the tools box to create new dialog items. See “Tool box” on page 5-19.

Dialog Attributes…

Opens the Dialog Box Attributes dialog box. In this dialog you can change the dialog’s attributes, such as title, dimensions and ID number.

To Choose from the options menu

Toggle dialog between edit mode and test mode. Test Dialog

Toggle display of Preferences dialog box. Preferences

Toggle display of tool box. Tools

Open Dialog Attributes window. Dialog Attributes…

Open Item Attributes window. Item Attributes…

5-8 MicroStation BASIC Guide

Page 133: 48784209 Microstation Basic

Dialog Builder

Ad

din

g D

ialo

g B

oxes

to

Mac

ros

5

600macro.bk : 605_BLDR.FRA Page 9 Friday, October 15, 1999 1:27 PM

Open the Dialog Box Attributes dialog by double-clicking in an unoccupied area of the dialog box or by double-clicking one of the rows in the open dialogs list box.

File…

Opens the select file dialog box in which the user can associate a file with the dialog box. The file to which the dialog box belongs is displayed to the right of the push-button. The dialog box is not automatically saved to the file.

Title

Specifies the character string that displays in the dialog box’s title bar.

ID#

Specifies the ID value of the dialog box being edited.

Width

Specifies the width of the dialog box in dialog coordinate units.

Height

Specifies the height of the dialog box in dialog coordinate units.

Item Attributes…

Opens the attributes dialog box that is associated with the type of item that is selected. There are different attribute dialogs for text, label, toggle button, group box, option button, push-button, color picker, level map, radio button and scale items.

Also open item attribute dialogs by double-clicking the item whose attributes are to be changed or by double-clicking an item in the list box containing the items in a dialog box.

Dialog Box Attributesdialog box

MicroStation BASIC Guide 5-9

Page 134: 48784209 Microstation Basic

Dialog Builder

600macro.bk : 605_BLDR.FRA Page 10 Friday, October 15, 1999 1:27 PM

Common item attributesEach item created in Builder has a dialog box for editing the item attributes. Many of these dialog boxes have common items which will be discussed here rather than with each specific dialog box.

Label

Contains the character string displayed on a text item.

Access String

Specifies the underlying BASIC variable that the item will be used to modify. Upon entry to the dialog, the underlying BASIC variable is used to set the appearance of the item. Upon exiting the reverse is true: the current value of the item is used to update the state of the underlying BASIC variable.

The following table shows the data types of the access strings for each of the following items supported by Builder:

The following items are not supported by Builder:

• Button Group Items

• Tool Palettes

• Color Picker Pull-down Menus

• Option Pull-down Menus

• Text Pull-down Menus

• Separator Items

Item Data Type of Access String

ColorPicker Long or Integer

Group Box No Access String

Label No Access String

LevelMap - Access String Array of 4 Integers

LevelMap - Active Level Long or Integer

Option Button Long or Integer

Push Button No Access String (uses an action button value)

Radio Button Long or Integer

Scale Single or Double

Text String, Long, Integer, Single, or Double

Toggle Button Long or Integer

5-10 MicroStation BASIC Guide

Page 135: 48784209 Microstation Basic

Dialog Builder

Ad

din

g D

ialo

g B

oxes

to

Mac

ros

5

600macro.bk : 605_BLDR.FRA Page 11 Friday, October 15, 1999 1:27 PM

• List Box Items

• Multiline Text Fields

• Popup Menu Items

• Scroll Bar Item

Text Editor dialog boxUsed to change the attributes of a text item.

Read Only

If on, the contents of the text item is not editable.

Label Above

If on, the label appears above the text item. By default, the label is displayed to the left of the item.

Custom Dialog Boxes

Data type characteristics are dynamically assigned to text items in custom dialogs. The type of information accepted by the text item is determined by the data type of the BASIC variable associated with the text item. For example, if the access string for a text item specifies a string variable, then the text item takes on the characteristics of a string text field. If the access string specifies a Double variable, the text field treats information provided by the user as double-precision floating point. This is also true for integer and long integer values.

Label Editor dialog boxUsed to change the attributes of a label item.

Word Wrap

If on, newline characters in a label result in a multiline label.

Bold Font

If on, the label is displayed using a bold font.

MicroStation BASIC Guide 5-11

Page 136: 48784209 Microstation Basic

Dialog Builder

600macro.bk : 605_BLDR.FRA Page 12 Friday, October 15, 1999 1:27 PM

Justification

Sets the justification of the label within the item.

Toggle Button Editor dialog boxUsed to change the attributes of a toggle button item.

Mask

If invert is TRUE, the bitwise OR operator combines mask with the variable specified by accessStr. If invert is FALSE, the bitwise AND operator combines the ones complement of mask with the variable specified by accessStr.

Invert

If on, indicates a TRUE state for invert.

Option Button Editor dialog boxUsed to change the attributes of an option button. An option button item contains a list of the following subitems:

Sub-Items List Box

Contains a description of the label, value, mask, and enabled state of each subitem in the option button. The information is modified in the list box by changing the text items and toggle button item described below.

Icon ID Label

Specifies the text string to be displayed for the subitem.

Value

Determines with mask the currently selected subitem. Only one subitem can be selected at a time.

Justification Meaning

Left The label is left-justified within the item.

Right The label is right-justified within the item.

Center The label is centered within the item.

5-12 MicroStation BASIC Guide

Page 137: 48784209 Microstation Basic

Dialog Builder

Ad

din

g D

ialo

g B

oxes

to

Mac

ros

5

600macro.bk : 605_BLDR.FRA Page 13 Friday, October 15, 1999 1:27 PM

Mask

Determines with value the currently selected subitem. Mask indicates which bits of the variable specified by accessStr are compared to value. For example, for a mask value of 0xC (1100 binary), bits 2 and 3 of accessStr are compared to value.

Enabled

Determines the state (enabled or disabled) of the subitem when the option button is first created. If this item is set to ON, the subitem can be selected; when it is set to OFF, the subitem will be dimmed (disabled).

Insert

Inserts a copy of the selected subitem to the subitem list of the option button.

Delete

Removes the currently selected subitem from the subitem list of the option button.

✍ The Access String related to an item needs to be an Integer.

Push Button EditorUsed to change the attributes of a push-button. All the dialog boxes created for the BASIC environment are modal. That means all user interactions must be focused within that single dialog and that the dialog box manager will ignore mouse presses while the pointer is outside the dialog box. Each activated push-button—except for Reset—dismisses the modal dialog and passes a return action value to the macro. This action value is handled by the programmer and used to determine the operation requested by the user.

MicroStation BASIC Guide 5-13

Page 138: 48784209 Microstation Basic

Dialog Builder

600macro.bk : 605_BLDR.FRA Page 14 Friday, October 15, 1999 1:27 PM

Default Attributes

Sets the attributes of the push-button. The choices are:

Push Button Type

Sets the type of push-button. Each type returns a different action ID. The programmer uses this return value from the push-button to carry out a specified action. Once any type of push-button is pressed, the dialog box that contains the push-button closes.

Types of push-button include:

The return ID’s of the other push-button include MBE_BUTTON_OK, MBE_BUTTON_CANCEL, MBE_BUTTON_DEFAULT, MBE_BUTTON_YES, MBE_BUTTON_NO, MBE_BUTTON_STOP, MBE_BUTTON_HELP, MBE_BUTTON_RETRY.

Action ID#

This text item is displayed if the push-button type is User Defined. The user sets this ID value, which is the value returned from the modal dialog box when the dialog box is closed. This ID value must be greater than or equal to 1000.

Color Picker dialog boxUsed to change the attributes of a color picker item.

Normal The push-button is not a Default or a Cancel push-button.

Default The push-button is a dialog box’s default button outlined with a recessed rectangle. The button is automatically activated when the user presses the <Return> key.

Cancel The push-button is a dialog box’s cancel button. The button is automatically activated when the user presses the <Esc> key and typically means that the operations to be performed using the dialog box should be aborted.

Type of push-button Details

User Defined Returns an ID value that is specified by the user. When the user selects this option choice, the Action ID# text item is displayed. The push-button returns an ID equal to the Action ID#.

Apply Returns an ID of MBE_BUTTON_APPLY.

Reset Has an ID of MBE_BUTTON_RESET. The modal dialog box is not closed. The Reset button sets all the items to the state they were in when the dialog box was first opened.

5-14 MicroStation BASIC Guide

Page 139: 48784209 Microstation Basic

Dialog Builder

Ad

din

g D

ialo

g B

oxes

to

Mac

ros

5

600macro.bk : 605_BLDR.FRA Page 15 Friday, October 15, 1999 1:27 PM

Mask

Indicates the bits of the variable specified by accessStr that are used to determine the current color index. Usually, mask should be set to 0xFFFFFFFF, which indicates that the entire variable will be used to derive the color index.

Associated Text Item ID #

Sets the resource ID of a text item that will be associated with the color picker item. As the user drags the mouse over the popped up color palette, the associated text item will be dynamically set to the index of the color square the pointer is on.

Level Map Editor dialog boxUsed to change the attributes of a level map item.

Access String

Sets the name of the BASIC variable (a 4-element array of type Integer) used to represent the level map.

Active Level Access String

Sets the name of the BASIC variable used to represent the active level. The active level is indicated with a circle and is selected with a double-click. If an active level is not applicable, specify an empty string for this item.

Scale Editor dialog boxUsed to change the attributes of a scale item.

Increment Amount

Sets the amount the current value of the scale is changed when the user clicks on the scale arrows.

Page Increment Amount

Sets the amount the current value of the scale is changed when the user clicks in the page area of the scale. The page areas are the areas between the slider and the scale arrows.

Minimum

Sets the value associated with the minimum position of the scale slider.

MicroStation BASIC Guide 5-15

Page 140: 48784209 Microstation Basic

Dialog Builder

600macro.bk : 605_BLDR.FRA Page 16 Friday, October 15, 1999 1:27 PM

Maximum

Sets the value associated with the maximum position of the scale slider.

Min Label

Sets the text string to be used as the label for the minimum value of the scale item.

Max Label

Sets the text string to be used as the label for the maximum value of the scale item.

To Display Format

Describes a format string to convert the value of the scale item into a display value when Show Value is on.

Associated Text ID

Sets the resource ID of the text item associated with the scale item. As the user drags the mouse on the slider, the associated text item will be dynamically set to the value of the scale based on the current slider position.

Orientation

Indicates whether the item is a vertical or a horizontal scale item. The choices are:

Has Arrows

If on, the scale item is drawn with single step adjustment arrows at each end of the scale.

Show Value

If on, the current scale value should be displayed alongside the slider.

Limits On Side

If on, the range limits for the scale are to be displayed at the side of the scale item and not at the ends. By default, scale ranges are displayed at the ends of the scale item.

Horizontal The item is a horizontal scale item.

Vertical The item is a vertical scale item.

5-16 MicroStation BASIC Guide

Page 141: 48784209 Microstation Basic

Group Box Editor dialog box

Ad

din

g D

ialo

g B

oxes

to

Mac

ros

5

600macro.bk : 605_BLDR.FRA Page 17 Friday, October 15, 1999 1:27 PM

Group Box Editor dialog boxUsed to change the attributes of a group box item. The group box contains only the label text item.

Radio Button Editor dialog boxUsed to change the attributes of a radio button item.

Mask

The mask text item with value determines the currently selected subitem. If the entire variable specified by accessStr is being compared to value, set this text item to 0xFFFFFFFF.

Value

The text item with mask determines the currently selected radio button subitem. Each subitem is a member in a list of radio buttons. Only one subitem can be selected at a time. Mask indicates the relevant bits of the variable specified by accessStr. For example, for a mask value of 0xC (1100 binary), bits 2 and 3 of accessStr are compared to value.

List ID

Associates radio buttons with other radio buttons in a list that groups all radio buttons together. The List ID text item specifies the ID of the list to which this radio button belongs.

MicroStation BASIC Guide 5-17

Page 142: 48784209 Microstation Basic

Radio Button Editor dialog box

600macro.bk : 605_BLDR.FRA Page 18 Friday, October 15, 1999 1:27 PM

Alignment menuThe Alignment menu contains selections that will help you create dialog boxes with aligned items for consistency. Many of the selections, when used together, can save time otherwise spent manually aligning dialog items.

Align [Left|Right|Top|Bottom]

Aligns the selected items by left, right, top or bottom edges. Left and right alignment does not affect vertical position, also top and bottom alignment does not affect horizontal position. The position to which the items are aligned is determined by the first item selected.

Center on Horizontal, Center on Vertical

Aligns the selected items about a common horizontal or vertical axis. Horizontal centering does not affect vertical position and vertical centering does not affect horizontal position.

Spread Horizontally, Spread Vertically

Spreads the selected item(s) an equal distance apart and from the edges of the dialog box. Horizontal spreading does not affect vertical position and vertical spreading does not affect horizontal position.

Space Vertically

Positions the selected items so they are evenly spaced vertically. Set Vertical spacing by choosing Preferences from the Options menu. Horizontal position is not affected.

To Choose from the Alignment menu

Align two or more items by left, right, top, or bottom edges

Align> Left|Right|Top|Bottom

Horizontally center selected items Center on Horizontal

Vertically center selected items Center on Vertical

Spread selected item(s) equally across width of the dialog box

Spread Horizontally

Spread selected item(s) equally across height of the dialog box

Spread Vertically

Space selected items adjacent to one another vertically

Space Vertically

Make each selected item the same size as the first item selected

Make Same Size

5-18 MicroStation BASIC Guide

Page 143: 48784209 Microstation Basic

Radio Button Editor dialog box

Ad

din

g D

ialo

g B

oxes

to

Mac

ros

5

600macro.bk : 605_BLDR.FRA Page 19 Friday, October 15, 1999 1:27 PM

Make Same Size

Resizes the selected items to the same size as the first item selected. Vertical and horizontal position are not affected.

Tool boxDialog items are placed using the tools listed. Items are placed with generic names and sizes. Names and other item attributes can be changed using the methods described in “Common item attributes” on page 5-10. Item sizes and positions can be manipulated in the main Builder window.

✓ The default item placement mode is “single shot.” If you single-click on the item placement tool, only one occurrence of the item can be placed before Builder reverts to the Item Selection tool. However, if you double-click on an item placement tool, Builder enters a mode where every click in the dialog places another occurrence of the item. Resetting returns to the Item Selection tool.

To In the tool box, select

Select one or more items to be modified.Item Selection Tool

Add a single-line user-editable text box.Place Text Item

Add a static text label.Place Label Item

Add a toggle button.Place Toggle Button Item

Add a labeled box that groups related items.Place Group Box Item

Add a user-selectable option button.Place Option Button Item

Add a push-button.Place Push Button Item

Add a color-picker item.Place Color Picker Item

Add a level map item.Place Level Map Item

Add a scale item.Place Scale Item

Add a radio button.Place Radio Button

MicroStation BASIC Guide 5-19

Page 144: 48784209 Microstation Basic

Radio Button Editor dialog box

600macro.bk : 605_BLDR.FRA Page 20 Friday, October 15, 1999 1:27 PM

Manipulation of Items

Items can be manipulated with the mouse by clicking and dragging. Move an item by clicking within the rectangular area of the item. Resize an item by clicking on the edge of an item. Appropriate resizing restrictions apply to some items. For example a text item may only be resized horizontally.

Exiting BuilderWhen the user exits Builder, the Save Before Exiting dialog box is displayed. It contains the list of modified dialogs and the Save, Save All, Save To and Save None push-buttons.

Save

Saves the dialog box that is selected in the list box.

Save All

Saves all the modified dialogs.

Save To…

Opens a dialog box which is used to save the dialog box that is selected in the list box to a file.

Save None

Exits Builder without saving any dialog boxes.

Save Before Exitingdialog box

5-20 MicroStation BASIC Guide

Page 145: 48784209 Microstation Basic

600macro.bk : 606_MDE.FRA Page 1 Friday, October 15, 1999 1:27 PM

6 The MDL Alternative

The most sophisticated way to customize MicroStation is to use application software that supplements the core functionality. If your organization requires it, you can also develop your own application software.

In addition to BASIC, MicroStation includes the MicroStation Development Environment (MDE), which includes the MicroStation Development Language (MDL). MDL combines a full set of development tools with direct access to the MicroStation “CAD engine” through built-in functions.

MDL has much to recommend it as a development facility, but it may not be right for you. The rest of this chapter consists of a brief description of MDE and MDL, with guidelines for choosing between MDL and MicroStation BASIC.

MicroStation Development EnvironmentMDE is an environment for developing MDL applications. MDL is the language of choice for the vast majority of new application development.

MDE is included with MicroStation and provides these tools:1

• Compiler, linker and “Make” utility

• Object librarian

• Resource compiler and librarian

• Tools for building graphical user interfaces

• Symbolic debugger that is optimized for use with MicroStation

1. On-line documentation for MDE is included with MicroStation. For information about obtaining printed MDE documentation, see the on-line documentation for MDE.

MicroStation BASIC Guide 6-1

Page 146: 48784209 Microstation Basic

MicroStation Development Environment

600macro.bk : 606_MDE.FRA Page 2 Friday, October 15, 1999 1:27 PM

MicroStation Development LanguageEssentially, MDL is the C programming language executed by MicroStation. MDL applications are run from inside MicroStation and appear to be part of MicroStation itself. In fact, much of MicroStation is implemented as MDL applications.

Advantages of MDL applications are as follows:

• They directly access MicroStation’s “CAD engine” through built-in functions.

• They have excellent performance.

• C is a well-known language.

• They are easy to debug with the supplied tools.

• They can be written so that they run without modification on all platforms on which MicroStation runs. Only a recompilation of the application is necessary.

Disadvantages of MDL applications are as follows:

• They cannot be ported to IGDS without extensive recoding.

• Knowledge of programming is a necessity.

MDL built-in functionsThe real power of MDL is in its built-in functions. An MDL application can call built-in functions to:

• Interface with the user.

• Create and manipulate graphic elements.

• Synchronize with MicroStation and other applications.

To give you a better idea of how completely MDL applications can access MicroStation’s “CAD engine” through built-in functions, here are some of the most important built-in function categories:

• Cells • Input handling

• Current transformation • Mathematical

• Database • Output

• Dimensioning • Parsing

• Element creation • Reference files

• Element descriptor • State control

• Element extraction • User interface

6-2 MicroStation BASIC Guide

Page 147: 48784209 Microstation Basic

MicroStation Development Environment

The

MD

L A

ltern

ativ

e 6

600macro.bk : 606_MDE.FRA Page 3 Friday, October 15, 1999 1:27 PM

When to use MDL instead of BASIC• the application must communicate directly with an executable

external to MicroStation through a messaging interface.

• the application requires non-modal dialog boxes.

• the application requires more control over its user interface than is supported in BASIC. MDL dialog box and dialog item hook functions would be used in this case.

• the application must call functions within a dynamic link module.

• the application must create new elements and use dynamics. Note that there are no create element functions in MicroStation BASIC.

• Element location and manipulation • View control

• External program communication

MicroStation BASIC Guide 6-3

Page 148: 48784209 Microstation Basic

MicroStation Development Environment

600macro.bk : 606_MDE.FRA Page 4 Friday, October 15, 1999 1:27 PM

6-4 MicroStation BASIC Guide

Page 149: 48784209 Microstation Basic

600macro.bk : 606P_PT2 Page 5 Friday, October 15, 1999 1:27 PM

Part II: Macro Language Reference

Page 150: 48784209 Microstation Basic

600macro.bk : 606P_PT2 Page 6 Friday, October 15, 1999 1:27 PM

Page 151: 48784209 Microstation Basic

600macro.bk : 607_A_Z.FRA Page 1 Friday, October 15, 1999 1:27 PM

7 Standard BASIC Reference

Elements belonging to the standard BASIC language are referred to as keywords. This chapter describes the BASIC keywords. To find a keyword:

• By function, see “BASIC Command Overview” on page 7-1

• In alphabetical order, see “A to Z Reference” on page 7-11

BASIC Command OverviewThe BASIC commands are listed in the following function groups:

• Operators

• Constants and special keywords

• Math and numerical operators

• Array handling

• System

• Miscellaneous

• Program control

• Variable control

• Character and string manipulation

• File handling

• Date and time

• Business calculations

• Dynamic Data Exchange (DDE), Windows platforms only

Operators

Keyword Used To

& Concatenate two strings

* Multiply two values

+ Add two numeric values or concatenate two strings.

- Subtract one value from another.

/ Divide one value by another.

MicroStation BASIC Guide 7-1

Page 152: 48784209 Microstation Basic

BASIC Command Overview

600macro.bk : 607_A_Z.FRA Page 2 Friday, October 15, 1999 1:27 PM

Constants and special keywords

Math and numerical operators

< Determine if one value or string is less than another.

<= Determine if one value or string is less than or equal to another.

<> Determine if one value or string is not equal to another.

= Determine if one value or string is equal to another.

> Determine if one value or string is greater than another.

>= Determine if one value or string is greater than or equal to another.

\ Perform integer division on two values.

^ Raise a value to a power.

And Perform a logical or bitwise AND.

Eqv Perform a logical or bitwise equivalence.

Imp Perform a logical or bitwise implication.

Is Determine if two object variables refer to the same object.

Like Compare a string with a pattern.

Mod Calculate a remainder.

Not Reverse the logical value or perform a bitwise NOT.

Or Perform a logical or bitwise OR.

Xor Perform a logical or bitwise exclusive OR.

Keyword Used To

' Denote a comment (makes the interpreter skip the rest of the line.)

_ Continue a line.

False (constant) Represent the value of zero or an untrue situation.

PI (constant) Represent the value of pi (π), 3.14159…

REM (statement) Make the interpreter skip the entire line.

True (constant) Represent the value of one or a valid situation.

Keyword Used to

Abs (function) Calculate the absolute value of a number.

Atn (function) Calculate the arctangent of a value.

CDbl (function) Calculate the double-precision equivalent of an expression.

Keyword Used To

7-2 MicroStation BASIC Guide

Page 153: 48784209 Microstation Basic

BASIC Command Overview

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 3 Friday, October 15, 1999 1:27 PM

Array handling

CInt (function) Convert an expression to an integer.

CLng (function) Calculate the long version of a value.

Cos (function) Calculate the cosine of an angle.

CSng (function) Calculate the single-precision version of a value.

Exp (function) Raise e to the power of a value.

Fix (function) Calculate the integer portion of a value.

Int (function) Calculate the integer portion of a value. Int also truncates numbers in a negative direction.

Log (function) Calculate the natural logarithm of a value.

Random (function) Generate a random number within the range of two values.

Randomize (statement)

Initialize the random number generator with a new seed.

Rnd (function) Generate a random number between 0 to 1.

Sgn (function) Determine if a number is less than, equal to, or greater than zero.

Sin (function) Calculate the sine of an angle.

Sqr (function) Calculate the square root of a value.

Tan (function) Calculate the tangent of an angle.

Keyword Used to

ArrayDims (function)

Return the number of dimensions in an array.

ArraySort (statement)

Sort a single-dimensional array.

Erase (statement) Eliminate the members of an array.

LBound (function) Determine the lower bound for a dimension of an array.

Option Base (statement)

Set the default lower bound for all array declarations.

ReDim (statement) Redimension an array, specifying new upper & lower bounds for each dimension.

UBound (function) Determine the upper bound for a dimension of an array.

Keyword Used to

MicroStation BASIC Guide 7-3

Page 154: 48784209 Microstation Basic

BASIC Command Overview

600macro.bk : 607_A_Z.FRA Page 4 Friday, October 15, 1999 1:27 PM

System

Miscellaneous

Program control

Keyword Used to

Basic.Capability% (method) Determine the capabilities of the host machine.

Basic.Eoln$ (property) Determine the EOL character sequence of the host machine.

Basic.FreeMemory (property) Determine available memory in BASIC’s data space.

Basic.OS (property) Determine the host machine operating environment.

Basic.PathSeparator$ (property) Determine the file system path separator used by the host machine.

Err (function) Obtain the value of the run-time error.

Err (statement) Set the value of the current run-time error (for use with the Error statement.)

Error (statement) Induce a particular run-time error.

Error$ (function) Obtain the text corresponding to a run-time error.

Keyword Used to

Beep (statement) Cause the system to beep once.

Erl (function) Return 0 (for compatibility with other versions of BASIC).

Print (statement) Print text to an output device.

Sleep (statement) Pause for a specified length of time.

Spc (function) Print a specified number of spaces to an output device.

Tab (function) Print the number of spaces necessary to reach a specified column.

Keyword Used to

Call (statement) Transfer program control to a subroutine.

Declare (statement) Create a prototype for a routine that occurs later in the source module.

Do...Loop (statement) Repeat a block of statements while or until a condition is true.

7-4 MicroStation BASIC Guide

Page 155: 48784209 Microstation Basic

BASIC Command Overview

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 5 Friday, October 15, 1999 1:27 PM

Variable control

End (statement) Terminate execution of the current macro.

Exit Do (statement) Terminate a Do…Loop statement.

Exit For (statement) Terminate a For…Next statement.

Exit Function (statement)

Terminate execution of a function.

Exit Sub (statement) Terminate execution of a subroutine.

For...Next (statement) Repeat a block of statements a specific number of times.

Function...End Function (statement)

Define a user function.

GoSub (statement) Transfer program control to a specific point with the intent to return to the statement following.

Goto (statement) Unconditionally transfer program control to a specific point.

If...Then...Else (statement)

Conditionally execute a block of statements.

Main (statement) Define the subroutine that initially receives control when macro execution commences.

On Error (statement) Define the action taken when a run-time error occurs.

Resume (statement) End the current error handler and continue execution.

Return (statement) Transfer program control to the statement following the most recent GoSub.

Select...Case (statement)

Execute a block of statements based on the value of an expression.

Stop (statement) Suspend execution of the macro and break into the debugger.

Sub...End Sub (statement)

Define a user subroutine.

While...Wend (statement) Repeat a block of statements while a condition is true.

Keyword Used to

Command$ (function) Obtain a string containing the arguments passed to the macro from the command line when the macro was started.

Const (statement) Declare a constant.

DEF… (statement) Establish default variable types.

Dim (statement) Declare a list of local variables and their corresponding types and sizes.

Environ$ (function) Obtain the value of an environment variable.

Global (statement) Declare global or public variables.

Keyword Used to

MicroStation BASIC Guide 7-5

Page 156: 48784209 Microstation Basic

BASIC Command Overview

600macro.bk : 607_A_Z.FRA Page 6 Friday, October 15, 1999 1:27 PM

Character and string manipulation

Let (statement) Assign the result of an expression to a variable.

Private (statement) Declare private variables.

Public (statement) Declare public or global variables.

Set (statement) Assign a value to an object variable.

Type (statement) Define a structure that can be subsequently used by the Dim statement to declare a variable of that type.

Keyword Used to

Asc (function) Obtain the numeric code for a character.

Chr$ (function) Obtain the character for a numeric code.

CStr (function) Convert an expression into a string without leaving white space.

Format$ (function) Format a string.

Hex$ (function) Convert a numeric value into a hexadecimal string.

InStr (function) Obtain the position of a string within another string.

Item$ (function) Obtain items from within a formatted list.

ItemCount (function) Determine how many items are in a formatted list.

LCase$ (function) Convert a string to lower case.

Left$ (function) Obtain a specified number of characters from the left end of a string.

Len (function) Determine the length of a string or the number of bytes in a nonstring variable.

Line$ (function) Obtain one or more lines from a text buffer.

LineCount (function) Determine the number of lines in a text buffer.

LSet (statement) Copy a string padding with spaces at the end or copy a structure.

LTrim$ (function) Remove leading spaces from a string.

Mid$ (function) Obtain a substring from a string.

Mid$ (statement) Replace a substring of a string.

Null (function) A string that contains no characters and requires no storage.

Oct$ (function) Convert a numeric value into an octal string.

Option Compare (statement)

Establish whether string comparisons are to be case sensitive or not.

Right$ (function) Obtain a specified number of characters from the right end of a string.

RSet (statement) Copy a string padding with spaces at the beginning.

Keyword Used to

7-6 MicroStation BASIC Guide

Page 157: 48784209 Microstation Basic

BASIC Command Overview

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 7 Friday, October 15, 1999 1:27 PM

File handling

RTrim$ (function) Remove trailing spaces from a string.

Space$ (function) Create a string containing a specified number of spaces.

Str$ (function) Convert an expression into a string.

StrComp (function) Compare two strings.

String$ (function) Create a string containing a specified number of a specific character.

Trim$ (function) Remove both leading and trailing spaces from a string.

UCase$ (function) Convert a string to upper case.

Val (function) Convert a string into a number.

Word$ (function) Obtain one or more complete words from a string.

WordCount (function) Count the number of words in a string.

Keyword Used to

Close (statement) Close opened files.

Dir$ (function) Obtain a list of the files in a directory.

ebArchive (constant) Archived file attribute.

ebDirectory (constant) Directory attribute.

ebHidden (constant) Hidden file attribute.

ebNone (constant) Select files with no attributes.

ebNormal (constant) Select Normal files — archive, volume, read only, or no attribute.

ebReadOnly (constant) Read only file attribute.

ebSystem (constant) System file attribute.

ebVolume (constant) Volume attribute.

Eof (function) Determine if the end of a file has been reached.

FileAttr (function) Obtain the file mode or file handle.

FileCopy (statement) Copy a file.

FileDateTime (function)

Obtain a file’s date and time.

FileDirs (statement) Fill an array with directory names from disk.

FileExists (function) Determine if a file exists.

FileLen (function) Determine the length of a file in bytes.

FileList (statement) Fill an array with filenames from disk.

FileParse$ (function) Extract a portion of a filename from a filename string.

Keyword Used to

MicroStation BASIC Guide 7-7

Page 158: 48784209 Microstation Basic

BASIC Command Overview

600macro.bk : 607_A_Z.FRA Page 8 Friday, October 15, 1999 1:27 PM

Date and time

FreeFile (function) Obtain the next available file number for use with the Open command.

Get (statement) Retrieve data from a random or binary file.

GetAttr (function) Obtain a file’s attributes.

Input # (statement) Retrieve formatted text from a file.

Input$ (function) Retrieve text from a sequential file.

Kill (statement) Delete file(s).

Line Input # (statement)

Retrieve an entire line of text from a file.

Loc (function) Determine the position of a file’s file pointer.

Lock (statement) Prevent a section of a file from being accessed by other processes.

Lof (function) Determine the length of a file.

MkDir (statement) Create a new directory on the disk.

Name (statement) Rename a file.

Open (function) Open a file for read and/or write operations.

Print# (statement) Write text to a sequential file.

Put (statement) Write data to a random or binary file.

Reset (statement) Close all open files.

RmDir (statement) Delete a directory.

Seek (function) Obtain the position of the file pointer.

Seek (statement) Set the position of the file pointer.

SetAttr (statement) Change a file’s attributes.

UnLock (statement) Restore access by other processes to a locked portion of a file.

Width# (statement) Specify the line width for a sequential file.

Write # (statement) Write formatted text to a sequential file.

Keyword Used to

Date$ (function) Obtain the current system date as a 10-character string.

Date$ (statement) Set the system date.

DateAdd (function) Add a time interval to a date.

DateDiff (function) Determines the number of time intervals between two dates.

DatePart (function) Obtain a portion of a date/time expression.

DateSerial (function) Convert a specific date to “days since December 30, 1899” format.

Keyword Used to

7-8 MicroStation BASIC Guide

Page 159: 48784209 Microstation Basic

BASIC Command Overview

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 9 Friday, October 15, 1999 1:27 PM

Business calculations

DateValue (function) Convert a date from a string to a double-precision value.

Day (function) Obtain the day of the month from a date value.

Hour (function) Obtain the hour of the day (24 hour format) from a time value.

Minute (function) Obtain the minute of the hour from a time value.

Month (function) Obtain the month of the year from a date value.

Now (function) Obtain the current date and time in “days since December 30, 1899” format.

Second (function) Obtain the second of the minute from a time value.

Time$ (function) Obtain the current time as an 8-character string.

Time$ (statement) Set the system time.

Timer (function) Obtain the number of seconds since midnight.

TimeSerial (function) Convert a specific time to “days since December 30, 1899” format.

TimeValue (function) Convert a time from a string to a value.

Weekday (function) Obtain the day of the week, from a date value.

Year (function) Obtain the year from a date value.

Keyword Used to

DDB (function) Calculate the depreciation of an asset using the double-declining balance method.

Fv (function) Calculate the future value of an annuity.

IPmt (function) Calculate the interest payments for an annuity.

IRR (function) Calculate the internal rate of return for a series of payments and receipts.

MIRR (function) Calculate the modified internal rate of return for a series of payments and receipts.

NPer (function) Calculate the number of periods of an annuity.

Npv (function) Calculate the net present value of an annuity.

Pmt (function) Calculate the payments for an annuity.

PPmt (function) Calculate the principal payment for a given period of an annuity.

Pv (function) Calculate the present value of an annuity.

Rate (function) Calculate the rate of interest for each period of an annuity.

Sln (function) Calculate the straight-line depreciation of an asset.

SYD (function) Calculate the sum of year’s digits depreciation of an asset.

Keyword Used to

MicroStation BASIC Guide 7-9

Page 160: 48784209 Microstation Basic

BASIC Command Overview

600macro.bk : 607_A_Z.FRA Page 10 Friday, October 15, 1999 1:27 PM

Dynamic Data Exchange (DDE), Windows platforms only

Keyword Used to

DDEExecute Send an execute message to another application.

DDEInitiate Initialize a DDE link to another application.

DDEPoke Set the value of a data item in another application.

DDERequest Get a string value associated with a data item.

DDESend Initiate a conversation with a DDE server application.

DDETerminate Close a DDE channel.

DDETerminateAll Close all DDE channels.

DDETimeOut Set the timeout for DDE command completion.

7-10 MicroStation BASIC Guide

Page 161: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 11 Friday, October 15, 1999 1:27 PM

A to Z ReferenceThis section contains a complete, alphabetical reference to all commands in the standard BASIC language. When syntax is described, the following notations are used:

&string_expression1 & string_expression2

Descr. Returns the concatenation of string_expression1 and string_expression2.

Adds string_expression2 to the end of string_expression1 and returns a string with a length that is the sum of the lengths of string_expression1 and string_expression2. This operator can be used interchangeably with the plus (+) operator when used with string operands and is provided for clarity of code.

Example Sub Main()'Assign a concatenated string to variable s$ and a string to s2$,'then concatenate the two variables and display in a dialog box.s$ = "This string" & " is concatenated"s2$ = " with the & operator"MbeMessageBox s$ & s2$

End Sub

Notation Description

keyword Elements belonging to the standard BASIC language, referred to in this manual as keywords, appear in the typeface shown to the left.

variable Items that are to be replaced with information that you supply appear in italics. The type of replacement is indicated in the following description.

text$ The presence of a type-declaration character following a parameter signifies that the parameter must be a variable of that type or an expression that evaluates to that type.

rnd# A function’s return type is indicated by a type-declaration character. This is strictly informative and does not mean that the function must be accompanied by that type-declaration character. Functions that return strings are an exception to this rule. In their case, the $ character is required.

[parameter%] Square brackets indicate that the enclosed items are optional.

{Input | Binary} Braces indicate that you must choose one of the enclosed items, which are separated by a vertical bar.

start% To end% Words that must appear as part of a statement’s syntax are shown without type-declaration characters (for example, To).

MicroStation BASIC Guide 7-11

Page 162: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 12 Friday, October 15, 1999 1:27 PM

''text

Descr. Causes the compiler to skip all characters between this character and the end of the current line. This is very useful for commenting your code to make it more readable.

Example Const crlf = Chr$(13) + Chr$(10)Sub Main()

'This whole line is treated as a comment.i$ = "Strings" 'This is a valid assignment with a comment.This line will cause an error (the apostrophe is missing).

End Sub

*expression1 * expression2

Descr. Returns the product of expression1 and expression2. The operands can be expressions of any numeric data type.

Example Sub Main()'This example assigns values to two variables and their product to'a third variable, then displays the product of S * T.S# = 123.55T# = 2.55U# = S * TMbeMessageBox Str$(S * T)

End Sub

+expression1 + expression2

Descr. If expression1 and expression2 are both numeric, then this operator returns the sum of expression1 and expression2. If both expressions are strings, then this operator returns a new string representing the concatenation of expression1 and expression2. Mixed string and numeric operands are invalid. For string operands, the plus (+) is interchangeable with the & operator. (See & [operator].)

Example Sub Main()'This example assigns string and numeric variable values and'then uses the + operator to concatenate the strings and form the'sums of numeric variables.i$ = "Strings" + " can be concatenated"j% = 120 + 5 'addition of numeric literalsk# = j% + 2.7 'addition of numeric variableMbeMessageBox i$ + Str$(j%) + Str$(k#)

End Sub

7-12 MicroStation BASIC Guide

Page 163: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 13 Friday, October 15, 1999 1:27 PM

-expression1 - expression2

Descr. Returns the difference between expression1 and expression2.

Example Sub Main()'This example assigns values to two numeric variables and their'difference to a third variable, then displays the result.I% = 100J# = 22.55K# = I - JMbeMessageBox "The difference is: " + Str$(K#)

End Sub

/expression1 / expression2

Descr. Returns the quotient of expression1 and expression2.

Example Sub Main()'This example assigns values to two variables and their quotient to a'third variable, then displays the result.I% = 100J# = 22.55K# = I / JMbeMessageBox "The quotient of I/J is: " + Str$(K#)

End Sub

<expression1 < expression2

Descr. Returns TRUE if expression1 is less than expression2; otherwise, returns FALSE. If both expressions are strings, the < operator performs a case-sensitive comparison between the two string expressions, returning TRUE if expression1 is less than expression2.

Lowercase characters in a string sort higher than uppercase characters, so a comparison of ‘a’ and ‘A’ would indicate that ‘A’ is less than ‘a’.

Example Sub Main()'Test two literals and display the result.If 5 < 2 Then

MbeMessageBox "Five is less than Two"Else

MbeMessageBox "Five is not less than Two"End If'Test two strings and display the result.

MicroStation BASIC Guide 7-13

Page 164: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 14 Friday, October 15, 1999 1:27 PM

If "This string expression" < "That string" ThenMbeMessageBox "This is less than That"

ElseMbeMessageBox "That is less than This"

End IfEnd Sub

<=expression1 <= expression2

Descr. Returns TRUE if expression1 is less than or equal to expression2; otherwise, returns FALSE. If both expressions are strings, the <= operator performs a case-sensitive comparison between the two expressions, returning TRUE if expression1 is less than or equal to expression2.

Lowercase characters in a string sort higher than uppercase characters, so a comparison of ‘a’ and ‘A’ would indicate that ‘A’ is less than ‘a’.

Example Sub Main()'Test two literals and display the result.If 5 <= 2 Then

MbeMessageBox "Five is less than or equal to Two"Else

MbeMessageBox "Five is not less than or equal to Two"End If'Test two strings and display the result.If "This string" <= "That string" Then

MbeMessageBox "This is less than or equal to That"Else

MbeMessageBox "That is less than or equal to This"End If

End Sub

<>expression1 <> expression2

Descr. Returns TRUE if expression1 is not equal to expression2; otherwise returns FALSE. If the two expressions are strings, the <> operator performs a case-sensitive comparison between the two expressions, returning TRUE if expression1 is not equal to expression2.

Lowercase characters in a string sort higher than uppercase characters, so a comparison of ‘a’ and ‘A’ would indicate that ‘A’ is less than ‘a’.

7-14 MicroStation BASIC Guide

Page 165: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 15 Friday, October 15, 1999 1:27 PM

Example Sub Main()'Test two literals and display the result.If 5 <> 2 Then

MbeMessageBox "Five is not equal to Two"Else

MbeMessageBox "Five is equal to Two"End If'Test two strings and display the result.If "This string" <> "That string" Then

MbeMessageBox "This is not equal to That"Else

MbeMessageBox "The strings are equal"End If

End Sub

=expression1 = expression2

Descr. Returns TRUE if expression1 is equal to expression2; otherwise returns FALSE. If the two expressions are strings, the = operator performs a case-sensitive comparison between the two expressions, returning TRUE if expression1 is equal to expression2. Strings of different lengths are never equal to one another.

This operator is also used for assignment of values to variables. It operates as a logical equivalency operator only in a logical comparison context.

Example Sub Main()'Assignment of values: the variable S is assigned a value of 100.22.S# = 100.22'Logical equivalence: the value of S is compared to 150.99.If S = 150.99 Then

MbeMessageBox "The value of S is 150.99"Else

MbeMessageBox "The value of S is not 150.99"End If

End Sub

>expression1 > expression2

MicroStation BASIC Guide 7-15

Page 166: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 16 Friday, October 15, 1999 1:27 PM

Descr. Returns TRUE if expression1 is greater than expression2; otherwise returns FALSE. If the two expressions are strings, the > operator performs a case-sensitive comparison between the two expressions, returning TRUE if expression1 is greater than expression2.

Example Sub Main()'Test two literals and display the result.If 5 > 2 Then

MbeMessageBox "Five is greater than Two"Else

MbeMessageBox "Five is less than or equal to Two"End If'Test two strings and display the result.If "This string" > "That string" Then

MbeMessageBox "This is greater than That"Else

MbeMessageBox "That is less than or equal to This"End If

End Sub

>=expression1 >= expression2

Descr. Returns TRUE if expression1 is greater than or equal to expression2; otherwise returns FALSE. If the two expressions are strings, the >= operator performs a case-sensitive comparison between the two expressions, returning TRUE if expression1 is greater than or equal to expression2.

Example Sub Main()'Test two literals and display the result.If 5 >= 2 Then

MbeMessageBox "Five is greater than or equal to Two"Else

MbeMessageBox "Five is less than Two"End If'Test two strings and display the result.If "This string" >= "That string" Then

MbeMessageBox "This is greater than or equal to That"Else

MbeMessageBox "That is less than This"End If

End Sub

\expression1 \ expression2

7-16 MicroStation BASIC Guide

Page 167: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 17 Friday, October 15, 1999 1:27 PM

Descr. Returns the integer division of expression1 and expression2.

This operator operates by rounding expression1 and expression2 prior to division. The integer part of the result is then returned as a nonfractional number.

Example Sub Main()'Assign the quotient of two literals to a variable and display the'result.s% = 100.99 \ 2.6MbeMessageBox "Integer divide of 100.99 \ 2.6 is: " & Str$(s)

End Sub

^expression1 ^ expression2

Descr. Returns expression1 raised to the power specified in expression2. Fractional and negative exponents are allowed.

The following are special cases:

It is important to note that raising a number to a negative exponent produces a fractional result (either a Double or a Single). In the statement a% = b%^c%, the variables b and c are first promoted to Doubles, then the power operation is applied, and finally the result converted to an Integer (rounding, if necessary) and stored in a.

Example Sub Main()s# = 2 ^ 5 'Returns 2 to the 5th power.r# = 16 ^ .5 'Returns the square root of 16.MbeMessageBox "Two to the 5th power is: " & Str$(s)

End Sub

_s$ = "This is a very long line that I want to split " + _ "onto two lines"

Special Case Value

n^0 1

0^-n undefined

0^+n 0

1^n 1

MicroStation BASIC Guide 7-17

Page 168: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 18 Friday, October 15, 1999 1:27 PM

Descr. The ‘_’ character is the line-continuation character.

This character allows you to split a single BASIC statement onto more than one line.

The line-continuation character cannot be used within strings and must be preceded by white space (either a space or a tab).

Example Const crlf = Chr$(13) + Chr$(10)Sub Main()

'The line-continuation operator is useful when concatenating long'strings.Msg$ = "This line is a line of text that" + crlf + "extends beyond " _

+ "borders of the editor" + crlf + "so it is split into " _+ "multiple lines"

'It is also useful for separating and continuing long calculation'lines:b# = .124a# = .223S# = ( (((Sin(b) ^ 2) + (Cos(a) ^ 2)) ^ .5) / _

(((Sin(a) ^ 2) + (Cos(b) ^ 2)) ^ .5) ) * 2.00MbeMessageBox Msg + crlf + "The value of S is: " + Str$(S)

End Sub

AbsAbs%(number%)

Abs&(number&)

Abs!(number!)

Abs#(number#)

Descr. Returns the absolute value of a given number.

When Integer variables are assigned the absolute value of real numbers, the real number is rounded first, and the absolute value of the rounded number is returned.

Example Sub Main()'Assign absolute values to variables of 4 types and display the result.S1% = Abs(- 10.55)S2& = Abs(- 10.55)S3! = Abs(- 10.55)S4# = Abs(- 10.55)MbeMessageBox Str$(S1) + Str$(S2) + Str$(S3) + Str$(S4)

End Sub

7-18 MicroStation BASIC Guide

Page 169: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 19 Friday, October 15, 1999 1:27 PM

Andexpression1 And expression2

Descr. Returns TRUE if both expression1 and expression2 are TRUE. If either expression is FALSE, then the And operator returns FALSE.

If the two expressions are numeric, then the result is the bitwise And of the two arguments.

If either of the two operands is a floating-point number, then the two operands are first converted to Longs, then a bitwise And is performed.

Example Sub Main()N1 = 1001N2 = 1000B1 = TrueB2 = False'Perform a numeric bitwise And operation and store the result in N3.N3 = N1 And N2'Perform a logical And comparing B1 and B2 and display the result.If B1 And B2 Then

MbeMessageBox "B1 and B2 is True; N3 is: " + Str$(N3)Else

MbeMessageBox "B1 and B2 is False; N3 is: " + Str$(N3)End If

End Sub

ArrayDimsArrayDims%(arrayvariable)

Descr. Returns the number of dimensions of a given array.

This function can be used to determine whether a given array contains any elements if the array is initially dimensioned with null dimensions and then redimensioned by another function, such as the FileList function, as shown in the following example.

Example Sub Main()'Allocate an empty (null-dimensioned)'array; fill the array with a list of'filenames, which resizes the array; then test the array dimension and'display an appropriate message.Dim f$()FileList f$,"C:\*.BAT"If ArrayDims(f$) = 0 Then

MicroStation BASIC Guide 7-19

Page 170: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 20 Friday, October 15, 1999 1:27 PM

MbeMessageBox "The array is empty"Else

MbeMessageBox "The array size is: " + Str$(ArrayDims(F$))End If

End Sub

ArraySortArraySort s$()

ArraySort a%()

ArraySort a&()

ArraySort a!()

ArraySort a#()

Descr. Sorts a single-dimensioned array. If a string array is specified, then the routine sorts alphabetically in ascending order (using case-sensitive string comparisons). If a numeric array is specified, the ArraySort statement sorts smaller numbers to the lowest array index locations.

A run-time error is generated if you specify an array with more than one dimension.

Example Sub Main()'Dimension an array and fill it with filenames using FileList,'then sort the array and display it.Dim F$()FileList f$,"C:\*.*"ArraySort f$result = MbeSelectBox% ("Choose a file", f$)

End Sub

AscAsc%(text$)

Descr. Returns the numeric code for the first character of the given string.

The return value is an Integer between 0 and 255.

Example Sub Main()s$ = "ABC"Dim a%(3)'Fill the array with the ASCII values of the string s components and'display the result.For i = 1 To 3

a%(i) = Asc(Mid$(s$,i,1))

7-20 MicroStation BASIC Guide

Page 171: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 21 Friday, October 15, 1999 1:27 PM

Next iMbeMessageBox Str$(a%(1)) + Str$(a%(2)) + Str$(a%(3))

End Sub

Atnatn#(number#)

Descr. Returns the angle (in radians) whose tangent is number.

Pi (3.1415926536) radians = 180 degrees.

One radian = 57.2957795131 degrees.

One degree = .0174532925 radians.

Example Sub Main()'Find the angle whose tangent is 1 (45 degrees) and display the result.a# = Atn(1.00)MbeMessageBox "1.00 is the tangent of " + Str$(a#) +

" radians (45 degrees)"End Sub

Basic.Capability%Basic.Capability%(which%)

Descr. This method returns TRUE if the specified capability exists on the host operating environment; otherwise, this function returns FALSE.

The which parameter specifies which capability to test for. It can be any of the following values:

Example Sub Main()'Test to see whether your current environment supports disk drives and'hidden file attributes and display the result.Msg$ = "This OS "If Basic.Capability(1) Then

Value Returns TRUE if the platform supports

1 Disk drives

2 System file attribute (ebSystem)

3 Hidden file attribute (ebHidden)

4 Volume label file attribute (ebVolume)

5 Archive file attribute (ebArchive)

6 Denormalized floating-point math

MicroStation BASIC Guide 7-21

Page 172: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 22 Friday, October 15, 1999 1:27 PM

Msg = Msg + "supports disk drives."else

Msg = Msg + "does not support disk drives."End IfMbeMessageBox Msg

End Sub

Basic.Eoln$Basic.Eoln$

Descr. Returns a string containing the end-of-line character sequence appropriate to the host operating environment.

This string will be either a carriage-return, a carriage-return line-feed, or a line-feed.

Example Sub Main()'This example writes two lines of text in a message box.MbeMessageBox "This is the first line of text " + Basic.Eoln$ + _"The second line"

End Sub

Basic.FreeMemoryBasic.FreeMemory&

Descr. Returns the number of bytes of free memory in BASIC’s data space.

This function returns the size of the largest free block in BASIC’s data space. Before this number is returned, the data space is compacted, consolidating free space into a single contiguous free block.

BASIC's data space contains strings and dynamic arrays.

Example Sub Main()'Display free memory in a dialog box.MbeMessageBox "The free memory space is: " + Str$(Basic.FreeMemory)

End Sub

Basic.OSBasic.OS

7-22 MicroStation BASIC Guide

Page 173: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 23 Friday, October 15, 1999 1:27 PM

Descr. Returns a number indicating the host operating environment.

Example Sub Main()'Determine the OS this version was created for and display the'appropriate message.o% = Basic.OSSelect Case o%

Case 2S$ = "Win32"

Case 12S$ = "DOS"

Case ElseS$ = "Neither Win32 nor DOS"

End SelectMbeMessageBox "The current version was created for " + S$

End Sub

Basic.PathSeparator$Basic.PathSeparator$

Descr. Returns a string containing the path separator appropriate for the host operating environment.

The returned string will be a slash ‘/’, a backslash ‘\’, or a colon ‘:’.

Example Sub Main()MbeMessageBox "The path separator for this environment is: " + _

Basic.PathSeparator$End Sub

Value Constant Platform

2 ebWin32 Microsoft Win32 (’95, NT, Win32s)

3 ebSolaris Sun Solaris 2.x

4 ebSunOS SunOS

5 ebHPUX HP/UX

7 ebIrix Silicon Graphics IRIX

8 ebAIX IBM AIX

10 ebMacintosh Apple Macintosh

12 ebDOS32 MS-DOS

13 ebClix Intergraph Clix

MicroStation BASIC Guide 7-23

Page 174: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 24 Friday, October 15, 1999 1:27 PM

BeepBeep

Descr. Makes a single system beep.

Example Sub Main()'Beep five times and display a reminder message.For i = 1 To 5

BeepSleep(500)

Next iMbeMessageBox "Do you have an upcoming appointment?"

End Sub

CallCall subroutine_name [(arguments)]

Descr. Transfers control to the given subroutine, optionally passing the specified arguments.

Using this statement is equivalent to:

subroutine_name [arguments]

Use of the Call statement is optional. The subroutine to which control is transferred by Call must be declared outside of the Main procedure, as shown in the following example.

Example Sub Example_Call (S$)'This subroutine is declared externally to Main and displays the text'passed in the parameter S$.MbeMessageBox "Example CALL: " + S$

End SubSub Main()

'Assign a string variable to display, then call subroutine'Example_Call, passing parameter S$ to be displayed in a'message box within the subroutine.S$ = "Display this text"Example_Call "Display this text"Call Example_Call ("Second form of Call statement")

End Sub

CDblCDbl#(number#)

7-24 MicroStation BASIC Guide

Page 175: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 25 Friday, October 15, 1999 1:27 PM

Descr. Returns the double-precision equivalent of the passed numeric expression (number).

This function has the same effect as assigning the numeric expression number to a double-precision variable.

Example Sub Main()i% = 100j! = 123.44MbeMessageBox Str$(CDbl(i * j))MbeMessageBox Str$(CDbl(i) * j)MbeMessageBox Str$(CDbl(i) * CDbl(j))

End Sub

Chr$Chr$(Code%)

Descr. Returns the character whose value is Code.

Code must be an integer between 0 and 255. In addition, Code cannot be an expression.

The Chr$ function can be used within constant declarations, as in the following example:

Example Const crlf$ = Chr$(13) + Chr$(10)Sub Main()

'Concatenate carriage return (13) and line feed (10) to clf$,'then display a multiple-line message using clf$ to separate lines.CLF$ = Chr$(13) + Chr$(10)MbeMessageBox ("First line" + CLF + "Second line")'Fill an array with the ASCII characters for ABC and display their'corresponding characters.Dim a%(3)For i = 1 To 3

a%(i) = (64 + i)Next iMbeMessageBox Chr$(a(1)) + Chr$(a(2)) + Chr$(a(3))

End Sub

CIntCInt%(number#)

MicroStation BASIC Guide 7-25

Page 176: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 26 Friday, October 15, 1999 1:27 PM

Descr. Returns the integer portion of the given expression.

The passed numeric expression must be within the following range:

-32768 <= number <= 32767

A run-time error results if the passed expression is not within the above range.

CInt has the same effect as assigning a numeric expression to a variable of type Integer. CInt differs from the Fix and Int functions in that CInt rounds instead of truncating.

Example Sub Main()'This example demonstrates the various results of integer manipulation'with CInt.'(1) Assign i to 100.55 and display its integer representation (101).i# = 100.55MbeMessageBox "CInt I = " + Str$(CInt(I))'(2) Set J to 100.22 and display the CInt representation (100).j# = 100.22MbeMessageBox "CInt J = " + Str$(CInt(J))'(3) Assign K (integer) to the CInt sum of I and J and display K (201).k% = CInt(I + J)MbeMessageBox("The integer sum of 100.55 and 100.22 is: " + Str$(k))'(4) Reassign i to 50.35 and recalculate K, then display'(note rounding).i# = 50.35k% = CInt(I + J)MbeMessageBox("The integer sum of 50.35 and 100.22 is: " + Str$(k))

End Sub

CLngCLng&(number#)

Descr. Returns a Long representing the result of the given numeric expression.

The passed numeric expression must be within the following range:

-2147483648 <= number <= 2147483647

A run-time error results if the passed expression is not within the above range.

CLng has the same effect as assigning a numeric expression to a Long variable.

7-26 MicroStation BASIC Guide

Page 177: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 27 Friday, October 15, 1999 1:27 PM

Example Sub Main()i% = 100j& = 123.666'Display results for various conversions of i and j (note rounding).MbeMessageBox Str$(CLng(i * j)) 'Displays 12367.MbeMessageBox Str$(CLng(i) * j) 'Displays 12366.MbeMessageBox Str$(CLng(i) * CLng(j)) 'Displays 12400.

End Sub

CloseClose [[#] filenumber% [,[#] filenumber%]]

Descr. If no arguments are specified, this statement closes all files. Otherwise, the Close statement closes each specified file.

Example Sub Main()'Open four files and close them in various combinations.Open "Test1" for Input Access Read Lock Read Write as #1 len=128Open "Test2" for Output as #2Open "Test3" for Random as #3Open "Test4" for Binary as #4Close #1 'Closes file 1 only.Close #2, #3 'Closes files 2 and 3.Close 'Closes all remaining files (4).

End Sub

Command$Command$

Descr. Returns a string representing the argument from the command line used to start the macro.

Example Sub Main()'Get the command line and parameters, check to see whether the string' "/s" is present, and display the result.CMD$ = Command$If (InStr(Cmd,"/s")) <> 0 Then

MbeMessageBox "Macro started with /s switch"Else

MbeMessageBox "Macro started without /s switch"End IfMbeMessageBox "Startup line was: " + CMD$

End Sub

MicroStation BASIC Guide 7-27

Page 178: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 28 Friday, October 15, 1999 1:27 PM

Constconst name = expression [,name = expression]...

Descr. Declares a constant for use within the current macro.

name is only valid within the current BASIC macro.

expression must be assembled from literals or other constants. Calls to functions are not allowed except calls to the Chr$ function when used in the declarations part of the code or outside the Sub Main...End Sub.

✍ The constants are declared before the Sub Main declaration.

Example Const CRLF = Chr$(13) + Chr$(10)Const T$ = "This is a constant"Sub Main()

'Display the declared constants in a dialog box (CRLF produces a new'line in the dialog box).MbeMessageBox T + CRLF + "The constants are shown above"

End Sub

CosCos#(angle#)

Descr. Returns the cosine of a given angle.

The angle parameter is given in radians.

Example Sub Main()'Assign the cosine of PI/4 radians (45 degrees) to C# and display its'value.C# = Cos(3.14159 / 4)MbeMessageBox "The cosine of 45 degrees is: " + Str$(C)

End Sub

CSngCSng!(number#)

Descr. Returns a single representing the result of the given numeric expression number.

This function has the same effect as assigning a numeric expression to a single variable.

Example Sub Main()'Assign variables of different types and display their CSng'conversions.

7-28 MicroStation BASIC Guide

Page 179: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 29 Friday, October 15, 1999 1:27 PM

S1# = CSng(150.61010101)S2& = CSng(150.62020202)S3% = CSng(150.63030303)S4! = CSng(150.64040404)MbeMessageBox Str$(S1) + Str$(S2) + Str$(S3) + Str$(S4)

End Sub

CStrCStr(number#)

Descr. Returns a string representing the result of the given expression. The result is returned in floating point ‘E’ notation, if the result is very small or very large. Unlike Str$, the string returned by CStr will not contain a leading space if the expression is positive.

Example Const crlf = Chr$(13) + Chr$(10)Sub Main()

'Assign two variables and display them using CStr conversions.A# = 123.456B# = -123.456MbeMessageBox CStr(A) + crlf + CStr(B)

End Sub

Date$Date$[()]

Date$ = newdate$

Descr. The Date$ function returns the current system date as a 10-character string. The statement form of Date$ sets the system date to the specified date.

The format for the date used by Date$ is MM-DD-YYYY.

Example Const crlf = Chr$(13) + Chr$(10)Sub Main()

' This example saves the current date to Cdate$, then changes‘ the date and displays the result. It then changes the date back' to the saved date and displays the result.Cdate$ = Date$()Date$ = "01/01/94"MbeMessageBox("Saved date is: " + Cdate + crlf + "Changed date is: " + _

Date$())Date$ = CdateMbeMessageBox("Restored date to: " + Cdate)

End Sub

MicroStation BASIC Guide 7-29

Page 180: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 30 Friday, October 15, 1999 1:27 PM

DateAddDateAdd#(interval$, increment&, date1$ | date1#)

Descr. The DateAdd function returns a double-precision number representing the sum of date1 and a specified number (increment) of a specified time interval (interval$).

DateAdd adds a specified number (increment) of time intervals (interval$) to the specified date (date1). The following table describes the parameters to the DateAdd function:

The interval$ parameter specifies what unit of time is to be added to the given date. It can be any of the following:

To add days to a date, you may use either day, day of the year, or weekday, as they are all equivalent ("d", "y", "w").

DateAdd will never return an invalid date/time expression. The following example adds two months to December 31, 1992:

s# = DateAdd("m", 2, "December 31, 1992")

Parameter Description

interval$ a string expression that indicates the time interval used in the addition.

increment a double-precision number that indicates the number of time intervals you wish to add. Positive values result in dates in the future; negative values result in dates in the past.

date1 a double-precision number or a valid date/time. String expression. An example of a valid date/time string would be “January 1, 1993.”

Time Interval

"y" Day of the year

"yyyy" Year

"d" Day

"m" Month

"q" Quarter

"ww" Week

"h" Hour

"n" Minute

"s" Second

"w" Weekday

7-30 MicroStation BASIC Guide

Page 181: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 31 Friday, October 15, 1999 1:27 PM

In this example, s is returned as the double-precision number equal to "February 28, 1993", not "February 31, 1993".

A run-time error is generated if you attempt to subtract a time interval that is larger than the time value of the date.

Example Sub Main()'This example gets today's date using the Date$ function; adds one'year, two months, one week, and two days to it; and then displays the'result in a dialog box.Dim dDate#Dim sDate$sDate$ = Date$NewDate# = DateAdd("yyyy", 3, sDate)NewDate = DateAdd("mm", 2, NewDate)NewDate = DateAdd("ww", 1, NewDate)NewDate = DateAdd("dd", 2, NewDate)s$ = "One year, two months, one week, and two days from now will be: "s$ = s$ + format$(NewDate, "long date")MbeMessageBox s$

End Sub

DateDiffDateDiff&(interval$, date1$ | date1#, date2$ | date2#)

Descr. Returns a double-precision number representing the number of given time intervals between date1 and date2.

The DateDiff function will return the number of days or the number of whole weeks between two dates. The following table describes the parameters:

Parameter Description

interval$ a string expression that indicates the specific time interval you wish to find the difference between.

date1 a double-precision number or a valid date/time string expression. An example of a valid date/time string would be "January 1, 1993".

date2 a double-precision number or a valid date/time string expression. An example of a valid date/time string would be "January 1, 1993".

MicroStation BASIC Guide 7-31

Page 182: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 32 Friday, October 15, 1999 1:27 PM

The following table lists the valid time interval strings and the meanings of each. The Format$ function uses the same expressions.

To find the number of days between two dates, you may use either day or day of the year, as they are both equivalent ("d", "y").

The time interval weekday ("w") will return the number of weekdays occurring between date1 and date2, counting the first occurrence but not the last. However, if the time interval is week ("ww"), the function will return the number of calendar weeks between date1 and date2, counting the number of Sundays. If date1 falls on a Sunday, then that day is counted, but if date2 falls on a Sunday, it is not counted.

DateDiff will return a negative date/time value if date1 occurs later in time than date2.

Example Sub Main()'This example gets today's date and adds 10 days to it. It then'calculates the difference between the two dates in days and weeks'and displays the result.Today$ = Date$TodayR# = DateValue(Date$)

NextWeek# = DateAdd("d", 10, Today)Difdays# = DateDiff("d", Today, NextWeek)Difweek# = DateDiff("ww", Today, NextWeek)S$ = "The difference between " + Str$(Today) + " and " + Str$(NextWeek)S$ = S$ + " is: " + Str$(Difdays) + " days or " + Str$(DifWeek) + _

" weeks"

Time Interval

"y" Day of the year

"yyyy" Year

"d" Day

"m" Month

"q" Quarter

"ww" Week

"h" Hour

"n" Minute

"s" Second

"w" Weekday

7-32 MicroStation BASIC Guide

Page 183: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 33 Friday, October 15, 1999 1:27 PM

MbeMessageBox S$End Sub

DatePartDatePart%(interval$, date1$ | date1#)

Descr. Returns a number representing a specified part of a valid date/time expression.

The DatePart function decomposes the given date and returns a given date/time element. The following table describes the parameters:

The following table lists the valid time interval strings and the meanings of each. The Format$ function uses the same expressions.

The weekday expression starts with Sunday as 1 and ends with Saturday as 7.

Example const crlf = chr$(13) + chr$(10)Sub Main()

'This example displays the parts of the current dateToday$ = Date$Qtr = DatePart("q",Today)Yr = DatePart("yyyy",Today)Mo = DatePart("m",Today)Wk = DatePart("ww",Today)Da = DatePart("d",Today)S$ = "Quarter: " + Str$(Qtr) + crlf

Parameter Description

interval$ a string expression that indicates the specific time interval you wish to identify within the given date.

date1 either a double-precision number or a valid date/time string expression. An example of a valid date/time string would be "January 1, 1993".

Time Interval

"y" Day of the year

"yyyy" Year

"d" Day

"m" Month

"q" Quarter

"ww" Week

MicroStation BASIC Guide 7-33

Page 184: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 34 Friday, October 15, 1999 1:27 PM

S$ = S$ + "Year : " + Str$(Yr) + crlfS$ = S$ + "Month : " + Str$(Mo) + crlfS$ = S$ + "Week : " + Str$(Wk) + crlfS$ = S$ + "Day : " + Str$(Da) + crlfMbeMessageBox S$

End Sub

DateSerialDateSerial#(year%, month%, day%)

Descr. The DateSerial function returns a double-precision number representing the specified date. The number is returned in days, where Dec 30, 1899 is 0.

Example Sub Main()'This example converts a date to a real number representing the'serial date in days since Dec 30, 1899 (which is day 0).Tdate# = DateSerial(1990,08,22)MbeMessageBox "DateSerial value for Aug 22, 1990, is: " + Str$(Tdate)

End Sub

DateValueDateValue#(date_string$)

Descr. Returns a double-precision number representing the date contained in the specified string argument.

Example Sub Main()'This example returns the day of the month for today's date.Tdate$ = Date$TDay = DateValue(Tdate)MbeMessageBox Tdate + "The date value is: " + Str$(Tday)

End Sub

DayDay%(serial#)

Descr. Returns the day of the date encoded in the specified serial parameter. The value returned is between 1 and 31 inclusive.

Example Sub Main()'This example returns the day of the month for today's date.Tdate$ = Date$TDay! = Day(DateValue(Tdate))MbeMessageBox ("The day part of " + Tdate + " is: " + Str$(TDay))

End Sub

7-34 MicroStation BASIC Guide

Page 185: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 35 Friday, October 15, 1999 1:27 PM

DDBDDB#(Cost#, Salvage#, Life#, Period#)

Descr. This function calculates the depreciation of an asset for a specified Period of time using the double-declining balance method.

The double-declining balance method calculates the depreciation of an asset at an accelerated rate. The depreciation is at its highest in the first period and becomes progressively lower in each additional period. DDB uses the following formula to calculate the depreciation:

DDB =((Cost - Total_depreciation_from_all_other_periods) * 2)/Life

DDB uses the following parameters:

Life and Period must be expressed using the same units. If Life is expressed in months, then Period must also be expressed in months.

Example Const crlf = Chr$(13) + Chr$(10)Sub Main()

'This example calculates the depreciation for capital equipment'that cost $10,000, has a service life of 10 years, and is worth'$2,000 as scrap. The dialog box displays the depreciation for each'of the first 4 years.S$ = "Depreciation Table" + crlf + crlfFor yy = 1 To 4

CurDep# = DDB(10000.0, 2000.0, 10, yy)S$ = S$ + "Year " + Str$(yy) + " : " + Str$(CurDep) + crlf

Next yyMbeMessageBox S$

End Sub

Parameter Description

Cost a double-precision number that represents the initial cost of the asset

Salvage a double-precision number that represents the estimated value of the asset at the end of its predicted useful life

Life a number that represents the predicted length of the asset's useful life

Period a number that represents the period for which you wish to calculate the depreciation

MicroStation BASIC Guide 7-35

Page 186: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 36 Friday, October 15, 1999 1:27 PM

DDEExecuteDDEExecute channel%, command$

Descr. Sends an execute message to another application.

The channel must first be initiated using DDEInitiate. An error will result if channel is invalid.

If the receiving application does not execute the instructions, BASIC generates a run-time error.

The format of command$ depends on the receiving application.

Win32 is the platform that applies to DDEExecute. The DDEML library is required for DDE support. This library is loaded when the first DDEInitiate statement is encountered and remains loaded until the BASIC system is terminated. Thus, the DDEML library is required only if DDE statements are used within a macro.

Example Sub Main()Dim ch As Integerq$ = Chr$(34)ch = DDEInitiate(“Excel”, “C:\SHEETS\TEST.XLS”)CMD$ = “[SELECT(“ + q$ + “R1C1:R8C1” + q$ + “)]”DDEExecute ch,cmd$DDETerminate ch

End Sub

DDEInitiateDDEInitiate%(app$, topic$)

Descr. Initializes a DDE link to another application and returns a unique number subsequently used to refer to the open DDE channel.

The function returns 0 if BASIC cannot establish the link. This will occur under any of the following circumstances:

1. The specified application is not running.

2. The topic was invalid for that application.

3. Memory or system resources are insufficient to establish the DDE link.

app$ specifies the name of the application (the server) with which a DDE conversion will be established. topic$ specifies the name of the topic for the conversation. The possible values for

7-36 MicroStation BASIC Guide

Page 187: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 37 Friday, October 15, 1999 1:27 PM

this parameter are described in the documentation for the server application.

Win32 is the platform that applies to DDEInitiate. The DDEML library is required for DDE support. This library is loaded when the first DDEInitiate statement is encountered and remains loaded until the BASIC system is terminated. Thus, the DDEML library is required only if DDE statements are used within a macro.

Example Sub Main()Dim ch As Integerq$ = Chr$(34)ch = DDEInitiate(“Excel”, “C:\SHEETS\TEST.XLS”)CMD$ = “[SELECT(“ + q$ + “R1C1:R8C1” + q$ + “)]”DDEExecute ch, cmd$DDETerminate ch

End Sub

DDEPokeDDEPoke channel%, dataItem$, value$

Descr. Sets the value of a data item in the receiving application associated with an open DDE link.

The channel must first be initiated using DDEInitiate. An error will result if channel is invalid.

The format for dataItem$ and value$ depends on the receiving application.

Win32 is the platform that applies to DDEPoke. The DDEML library is required for DDE support. This library is loaded when the first DDEInitiate statement is encountered and remains loaded until the BASIC system is terminated. Thus, the DDEML library is required only if DDE statements are used within a macro.

Example Sub Main()ch = DDEInitiate(“Excel”, “C:\SHEETS\TEST.XLS”)DDEPoke ch, “R1C1”, “980”DDETerminate ch

End Sub

MicroStation BASIC Guide 7-37

Page 188: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 38 Friday, October 15, 1999 1:27 PM

DDERequestDDERequest$ (channel%, dataItem$)

Descr. Returns a string representing the value of the given data item in the receiving application associated with the open DDE channel.

The channel must first be initiated using DDEInitiate. An error will result if channel is invalid.

The formats for dataItem$ and the returned value depend on the receiving application.

Win32 is the platform that applies to DDERequest. The DDEML library is required for DDE support. This library is loaded when the first DDEInitiate statement is encountered and remains loaded until the BASIC system is terminated. Thus, the DDEML library is required only if DDE statements are used within a macro.

Example Sub Main()ch = DDEInitiate(“Excel”, “C:\SHEETS\TEST.XLS”)s$ = DDERequest$(ch, “R1C1”)DDETerminate chMbeMsgBox s$

End Sub

DDESendDDESend application$, topic$, item$, data$

Descr. Initiates a DDE conversation with the server as specified by application$ and topic$ and sends that server a new value for the specified item.

The DDESend statement performs the equivalent of the following statements:

ch% = DDEInitiate(application$, topic$)DDEPoke ch$, item$, data$DDETerminate ch%

Win32 is the platform that applies to DDESend. The DDEML library is required for DDE support. This library is loaded when the first DDEInitiate statement is encountered and remains loaded until the BASIC system is terminated. Thus, the DDEML library is required only if DDE statements are used within a macro.

Example ‘ The following code fragment sets the content of the first cell in an ‘ Excel spreadsheet.

7-38 MicroStation BASIC Guide

Page 189: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 39 Friday, October 15, 1999 1:27 PM

On Error Goto Trap1 DDESend “Excel”, “C:\EXCEL\TEST.XLS”, “R1C1”, “Hello, world.” On Error Goto 0 ‘ Add more lines here ...

Trap1:MbeMsgBox “Error sending data to Excel.”Exit Sub ‘Reset error handler

DDETerminateDDETerminate channel%

Descr. Closes the specified DDE channel.

The channel must first be initiated using DDEInitiate. An error will result if channel is invalid.

All open DDE channels are automatically terminated when the macro ends.

Win32 is the platform that applies to DDETerminate. The DDEML library is required for DDE support. This library is loaded when the first DDEInitiate statement is encountered and remains loaded until the BASIC system is terminated. Thus, the DDEML library is required only if DDE statements are used within a macro.

Example Sub Main()Dim ch As Integerq$ = Chr$(34)ch = DDEInitiate(“Excel”, “C:\SHEETS\TEST.XLS”)CMD$ = “[SELECT(“ + q$ + “R1C1:R8C1” + q$ + “)]”DDEExecute ch, cmd$DDETerminate ch

End Sub

DDETerminateAllDDETerminateAll

Descr. Closes all open DDE channels.

All open DDE channels are automatically terminated when the macro ends.

Win32 is the platform that applies to DDETerminateAll. The DDEML library is required for DDE support. This library is loaded when the first DDEInitiate statement is encountered and remains

MicroStation BASIC Guide 7-39

Page 190: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 40 Friday, October 15, 1999 1:27 PM

loaded until the BASIC system is terminated. Thus, the DDEML library is required only if DDE statements are used within a macro.

Example Sub Main()Dim ch As Integerq$ = Chr$(34)ch = DDEInitiate(“Excel”, “C:\SHEETS\TEST.XLS”)CMD$ = “[SELECT(“ + q$ + “R1C1:R8C1” + q$ + “)]”DDEExecute ch, cmd$DDETerminateAll

End Sub

DDETimeOutDDETimeOut milliseconds&

Descr. This statement sets the number of milliseconds that must elapse before a DDE command times out. The default is 10,000 (10 seconds).

Win32 is the platform that applies to DDETimeOut. The DDEML library is required for DDE support. This library is loaded when the first DDEInitiate statement is encountered and remains loaded until the BASIC system is terminated. Thus, the DDEML library is required only if DDE statements are used within a macro.

Example Sub Main()Dim ch As Integerq$ = Chr$(34)ch = DDEInitiate(“Excel”, “C:\SHEETS\TEST.XLS”)DDETimeOut (20000)CMD$ = “[SELECT(“ + q$ + “R1C1:R8C1” + q$ + “)]”DDEExecute ch, cmd$DDETerminate ch

End Sub

DeclareDeclare Sub name [([argumentlist])]

Declare Function name [([argumentlist])] [As type]

Descr. You can use the Declare statement to create a prototype for a BASIC routine that occurs later in the source module.

The name parameter is any valid BASIC name. When you declare functions, you can include a type-declaration character to indicate the return type.

7-40 MicroStation BASIC Guide

Page 191: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 41 Friday, October 15, 1999 1:27 PM

The optional argumentlist specifies the arguments received by the routine. By default, arguments are passed by reference. When a routine requires a value rather than a reference, include the ByVal keyword. For example, the following subroutine:

Sub MessageBeep (ByVal numBeeps%, message#)

would be declared as follows:

Declare Sub MessageBeep (ByVal numBeeps%, message#)

For function declarations, the return type can be specified using a type-declaration character (i.e., $, % or &) or by specifying the [As type] clause. The valid types are Integer, Long and String.

Declare statements must appear outside of any Sub or Function declaration. Declare statements are only valid during the life of that macro.

DEF…DEFInt letterrange

DEFLng letterrange

DEFStr letterrange

DEFsng letterrange

DEFdbl letterrange

Descr. Establishes the default type assigned to undeclared or untyped variables.

The DEF… statement controls automatic type declaration of variables. Normally, if a variable is encountered that hasn't yet been declared with the Dim statement or does not appear with an explicit type-declaration character, then that variable is declared implicitly as an integer (DEFInt A-Z). This can be changed using the DEF… statement to specify starting letter ranges for type other than integer. The letterrange parameter is used to specify starting letters. Thus, any variable that begins with a specified character will be declared using the specified type.

The syntax for letterrange is:

letter [-letter] [,letter [-letter]]...

DEF… variable types are superseded by an explicit type declaration—using either a type-declaration character or the Dim statement.

MicroStation BASIC Guide 7-41

Page 192: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 42 Friday, October 15, 1999 1:27 PM

DEF… only affects how macros are compiled and has no effect at run time. DEF… can only appear outside all Sub and Function declarations.

Example DEFStr a-lDEFLng m-rDEFSng s-uDEFDbl v-wDEFInt x-zSub Main()

a = "This stuff"m = 100.52s = 100.52v = 100.55x = 100.52MbeMessageBox a & Str$(m) & Str$(s) & Str$(v) & Str$(x)

End Sub

DimDim name [(<subscripts>)] [As [New] type] [,name [(<subscripts>)] _[As [New] type]]...

Descr. Declares a list of local variables and their corresponding types and sizes.

If a type-declaration character is used when specifying name (such as %, &, $ or !), the optional [As type] expression is not allowed. For example, the following are allowed:

Example Dim Temperature As IntegerDim Temperature%

The subscripts parameter allows the declaration of dynamic and fixed arrays. subscripts uses the following syntax:

[lower to] upper [,[lower to] upper]...

The lower and upper parameters are Integers specifying the lower and upper bounds of the array. If lower is not specified, then the lower bound as specified by Option Base is used (or 0 if no Option Base statement has been encountered). BASIC supports a maximum of 60 array dimensions.

The total size of an array (not counting space for strings) is limited to 64K.

Dynamic arrays are declared by not specifying any bounds:

Example Dim a()

7-42 MicroStation BASIC Guide

Page 193: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 43 Friday, October 15, 1999 1:27 PM

The type parameter specifies the type of the data item being declared. It can be any of the following data types: String, Integer, Long, Single, Double, Object, application-defined object, application-defined data type, or any user-defined data type.

A Dim statement within a subroutine or function declares variables local to that subroutine or function. If the Dim statement appears outside of any subroutine or function declaration, then that variable has the same scope as variables declared with the Private statement.

Implicit Variable Declaration

If BASIC encounters a variable that has not been explicitly declared with Dim, then the variable will be implicitly declared using the specified type-declaration character (%, $ or &). If the variable appears without a type-declaration character, then the first letter is matched against any pending DEF… statements, using the specified type if found. If no DEF… statement has been encountered corresponding to the first letter of the variable name, then Integer is used.

Creating New Objects

The optional [New] keyword is used to declare a new instance of the specified application-defined object. This keyword can only be used with application-defined object data types. Furthermore, this keyword cannot be used when declaring arrays.

At run time, the application or extension that defines that object type is notified that a new object is being defined. The application should respond by creating a new physical object (within the appropriate context) and returning a reference to that object, which is immediately assigned to the variable being declared.

When that variable goes out of scope (i.e., the Sub or Function procedure in which the variable is declared ends), the application is notified. The application can choose any appropriate actions, such as destroying the physical object.

Example Sub Main()'The following are examples using the Dim statement to declare various'variable types.Dim a As integerDim a%Dim b As longDim b&

MicroStation BASIC Guide 7-43

Page 194: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 44 Friday, October 15, 1999 1:27 PM

Dim c As stringDim c$Dim MyArray(10) As integerDim MyStrings$(2,10)Dim FileNames$(5 to 10)Dim Values(1 to 10, 100 to 200)

End Sub

Dir$Dir$[(filespec$ [,attributes])]

Descr. If filespec$ is specified, then the Dir$ function returns the first file matching that filespec$. If filespec$ is not specified, then Dir$ returns the next file matching the initial filespec$ as shown in the example.

The filespec$ argument can include wild cards, such as * and ?. The * character matches any sequence of zero or more characters, whereas the ? character matches any single character. Multiple *'s and ?'s can appear within the expression to form complete searching patterns. The following table shows some examples:

An error is generated if Dir$ is called without first calling it with a valid filespec$.

If there is no matching filespec$, then an empty string is returned.

If no path is specified on filespec$, then the current directory is used.

This pattern Matches these files

Doesn’t match these files

*S*.TXT SAMPLE.TXTGOOSE.TXTSAMS.TXT

SAMPLESAMPLE.DAT

C*T.TXT CAT.TXTACATS.TXT

CAP.TXT

C*T CATCAP.TXT

CAT.DOC

C?T CATCUTCT

CAT.TXTCAPIT

* (All files)

7-44 MicroStation BASIC Guide

Page 195: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 45 Friday, October 15, 1999 1:27 PM

You can control which files are included in the search by specifying the optional attributes parameter. This parameter contains any OR’ed combination of the following attributes:

Example Const crlf = Chr$(13) + Chr$(10)Sub Main()

'This example dimensions a null array and fills it with directory'entries. The result is displayed in a dialog box.Dim a$(10)a(1) = Dir$("*.*")i% = 1While (a(i) <> "") And (i < 10)

i = i+1a(i) = Dir$

WendMbeMessageBox a(1) + crlf + a(2) + crlf + a(3) + crlf + a(4)

End Sub

Do...LoopDo {While | Until} condition statements Loop

Dostatements

Loop {While | Until} condition

Dostatements

Loop

Descr. Repeats a block of BASIC statements while a condition is TRUE or until a condition is TRUE. If the {While | Until} conditional clause is not specified, then the loop repeats the statements forever (or until BASIC encounters an Exit Do statement).

The condition parameter specifies any Boolean expression.

Example Const crlf = Chr$(13) + Chr$(10)Sub Main()

'The first example uses the Do...While statement, which performs the'iteration, then checks the condition, and repeats if the condition

Constant Value Includes

ebNormal 0 Clear the read-only and archive attributes

ebReadOnly 1 Set read-only attribute

ebHidden 2 Set hidden attribute

ebSystem 4 Set system file attribute

ebArchive 32 Set archive attribute

MicroStation BASIC Guide 7-45

Page 196: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 46 Friday, October 15, 1999 1:27 PM

'is True.Dim a$(100)i% = 0Do

i = i+1If i = 1 Then

a(i) = Dir$("*.*")Else

a(i) = Dir$End If

Loop While (a(i) <> "")Msg$ = "There are " + Str$(i) + " files found" + crlfMbeMessageBox Msg + a(1) + crlf + a(2) + crlf + a(3) + crlf + a(10)'The second example uses the Do While...Loop, which checks the'condition and then repeats if the condition is True.Dim a$(100)i% = 1a(i) = Dir$("*.*")Do While a(i) <> ""

i = i+1a(i) = Dir$

LoopMsg$ = "There are " + Str$(i) + " files found" + crlfMbeMessageBox Msg + a(1) + crlf + a(2) + crlf + a(3) + crlf + a(10)'The third example uses the Do Until...Loop, which does the iteration'and then checks the condition and repeats if the condition is True.Dim a$(100)i% = 1a(i) = Dir$("*.*")Do Until a(i) = ""

i = i+1a(i) = Dir$

LoopMsg$ = "There are " + Str$(i) + " files found" + crlfMbeMessageBox Msg + a(1) + crlf + a(2) + crlf + a(3) + crlf + a(10)'The last example uses the Do...Until Loop, which performs the'iteration first, checks the condition, and repeats if the condition'is True.Dim a$(100)i% = 0Do

i = i+1If i = 1 Then

a(i) = Dir$("*.*")Else

a(i) = Dir$End If

7-46 MicroStation BASIC Guide

Page 197: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 47 Friday, October 15, 1999 1:27 PM

Loop Until (a(i) = "")Msg$ = "There are " + Str$(i) + " files found" + crlfMbeMessageBox Msg + a(1) + crlf + a(2) + crlf + a(3) + crlf + a(10)

End Sub

ebArchiveDescr. 32-bit position of a file attribute indicating that a file hasn't been backed up.

Example Sub Main()'Dimension an array and fill it with filenames with Archive bit set.Dim s$()FileList(s$), "*.*", ebArchivea% = SelectBox("Archived Files", "Choose one", s$)If a >= 0 Then 'If a% is -1, then user pressed Cancel.

MbeMessageBox "You selected ARCHIVE file " + s$(a)Else

MbeMessageBox "No selection made"End If

End Sub

ebDirectoryDescr. 16-bit position of a file attribute indicating that a file is a directory entry.

Example Sub Main()'Dimension an array and fill it with directory names using the'ebDirectory constant.Dim s$()FileList(s$), "*.*", ebDirectorya% = MbeSelectBox("Choose One", s(), "Directories")If a >= 0 Then

MbeMessageBox "You selected directory " + S$(a)Else

MbeMessageBox "No selection made"End If

End Sub

ebHiddenDescr. 2-bit position of a file attribute indicating that a file is hidden.

Example Sub Main()'Dimension an array and fill it with filenames using‘the ebHidden attribute.Dim s$()FileList(S$), "*.*", ebHidden

MicroStation BASIC Guide 7-47

Page 198: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 48 Friday, October 15, 1999 1:27 PM

a% = SelectBox("Hidden Files","Choose one", S$)If a >= 0 Then

MbeMessageBox "You selected hidden file " + S$(a)Else

MbeMessageBox "No selection made"End If

End Sub

ebNoneDescr. 64-bit value used to select files with no other attributes. This value can be used with

the Dir$ and FileList commands. These functions will return only files with no attributes set when used with this constant.

Example Sub Main()'Dimension an array and fill it with filenames with no attributes set.Dim s$()FileList(S$), "*.*", ebNonea% = SelectBox("No Attributes", "Choose one", S$)If a >= 0 Then

MbeMessageBox "You selected file " + S$(a)Else

MbeMessageBox "No selection made"End If

End Sub

ebNormalDescr. 0

Value used to search for "normal" files. This value can be used with the Dir$ and FileList commands and will return files with the Archive, Volume, ReadOnly or no attributes set. It will not match files with Hidden, System or Directory attributes.

Example Sub Main()'Dimension an array and fill it with filenames with Normal attributes.Dim s$()FileList(S$),"*.*", ebNormala% = SelectBox("Normal Files", "Choose one", S$)If a >= 0 Then

MbeMessageBox "You selected file " + S$(a)Else

MbeMessageBox "No selection made"End If

End Sub

7-48 MicroStation BASIC Guide

Page 199: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 49 Friday, October 15, 1999 1:27 PM

ebReadOnlyDescr. Bit[1] position of a file attribute indicating that a file is read-only.

Example Sub Main()'Dimension an array & fill it with filenames with ReadOnly attributes.Dim s$()FileList(S$), "*.*", ebReadOnlya% = SelectBox("ReadOnly", "Choose one", S$)If a >= 0 Then

MbeMessageBox "You selected file " + S$(a)Else

MbeMessageBox "No selection made"End If

End Sub

ebSystemDescr. Bit[4] position of a file attribute indicating that a file is a system file.

Example Sub Main()'Dimension an array and fill it with filenames with System attributes.Dim s$()FileList(S$), "*.*", ebSystema% = SelectBox("System Files", "Choose one", S$)If a >= 0 Then

MbeMessageBox "You selected file " + S$(a)Else

MbeMessageBox "No selection made"End If

End Sub

ebVolumeDescr. Bit[8] position of a file attribute indicating that a file is the volume label.

Example Sub Main()'Dimension an array and fill it with filenames with Volume attributes.Dim s$()FileList(S$), "*.*", ebVolumeIf ArrayDims(a) > 0 Then

MbeMessageBox "The volume name is: " + a(1)Else

MbeMessageBox "No volumes found"End If

End Sub

MicroStation BASIC Guide 7-49

Page 200: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 50 Friday, October 15, 1999 1:27 PM

EndEnd

Descr. Terminates execution of the current macro. All open files are closed.

Example Sub Main()MbeMessageBox "The next line will terminate the script"End

End Sub

Environ$Environ$(variable$)

Environ$(VariableNumber%)

Descr. Returns the value of the specified environment variable.

If variable$ is specified, then this function looks for that variable$ in the environment. If variable$ cannot be found, an empty string is returned.

If VariableNumber is specified, then this function looks for the nth variable within the environment (the first variable being number 1). If there is no such environment variable, then an empty string is returned. Otherwise, the entire entry from the environment is returned in the following format:

variable = value

Example Sub Main()'This example looks for the DOS Comspec variable and displays the'value in a dialog box.Dim a$(1)a(1) = Environ$("COMSPEC")MbeMessageBox a(1)

End Sub

To retrieve and set the values of MicroStation configuration variables, use the MicroStation BASIC extensions: MbeGetConfigVar (page 8-143) and MbeDefineConfigVar.

See also MbeGetConfigVar, MbeSetConfigVar.

EofEof%(filenumber%)

7-50 MicroStation BASIC Guide

Page 201: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 51 Friday, October 15, 1999 1:27 PM

Descr. Returns TRUE if the end of file has been reached for the given file; otherwise returns FALSE.

The filenumber parameter is a number that is used to refer to the open file—the number passed to the Open statement.

With sequential files, Eof returns TRUE when the end of the file has been reached (i.e., the next file read command will result in a run-time error).

With Random or Binary files, Eof returns TRUE after an attempt has been made to read beyond the end of the file. Thus, Eof will only return TRUE when Get was unable to read the entire record.

Example Sub Main()'This example opens the Autoexec.Bat file and reads lines from the'file until the end of file is reached.Dim S$Open "C:\AUTOEXEC.BAT" For Input As 1Do While Not Eof(1)

Input #1,SLoopCloseMbeMessageBox "The last line was" + crlf + S

End Sub

Eqvexpression1 Eqv expression2

Descr. If both operands are relational, then Eqv returns the logical equivalence of expression1 and expression2. Eqv returns TRUE if expression1 and expression2 are the same (i.e., either both TRUE or both FALSE); otherwise Eqv returns FALSE.

If both operands are numeric, then the result is the bitwise Eqv of the arguments.

If either of the two operands is a floating-point number, the two operands are converted to Longs, then a bitwise Eqv is performed.

For numeric operands, bitwise Eqv works as follows:

Bit in expression1 Bit in expression2 Bit in result

1 1 1

0 1 0

1 0 0

0 0 1

MicroStation BASIC Guide 7-51

Page 202: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 52 Friday, October 15, 1999 1:27 PM

Example Sub Main()'This example assigns False to A, performs some equivalent operations,'and displays a dialog box with the result. Since A is equivalent to'False, and False is equivalent to 0, and by definition, A = 0, then'the dialog box will display "A is False".A = FalseIf ((A Eqv False) And (False Eqv 0) And (A = 0)) Then

MbeMessageBox "A is False"Else

MbeMessageBox "A is True"End If

End Sub

EraseErase array1 [,array2]...

Descr. The Erase statement erases the elements of the specified arrays.

For dynamic arrays, the elements are erased and the array is redimensioned to have no dimensions (and therefore no elements). For fixed arrays, only the elements are erased; the array dimensions are not changed.

After a dynamic array is erased, the array will contain no elements and no dimensions. Thus, before the array can be used by your program, the dimensions must be reestablished using the Redim statement.

Up to 32 parameters can be specified with the Erase statement.

The meaning of erasing an array element depends on the type of element being erased:

Example Sub Main()Dim a$(1)

Element type What Erase does to that element

Integer Sets the element to 0.

Long Sets the element to 0.

Double Sets the element to 0.0.

Single Sets the element to 0.0.

String Frees the string, then sets the element to an empty string.

Object Decrements the reference count and sets the element to Nothing.

User-defined types Sets each structure element as a separate variable.

7-52 MicroStation BASIC Guide

Page 203: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 53 Friday, October 15, 1999 1:27 PM

a(1) = Dir$("*.*")MbeMessageBox aErase aMbeMessageBox a(1)

End Sub

ErlErl%[()]

Descr. Returns 0 (BASIC does not support line numbers).

Example Sub Main()'Since the Erl function normally specifies a line number, it will'always return 0 within this product, as shown below.a = ErlIf a = 0 Then

MbeMessageBox "Returned 0"Else

MbeMessageBox "Returned non-0" + Str$(a)End If

End Sub

Err (function)Err%[()]

Descr. The Err function returns an Integer representing the run time error that caused the current error trap.

Err can only be used while within an error trap.

When a function or statement ends, the value returned by Err is reset to 0.

Example Sub Main()'This example forces error 10, with a subsequent transfer to'the TestError label. TestError tests the error and, if not'error 55, resets Err to 999 (user-defined error) and returns to'the Main subroutine.On Error Goto TestErrorError 10MbeMessageBox("The returned error is: " + Str$(Err()) + " : " + Error$)Exit Sub

TestError:If Err = 55 Then 'File already open.

MbeMessageBox "Cannot copy an open file. Close it and try again."Else

MicroStation BASIC Guide 7-53

Page 204: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 54 Friday, October 15, 1999 1:27 PM

MbeMessageBox "Error " + Str$(Err) + " has occurred"Err = 999

End IfResume Next

End Sub

Err (statement)Err = value%

Descr. The statement form of Err sets the value returned by the Err function to a specific value.

Only positive values less than 32767 are valid.

Setting value to -1 has the side effect of resetting the error state. This allows you to perform error trapping within an error handler.

Example Sub Main()'This example forces error 10, with a subsequent transfer to'the TestError label. TestError tests the error and, if not'error 55, resets Err to 999 (user-defined error) and returns to'the Main subroutine.On Error Goto TestErrorError 10MbeMessageBox("The returned error is: " + Str$(Err()) + " : " + Error$)Exit Sub

TestError:If Err = 55 Then 'File already open.

MbeMessageBox "Cannot copy an open file. Close it and try again."Else

MbeMessageBox "Error " + Str$(Err) + " has occurred"Err = 999

End IfResume Next

End Sub

ErrorError errornumber%

Descr. This function simulates the occurrence of the given run-time error.

The errornumber parameter can be a built-in error number or a user-defined error number. Err can be used within the error trap handler to determine the value of the error.

7-54 MicroStation BASIC Guide

Page 205: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 55 Friday, October 15, 1999 1:27 PM

Example Sub Main()'This example forces error 10, with a subsequent transfer to'the TestError label. TestError tests the error and, if not'error 55, resets Err to 999 (user-defined error) and returns to'the Main subroutine.On Error Goto TestErrorError 10MbeMessageBox("The returned error is: " + Str$(Err()) + " : " + Error$)Exit Sub

TestError:If Err = 55 Then 'File already open.

MbeMessageBox "Cannot copy an open file. Close it and try again."Else

MbeMessageBox "Error " + Str$(Err) + " has occurred"Err = 999

End IfResume Next

End Sub

Error$Error$ [(errornumber%)]

Descr. Returns the text corresponding to the given error number or the most recent error.

If errornumber is omitted, then the function returns the text corresponding to the most recent run-time error. If no run-time error has occurred, then an empty string ("") is returned.

If the Error statement was used to generate a user-defined run-time error, then this function will return an empty string ("").

Example Sub Main()'This example forces error 10, with a subsequent transfer to'the TestError label. TestError tests the error and, if not'error 55, resets Err to 999 (user-defined error) and returns to'the Main subroutine.On Error Goto TestErrorError 10MbeMessageBox("The returned error is: " + Str$(Err()) + " : " + Error$)Exit Sub

TestError:If Err = 55 Then 'File already open.

MbeMessageBox "Cannot copy an open file. Close it and try again."Else

MbeMessageBox "Error " + Str$(Err) + " has occurred"Err = 999

End If

MicroStation BASIC Guide 7-55

Page 206: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 56 Friday, October 15, 1999 1:27 PM

Resume NextEnd Sub

Exit DoExit Do

Descr. This statement can only appear within a Do...Loop statement. It causes execution to continue on the next statement after the Loop clause.

Example Sub Main()'This example will load an array with directory entries unless there'are more than three entries, in which case, the Exit Do terminates'the loop.'If fewer than 3 entries are found, a dialog box displays the count;'otherwise, a dialog box displays "More than three entries found."Dim a$(5)i% = 0Do

i = i+1If i = 1 Then

a(i) = Dir$("*.*")Else

a(i) = Dir$End If

If i >= 3 Then Exit DoLoop While (a(i) <> "")If i <> 3 Then

MbeMessageBox "There are " + Str$(i) + " files found"Else

MbeMessageBox "Exited on i = 3"End IfMbeMessageBox a(1) + crlf + a(2) + crlf + a(3) + crlf + a(10)

End Sub

Exit ForExit For

Descr. This statement ends the For...Next block in which it appears. Execution will continue on the line immediately after the Next statement.

This statement can only appear within a For...Next block.

Example Const crlf = Chr$(13) + Chr$(10)Sub Main()

'This example will fill an array with directory entries‘until a null entry is encountered or 100 entries have been

7-56 MicroStation BASIC Guide

Page 207: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 57 Friday, October 15, 1999 1:27 PM

‘processed. The dialog box displays a count of files found and‘then some entries from the array.Dim a$(100)Dim i%For i% = 1 To 100

If i = 1 Thena(i) = Dir$("*.*")

Elsea(i) = Dir$

End IfIf (a(i) = "") Or (i >= 100) Then Exit For

Next iMsg$ = "There are " + Str$(i) + " files found" + crlfMbeMessageBox Msg + a(1) + crlf + a(2) + crlf + a(3) + crlf + a(10)

End Sub

Exit FunctionExit Function

Descr. This statement ends execution of the function in which it appears. Execution will continue on the statement or function following the call to this function.

This statement can only appear within a function.

Example Function Test_Exit () As Integer'This function displays a message & then terminates with Exit Function.MbeMessageBox("Testing function exit: returning to Main")Test_Exit = 0Exit FunctionMbeMessageBox("This line should never execute")

End FunctionSub Main()

a% = Test_Exit()MbeMessageBox "This is the last line of Main"

End Sub

Exit SubExit Sub

Descr. This statement ends the current subroutine. Execution is transferred to the statement following the call to the current subroutine.

This statement can appear anywhere within a subroutine. It cannot appear within a function.

MicroStation BASIC Guide 7-57

Page 208: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 58 Friday, October 15, 1999 1:27 PM

Example Sub Main()'This example displays a dialog box & then exits. The last line should'never execute because of the Exit Sub statement.MbeMessageBox("Terminating Main")Exit SubMbeMessageBox("Still here in Main")

End Sub

ExpExp#(value#)

Descr. Returns the value of e raised to the power of value.

Range of value: 0 <= value <= 709.782712893.

A run-time error is generated if value is out of the range specified above.

Example Sub Main()'This example assigns a to e raised to the 12.4 power and displays it'in a dialog box.a# = Exp(12.40)MbeMessageBox "e to the 12.4 power is: " + Str$(a)

End Sub

FalseDescr. 0, used in conditionals and Boolean expressions.

Example Sub Main()'This example assigns False to A, performs some equivalent operations,'and displays a dialog box with the result. Since A is equivalent to'False, and False is equivalent to 0, and by definition, A = 0, then'the dialog box will display "A is False".A = Falseif ((A = False) and (False Eqv 0) And (A = 0)) Then

MbeMessageBox "A is False"Else

MbeMessageBox "A is True"End If

End Sub

FileAttrFileAttr%(filenumber%, attribute%)

7-58 MicroStation BASIC Guide

Page 209: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 59 Friday, October 15, 1999 1:27 PM

Descr. Returns the file mode (if attribute is 1) or the operating system file handle (if attribute is 2).

If attribute is 1, then one of the following values is returned:

The filenumber parameter is a number that is used to refer to the open file—the number passed to the Open statement.

Example Sub Main()'This example opens a file for input, reads the file attributes, and'determines the file mode for which it was opened. The result is'displayed in a dialog box.Open "C:\AUTOEXEC.BAT" For Input As 1a% = FileAttr(1,1)Select Case a

Case 1MbeMessageBox "Opened for input"

Case 2MbeMessageBox "Opened for output"

Case 3MbeMessageBox "Opened for random"

Case 4MbeMessageBox "Opened for append"

Case 32MbeMessageBox "Opened for binary"

Case ElseMbeMessageBox "Unknown file mode"

End Selecta = FileAttr(1,2)MbeMessageBox "File handle is: " + Str$(a)Close

End Sub

FileCopyFileCopy source$, destination$

Descr. The FileCopy command copies a source$ file to a destination$ file.

The source$ parameter must specify a single file. It cannot contain wild cards (? or *) but may contain path information.

1 Input

2 Output

4 Random

8 Append

32 Binary

MicroStation BASIC Guide 7-59

Page 210: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 60 Friday, October 15, 1999 1:27 PM

The destination$ specifies a single, unique destination file and may contain drive and path specifiers. The file will be copied and renamed if the source$ and destination$ filenames are not the same. Note that some platforms do not support drive letters and may not support dots to indicate current and parent directories.

Example Sub Main()'This example copies the Autoexec.Bat file to "AUTOEXEC.SAV", then'opens the copied file and tries to copy it again, generating an error.On Error Goto ErrHandlerFileCopy "C:\AUTOEXEC.BAT", "C:\AUTOEXEC.SAV"Open "C:\AUTOEXEC.SAV" For Input As # 1FileCopy "C:\AUTOEXEC.SAV", "C:\AUTOEXEC.SV2"CloseExit Sub

ErrHandler:If Err = 55 Then 'File already open.

MbeMessageBox "Cannot copy an open file. Close it and try again."Else

MbeMessageBox "An unspecified file copy error has occurred"End IfResume Next

End Sub

FileDateTimeFileDateTime#(filename$)

Descr. The FileDateTime function returns a double-precision number representing the date and time of the given file. The number is returned in days, where Dec 30, 1899 is 0.

FileDateTime retrieves the date and time of the file specified by filename$. A run-time error results if the file does not exist. The value returned can be used with the date/time functions (i.e., Year, Month, Day, Weekday, Minute, Second, Hour) to extract the individual elements.

Example Sub Main()'This example gets the file date/time of the Autoexec.Bat file and'displays it in a dialog box.If FileExists "C:\Autoexec.Bat" Then

A# = FileDateTime("C:\AUTOEXEC.BAT")MbeMessageBox Str$(Year(A)) + Str$(Month(A)) + Str$(Day(A))

ElseMbeMessageBox "The file does not exist"

End IfEnd Sub

7-60 MicroStation BASIC Guide

Page 211: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 61 Friday, October 15, 1999 1:27 PM

FileDirsFileDirs array$() [,dirspec$]

Descr. This statement fills an array$ with directory names from disk.

array$() is any previously declared string array. The FileDirs function reallocates this array to exactly hold all the directory names matching a given specification.

array$ must specify either a 0- or a 1-dimensioned dynamic array or a single-dimensioned fixed array. If the array is dynamic, then it will be redimensioned to exactly hold the new number of elements. If the array is fixed, each array element is first erased, then the new elements are placed into the array. If there are fewer elements than will fit in the array, then the remaining elements are unused. A run-time error results if the array is too small to hold the new elements.

The dirspec$ parameter specifies the file search mask, such as:

T*. C:\*.*

If dirspec$ is not specified, then * is used, which fills the array with all the subdirectory names within the current directory.

Example Sub Main()'This example fills an array with directory entries and displays the'first one.Dim A$()FileDirs A,"C:\*.*"

MbeMessageBox A(1)End Sub

FileExistsFileExists%(filename$)

Descr. TRUE if the filename$ is a valid file; FALSE otherwise.

FileExists determines whether a given filename$ is valid. FileExists will return FALSE if filename$ specifies a subdirectory.

Example Sub Main()'This example checks to see whether there is an Autoexec.Bat file in'the root directory of the C drive, then displays either its date and'time of creation or the fact that it does not exist.If FileExists("C:\AUTOEXEC.BAT") Then

a# = FileDateTime("C:\AUTOEXEC.BAT")

MicroStation BASIC Guide 7-61

Page 212: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 62 Friday, October 15, 1999 1:27 PM

MbeMessageBox Str$(Year(A#)) + Str$(Month(A#)) + Str$(Day(A#))Else

MbeMessageBox "File does not exist"End If

End Sub

FileLenFileLen&(filename$)

Descr. Returns the length of the given filename$ in bytes.

This function is used in place of Lof to retrieve the length of a file without first opening the file. A run-time error results if the file does not exist.

Example Sub Main()'This example checks to see whether there is a C:\AUTOEXEC.BAT file'and, if there is, displays the length of the file.If (FileExists("C:\AUTOEXEC.BAT") And _

(FileLen("C:\AUTOEXEC.BAT") <> 0)) Thenb% = FileLen("C:\AUTOEXEC.BAT")MbeMessageBox "The length of Autoexec.Bat is: " + Str$(B)

ElseMbeMessageBox "File does not exist"

End IfEnd Sub

FileListFileList array$() [,filespec$ [,include_attr% [,exclude_attr]]]

Descr. This statement fills an array with filenames from disk. The filenames must conform to an eight character filename handle and three character filename extension (8.3 DOS format), or an MDL abort will occur.

The array$() is any previously declared string array. The FileList function reallocates this array to exactly hold all the files matching a given filespec$.

The filespec$ argument can include wild cards, such as * and ?. The * character matches any sequence of zero or more characters, whereas the ? character matches any single character. Multiple *s and ?s can appear within the expression to form

7-62 MicroStation BASIC Guide

Page 213: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 63 Friday, October 15, 1999 1:27 PM

complete searching patterns. The following table shows some examples:

Thus, if filespec$ is not specified, * is used.

include_attr is a number indicating what types of files you want included in the list. Similarly, exclude_attr specifies attributes of files you want excluded from the list. These numbers can be any combination of the following:

If include_attr is not specified, then the value 97 is used (ebReadOnly Or ebArchive Or ebNone). If exclude_attr is not specified, then hidden files and subdirectories are excluded from the list (18).

Example Const crlf = Chr$(13) + Chr$(10)Sub Main()

'This example fills an array a with the directory of the current drive'for all files that have normal or no attributes and excludes those

This pattern Matches these filesDoesn’t match these files

*S*.TXT SAMPLE.TXTGOOSE.TXTSAMS.TXT

SAMPLESAMPLE.DAT

C*T.TXT CAT.TXTACATS.TXT

CAP.TXT

C*T CATCAP.TXT

CAT.DOC

C?T CATCUTCT

CAT.TXTCAPIT

* (All files)

Constant Value Includes

ebNormal 0 Read-only, archive, subdir, none

ebReadOnly 1 Read-only files

ebHidden 2 Hidden files

ebSystem 4 System files

ebVolume 8 Volume label

ebDirectory 16 DOS subdirectories

ebArchive 32 Files that have changed since the last backup

ebNone 64 Files with no attributes

MicroStation BASIC Guide 7-63

Page 214: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 64 Friday, October 15, 1999 1:27 PM

'with system attributes. The dialog box displays four filenames from'the array.Dim a$()FileList a,"*.*", (ebNormal + ebNone), ebSystemIf ArrayDims(a) > 0 Then

MbeMessageBox a(1) + crlf + a(2) + crlf + a(3) + crlf + a(4)Else

MbeMessageBox "No files found"End If

End Sub

FileParse$FileParse$(filename$[, operation])

Descr. This statement takes a filename and extracts a given portion of the filename from it.

filename$ can specify any valid filename (it does not have to exist). For example:

..\test.datC:\sheets\test.dattest.dat

The optional operation parameter specifies which portion of the filename$ to extract. It can be any of the following values.

If operation is not specified, then the full name is returned. A run-time error will result if operation is not one of the above values.

A runtime error results if filename$ is empty.

Example Const crlf = Chr$(13) + Chr$(10)Sub Main()'This example parses the file string "C:\TestSub\Autoexec.Bat" into its'component parts and displays them in a dialog box.Dim a$(6)Dim i%For i = 1 To 5

a(i) = FileParse$("C:\TestSub\Autoexec.Bat",i-1)

0 Full name c:\sheets\test.dat

1 Drive c

2 Path c:\sheets

3 Name test.dat

4 Root test

5 Extension dat

7-64 MicroStation BASIC Guide

Page 215: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 65 Friday, October 15, 1999 1:27 PM

Next iMbeMessageBox a(1)+ crlf + a(2) + crlf + a(3) + crlf + a(4) + crlf + a(5)

End Sub

FixFix%(number#)

Descr. Returns the integer part of number.

This function returns the integer part of the given value by removing the fractional part. The sign is preserved.

Fix differs from the Int function in that Fix truncates negative numbers in a positive direction.

Example Sub Main()'This example returns the fixed part of a number and assigns it to b,'then displays the result in a dialog box.a# = -19923.45b% = Fix(a)MbeMessageBox ("The fixed portion of 19923.45 is: " + Str$(b))

End Sub

For...NextFor counter = start To end [Step increment]

[statements][Exit For][statements]

Next [counter]

Descr. Repeats a block of statements a specified number of times, incrementing a loop counter by a given increment each time through the loop.

If increment is not specified, then 1 is assumed. The expression given as increment is evaluated only once. Changing the step during execution of the loop will have no effect.

The first time through the loop, counter is equal to start. Each time through the loop, increment is added to counter by the amount specified in increment.

The For...Next statement continues executing until an Exit For statement is encountered when counter is greater than end. The expression specified by end is evaluated only once. Thus, changing the end expression during execution of the loop will have no effect.

MicroStation BASIC Guide 7-65

Page 216: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 66 Friday, October 15, 1999 1:27 PM

If end is greater than start, then increment must be positive. If end is less than start, then increment must be negative.

For...Next statements can be nested. In such a case, the Next [counter] statement applies to the innermost For...Next.

The Next [counter] can be optimized for next loops by separating each counter with a comma. The ordering of the counters must be consistent with the nesting order (innermost counter appearing before outermost counter):

Next i,j

Example Function Factorial (n%) As Integer'Calculate N factorial.f% = nFor i% = n To 2 Step -1

f = f * iNext iFactorial = f

End FunctionSub Main()

'This example calculates the value of 5 factorial using a For...Next'loop in function factorial.MbeMessageBox "5 factorial is: " + Str$(Factorial(5))'Constructs a truth table for the OR statement using nested loops.Msg$ = NullFor X% = True To False

For Y% = True To FalseZ = X Or YMsg = Msg + Format$(Abs(X),"0") + " OR "Msg = Msg + Format$(Abs(Y),"0") + " = "Msg = Msg + Format$(Z,"True/False") + crlf

Next YNext XMbeMessageBox Msg

End Sub

Format$Format$(Expression [,Userformat$])

7-66 MicroStation BASIC Guide

Page 217: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 67 Friday, October 15, 1999 1:27 PM

Descr. Returns a string formatted to user specification.

The Format$ function has two parts, consisting of:

If no Userformat$ parameter is given and the expression is numeric, then Format$ performs the same function as the Str$ command, except that it does not preserve a leading space for positive values.

Built-In Formats

To format numeric expressions, you can specify one of the built-in formats. There are two categories of built-in formats: one deals with numeric expressions and the other with date/time values.The following tables list the built-in numeric and date/time format strings, followed by an explanation of what each does.

Expression A string or numeric expression to be formatted. The numeric expression can be entered as a double, a single, an integer, a long, a scientific notation, or a string.

Userformat$ A format expression that can be either one of the built-in BASIC formats or a user-defined format consisting of characters that specify how the expression should be displayed.String, numeric, and date/time formats cannot be mixed in a single Userformat$ expression.

Numeric Format

Description

General Number Display the numeric expression as is, with no additional formatting.

Currency Display the numeric expression as currency, with thousand separator if necessary. The actual formatted output depends on the Currency settings in the International section of the Control Panel.

Fixed Display at least one digit to the left of the decimal separator and two digits to the right.

Standard Display the numeric expression with thousand separator if necessary. Display at least one digit to the left of the decimal separator and two digits to the right.

Percent Display the numeric expression multiplied by 100. A percent sign (%) will appear at the right of the formatted output. Two digits are displayed to the right of the decimal separator.

Scientific Display the number using scientific notation. One digit appears before the decimal separator and two after.

Yes/No Display No if the numeric expression is 0. Display Yes for all other values.

MicroStation BASIC Guide 7-67

Page 218: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 68 Friday, October 15, 1999 1:27 PM

Date formats are listed in the following table:

User-Defined Formats

In addition to the built-in formats, you can also specify a user-defined format, by using characters that have special meaning when used in a format expression. The following tables list the

True/False Display False if the numeric expression is 0. Display True for all other values.

On/Off Display Off if the numeric expression is 0. Display On for all other values.

Date Format Description

General Date Display the date and time. If there is no fractional part in the numeric expression, then only the date is displayed. If there is no integral part in the numeric expression, then only the time is displayed. Output is in the following form: 1/1/93 01:00:00 AM.

Long Date Display a long date, as specified in the International section of the Control Panel.

Medium Date Display a short date, as specified in the International section of the Control Panel, only print out the abbreviated name of the month.

Short Date Display a short date, as specified in the International section of the Control Panel.

Long Time Display the long time, as defined in the International section of the control panel. The default is: h:mm:ss. When Format$ is used to format a time value, the Expression argument should be a double-precision floating point value. Such a value can be obtained using the TimeValue function.

Medium Time Display the time using the 12-hour clock. Hours and minutes are displayed, and the AM/PM designator is at the end. When Format$ is used to format a time value, the Expression argument should be a double-precision floating point value. Such a value can be obtained using the TimeValue function.

Short Time Display the time using the 24-hour clock. Hours and minutes are displayed.When Format$ is used to format a time value, the Expression argument should be a double-precision floating point value. Such a value can be obtained using the TimeValue function.

Numeric Format

Description

7-68 MicroStation BASIC Guide

Page 219: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 69 Friday, October 15, 1999 1:27 PM

characters you can use for numeric, string, and date/time formats and explain their functions.

Character Meaning

Empty string This displays the numeric expression as is, with no additional formatting.

0 This is a digit placeholder.

This will display a number or a 0. If there exists a number in the numeric expression in the position where the 0 appears, the number will be displayed. Otherwise, a 0 will be displayed. If there are more 0s in the format string than there are digits, the leading and trailing 0s are displayed without modification.

# This is a digit placeholder.

This will display a number or nothing. If there exists a number in the numeric expression in the position where the pound sign appears, the number will be displayed. Otherwise, nothing will be displayed. Leading and trailing 0s are not displayed.

. This is the decimal placeholder.

This designates the number of digits to the left of the decimal and the number of digits to the right. The character used in the formatted string depends on the decimal placeholder character specified in the International section of the Control Panel.

% This is the percentage operator.

The numeric expression is multiplied by 100, and the percent character is inserted in the same position as it appears in the user-defined format string.

, This is the thousand separator.

The common use for the thousand separator is to separate thousands from hundreds. To specify this use, the thousand separator must be surrounded by digit placeholders. Commas appearing before any digit placeholders are specified are just displayed. Adjacent commas with no digit placeholders specified between them and the decimal mean divide the number by 1,000 for each adjacent comma in the format string. A comma immediately to the left of the decimal has the same function. The actual thousand separator character used depends on the character specified in the International section of the Control Panel.

MicroStation BASIC Guide 7-69

Page 220: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 70 Friday, October 15, 1999 1:27 PM

Numeric formats can contain one to three parts. Each part is separated by a semicolon. If you specify one format, it applies to all values. If you specify two formats, the first applies to positive values and the second to negative values. If you specify three formats, the first applies to positive values, the second to negative

E-E+e-e+ These are the scientific notation operators.

This displays the number in scientific notation. At least one digit placeholder must exist to the left of E-, E+, e-, or e+. Any digit placeholders displayed to the left of E-, E+, e-, or e+ determine the number of digits displayed in the exponent. Using E+ or e+ places a + in front of positive exponents and a - in front of negative exponents. Using E- or e- places a - in front of negative exponents and nothing in front of positive exponents.

: This is the time separator.

This separates hours, minutes, and seconds when time values are being formatted. The actual character used depends on the character specified in the International section of the Control Panel.

/ This is the date separator.

This separates months, days, and years when date values are being formatted. The actual character used depends on the character specified in the International section of the Control Panel.

-+$()space These are the literal characters you can display.

To display any other character, you should precede it with a backslash or enclose it in quotes.

\ This designates the next character as a displayed character.

To display characters, precede them with a backslash. To display a backslash, use two backslashes. Double quotation marks can also be used to display characters. Numeric formatting characters, date/time formatting characters, and string formatting characters cannot be displayed without a preceding backslash.

"ABC" This displays the text between the quotation marks.

The text between the quotation marks is displayed, but the quotation marks are not. To designate a double quotation mark within a format string, use two adjacent double quotation marks.

* This will display the next character as the fill character.

Any empty space in a field will be filled with the specified fill character.

Character Meaning

7-70 MicroStation BASIC Guide

Page 221: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 71 Friday, October 15, 1999 1:27 PM

values, and the third to 0s. If you include semicolons with no format between them, the format for positive values is used.

String formats are listed in the following table:

Date/time formats are listed in the following table:

Character Meaning

@ This is a character placeholder.

This will display a character if one exists in the expression in the same position. Otherwise, it will display a space. Placeholders are filled from right to left unless the format string specifies left to right.

& This is a character placeholder.

This will display a character if one exists in the expression in the same position. Otherwise, it will display nothing. Placeholders are filled from right to left unless the format string specifies left to right.

< This character forces lowercase.

All characters in the expression are displayed in lowercase.

> This character forces uppercase.

All characters in the expression are displayed in uppercase.

! This character forces placeholders to be filled from left to right. The default is right to left.

Character Meaning

c Display the date as ddddd and the time as ttttt. Only the date is displayed if no fractional part exists in the numeric expression. Only the time is displayed if no integral portion exists in the numeric expression.

d Display the day without a leading 0 (1-31).

dd Display the day with a leading 0 (01-31).

ddd Display the day of the week abbreviated (Sun-Sat).

dddd Display the day of the week (Sunday-Saturday).

ddddd Display the date as a Short Date, as specified in the International section of the Control Panel.

dddddd Display the date as a Long Date, as specified in the International section of the Control Panel.

w Display the number of the day of the week (1-7). Sunday is 1; Saturday is 7.

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

MicroStation BASIC Guide 7-71

Page 222: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 72 Friday, October 15, 1999 1:27 PM

Example Sub Main()a# = 1199.234MbeMessageBox Format$(a,"General Number")MbeMessageBox Format$(a,"Currency")MbeMessageBox Format$(a,"Standard")MbeMessageBox Format$(a,"Fixed")MbeMessageBox Format$(a,"Percent")MbeMessageBox Format$(a,"Scientific")MbeMessageBox Format$(True,"Yes/No")

m Display the month without a leading 0 (1-12). If m immediately follows h or hh, m is treated as minutes (0-59).

mm Display the month with a leading 0 (01-12). If mm immediately follows h or hh, mm is treated as minutes with a leading 0 (00-59).

mmm Display the month abbreviated (Jan-Dec).

mmmm Display the month (January-December).

q Display the quarter of the year (1-4).

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

yy Display the year, not the century (00-99).

yyyy Display the year (1000-9999).

h Display the hour without a leading 0 (0-24).

hh Display the hour with a leading 0 (00-24).

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

nn Display the minute with a leading 0 (00-59).

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

ss Display the second with a leading 0 (00-59).

ttttt Display the time according the International section of the Control Panel. A leading 0 is displayed if specified in the Control Panel.

AM/PM Display the time using a 12-hour clock. Display an uppercase AM for time values before 12 noon. Display an uppercase PM for time values after 12 noon and before 12 midnight.

am/pm Display the time using a 12-hour clock. and append a lowercase am or pm.

A/P Display the time using a 12-hour clock. and append an uppercase A or P.

a/p Display the time using a 12-hour clock. and append a lowercase a or p.

AMPM Display the time using a 12-hour clock. Display the string s1159 for values before 12 noon and s2359 for values after 12 noon and before 12 midnight.

Character Meaning

7-72 MicroStation BASIC Guide

Page 223: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 73 Friday, October 15, 1999 1:27 PM

MbeMessageBox Format$(True,"True/False")MbeMessageBox Format$(True,"On/Off")da$ = Date$MbeMessageBox Format$(da,"General Date")MbeMessageBox Format$(da,"Long Date")MbeMessageBox Format$(da,"Medium Date")MbeMessageBox Format$(da,"Short Date")ti$ = Time$tiDouble# = TimeValue(ti)MbeMessageBox Format$(tiDouble,"Long Time")MbeMessageBox Format$(tiDouble,"Medium Time")MbeMessageBox Format$(tiDouble,"Short Time")A# = 12445601.234MbeMessageBox Format$(A,"0,0.00")MbeMessageBox Format$(A,"##,###,###.###")

End Sub

FreeFileFreeFile%[()]

Descr. Returns the next available file number. This number is suitable for use in the Open statement.

The value returned will always be between 1 and 255 inclusive.

Example Sub Main()'This example assigns A to the next free file number and displays it'in a dialog box.A = FreeFileMbeMessageBox "The next free file number is: " + Str$(A)

End Sub

Function...End FunctionFunction name[(parameter [As type]...)] [As type]

name = expressionEnd Function

Descr. Creates a user-defined function.

The return value is determined by the following statement:

name = expression

The name of the function follows BASIC naming conventions. It can include type-declaration characters: %, & and $.

MicroStation BASIC Guide 7-73

Page 224: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 74 Friday, October 15, 1999 1:27 PM

If no assignment is encountered before the function exits, then 0 will be returned for numeric functions, and an empty string will be returned for string functions.

The type of the return value is determined by the As type clause on the Function statement itself. As an alternative, a type-declaration character can be added to the Function name:

Function Test() As StringTest = "Hello, World"

End FunctionFunction Test$()

Test = "Hello, World"End Function

Parameters are passed to a function by reference, meaning that any modifications to a passed parameter change that variable in the caller. To avoid this, simply enclose variable names in parentheses, as in the following example function calls:

i = UserFunction(10,12,(j))

If a function is not to receive a parameter by reference, then the optional ByVal keyword can be used:

Function Test(ByVal filename As String) As Stringstatements

End Function

A function returns to the caller when either of the following statements is encountered:

End FunctionExit Function

Functions can be recursive.

Example Function Factorial(n%) As Integer'This function calculates N! (N-factorial).f% = 1For i = n To 2 Step -1

f = f * iNext iFactoral = f

End FunctionSub Main()

'This example calls user-defined function Factorial and displays‘the result in a dialog box.A% = 0

7-74 MicroStation BASIC Guide

Page 225: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 75 Friday, October 15, 1999 1:27 PM

Do While A% < 2A% = MbeInputBox("Enter an integer number greater than 2: ")

NextB = factorial(A)MbeMessageBox "The factorial of " + Str$(A) + " is: " + Str$(B)

End Sub

FvFv#(Rate#, Nper#, Pmt#,Pv#, Due%)

Descr. This function calculates the future value of an annuity based on periodic fixed payments and a constant rate of interest.

An annuity is a series of fixed payments made to an insurance company or other investment company over a period of time. Examples of annuities are mortgages and monthly savings plans.

Fv requires the following parameters:

Rate and NPer values must be expressed in the same units. If Rate is expressed as a percentage per month, then NPer must also be expressed in months. If Rate is an annual rate, then the NPer must also be given in years.

Positive numbers represent cash received, whereas negative numbers represent cash paid out.

Parameter Description

Rate a double-precision number representing the interest rate per period. Make sure that annual rates are normalized for monthly periods (divided by 12).

NPer a double-precision number representing the total number of payments (periods) in the annuity.

Pmt a double-precision number representing the amount of each payment per period. Payments are entered as negative values, whereas receipts are entered as positive values.

Pv a double-precision number representing the present value of your annuity. In the case of a loan, the present value would be the amount of the loan, whereas in the case of a retirement annuity, the present value would be the amount of the fund.

Due indicates when payments are due for each payment period. A 0 specifies payment at the end of each period, whereas a 1 indicates payment at the start of each period.

MicroStation BASIC Guide 7-75

Page 226: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 76 Friday, October 15, 1999 1:27 PM

Example Sub Main()'This example calculates the future value of 100 dollars paid'periodically for a period of 10 years (120 months) at a rate of'10% per year (or .10/12 per month) with payments made on the'first of the month. The value is displayed in a dialog box.'Note that payments are negative values.a# = Fv((.10/12),120,-100.00,0,1)MbeMessageBox "Future value is: " + Format$(a,"Currency")

End Sub

GetGet [#] filenumber% [,recordnumber%], variable

Descr. Retrieves data from a random or binary file and stores that data into the specified variable.

The variable parameter is the name of any variable of any of the following types:

The optional recordnumber parameter specifies which record is to be read from the file. For binary files, this number represents the first byte to be read starting with the beginning of the file (the

Variable type File storage description

Integer 2 bytes are read from the file.

Long 4 bytes are read from the file.

String In binary files, variable-length strings are read by first determining the specified string variable's length and then reading that many bytes from the file.In random files, variable-length strings are read by first reading a 2-byte length and then reading that many characters from the file.

Double 8 bytes are read from file (IEEE format).

Single 4 bytes are read from file (IEEE format).

User-defined Each member of a user-defined data type is read individually.In binary files, variable-length strings within user-defined types are read by first reading a 2-byte length followed by the string's content. This storage is different from variable-length strings outside of user-defined types.When reading user-defined types, the record length must be greater than or equal to the combined size of each element within the data type.

Arrays Arrays cannot be read from a file using the Get statement.

Objects Object variables cannot be read from a file using the Get statement.

7-76 MicroStation BASIC Guide

Page 227: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 77 Friday, October 15, 1999 1:27 PM

first byte is 1). For random files, this number represents the record number starting with the beginning of the file (the first record is 1). This value ranges from 1 to 2147483647. If recordnumber is not specified, the next record is read from the file (if no records have been read yet, then the first record in the file is read). If recordnumber is not specified, the commas must still appear, as in the following example:

Example Get #1,,recvar

If recordnumber is specified, it overrides any previous change in file position specified with the Seek statement.

With random files, a run-time error will occur if the length of the data being read exceeds the reclen parameter specified with the Open statement. If the length of the data being read is less than the record length, the file pointer is advanced to the start of the next record. With binary files, the data elements being read are contiguous—the file pointer is never advanced.

Example Const Crlf = Chr$(13) + Chr$(10)Sub Main()

'This example opens a file for random write, then writes 10'records into the file with the values 10...50. Then the file'is closed and reopened in random mode for read, and the'records are read with the Get statement. The result is displayed'in a dialog box.Open "Test2.Dat" For Random Access Write As #1For X% = 1 to 10

Y% = X * 10Put #1,X,Y

Next XClosePstr$ = ""Open "Test2.Dat" For Random Access Read As #1For Y = 1 to 5

Get #1,y,XPstr = Pstr + "Record " + Str$(Y) + ": " + Str$(X) + crlf

Next YMbeMessageBox PstrClose

End Sub

MicroStation BASIC Guide 7-77

Page 228: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 78 Friday, October 15, 1999 1:27 PM

GetAttrGetAttr%(filename$)

Descr. This function returns an Integer containing the attributes of the specified file.

The attribute value returned is the sum of the attribute bits set for the file. The value of each attribute is as follows:

To determine whether a particular attribute is set, you can And the values shown above with the value returned by GetAttr. If the result is TRUE, the attribute is set.

Example Sub Main()'This example tests to see whether Test2.DAT exists. If it does not,'then it creates the file. The file attributes are then'retrieved with the GetAttr function, and the result is displayed.If Not FileExists("Test2.Dat") Then

Open "Test2.Dat" For Random Access Write As #1Close

End IfMsg$ = ""Y% = GetAttr("Test2.Dat")If Y And ebNone Then Msg = Msg + "No Archive bit is set" + crlfIf Y And ebRead Then Msg = Msg + "The Read-Only bit is set" + crlfIf Y And ebHidden Then Msg = Msg + "The Hidden bit is set" + crlfIf Y And ebSystem Then Msg = Msg + "The System bit is set" + crlfIf Y And ebVolume Then Msg = Msg + "The Volume bit is set" + crlfIf Y And ebDirectory Then Msg = Msg + "The Directory bit is set" + crlfIf Y And ebArchive Then Msg = Msg + "The Archive bit is set"MbeMessageBox Msg

End Sub

Constant Value Includes

ebNormal 0 Read-only, archive, subdir, none

ebReadOnly 1 Read-only files

ebHidden 2 Hidden files

ebSystem 4 System files

ebVolume 8 Volume label

ebDirectory 16 DOS subdirectories

ebArchive 32 Files that have changed since the last backup

ebNone 64 Files with no attributes

7-78 MicroStation BASIC Guide

Page 229: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 79 Friday, October 15, 1999 1:27 PM

GlobalDescr. See Public.

GoSubGoSub label

Descr. This statement causes execution to continue at the specified label. Execution can later be returned to the statement following the GoSub by using the Return statement.

The label parameter must be a label within the current function or subroutine. GoSub outside the context of the current function or subroutine is not allowed.

Example Sub Main()'This example gets a name from the user and then branches‘to a subroutine'to check the input. If the user clicks Cancel or enters a null name,'the program terminates; otherwise, the name is set to Michael,'and a message is displayed.UName$ = Ucase$(MbeInputBox$("Enter your name: "))GoSub CheckNameMbeMessageBox "Hello, " + UNameExit Sub

CheckName:If (UName$ = "") Then

GoSub BlankNameElseIf UName = "MICHAEL" Then

GoSub RightNameElse

GoSub OtherNameEnd IfReturn

BlankName:MbeMessageBox "No name? Clicked Cancel? I'm shutting down"Exit Sub

RightName:Return

OtherName:MbeMessageBox "I am renaming you Michael!"UName = "MICHAEL"Return

End Sub

MicroStation BASIC Guide 7-79

Page 230: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 80 Friday, October 15, 1999 1:27 PM

GotoGoto label

Descr. Transfers execution to the line containing the specified label.

The compiler will produce an error if label does not exist.

The label must appear within the same subroutine or function as the Goto.

Labels must begin with a letter and end with a colon. Keywords cannot be used as labels. Labels are not case-sensitive.

Example Sub Main()'This example gets a name from the user and then branches to‘a statement,'depending on the input name. If the name is not Michael, it is reset'to Michael unless it is null or the user clicks Cancel--in which case,'the program displays a message and terminates.UName$ = Ucase$(MbeInputBox$("Enter your name: "))If Uname = "MICHAEL" Then

Goto RightNameElse

Goto WrongNameEnd If

WrongName:If (UName$ = "") Then

MbeMessageBox "No name? Clicked Cancel? I'm shutting down"Else

MbeMessageBox "I am renaming you Michael!"UName = "MICHAEL"Goto RightName

End IfExit Sub

RightName:MbeMessageBox "Hello, Michael!"

End Sub

Hex$Hex$(number&)

Descr. Returns a string containing the hexadecimal equivalent of the specified number.

The returned string contains only the number of hexadecimal digits necessary to represent the number, up to a maximum of eight.

7-80 MicroStation BASIC Guide

Page 231: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 81 Friday, October 15, 1999 1:27 PM

The number parameter can be any type but is rounded to the nearest whole number before converting to hex. If the passed number is an Integer, then a maximum of four digits are returned; otherwise, up to eight digits can be returned.

Example Sub Main()'This example inputs a number and displays it in decimal and'hex until the input number is 0 or an invalid input.Do

XS$ = MbeInputBox$("Enter a number: ")X = Val(XS)If X <> 0 Then

MbeMessageBox "Dec:" + Str$(X) + " Hex: " + Hex$(X)Else

MbeMessageBox "Terminating program"End If

Loop While X <> 0End Sub

HourHour%(serial#)

Descr. Returns the hour of the day encoded in the specified serial parameter. The value returned is between 0 and 23 inclusive.

Example Sub Main()'This example takes the current time; extracts the hour,'minute, and second; and displays them as the current time.XT# = TimeValue(Time$())XH# = Hour(XT)XM# = Minute(XT)XS# = Second(XT)MbeMessageBox "Current time is: " + Str$(XH)+":"+Str$(XM)+":"+Str$(XS)

End Sub

If...Then...ElseSyntax 1

If condition Then statement [Else statement]

MicroStation BASIC Guide 7-81

Page 232: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 82 Friday, October 15, 1999 1:27 PM

Syntax 2If condition Then

[statement][ElseIf condition Then

[statement]][Else

[statement]]End If

Descr. Conditionally executes a statement or group of statements.

In the single-line version, the statement can either be a single statement, or many statements can be separated using the colon (:).

Example Sub Main()'This example inputs a name from the user and checks to see whether it'is Michael or Mike using three forms of‘the If...Then...Else statement.'It then branches to a statement that displays a welcome message'depending on the user's name.UName$ = Ucase$(MbeInputBox$("Enter your name: "))If UName$ = "MICHAEL" Then GoSub MikeNameIf UName = "MIKE" Then

GoSub MikeNameExit Sub

End IfIf UName = "" Then

MbeMessageBox ("Your name can't be <null>; I'll call you Mike!")UName = "MIKE"GoSub MikeName

ElseIf UName = "MICHAEL" ThenGoSub MikeName

ElseGoSub OtherName

End IfExit Sub

MikeName:MbeMessageBox "Hello, Michael!"Return

OtherName:MbeMessageBox "Hello, " + UName + "!"Return

End Sub

7-82 MicroStation BASIC Guide

Page 233: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 83 Friday, October 15, 1999 1:27 PM

Impexpression1 Imp expression2

Descr. If both operands are relational, then Imp returns the logical implication of expression1 and expression2. Imp returns FALSE when expression1 is TRUE and expression2 is FALSE; otherwise, Imp returns TRUE.

If both operands are numeric, then the result is the bitwise Imp of the arguments.

If either of the two operands is a floating-point number, then the two operands are first converted to Longs, then a bitwise Imp is performed.

For numeric operands, bitwise Imp works as follows:

Example Sub Main()'This example compares the result of two expressions to determine'whether one implies the other.a=10b=20c=30d=40If (a < b) Imp (c < d) Then

MbeMessageBox "a is less than b implies that c is less than d"Else

MbeMessageBox “a is less than b does not imply that c is” + _“less than d”

End IfIf (a < b) Imp (c > d) Then

MbeMessageBox “a is less than b implies that c is” + _“greater than d”

ElseMbeMessageBox “a is less than b does not imply that c is” + _

“greater than d”End If

End Sub

Bit in expression1 Bit in expression2 Bit in result

1 1 1

0 1 1

1 0 0

0 0 1

MicroStation BASIC Guide 7-83

Page 234: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 84 Friday, October 15, 1999 1:27 PM

Input #Input [#]filenumber%, variable[,variable]...

Descr. This statement reads data from the file referenced by filenumber into the given variables.

Each variable must be type-matched to the data in the file. For example, a string variable must be matched to a string in the file.

The following parsing rules are observed while reading each variable in the variable list:

1. Leading white space is ignored (spaces and tabs).

2. When reading strings, if the first character on the line is a quotation mark, then characters are read up to the next quotation mark or the end-of-line, whichever comes first. Blank lines are read as empty strings. If the first character read is not a double quotation mark, then characters are read up to the first comma or the end of the line, whichever comes first. String delimiters (quotation mark, comma or end-of-line) are not included in the returned string.

3. When reading numbers, scanning stops when the first non-numerical character (such as a comma, a letter, or any other unexpected character) is encountered. Numeric errors are ignored while reading numbers from a file. The resultant number is automatically converted to the same type as the variable into which the value will be placed. If there is an error in conversion, then 0 is stored into the variable.

4. End of line is interpreted as either a single line feed or a carriage-return line-feed pair. Thus, text files from any platform can be interpreted using this command.

The filenumber parameter is a number that is used to refer to the open file—the number passed to the Open statement.

filenumber must reference a file opened in Input mode. It is good practice to use the Write statement to write date elements to files read with the Input statement to ensure that the variable list is consistent between the input and output routines.

Example Sub Main()'This example creates a file called Test2.Dat and writes a series of'variables into it. Then the variables are read using‘the Input # function.Open "Test2.Dat" for output as #1C$ = MbeInputBox$("Enter some text: ")A# = 10.0

7-84 MicroStation BASIC Guide

Page 235: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 85 Friday, October 15, 1999 1:27 PM

Write #1,A,C,192, A+20CloseOpen "Test2.Dat" for input as #1Input #1,X%,ST$,Y%,Z%

MbeMessageBox “Recrd: + Str$(X) + " " + ST + " " + Str$(Y) + " " + Str$(Z)Close

End Sub

Input$Input$(numbytes%,[#]filenumber%)

Descr. Returns a character string containing numbytes characters read from a given sequential file.

The Input$ function reads all characters, including spaces and end-of-lines.

The filenumber parameter must reference a file opened in either Input or Binary mode. filenumber is a number that is used to refer to the open file—the number passed to the Open statement.

Example Sub Main()'This example opens the Autoexec.Bat file and displays it in a'dialog box.X = FileLen("C:\Autoexec.Bat")If X > 0 Then

Open "C:\Autoexec.Bat" for input as #1Else

MbeMessageBox "File not found or empty"Exit Sub

End IfIf X > 80 Then

Ins$ = Input$ (80,#1)Else

Ins = Input$ (X,#1)End IfCloseMbeMessageBox "File length: " + Str$(X) + Chr$(13) + Chr$(10) + Ins

End Sub

InStrInStr([start%,] search$, find$ [,compare%])

MicroStation BASIC Guide 7-85

Page 236: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 86 Friday, October 15, 1999 1:27 PM

Descr. Returns the first character position of string find$ within string search$.

If the string is found, then its character position within search$ is returned, with 1 being the character position of the first character.

If start is specified, then the search starts at that character position within search$. The start parameter must be between 1 and 65535. If not specified, then the search starts at the beginning (start = 1).

If the string is not found or start is greater than the length of search$ or search$ is empty, then 0 is returned.

The compare parameter controls how the strings are compared:

If compare is not specified, then string comparisons use the current Option Compare setting. If no Option Compare statement has been encountered, then Binary is used (i.e., string comparisons are case-sensitive).

Example Sub Main()'This example checks to see whether one string is in another and,'if it is, then it copies the string to a variable and displays the'result.A$ = "This string contains the name Stuart and other characters"X% = InStr (A$,"Stuart",0)Y% = InStr (A$,"Stuart",1)If X <> 0 Then

B$ = Mid$(A$,X,6)MbeMessageBox B + " was found--same case"Exit Sub

ElseIf Y <> 0 ThenB$ = Mid$(A$,Y,6)MbeMessageBox B + " was found--different case"ExitSub

ElseMbeMessageBox "String not found"

End IfEnd Sub

IntInt%(number#)

0 String comparisons are case-sensitive.

1 String comparisons are case-insensitive.

Any other value A run-time error is produced.

7-86 MicroStation BASIC Guide

Page 237: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 87 Friday, October 15, 1999 1:27 PM

Descr. This function returns the integer part of a given value by returning the first integer less than the given value, sign is preserved.

Int differs from the Fix function, in that Int truncates negative numbers in a negative direction.

Example Sub Main()'This example extracts the integer part of a number.A# = -1234.5224B% = Int (A)MbeMessageBox "The integer part of -1234.5224 is: " + Str$(B)

End Sub

The output of the previous example is: -1235.

IPmtIPmt#(rate#, per#, nper#, pv#, fv#, due%)

Descr. This function returns the interest payment for a given period of an annuity based on periodic, fixed payments and a fixed interest rate.

An annuity is a series of fixed payments made to an insurance company or other investment company over a period of time. Examples of annuities are mortgages, monthly savings plans and retirement plans.

The following table describes the different parameters:

Parameter Description

Rate A double-precision number that represents the interest rate per period. If the payment periods are monthly, be sure to divide the annual interest rate by 12 to get the monthly rate.

Per A double-precision number that represents the payment period for which you are calculating the interest payment. If you want to know the interest paid or received during period 20 of an annuity, this value would be 20.

NPer A double-precision number that represents the total number of payments in the annuity. This is usually expressed in months, and you should be sure that the interest rate given above is for the same period that you enter here.

Pv A double-precision number that represents the present value of your annuity. In the case of a loan, the present value would be the amount of the loan because that is the amount of cash you have in the present. In the case of a retirement plan, this value would be the current value of the fund because you have a set amount of principal in the plan.

MicroStation BASIC Guide 7-87

Page 238: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 88 Friday, October 15, 1999 1:27 PM

Rate and Nper must be in expressed in the same units. If Rate is expressed in percentage paid per month, then NPer must also be expressed in months. If Rate is an annual rate, then the period given in Nper should also be in years or the annual Rate should be divided by 12 to represent a monthly rate.

If the function returns a negative value, it represents interest you are paying out, whereas positive values represent interest paid to you.

Example Const crlf = Chr$(13) + Chr$(10)Sub Main()

'This example calculates the amount of interest paid‘on a $1,000.00 loan financed over 36 months with an‘annual interest rate of 10%. Payments are due at the beginning of‘the month. The interest paid during the first 10 months‘is displayed in a table.Msg = ""For x = 1 to 10

IPM# = IPmt((.10/12) , x, 36, 1000, 0, 1)Msg = Msg + Format$(X,"00") + " : " + Format$(IPM," 0,0.00") + crlf

Next xMbeMessageBox Msg

End Sub

IRRIRR#(ValueArray#(), Guess#)

Descr. This function returns the internal rate of return for a series of periodic payments and receipts.

The internal rate of return is the equivalent rate of interest for an investment consisting of a series of positive and/or negative cash flows over a period of regular intervals. It is usually used to

Fv A double-precision number that represents the future value of your annuity. In the case of a loan, the future value would be zero because you will have paid it off. In the case of a savings plan, the future value would be the balance of the account after all payments are made.

Due A parameter that indicates when payments are due. If this parameter is 0, then payments are due at the end of each period (usually, the end of the month). If this value is 1, then payments are due at the start of each period (the beginning of the month).

Parameter Description

7-88 MicroStation BASIC Guide

Page 239: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 89 Friday, October 15, 1999 1:27 PM

project the rate of return on a business investment that requires a capital investment up front and a series of investments and returns on investment over time.

IRR requires the following parameters:

The value of IRR is found by iteration. It starts with the value of Guess and cycles through the calculation adjusting Guess until the result is accurate within 0.00001 percent. After 20 tries, if a result cannot be found, IRR fails, and the user must pick a better guess.

Example Const crlf = Chr$(13) + Chr$(10)Sub Main()

'This example illustrates the purchase of a lemonade stand for $800'and a series of incomes from the sale of lemonade over 12 months.'The projected incomes for this example are generated in two'For...Next Loops, and then the internal rate of return is calculated'and displayed. (Not a bad investment!)Dim Valu#(12)Valu(1) = - 800 'initial investmentPStr$ = Str$(Valu(1)) + ", "'Calculate the second through fifth months' sales.For X = 2 To 5

Valu(X) = 100 + (X*2)PStr = PStr + Str$(Valu(X)) + ", "

Next x'Calcluate the sixth through twelfth months' sales.For X = 6 To 12

Valu(X) = 100 + (X*10)PStr = PStr + Str$(Valu(X)) + ", "

Next x'Calcluate the equivalent investment return rate.Retrn# = IRR(Valu,.1)PStr = "The values: " + crlf + PStr + crlf + crlfMbeMessageBox PStr + "Return rate: " + Format$(Retrn,"Percent")

End Sub

Parameter Description

ValueArray() An array of double-precision numbers that represent payments and receipts. Positive values are payments, and negative values are receipts.There must be at least one positive and one negative value to indicate the initial investment (negative value) and the amount earned by the investment (positive value).

Guess A number you guess as the value that the IRR function will return. The most common guess is .1 (10 percent).

MicroStation BASIC Guide 7-89

Page 240: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 90 Friday, October 15, 1999 1:27 PM

Isobject Is [object | Nothing]

Descr. The Is operator returns TRUE if the two operands refer to the same object; otherwise, it returns FALSE.

This operator is used to determine whether two object variables refer to the same object. Both operands must be object variables of the same type (i.e., the same application-defined object type or both of type object).

The reserved word Nothing can be used to determine whether an object variable is uninitialized. Uninitialized object variables reference no object.

Item$Item$(text$, first%, last% [, delimiters$])

Descr. Returns all the items between first and last within the specified formatted text list.

An item is a substring of a delimited text string delimited by commas, end-of-lines or user-defined delimiters. The first parameter specifies the first item in the sequence to return. All items between first and last are returned.

By default, items are separated by commas and end of lines. This can be changed by specifying different delimiters in the delimiters$ parameter.

If first is greater than the number of items in text$, then an empty string is returned.

If last is greater than the number of items in text$, then all items from first to the end of text are returned.

Example Const Crlf = Chr$(13) + Chr$(10)Sub Main()

'This example creates two delimited lists and extracts a range from'each, then displays the result in a dialog box.IList$ = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15"SList$ = "1/2/3/4/5/6/7/8/9/10/11/12/13/14/15"R5List$ = Item$(IList,5,12)R2List$ = Item$(SList,2,9,"/")MbeMessageBox "Returned lists are: " + crlf + R5List + crlf + R2List

End Sub

7-90 MicroStation BASIC Guide

Page 241: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 91 Friday, October 15, 1999 1:27 PM

ItemCountItemCount%(text$ [, delimiters$])

Descr. Returns the number of items in the specified delimited text.

Items are substrings of a delimited text string. By default, items are separated by commas and/or end-of-lines. This can be changed by specifying different delimiters in the delimiters$ parameter. For example, to parse items using a backslash:

n = ItemCount(text$,"\")

Example Sub Main()'This example creates two delimited lists and then counts the number'of items in each. The counts are displayed in a dialog box.IList$ = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15"SList$ = "1/2/3/4/5/6/7/8/9/10/11/12/13/14/15/16/17/18/19"R1% = ItemCount(IList)R2% = ItemCount(SList,"/")

MbeMessageBox “Lists contain: " + Str$(R1) +" and " + Str$(R2) +" items”End Sub

KillKill filespec$

Descr. Deletes all files matching filespec$.

The filespec$ argument can include wild cards, such as * and ?. The * character matches any sequence of zero or more characters, whereas the ? character matches any single character. Multiple *'s and ?'s can appear within the expression to form complex searching patterns. The following table shows some examples:

This pattern Matches these files Doesn’t match these files

*S*.TXT SAMPLE.TXTGOOSE.TXTSAMS.TXT

SAMPLESAMPLE.DAT

C*T.TXT CAT.TXTACATS.TXT

CAP.TXT

C*T CATCAP.TXT

CAT.DOC

MicroStation BASIC Guide 7-91

Page 242: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 92 Friday, October 15, 1999 1:27 PM

Example Sub Main()'This example looks to see whether file Test1.Dat exists.'If it does not, then it creates both Test1 and Test2.Dat.'The existence of the files is tested again; if they exist,'a message is generated, and then they are deleted. The final'test looks to see whether they are still'there and displays the result.If Not FileExists("Test1.Dat") Then

Open "Test1.Dat" For Output As #1Open "Test2.Dat" For Output As #2Close

End IfIf FileExists ("Test1.Dat") Then

MbeMessageBox "File Test1.Dat exists"Kill "Test?.Dat"

End IfIf FileExists ("Test1.Dat") Then

MbeMessageBox "File Test1.Dat still exists"Else

MbeMessageBox "Test?.Dat successfully deleted"End If

End Sub

LBoundLBound%(ArrayVariable() [, dimension%])

Descr. Returns the lower bound of the specified dimension of the specified array variable.

If dimension is not specified, the first dimension is assumed (i.e., dimension = 1).

Example Sub Main()'This example dimensions two arrays and displays their lower bounds.Dim A(5 To 12)Dim B(2 To 100, 9 To 20)LBa = LBound(A)LBb = LBound(B,2)MbeMessageBox “Lowr bnd A: " + Str$(LBa) + " Lowr bnd B: “ + Str$(LBb)'This example uses LBound and UBound to dimension a dynamic array to'hold a copy of an array redimmed by the FileList statement.Dim FL$()

C?T CATCUTCT

CAT.TXTCAPIT

* (All files)

7-92 MicroStation BASIC Guide

Page 243: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 93 Friday, October 15, 1999 1:27 PM

FileList FL,"*.*"count = UBound(FL)Redim NL$(LBound(FL) To UBound(FL))For X = 1 To count

NL(X) = FL(X)Next xMbeMessageBox "The last element of the new array is: " + NL(count)

End Sub

LCase$LCase$(str)

Descr. Returns the lowercase equivalent of the specified string.

Example Sub Main()'This example shows the LCase function used to change uppercase'names to lowercase with an uppercase first letter.Lname$ = "WILLIAMS"Fl$ = Left$(Lname,1)Rest$ = Mid$(Lname,2,Len(Lname))Lname = Fl + LCase$(Rest)MbeMessageBox "The converted name is: " + Lname

End Sub

Left$Left$(str$, NumChars%)

Descr. Returns the leftmost NumChars characters from a given string.

If NumChars is 0, then an empty string is returned.

If NumChars is greater than or equal to the number of characters in the specified string, the entire string is returned.

Example Sub Main()'This example shows the Left$ function used to change uppercase'names to lowercase with an uppercase first letter.Lname$ = "WILLIAMS"Fl$ = Left$(Lname,1)Rest$ = Mid$(Lname,2,Len(Lname))Lname = Fl + LCase$(Rest)MbeMessageBox "The converted name is: " + Lname

End Sub

MicroStation BASIC Guide 7-93

Page 244: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 94 Friday, October 15, 1999 1:27 PM

LenLen%(str$)

Len%(variable)

Descr. Returns the number of characters in a given string, or 0 if the string is empty.

If used with a non-String variable, Len returns the number of bytes occupied by that variable.

When used with user-defined data types, the function returns the combined size of each member within the structure. Since variable-length strings are stored elsewhere, the size of each variable-length string within a structure is 2 bytes.

The following table describes the sizes of the individual data elements:

The Len function always returns 0 with object variables or any application-defined object variable.

Example Const Crl = Chr$(13) + Chr$(10)Sub Main()

'This example shows the Len function used in a routine to change'uppercase names to lowercase with an uppercase first letter.Lname$ = "WILLIAMS"Fl$ = Left$(Lname,1)Ln% = Len(Lname)Rest$ = Mid$(Lname,2,Ln)

Data element Size

Integer 2 bytes.

Long 4 bytes.

Float 4 bytes.

Double 8 bytes.

String Number of characters in the string.

Objects 0 bytes. Both application-defined object variables and variables of type object are always returned as 0 size.

User-defined type

Combined size of each structure member element.

Variable-length strings within structures require 2 bytes of storage. Arrays within structures are fixed in their dimensions. The elements for fixed arrays are stored within the structure and therefore require the number of bytes for each array element multiplied by each array dimension:array_element_size * dimension1 * dimension2...

7-94 MicroStation BASIC Guide

Page 245: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 95 Friday, October 15, 1999 1:27 PM

Lname = Fl + LCase$(Rest)MbeMessageBox "The converted name is: " + Lname'This example returns a table of lengths for standard numeric types.Dim Lns(4)A% = 100B& = 200C! = 200.22D# = 300.22Lns(1) = Len(A)Lns(2) = Len(B)Lns(3) = Len(C)Lns(4) = Len(D)Pstr$ = "Lengths of standard types:" + crlfPstr = Pstr + "Integer: " + Str$(Lns(1)) + crlfPstr = Pstr + "Long: " + Str$(Lns(2)) + crlfPstr = Pstr + "Single: " + Str$(Lns(3)) + crlfPstr = Pstr + "Double: " + Str$(Lns(4)) + crlfMbeMessageBox Pstr

End Sub

Let[Let] variable = expression

Descr. Assigns the result of an expression to a variable.

Let is supported for compatibility with other implementations of BASIC.

Example Sub Main()Let A$ = "This is a String"Let B% = 100Let C# = 1213.3443

End Sub

Likeexpression$ Like pattern$

Descr. The Like operator compares two strings, returning TRUE if expression$ matches the given pattern$. FALSE is returned if the match fails at any point.

Case sensitivity is controlled by the Option Compare setting.

MicroStation BASIC Guide 7-95

Page 246: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 96 Friday, October 15, 1999 1:27 PM

pattern$ can contain special characters that allow more flexible matching:

A range specifies a grouping of characters. To specify a match of any of a group of characters, use the syntax [ABCDE]. To specify a range of characters, use the syntax [A-Z]. Special characters must appear within brackets, such as []*?#.

The following table shows some examples:

Example Sub Main()'This example demonstrates various uses of the Like function.A$ = "This is a string variable of 123456 characters"B$ = "123.45"If A Like "[A-Z][g-i]*" Then MbeMessageBox "Comparison is True"If B Like "##3.##" Then MbeMessageBox "Comparison is True"If A Like "*variable" Then MbeMessageBox "Comparison is True"

End Sub

Line Input #Line Input [#]filenumber%, text$

Descr. This statement reads an entire line into the given string variable text$.

The file is read up to the next end of line, but the end-of-line (EOL) character(s) are not returned in the string. The file pointer is positioned after the terminating end of line.

Character Evaluates to

? Matches a single character.

* Matches one or more characters.

# Matches any digit.

[range] Matches if the character in question is within the specified range.

[!range] Matches if the character in question is not within the specified range.

expression$ pattern$ (True) pattern$ (False)

"MBE" "M*E", "M*" "M* B"

"MicroStation" "M*[a-e]roStation" "M[a-e]ro"

"Version" "V[e]?s*n" "V[r]?s*N"

"5.0" "#.#","#?#" "###", "#?[!0-9]"

"[ABC]" "[[]*]" "[ABC]", "[*]"

7-96 MicroStation BASIC Guide

Page 247: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 97 Friday, October 15, 1999 1:27 PM

The filenumber parameter is a number that is used to refer to the open file—the number passed to the Open statement. filenumber must reference a file opened in Input mode.

The text$ parameter is any string variable reference. This statement will automatically declare the variable if the specified variable has not yet been used or dimensioned.

This statement recognizes either a single line-feed or a carriage-return line-feed pair as the EOL delimiter.

Example Const Crlf = Chr$(13) + Chr$(10)Sub Main()

'This example reads five lines of the Autoexec.Bat file and'displays them in a dialog box.Open "C:\Autoexec.Bat" For Input As #1For X = 1 To 5

Line Input # 1,Lin$Msg$ = Msg + Lin$ + crlf

Next xMbeMessageBox Msg

End Sub

Line$Line$(text$, first%[, last%])

Descr. Returns a single line or a group of lines from a text buffer between first and last.

Lines are delimited by carriage-return line-feed pairs.

If last is not specified, only one line is returned.

If first is greater than the number of lines in text$, an empty string is returned.

If last is greater than the number of lines in text$, all lines from first to the end of the text are returned.

Example Const crlf = Chr$(13) + Chr$(10)Sub Main()

'This example reads five lines of the Autoexec.Bat file, extracts the‘third and fourth lines with the Line$ function, and displays them‘in a dialog box.Txt$ = NullOpen "C:\Autoexec.Bat" For Input As #1For X = 1 To 5

Line Input # 1,Lin$

MicroStation BASIC Guide 7-97

Page 248: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 98 Friday, October 15, 1999 1:27 PM

Txt = Txt + Lin+ crlfNext xLines$ = Line$(Txt,3,4)MbeMessageBox Lines

End Sub

LineCountLineCount%(text$)

Descr. Returns the number of lines in the specified text file.

Lines are delimited by carriage-return, line-feed, or both.

Example Const crlf = Chr$(13) + Chr$(10)Sub Main()

Txt$ = NullX = 1Open "C:\Autoexec.Bat" For Input As #1While (X < 20) And Not EOF(1)

Line Input # 1,Lin$Txt = Txt + Lin + crlfX = X + 1

WendLines! = LineCount(Txt)MbeMessageBox “Number of lines”MbeMessageBox “in Txt is: “ + Str$(Lines) + crlf + crlf + Txt

End Sub

LocLoc%(filenumber%)

Descr. Returns the position of the file pointer in the given file.

The filenumber parameter is a number that is used to refer to the open file—the number passed to the Open statement.

The Loc function returns different values depending on the mode in which the file was opened:

File mode Returns

Input current byte position divided by 128.

Output current byte position divided by 128.

Append current byte position divided by 128.

7-98 MicroStation BASIC Guide

Page 249: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 99 Friday, October 15, 1999 1:27 PM

Example Const crlf = Chr$(13) + Chr$(10)Sub Main()

'This example reads 25 lines of the Autoexec.Bat file, determines the‘current location of the file pointer, and displays it in a‘dialog box.Open "C:\Autoexec.Bat" For Input As #1For X = 1 To 25

If Not EOF(1) ThenLine Input # 1,Lin$Msg$ = Msg + Lin$ + crlf

End IfNext xLc% = Loc(1)CloseMbeMessageBox "The file location is: " + Str$(Lc)

End Sub

LockLock [#] filenumber% [,{record& | [start&] To end&}]

Descr. The Lock statement locks a section of the specified file, preventing other processes from accessing that section of the file until the Unlock statement is issued.

The filenumber parameter is a number that is used to refer to the open file—the number passed to the Open statement.

For sequential files, the record, start and end parameters are ignored. The entire file is locked.

The section of the file is specified using one of the following:

Binary position of the last byte read or written.

Random number of the last record read or written.

Syntax Description

No parameters Lock the entire file (no record specification is given).

record& Lock the specified record number (for Random files) or byte (for Binary files).

to end& Lock from the beginning of the file to the specified record (for Random files) or byte (for Binary files).

start& to end& Lock the specified range of records (for Random files) or bytes (for Binary files).

File mode Returns

MicroStation BASIC Guide 7-99

Page 250: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 100 Friday, October 15, 1999 1:27 PM

The lock range must be the same as that used to subsequently unlock the file range, and all locked ranges must be unlocked before the file is closed. Ranges within files are not unlocked automatically when your script terminates, which can cause file access problems for other processes. It is a good idea to group the Lock and Unlock statements close together in the code, both for readability and so subsequent readers can see that the lock and unlock are performed on the same range. This practice also reduces errors in file locks.

Example Const Crlf = Chr$(13) + Chr$(10)Sub Main()

'This example creates Test2.Dat and fills it with 10 string'variable records. These are displayed in a dialog box. The file'is then reopened for read/write, and each record is locked,'modified, rewritten, and unlocked. The new records are then'displayed in a dialog box.A$ = "This is record number: "B$ = "0"Rec$ = ""Msg$ = ""Open "Test2.Dat" For Random Access Write Shared As #1For x% = 1 To 10

Rec = A + Str$(x)Lock #1,xPut #1,,RecUnlock #1,xMsg = Msg + Rec + crlf

Next xCloseMbeMessageBox "The records are: " + crlf + MsgMsg = ""Open "Test2.Dat" For Random Access Read Write Shared As #1For x = 1 To 10

Rec = Mid$(Rec,1,23) + Str$(11-x)Lock #1,xPut #1,x,RecUnlock #1,xMsg = Msg + Rec + crlf

Next xMbeMessageBox "The records are: " + crlf + MsgClose

End Sub

7-100 MicroStation BASIC Guide

Page 251: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 101 Friday, October 15, 1999 1:27 PM

LofLof%(filenumber%)

Descr. Returns the number of bytes in the given file.

The filenumber parameter is a number that is used to refer to the open file—the number passed to the Open statement.

The file must currently be open.

Example Const Crlf = Chr$(13) + Chr$(10)Sub Main()

'This example creates a test file, writes 10 records into it,'then finds the length of the file and displays it in a message box.A$ = "This is record number: "Rec$ = NullMsg$ = NullOpen "Test2.Dat" For Random Access Write Shared As #1For x% = 1 To 10

Rec = A + Str$(x)Put #1,,RecMsg = Msg + Rec + crlf

Next xCloseOpen "Test2.Dat" For Random Access Read Write Shared As #1X% = Lof(1)CloseMbeMessageBox "The length of Test2.Dat is: " + Str$(X)

End Sub

LogLog#(number#)

Descr. Returns the natural logarithm of a given number.

The value of number must be greater than 0. The value of e is 2.71828.

Example Sub Main()'This example calculates the natural log of 100 and displays it in'a message box.X# = Log(100)MbeMessageBox "The natural logarithm of 100 is: " + Str$(X)

End Sub

MicroStation BASIC Guide 7-101

Page 252: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 102 Friday, October 15, 1999 1:27 PM

LSetLSet dest$ = source$

LSet dest_udt_variable = source_udt_variable

Descr. In syntax 1, the LSet statement copies the source string source$ into the destination string dest$. If source$ is shorter in length than dest$, then the string is left-aligned within dest$, and the remaining characters are padded with spaces. If source$ is longer in length than dest$, then source$ is truncated, copying only the leftmost number of characters that will fit in dest$.

In syntax 2, the source structure is copied byte for byte into the destination structure. This is useful for copying structures of different types. Only the number of bytes of the smaller of the two structures is copied. Neither the source structure nor the destination structure can contain strings.

Example Const Crlf = Chr$(13) + Chr$(10)Sub Main()

'This example replaces a 40-character string of asterisks (*) with'an RSet and LSet string and then displays the result.Dim Msg$, TmpStr$TmpStr = String$(40, "*")Msg = "Here are two strings that have been right-" + crlfMsg = Msg + "and left-justified in a 40-character string"Msg = Msg + crlf + crlfRSet TmpStr = "Right->"Msg = Msg & TmpStr & crlfLSet TmpStr = "<-Left"Msg = Msg & TmpStr & crlfMbeMessageBox Msg

End Sub

LTrim$LTrim$(str$)

Descr. Returns the specified string with leading spaces removed.

Example Const crlf = Chr$(13) + Chr$(10)Sub Main()

'This example displays a right-justified string and its LTrim result.A$ = " <= This is a right-justified string"B$ = LTrim$(A)MbeMessageBox A + crlf + B

End Sub

7-102 MicroStation BASIC Guide

Page 253: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 103 Friday, October 15, 1999 1:27 PM

MainSub Main()

End Sub

Descr. This defines the subroutine that receives execution control from the host application.

Example Sub Main()MbeMessageBox "This is a Main subroutine"

End Sub

Mid$Mid$(str$, start% [, length%])

Mid$(str$, start%[, length%]) = newvalue$

Descr. The Mid$ function returns a substring of the specified string, beginning with start, for length characters. The statement form of Mid$ replaces one part of a string with another.

If length is not specified, then the entire string, starting at start, is returned or replaced.

If start is greater than the length of str$, then an empty string is returned.

The str$ parameter specifies the string variable containing the substring to be copied or replaced. The substring within str$ to be operated on starts at the character position specified by start for length number of characters. If length is not specified, then the rest of the string is assumed.

The newvalue$ parameter is any string or string expression to be inserted into the target string. The resultant string is never longer than the original length of str$.

Example Const Crlf = Chr$(13) + Chr$(10)Sub Main()

'This example displays a substring from the middle of a string'variable using the Mid$ function and replaces the first four'characters with "NEW " using the Mid$ statement.A$ = "This is the Main string containing text"B$ = Mid$(A,13,Len(A$))Mid$ (B,1) = "NEW "MbeMessageBox A + crlf + B

End Sub

MicroStation BASIC Guide 7-103

Page 254: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 104 Friday, October 15, 1999 1:27 PM

MinuteMinute%(serial#)

Descr. Returns the minute of the hour encoded in the specified serial parameter. The value returned is between 0 and 59 inclusive.

Example Sub Main()'This example takes the current time; extracts the hour,'minute, and second; and displays them as the current time.XT# = TimeValue(Time$())XH# = Hour(XT)XM# = Minute(XT)XS# = Second(XT)MbeMessageBox "Current time is: " + Str$(XH)+":"+Str$(XM)+":"+Str$(XS)

End Sub

MIRRMIRR#(ValueArray#(), FinanceRate#, ReinvestRate#)

Descr. This function returns the modified internal rate of return for a series of periodic payments and receipts.

The modified internal rate of return is the equivalent rate of return on an investment in which payments and receipts are financed at different rates. The interest cost of investment and the rate of interest received on the returns on investment are both factors in the calculations.

The MIRR function requires the following parameters:

FinanceRate and ReinvestRate should be expressed as percentages. For example, 11 percent should be expressed as 0.11.

Parameter Description

ValueArray() An array of double-precision numbers representing the payments and receipts. Positive values are payments (invested capital), and negative values are receipts (returns on investment).There must be at least one positive (investment) value and one negative (return) value

FinanceRate A double-precision number representing the interest rate paid on invested monies (paid out).

ReinvestRate A double-precision number representing the rate of interest received on incomes from the investment (receipts).

7-104 MicroStation BASIC Guide

Page 255: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 105 Friday, October 15, 1999 1:27 PM

To return the correct value, be sure to order your payments and receipts in the correct sequence.

Example Const crlf = Chr$(13) + Chr$(10)Sub Main()

'This example illustrates the purchase of a lemonade stand for $800'financed with money borrowed at 10%. The returns are estimated to'accelerate as the stand gains popularity. The proceeds are placed'in a bank at 9 percent interest. The incomes are estimated'(generated) over 12 months. This program first generates the'income stream array in two For...Next loops, and then the modified'internal rate of return is calculated and displayed. Notice that the‘annual rates are normalized to monthly rates by dividing them by 12.Dim Valu#(12)Valu(1) = -800 'initial investmentPStr$ = Str$(Valu(1)) + ", "For X = 2 To 5

Valu(X) = 100 + (X*2) 'incomes months 2-5PStr = PStr + Str$(Valu(X)) + ", "

Next xFor X = 6 To 12

Valu(X) = 100 + (X*10) 'incomes months 6-12PStr = PStr + Str$(Valu(X)) + ", "

Next xRetrn# = MIRR (Valu,.1/12,.09/12) 'note: normalized annual ratesPStr = "The values: " + crlf + PStr + crlf + crlfMbeMessageBox PStr + "Modified rate: " + Format$(Retrn,"Percent")

End Sub

MkDirMkDir dir$

Descr. Creates a new directory as specified by dir$.

Example Sub Main()'This example creates a new directory on the default drive. If'this causes an error 70, then the directory already exists and'the program terminates. If no error, the directory is removed'with the RmDir statement.On Error Resume NextMkDir "TestDir"If Err = 70 Then 'Check whether directory exists.

Msg$ = "Directory exists! Error: " + Str$(Err)RmDir "TestDir"

ElseMsg = "TestDir created. Error: " + Str$(Err)

End If

MicroStation BASIC Guide 7-105

Page 256: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 106 Friday, October 15, 1999 1:27 PM

MbeMessageBox MsgEnd Sub

Modexpression1 Mod expression2

Descr. Returns the remainder of expression1 /expression2 as a whole number.

Both operands are converted to whole numbers before performing the modulo operation.

Example Const crlf = Chr$(13) + Chr$(10)Sub Main()

'This example uses the Mod operator to determine the value of a'randomly selected card where card 1 is the ace (1) of clubs and'card 52 is the king (13) of spades. Since the values recur in a'sequence of 13 cards within 4 suits, we can use the Mod function to'determine the value of any given card number.CVal$="ACE,TWO,THREE,FOUR,FIVE,SIX,SEVEN,EIGHT,NINE,TEN,JACK,QUEEN,KING"RandomizeCard% = Random(1,52)Value = Card Mod 13If Value = 0 Then Value = 13CardNum$ = Item$(Cval,Value)If Card < 53 Then Suit$ = "spades"If Card < 40 Then Suit$ = "hearts"If Card < 27 Then Suit$ = "diamonds"If Card < 14 Then Suit$ = "clubs"Msg$ = "Card number " + Str$(Card) + " is the "Msg$ = Msg$ + CardNum + " of " + SuitMbeMessageBox Msg

End Sub

MonthMonth%(serial#)

Descr. Returns the month of the date encoded in the specified serial parameter. The value returned is between 1 and 12 inclusive. The serial value for a text formatted date can be obtained with the DateValue function.

Example Sub Main()'This example returns the current month in a dialog box.Mons$ = "Jan., Feb., Mar., Apr., May, Jun., Jul., Aug., Sep., Oct., Nov

., Dec."Tdate$ = Date$TDay! = Month(DateValue(Tdate))

7-106 MicroStation BASIC Guide

Page 257: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 107 Friday, October 15, 1999 1:27 PM

MbeMessageBox ("The current month is: " + Item$(Mons,TDay))End Sub

NameName oldfile$ As newfile$

Descr. Renames a file.

Each parameter must specify a single filename. Wild-card characters such as * and ? are not allowed.

Example Sub Main()'This example creates a file called Test.Dat and then renames'it to Test2.Dat.On Error Resume NextIf FileExists ("Test.Dat") Then

Name "Test.Dat" As "Test2.Dat"If Err <> 0 Then

Msg$ = "File exists and cannot be renamed! Error: " + Str$(Err)Else

Msg = "File exists and renamed to Test2.Dat"End If

ElseOpen "Test.Dat" For Output As #1CloseName "Test.Dat" As "Test2.Dat"If Err <> 0 Then

Msg$ = "File created but not renamed! Error: " + Sr$(Err)Else

Msg = "File created and renamed to Test2.Dat"End If

End IfMbeMessageBox Msg

End Sub

NotNot expression1

Descr. TRUE if expression1 is FALSE; otherwise, returns FALSE.

If the operand is numeric, then the result is the bitwise Not of the argument.

If the operand is a floating-point value (either Single or Double), it is first converted to a Long, then a bitwise Not is performed.

MicroStation BASIC Guide 7-107

Page 258: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 108 Friday, October 15, 1999 1:27 PM

Example Const crlf = Chr$(13) + Chr$(10)Sub Main()

'This example demonstrates the use of the Not operator in comparing'logical expressions and for switching a True/False toggle variable.A = TrueB = FalseSWITCH = TrueIf (A and Not B) And (Not (A = B)) Then

Msg$ = "A And Not B = True" + crlfElse

Msg = "A And Not B = False" + crlfEnd IfMsg = Msg + "Switch is now " + Format$(Switch,"True/False") + crlfSwitch = Not SwitchMsg = Msg + "Switch is now " + Format$(Switch,"True/False") + crlfSwitch = Not SwitchMsg = Msg + "Switch is now " + Format$(Switch,"True/False")MbeMessageBox Msg

End Sub

NowNow#[()]

Descr. The Now function returns a double-precision number representing the current date and time. The number is returned in days where Dec 30, 1899, is 0.

Example Sub Main()'This example shows how the Now function can be used as an elapsed-'time counter.T1# = Now()MbeMessageBox "Wait a while and click OK"T2# = Now()T3# = Second(T2) - Second(T1)MbeMessageBox "Elapsed time was: " + Str$(T3) + " seconds"

End Sub

NPerNPer#(Rate#, Pmt#, Pv#, Fv#, Due%)

Descr. This function returns the number of periods for an annuity based on periodic fixed payments and a constant rate of interest.

An annuity is a series of fixed payments paid to or received from an investment over a period of time. Examples of annuities are mortgages, retirement plans, monthly savings plans, and term loans.

7-108 MicroStation BASIC Guide

Page 259: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 109 Friday, October 15, 1999 1:27 PM

NPer requires the following parameters:

Positive numbers represent cash received, whereas negative numbers represent cash paid out.

Example Sub Main()'This example calculates the number of $100.00 monthly payments‘necessary to accumulate $10,000.00 at an annual rate of 10%. Payments‘are made at the beginning of the month.ag# = NPer((.10/12),100,0,10000,1)MbeMessageBox "Number of monthly periods is: " + Format$(ag,"Standard")

End Sub

Parameter Description

Rate A double-precision number representing the interest rate per period. If the periods are monthly, be sure to normalize annual rates by dividing them by 12.

Pmt A double-precision number representing the amount of each payment or income. Income is represented by positive values, whereas payments are represented by negative values.

Pv A double-precision number representing the present value of your annuity. In the case of a loan, the present value would be the amount of the loan, and the future value (see below) would be zero.

Fv A double-precision number representing the future value of your annuity. In the case of a loan, the future value would be zero, and the present value would be the amount of the loan.

Due Parameter that indicates when payments are due for each payment period. A 0 specifies payment at the end of each period, whereas a 1 indicates payment at the start of each period.

MicroStation BASIC Guide 7-109

Page 260: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 110 Friday, October 15, 1999 1:27 PM

NpvNpv#(Rate#, ValueArray#())

Descr. This function calculates the net present value of an annuity based on periodic payments and receipts, and a discount rate.

Npv requires the following parameters:

Positive numbers represent cash received, whereas negative numbers represent cash paid out.

For accurate results, be sure to enter your payments and receipts in the correct order, as Npv uses the order of the array values to interpret the order of the payments and receipts.

If your first cash flow occurs at the beginning of the first period, that value must be added to the return value of Npv. It should not be included in the array of cash flows.

Npv differs from the Pv function in that the payments are due at the end of the period and the cash flows are variable. Pv's cash flows are constant, and payment may be made at either the beginning or end of the period.

Example Const crlf = Chr$(13) + Chr$(10)Sub Main()

'This example illustrates the purchase of a lemonade stand for $800'financed with money borrowed at 10%. The returns are estimated to'accelerate as the stand gains popularity. The incomes are estimated'(generated) over 12 months. This program first generates the income'stream array in two For...Next loops, and then the net present value'(Npv) is calculated and displayed. Note normalization of the annual‘10% rate.Dim Valu#(12)Valu(1) = -800 'initial investmentPStr$ = Str$(Valu(1)) + ", "For X = 2 To 5 'months 2-5

Valu(X) = 100 + (X*2)

Parameter Description

Rate A double-precision number that represents the interest rate over the length of the period. If the values are monthly, annual rates must be divided by 12 to normalize them to monthly rates.

ValueArray() An array of double-precision numbers representing the payments and receipts. Positive values are payments, and negative values are receipts.There must be at least one positive and one negative value.

7-110 MicroStation BASIC Guide

Page 261: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 111 Friday, October 15, 1999 1:27 PM

PStr = PStr + Str$(Valu(X)) + ", "Next xFor X = 6 To 12 'months 6-12

Valu(X) = 100 + (X*10) 'accelerated incomePstr = PStr + Str$(Valu(X)) + ", "

Next xNetVal# = NPV ((.10/12),Valu)PStr = "The values: " + crlf + PStr + crlf + crlfMbeMessageBox PStr + "Net present value: " + Format$(NetVal,"Currency")

End Sub

NullNull[()]

Descr. Returns a null string (a string that contains no characters and requires no storage).

An empty string ("") can also be used to remove all characters from a string. However, empty strings still require some memory for storage. Null strings require no memory.

Example Sub Main()'This example shows how the Null function can be used to initialize'and reset strings.A$ = Null()B$ = "This string is several characters long"MbeMessageBox "A: >" + A + "< B: =>" + B + "<="B = NullMbeMessageBox "A: =>" + A + "<= B: =>" + B + "<="

End Sub

Oct$Oct$(number%)

Descr. Returns a string containing the octal equivalent of the specified number.

The returned string contains only the number of octal digits necessary to represent the number.

The number parameter can be any type but is rounded to the nearest whole number before converting to the octal equivalent.

Example Const crlf = Chr$(13) + Chr$(10)Sub Main()

'This example displays the octal equivalent of several numbers.St$ = "The octal values are: " + crlfFor X% = 1 To 5

MicroStation BASIC Guide 7-111

Page 262: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 112 Friday, October 15, 1999 1:27 PM

Y% = X * 10St = St + Str$(Y) + " : $" + Oct$(Y) + crlf

Next xMbeMessageBox St

End Sub

On ErrorOn Error {Goto label | Resume Next | Goto 0}

Descr. Defines the action taken when a trappable run-time error occurs.

The form On Error Goto label causes execution to transfer to the specified label when a run-time error occurs.

The form On Error Resume Next causes execution to continue at the next line after the line that caused the error.

The form On Error Goto 0 causes any existing error trap to be removed.

If an error trap is in effect when the macro ends, then an error will be generated.

An error trap is only active within the subroutine or function in which it appears.

Once an error trap has gained control, appropriate action should be taken, and then control should be resumed using the Resume statement. Resume resets the error handler and continues execution. If a procedure ends while an error is pending, then an error will be generated. (The Exit Sub or Exit Function statement also resets the error handler, allowing a procedure to end without displaying an error message.)

Errors within an Error Handler

If an error occurs within the error handler, then the error handler of the caller (or any procedure in the call stack) will be invoked. If there is no such error handler, then the error is fatal, causing the macro to stop executing. The following statements reset the error state (i.e., these statements turn off the fact that an error occurred):

ResumeErr=-1

7-112 MicroStation BASIC Guide

Page 263: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 113 Friday, October 15, 1999 1:27 PM

Resume forces execution to continue either on the same line or on the line following the line that generated the error. The Err=-1 statement allows explicit resetting of the error state so that the script can continue normal execution without resuming to the statement that caused the error condition.

The On Error statement will not reset the error. Thus, if an On Error statement occurs within an error handler, it has the effect of changing the location of a new error handler for any new errors that may occur once the error has been reset.

Example Sub Main()'This example tries to create a new subdirectory in the current path.'If it is successful, then it displays a message "Directory created."'Otherwise, it executes the error trap and changes the message. After'performing this twice, the error trap is reset to Resume Next,'which ignores the error (if any) and tries to remove the directory.'If there is an error, the next line resets the error trap with On'Error Goto 0, and the RmDir is executed again (to create an error'for this example). The last RemDir statement will cause a run-time'error that is not trapped.Msg$ = NullOn Error Goto DirErrorFor X = 1 To 2

Msg = "Directory created"MkDir "TestDir"MbeMessageBox Msg

Next xRmDir "TestDir"On Error Resume NextRmDir "TestDir"MbeMessageBox "No error trap: RmDir failed"On Error Goto 0RmDir "TestDir"Exit Sub

DirError:If Err = 70 Then

Msg$ = "Directory exists! Error: " + Str$(Err)RmDir "TestDir"Resume Next

ElseMsg$ = "Unspecified error (remove directory)! " + Str$(Err)Resume Next

End IfEnd Sub

MicroStation BASIC Guide 7-113

Page 264: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 114 Friday, October 15, 1999 1:27 PM

OpenOpen filename$ [For mode] [Access accessmode] [lock] As [#] filenumber% _ [Len = reclen%]

Descr. The Open statement opens a file for a given mode, assigning the open file to the supplied filenumber.

The filename$ parameter is a string expression that contains a valid filename. filenumber is a number between 1 and 255. The FreeFile function can be used to determine an available file number.

The mode parameter determines the type of operations that can be performed on that file:

If mode is missing, Random is used.

The accessmode parameter determines what type of I/O operations can be performed on the file:

File mode Description

Input Opens an existing file for sequential input (filename$ must exist). The value of accessmode, if specified, must be Read.

Output Open an existing or create a new file for sequential output, truncating its length to zero. The value of accessmode, if specified, must be Write.

Append Open an existing or create a new file for sequential output, positioning the file pointer at the end of the file. The value of accessmode, if specified, must be Read Write.

Binary Open existing or create a new file for binary I/O. Existing binary files are never truncated in length. The value of accessmode, if specified, determines how the file can subsequently be accessed.

Random Open existing or create a new file for record I/O. Existing random files are truncated only if accessmode is Write. The reclen parameter determines the record length for I/O operations.

Access Description

Read Opens the file for reading only. This value is valid only for files opened in Binary, Random or Input mode.

Write Opens the file for writing only. Opening a file in Random mode with accessmode set to Write truncates the file's length to 0. This value is valid only for files opened in Binary, Random or Output mode.

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

7-114 MicroStation BASIC Guide

Page 265: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 115 Friday, October 15, 1999 1:27 PM

If accessmode is not specified, the following defaults are used:

The lock parameter determines what access rights are granted to other processes that attempt to open the same file. If lock is not specified, the file is opened in compatibility mode (i.e., only the current process can access the file). The following table describes the values for lock:

If the file does not exist and lock is specified, the file is opened twice—once to create the file and again to establish the correct sharing mode.

Files opened in Random mode are divided up into a sequence of records, each of the length specified by the reclen parameter. If this parameter is missing, then 128 used. For files opened for sequential I/O, reclen specifies the size of the internal buffer when performing I/O. Larger buffers mean faster file access. For Binary files, reclen is ignored.

Example Sub Main()'This example opens several files in various configurations.Open "Test1.Dat" For Output Access Write Lock Write As #2Close

File mode Default value for accessmode

Input Read

Output Write

Append Read Write

Binary When the file is initially opened, access is attempted three times in the following order:1. Read Write2. Write3. Read

Random Same as Binary files

Lock value Description

Shared Another process can both read this file and write to it. (Deny none)

Lock Read Another process can write to this file but not read it. (Deny read)

Lock Write Another process can read this file but not write to it. (Deny write)

Lock Read Write Another process is prevented both from reading this file and from writing to it. (Exclusive)

MicroStation BASIC Guide 7-115

Page 266: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 116 Friday, October 15, 1999 1:27 PM

Open "Test1.Dat" For Input Access Read Shared As #1CloseOpen "Test1.Dat" For Append Access Write Lock Read Write as #3CloseOpen "Test1.Dat" For Binary Access Read Write Shared As #4CloseOpen "Test1.Dat" For Random Access Read Write Lock Read As #5CloseOpen "Test1.Dat" For Input Access Read Write Shared As #6CloseKill "Test1.Dat"

End Sub

Option BaseOption Base {0 | 1}

Descr. This statement sets the lower bound for array declarations. By default, the lower bound used for all array declarations is 0.

This statement must appear outside of any functions or subroutines.

Example Option Base 1Sub Main()

Dim a(10) Contains 10 elements (not 11).End Sub

Option CompareOption Compare [Binary | Text]

Descr. The Option Compare statement controls how strings are compared.

When Option Compare is set to Binary, string comparisons are case-sensitive (i.e., ‘A’ does not equal ‘a’). When it is set to Text, string comparisons are case-insensitive (i.e., ‘A’ is equal to ‘a’).

The default value for Option Compare is Binary.

Option Compare affects all string comparisons in any statements that follow it. Additionally, the setting affects the default behavior of Instr, StrComp and the Like operator. The following table shows the types of string comparisons affected by this setting:

> < <>

7-116 MicroStation BASIC Guide

Page 267: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 117 Friday, October 15, 1999 1:27 PM

Option Compare must appear outside the scope of all subroutines and functions. In other words, it cannot appear within a Sub or Function block.

Example 'This example shows the use of Option Compare.Option Compare BinarySub CompareBinary

A$ = "This String Contains UPPERCASE"B$ = "this string contains uppercase"If A = B Then

MbeMessageBox "The two strings were compared case-insensitive"Else

MbeMessageBox "The two strings were compared case-sensitive"End if

End SubOption Compare TextSub CompareText

A$ = "This String Contains UPPERCASE"B$ = "this string contains uppercase"If A = B Then

MbeMessageBox "The two strings were compared case-insensitive"Else

MbeMessageBox "The two strings were compared case-sensitive"End if

End SubSub Main()

CompareBinary 'Calls subroutine above.CompareText 'Calls subroutine above.

End Sub

Orexpression1 Or expression2

Descr. True if either expression1 or expression2 is TRUE; otherwise, FALSE.

If both operands are numeric, the result is the bitwise Or of the arguments.

If either operand is a floating-point number, both operands are first converted to Longs, then a bitwise Or is performed.

Example Sub Main()'Uses the Or operator in a logical comparison.

<= >= Instr

StrComp Like

MicroStation BASIC Guide 7-117

Page 268: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 118 Friday, October 15, 1999 1:27 PM

A$ = "First line"B$ = "Second line"If (A = "First line") Or (B = "Another line") Then

MbeMessageBox "The comparison is True"Else

MbeMessageBox "The comparison is False"End If'Constructs a truth table for the Or statement.Msg$ = NullFor X% = True To False

For Y% = True To FalseZ = X Or YMsg = Msg + Format$(Abs(X),"0") + " Or "Msg = Msg + Format$(Abs(Y),"0") + " = "Msg = Msg + Format$(Z,"True/False") + crlf

Next yNext xMbeMessageBox Msg

End Sub

PIPI

Descr. 3.141592653589793238462643383279. PI can also be determined using the following formula:

4 * Atn(1)

Example Const crlf = Chr$(13) + Chr$(10)Sub Main()

'This example illustrates the use of the PI constant.Dia# = 5Circ# = PI * DiaArea# = PI * ((Dia / 2) ^ 2)Msg$ = "Diameter: 5" + crlfMsg = Msg + "Circumference: " + Format$(Circ,"Standard") + crlfMsg = Msg + "Area: " + Format$(Area,"Standard")MbeMessageBox Msg

End Sub

PmtPmt#(Rate#, NPer#, Pv#, Fv#, Due%)

7-118 MicroStation BASIC Guide

Page 269: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 119 Friday, October 15, 1999 1:27 PM

Descr. The Pmt function returns the payment for an annuity based on fixed, periodic payments and a constant interest rate.

An annuity is a series of fixed payments made to an insurance company or other investment company over a period of time. Examples of annuities are mortgages and monthly savings plans.

Pmt requires the following parameters:

Rate and NPer must be expressed in the same units. If Rate is expressed in months, then NPer must also be expressed in months.

Positive numbers represent cash received, whereas negative numbers represent cash paid out.

Example Sub Main()'This example calculates the payment necessary to repay a $1,000.00‘loan over 36 months at an annual rate of 10%. Payments are due at‘the beginning of the period.X = Pmt((.1/12),36,1000.00,0,1)Msg$ = "The payment to amortize $1,000 over 36 months @ 10% is: "MbeMessageBox Msg + Format$(X,"Currency")

End Sub

PPmtPPmt#(Rate#, Per#, NPer#, Pv#, Fv#, Due%)

Parameter Description

Rate A double-precision number representing the interest rate per period. If the periods are given in months, be sure to normalize annual rates by dividing them by 12.

NPer A double-precision number representing the total number of payments in the annuity.

Pv A double-precision number representing the present value of your annuity. In the case of a loan, the present value would be the amount of the loan.

Fv A double-precision number representing the future value of your annuity. In the case of a loan, the future value would be 0.

Due Parameter that indicates when payments are due for each payment period. A 0 specifies payment at the end of each period, whereas a 1 specifies payment at the start of each period.

MicroStation BASIC Guide 7-119

Page 270: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 120 Friday, October 15, 1999 1:27 PM

Descr. The PPmt function calculates the principal payment for a given period of an annuity based on fixed, periodic payments and a constant interest rate.

An annuity is a series of fixed payments made to an insurance company or other investment company over a period of time. Examples of annuities are mortgages and monthly savings plans.

PPmt requires the following parameters:

Rate and NPer must be in the same units to calculate correctly. If Rate is expressed in months, NPer must also be expressed in months.

Negative values represent payments paid out, whereas positive values represent payments received.

Example Const crlf = Chr$(13) + Chr$(10)Sub Main()

'This example calculates the principal paid during each year on a‘loan of $1,000.00 with an annual rate of 10%. The result is displayed‘as a table containing the following information: payment, principal‘payment, principal 'balance.Pay = Pmt(.1,10,1000.00,0,1)Msg$ = "Amortization table for 1,000" + crlf + "at 10% annually for"Msg = Msg + " 10 years: " + crlf + crlfBal = 1000.00For Per = 1 to 10

Prn = PPmt(.1,Per,10,1000,0,0)Bal = Bal + PrnMsg = Msg + Format$(Pay,"Currency") + " " + Format$(Prn,"Currency")

Parameter Description

Rate a double-precision number representing the interest rate per period.

Per a double-precision number representing the number of payment periods. Per can be no less than 1 and no greater than NPer.

NPer a double-precision number representing the total number of payments in the annuity.

Pv a double-precision number representing the present value of annuity. In the case of a loan, the present value would be the amount of the loan.

Fv a double-precision number representing the future value of your annuity. In the case of a loan, the future value would be 0.

Due indicates when payments are due. If 0, then payments are due at the end of each period; if 1, then payments are due at the start of each period.

7-120 MicroStation BASIC Guide

Page 271: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 121 Friday, October 15, 1999 1:27 PM

Msg = Msg + " " + Format$(Bal,"Currency") + crlfNext PerMbeMessageBox Msg

End Sub

PrintPrint [[{Spc(n) | Tab(n)}][expressionlist][{; | ,}]]

Descr. The Print statement prints data to an output device.

The actual output device depends on the platform on which BASIC is running.

Strings are written in their literal form, with no enclosing quotes.

Integers and Longs are written with an initial space reserved for the sign (space = positive). Additionally, there is a space following each number.

Each expression in expressionlist is separated with a comma ‘,’ or semicolon ‘;’. A comma means that the next expression is output in the next print zone. A semicolon means that the next expression is output immediately after the current expression. Print zones are defined every 14 spaces.

If the last expression in the list is not followed by a comma or a semicolon, a carriage return is printed to the file. If the last expression ends with a semicolon, no carriage return is printed. The next Print statement will output information immediately following the expression. If the last expression in the list ends with a comma, the file pointer is positioned at the start of the next print zone on the current line.

The Tab and Spc functions provide additional control over the column position. Tab moves the file position to the specified column, whereas Spc outputs the specified number of spaces.

Example Sub Main()'The next example opens a viewport and prints some data.Viewport.Openi% = 10s$ = "This is a test"Print "The value of i=";i%,"the value of s=";s$'Print the value of i% in print zone 1 and s$ in print zone 3.Print i%,,s$'Print the value of i% and s$ separated by 10 spaces.Print i%;Spc(10);s$

MicroStation BASIC Guide 7-121

Page 272: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 122 Friday, October 15, 1999 1:27 PM

'Print the value of i in column 1 and s$ in column 30.Print i%;Tab(30);s$'Print the value of i% and s$...Print i%;s$,Print 67

End Sub

Print#Print filenumber%, [[{Spc(n) | Tab(n)}][expressionlist][{;|,}]]

Descr. Writes data to a sequential disk file.

filenumber is a number used to refer to the open file—the number passed to the Open statement.

Strings are written in their literal form, with no enclosing quotes.

Integers and Longs are written with an initial space reserved for the sign (space = positive). Additionally, there is a space following each number.

Each expression in expressionlist is separated with a comma ‘,’ or semicolon ‘;’. A comma means that the next expression is output in the next print zone. A semicolon means that the next expression is output immediately after the current expression. Print zones are defined every 14 spaces.

If the last expression in the list is not followed by a comma or semicolon, then an end-of-line is printed to the file. If the last expression ends with a semicolon, no end of line is printed. The next Print statement will output information immediately following the expression. If the last expression in the list ends with a comma, the file pointer is positioned at the start of the next print zone on the current line.

The Write statement always outputs information ending with an end-of-line. Thus, if a Print statement is followed by a Write , the file pointer is positioned on a new line. Print can only be used with files that are opened in Output or Append mode.

The Tab and Spc functions provide additional control over the file position. Tab moves the file position to the specified column, whereas Spc outputs the specified number of spaces.

Example Sub Main()'The next example opens a file and prints some data.Open "Test.Dat" For Output As #1

7-122 MicroStation BASIC Guide

Page 273: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 123 Friday, October 15, 1999 1:27 PM

i% = 10s$ = "This is a test"Print #1,"The value of i=";i%,"the value of s=";s$'Print the value of i% in print zone 1 and s$ in print zone 3.Print #1,i%,,s$'Print the value of i% and s$ separated by 10 spaces.Print #1,i%;Spc(10);s$'Print the value of i in column 1 and s$ in column 30.Print #1,i%;Tab(30);s$'Print the value of i% and s$...Print #1,i%;s$,Print #1,67Close #1

End Sub

PrivatePrivate name [(subscripts)] [As type] [, name [(subscripts)] [As type]]...

Descr. Declares a list of private variables and their corresponding types and sizes.

Private variables are global to every subroutine and function within the currently executing macro.

If a type-declaration character is used when specifying name (such as %, &, $ or !), the optional [As type] expression is not allowed. For example, the following are allowed:

Private foo As IntegerPrivate foo%

subscripts allows the declaration of arrays. This parameter uses the following syntax:

[lower To] upper [,[lower To] upper]...

The lower and upper parameters are integers specifying the lower and upper bounds of the array. If lower is not specified, then the lower bound as specified by Option Base is used (or 0 if no Option Base statement has been encountered). Up to 60 array dimensions are allowed.

The total size of an array (not counting space for strings) is limited to 64K.

Dynamic arrays are declared by not specifying any bounds:

Private a()

MicroStation BASIC Guide 7-123

Page 274: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 124 Friday, October 15, 1999 1:27 PM

type specifies the data type of the item being declared. It can be any of the following data types: String, Integer, Long, Single, Double, object, application-defined object, application-defined data type, or any user-defined data type.

If a variable is seen that has not been explicitly declared with either Dim, Public or Private, then it will be implicitly declared local to the routine in which it is used.

See also Public.

PublicPublic name [(subscripts)] [As type] [, name [(subscripts)] [As type]]...

Descr. Declares a list of public variables and their corresponding types and sizes.

Public variables are global to all Subs and Functions in all loaded macros.

If a type-declaration character is used when specifying name (such as %, &, $ or !), the optional [As type] expression is not allowed. For example, the following are allowed:

Public foo As IntegerPublic foo%

subscripts allows the declaration of arrays. This parameter uses the following syntax:

[lower To] upper [,[lower To] upper]...

lower and upper are integers specifying the lower and upper bounds of the array. If lower is not specified, then the lower bound as specified by Option Base is used (or 0 if no Option Base statement has been encountered). Up to 60 array dimensions are allowed.

The total size of an array (not counting space for strings) is limited to 64K.

Dynamic arrays are declared by not specifying any bounds:

Public a()

type specifies the type of the data item being declared. It can be any of the following data types: String, Integer, Long, Single, Double, object, application-defined object, application-defined data type, or any user-defined data type.

7-124 MicroStation BASIC Guide

Page 275: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 125 Friday, October 15, 1999 1:27 PM

If a variable is seen that has not been explicitly declared with either Dim, Public or Private, then it will be implicitly declared local to the routine in which it is used.

For compatibility, the keyword Global is also supported—it has the same meaning as Public.

Example 'This example uses a subroutine to calculate the area of 10 circles'and displays the result in a dialog box. The variables R and Ar are‘declared as Public variables so that they can be used in both Main‘and Area.Public R#,Ar#Sub Area()

Ar = (R ^ 2) * PiEnd SubSub Main()

Msg$ = NullFor X = 1 To 10

R = XAreaMsg = Msg + Str$(R) + " : " + Str$(Ar) + crlf

Next xMbeMessageBox Msg

End Sub

PutPut [#] filenumber% , [recordnumber%], variable

Descr. Writes data from the specified variable to a Random or Binary file.

variable is the name of any variable of any of the following types:

Variable type File storage description

Integer 2 bytes are written to the file.

Long 4 bytes are written to the file.

String In Binary files, variable-length strings are written by first determining the specified string variable's length, then writing that many bytes to the file.In Random files, variable-length strings are written by first writing a 2-byte length, then writing that many characters to the file.

Double 8 bytes are written to the file (IEEE format).

Single 4 bytes are written to the file (IEEE format).

MicroStation BASIC Guide 7-125

Page 276: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 126 Friday, October 15, 1999 1:27 PM

The optional recordnumber parameter specifies which record is to be written to the file. For Binary files, this number represents the first byte to be written starting with the beginning of the file (the first byte is 1). For Random files, this number represents the record number starting with the beginning of the file (the first record is 1). This value ranges from 1 to 2147483647. If recordnumber is not specified, the next record is written to the file (if no records have been written yet, then the first record in the file is written). If recordnumber is not specified, the commas must still appear, as in the following example:

Put #1,,recvar

If recordlength is specified, it overrides any previous change in file position specified with the Seek statement.

With Random files, a run-time error will occur if the length of the data being written exceeds the record length (specified as the reclen parameter with the Open statement). If the length of the data being written is less than the record length, the entire record is written along with padding (whatever data happens to be in the I/O buffer at that time). With Binary files, the data elements are written contiguously. The data elements are never separated with padding.

Example Const crlf = Chr$(13) + Chr$(10)Sub Main()

'This example opens a file for random write, then writes 10'records into the file with the values 10...50. Then the file'is closed and reopened in random mode for read, and the'records are read with the Get statement. The result is displayed'in a dialog box.Open "Test2.Dat" For Random Access Write As #1For X% = 1 To 10

Y% = X * 10

User-defined types

Each member of a user-defined data type is written individually.In Binary files, variable-length strings within user-defined types are written by first writing a 2-byte length followed by the string's content. This storage is different than variable-length strings outside of user-defined types.When writing user-defined types, the record length must be greater than or equal to the combined size of each element within the data type.

Arrays Arrays cannot be written to a file using the Put statement.

Objects Object variables cannot be written to a file using the Put statement.

Variable type File storage description

7-126 MicroStation BASIC Guide

Page 277: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 127 Friday, October 15, 1999 1:27 PM

Put #1,X,YNext XClosePstr$ = ""Open "Test2.Dat" For Random Access Read As #1For Y = 1 To 5

Get #1,y,XPstr = Pstr + "Record " + Str$(Y) + ": " + Str$(X) + crlf

Next YMbeMessageBox PstrClose

End Sub

PvPv#(Rate#, NPer#, Pmt#, Fv#, Due%)

Descr. The Pv function calculates the present value of an annuity based on future periodic, fixed payments and a constant interest rate.

Pv requires the following parameters:

Rate and NPer must be expressed in the same units. If Rate is expressed in months, then NPer must also be expressed in months.

Positive numbers represent cash received, whereas negative numbers represent cash paid out.

Example Sub Main()'This example demonstrates the present value (the amount you'd have

Parameter Description

Rate A double-precision number representing the interest rate per period. When used with monthly payments, be sure to normalize annual percentage rates by dividing them by 12.

NPer A double-precision number representing the total number of payments in the annuity.

Pmt A double-precision number representing the amount of each payment per period.

Fv A double-precision number representing the future value of the annuity after the last payment has been made. In the case of a loan, the future value would be 0.

Due Number that determines when the payments are due for each payment period. A 0 specifies payment at the end of each period, whereas a 1 specifies payment at the start of each period.

MicroStation BASIC Guide 7-127

Page 278: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 128 Friday, October 15, 1999 1:27 PM

‘to pay now) for a $100,000 annuity that pays an annual income‘of $5,000 over 20 years at an annual interest rate of 10%.PVal = Pv(.1,20,-5000,100000,1)MbeMessageBox "The present value is: " & Format$(PVal,"Currency")

End Sub

RandomRandom&(min&, max&)

Descr. Returns a random number greater than or equal to min and less than or equal to max.

A runtime error is generated if min is greater than max.

The expressions that appear in place of min and max will be rounded to the nearest whole number.

Example Const crlf = Chr$(13) + Chr$(10)Sub Main()

'This example uses the random number generator to generate ten'lottery numbers:Msg$ = NullRandomizeFor X = 1 To 10

Y = Random(0,100)Msg = Msg + Str$(Y) + crlf

Next xMbeMessageBox "Ten Numbers for the Lottery: " + crlf + Msg

End Sub

RandomizeRandomize [seed&]

Descr. Initializes the random number generator with a new seed.

If seed is not specified, then the current value of the system clock is used.

Example Const crlf = Chr$(13) + Chr$(10)Sub Main()

'This example sets the randomize seed to a random number between'100 and 1000, then generates ten random numbers for the lottery.RandomizeMsg$ = NullFor X = 1 To 10

Y = Random(0,100)Msg = Msg + Str$(Y) + crlf

7-128 MicroStation BASIC Guide

Page 279: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 129 Friday, October 15, 1999 1:27 PM

Next xMbeMessageBox "Ten Numbers for the Lottery: " + crlf + Msg

End Sub

RateRate#(NPer#, Pmt#, PV#, FV#, Due%, Guess#)

Descr. This function returns the rate of interest for each period of an annuity.

An annuity is a series of fixed payments made to an insurance company or other investment company over a period of time. Examples of annuities are mortgages and monthly savings plans.

Rate requires the following parameters:

Positive numbers represents cash received, while negative values represent cash paid out.

The value of Rate is found by iteration. It starts with the value of Guess, and cycles through the calculation adjusting Guess until the result is accurate within 0.00001 percent. If a result cannot be found after 20 tries, Rate fails and the user must pick a better guess.

Example Sub Main()'This example calculates the rate of interest necessary to save $10,000'by paying $550 each year for 10 years. The guess rate is 10%.R# = Rate(10,-550,000,10000,1,.1)

Parameter Description

NPer a double-precision number representing the total number of payments in the annuity.

Pmt a double-precision number representing the amount of each payment per period.

PV a double-precision number representing the present value of your annuity. In a loan situation, the present value would be the amount of the loan.

FV a double-precision number representing that future value of the annuity after the last payment has been made. In the case of a loan, the future value would be zero.

Due determines when the payments are due for each payment period. A 0 specifies payment at the end of each period while 1 indicates payment at the start of each period.

Guess a number you guess as the value the Rate function will return. The most common guess is .1 (10 percent).

MicroStation BASIC Guide 7-129

Page 280: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 130 Friday, October 15, 1999 1:27 PM

MbeMessageBox "The Rate required is: " + Format$(R,"Percent")End Sub

ReDimRedim [Preserve] variablename (subscriptRange) [As type],...

Descr. This statement redimensions an array, specifying a new upper and lower bound for each dimension of the array.

The variablename parameter specifies the name of an existing array (previously declared using the Dim statement), or the name of a new array variable. If the array variable already exists, then it must be previously declared with the Dim statement with no dimensions, as shown in the following example:

Dim a$() 'dynamic array of strings (no dimensions yet)

Dynamic arrays can be redimensioned any number of times.

The subscriptRange parameter specifies the new upper and lower bounds for each dimension of the array using the following syntax:

[lower% To] upper% [,[lower% To] upper%]...

If lower is not specified, then 0 is used (or the value set using the option base statement.

The type parameter can be used to specify the array element type. Arrays can be declared using any fundamental data type, user-defined data types, and objects.

Redimensioning an array erases all elements of that array unless the preserve keyword is specified. When this keyword is specified, existing data in the array is preserved where possible. If the number of elements in an array dimension increased, the new elements are initialized to zero (or empty string). If the number of elements in an array dimension is decreased, then the extra elements will be deleted. If the preserve is specified, then the number of dimensions of the array being dimensions must either be 0 or the same as the new number of dimensions.

Example Sub Main()'This example uses the FileList statement to redim and fill an array'with file name strings. A new array is then redimmed to hold the'number of elements found by FileList and the FileList array is'copied into it and partially displayed.Dim FL$()

7-130 MicroStation BASIC Guide

Page 281: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 131 Friday, October 15, 1999 1:27 PM

FileList FL,"*.*"count = Ubound(FL)ReDim NL$(Lbound(FL) To Ubound(FL))For X = Lbound(FL) to count

NL(X) = FL(X)Next xMbeMessageBox "The last element of the new array is: " + NL(count)

End Sub

REMREM text

Descr. Causes the compiler to skip all characters on that line.

Example Sub Main()REM This line is a line of comments which serve to illustrate theREM workings of the code and insert comments to make it moreREM readable and maintainable in the future.

End Sub

ResetReset

Descr. Closes all open files, writing out all I/O buffers.

Example Sub Main()'A file is opened for output, and closed with the Reset Statement'then deleted with the Kill statement.Open "Test.Dat" for output access write as # 1ResetKill "Test.Dat"If FileExists("Test.Dat") Then

MbeMessageBox "The file was not deleted"Else

MbeMessageBox "The file was deleted"End If

End Sub

ResumeResume {[0] | Next | label}

Descr. Ends an error handler and continues execution.

The form Resume 0 (or simply Resume by itself) causes execution to continue with the statement that caused the error.

MicroStation BASIC Guide 7-131

Page 282: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 132 Friday, October 15, 1999 1:27 PM

The form Resume Next causes execution to continue with the statement following the statement that caused the error.

The form Resume label causes execution to continue at the specified label.

The Resume statement resets the error state. This means that, after executing this statement, new errors can be generated and trapped as normal.

Example Sub Main()'This example tries to create a new subdirectory in the current path.'If it is successful then it displays a message "Directory created"'Otherwise it executes the error trap and changes the message. After'performing this twice, the error trap is reset to "Resume Next" which'ignores the error (if any) and tries to remove the directory. If there'is an error the next line resets the error trap with "On Error Goto 0"'and the RmDir is executed again (to create an error for this example.)'The lastRemDir statement will cause a run-time error which is not'trapped.Msg$ = NullOn Error Goto DirErrorFor X = 1 To 2

Msg = "Directory Created"MkDir "TestDir"MbeMessageBox Msg

Next xRmDir "TestDir"On Error Resume NextRmDir "TestDir"MbeMessageBox "No Error Trap: RmDir Failed"

RemoveError:On Error Goto 0RmDir "TestDir"Exit Sub

DirError:If Err = 70 Then

Msg$ = "Directory exists! Error: " + Str$(Err)RmDir "TestDir"Resume Next

ElseMsg$ = "Unspecified Error (Remove Directory)! " + Str$(Err)Resume RemoveError

End IfEnd Sub

7-132 MicroStation BASIC Guide

Page 283: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 133 Friday, October 15, 1999 1:27 PM

ReturnReturn

Descr. Transfers execution control to the statement following the most recent Gosub. A runtime error results if a Return statement is encountered without a corresponding Gosub statement.

Example Sub Main()'A subroutine is called and then execution is returned to the main'routine by the Return statement.If True Then Gosub SubTrueMbeMessageBox "The main routine continues here"Exit Sub

SubTrue:MbeMessageBox "This message is generated in the Subroutine"Return

End Sub

Right$Right$(str$, NumChars$)

Descr. Returns the specified rightmost characters from a string.

If NumChars is greater than or equal to the length of the string, then the entire string is returned. If NumChars is 0, then an empty string is returned.

Example Sub Main()'This example shows the Right$ function used in a routine to change'upper case names to lower case with an upper case first letter.

Lname$ = "WILLIAMS"X = Len(Lname)Rest$ = Right$(Lname,X - 1)FL$ = Left$(Lname,1)Lname = Fl + LCase$(Rest)MbeMessageBox "The Converted name is: " + Lname

End Sub

RmDirRmDir dir$

Descr. Removes the specified directory.

Example Sub Main()'This routine creates a directory and then deletes it with RmDirOn Error Goto ErrMake

MicroStation BASIC Guide 7-133

Page 284: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 134 Friday, October 15, 1999 1:27 PM

MkDir("TEST01")On Error Goto ErrRemoveRmDir("Test01")

ErrMake:MbeMessageBox "The directory could not be created"Exit Sub

ErrRemove:MbeMessageBox "The directory could not be removed"Exit Sub

End Sub

RndRnd![(number!)]

Descr. Returns a single precision random number between 0 and 1.

If number is omitted, the next random number is returned. Otherwise, the number parameter has the following meaning:

Example Const crlf = Chr$(13) + Chr$(10)Sub Main()

'This routine generates a list of random numbers and displays themFor x = -1 To 8

y! = Rnd(1) * 100Msg$ = Msg + Str$(X) + " : " + Str$(y) + crlf

NextMbeMessageBox msg + "Last form: " +Str$(Rnd)

End Sub

RSetRSet dest$ = source$

Descr. The RSet statement copies the source string source$ into the destination string dest$. If source$ is shorter in length than dest$, then the string is right aligned within dest$ and the remaining characters are padded with spaces. If source$ is longer in length than dest$, then source$ is truncated, copying only the leftmost number of characters that will fit in dest$.

Example Const crlf = Chr$(13) + Chr$(10)Sub Main()

'This example Replaces a 40 character string of asterisks (*) with

number < 0 Always returns the same number

number = 0 Returns the last number generated

number > 0 Returns the next random number

7-134 MicroStation BASIC Guide

Page 285: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 135 Friday, October 15, 1999 1:27 PM

'a RSet and LSet string and then displays the results.Dim Msg$, TmpStr$TmpStr = String$(40, "*")Msg = "Here are two strings that have been right" + crlfMsg = Msg + "and left justified in a 40 character string"Msg = Msg + crlf + crlfRSet TmpStr = "Right->"Msg = Msg & TmpStr & crlfLSet TmpStr = "<-Left"Msg = Msg & TmpStr & crlfMbeMessageBox Msg

End Sub

RTrim$RTrim$(str$)

Descr. Returns the string with the trailing spaces removed.

Example Const crlf = Chr$(13) + Chr$(10)Sub Main()

'This example displays a left justified string and it's RTrim result.A$ = "This is a left justified string "B$ = RTrim$(A)MbeMessageBox A + "<=" + crlf + B + "<="

End Sub

SecondSecond%(serial#)

Descr. Returns the second of the day encoded in the specified serial parameter. The value returned is between 0 and 59 inclusive.

Example Sub Main()'This example takes the current time and extracts the hour,'minute, and second and displays them as the current time.XT# = TimeValue(Time$())XH# = Hour(XT)XM# = Minute(XT)XS# = Second(XT)MbeMessageBox "Current Time is: " + CStr(XH)+":"+CStr(XM)+":"+CStr(XS)

End Sub

Seek (function)Seek&(filenumber%)

MicroStation BASIC Guide 7-135

Page 286: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 136 Friday, October 15, 1999 1:27 PM

Descr. Returns the position of the file pointer in a file relative to the beginning of the file.

filenumber is a number that is used by the OS to refer to the open file—the number passed to the open statement.

The value returned depends on the mode in which the file was opened:

The value returned is always between 1 and 2147483647 where the first byte (or first record) in the file is 1.

Example Sub Main()'This example opens a file for random write then writes ten'records into the file using the PUT statement. The file position‘is displayed using the Seek Function, and the file is closed.Open "Test2.Dat" for random access write as #1

For X% = 1 to 10Y% = X * 10Put #1,X,Y

Next XY = Seek(1)MbeMessageBox "The current file position is: " + Str$(Y)Close

End Sub

Seek (statement)Seek [#] filenumber%, position&

Descr. Sets the position of the file pointer within a given file so that the next read or write operation will occur at the specified position.

The filenumber parameter is a number that is used by the OS to refer to the open file—the number passed to the open statement. filenumber should always be between 1 and 2147483647 where the first byte (or first record) in the file is 1.

The position parameter specifies the location within the file to position the file pointer. It is a number between 1 and

File Mode Returns

Input byte position for the next read

Output byte position for the next write

Append byte position for the next write

Random number of the next record to be written or read

Binary byte position for the next read or write

7-136 MicroStation BASIC Guide

Page 287: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 137 Friday, October 15, 1999 1:27 PM

2147483647, where the first byte (or record number) in the file is 1. For files opened in either Binary, Output, Input or Append modes, position is the byte position within the file. For Random files, position is the record number.

A file can be extended by seeking beyond the end-of-file and writing data there.

Example Sub Main()'This example opens a file for random write then writes ten'records into the file using the PUT statement. The file is'then re-opened for read and the ninth record is read using'the Seek and Get Functions.Open "Test2.Dat" For Random Access Write As #1

For X = 1 To 10Rec$ = “Record #” + Str$(X)Put #1,X,Rec$

Next XCloseOpen "Test2.Dat" For Random Access Read As #1Seek #1,9Get #1,,Rec$MbeMessageBox "The Ninth Record = " + Str$(X)Close

End Sub

Select...CaseSelect Case testexpression

[Case expressionlist [statement_block]][Case expressionlist [statement_block]] ...[Case Else [statement_block]]End Select

Descr. This statement is used to execute a block of BASIC statements depending on the value of a given expression.

The Select Case statement uses the following arguments:

testexpression Any numeric or string expression

MicroStation BASIC Guide 7-137

Page 288: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 138 Friday, October 15, 1999 1:27 PM

If the testexpression matches any of the expressions contained in expressionlist, then the accompanying block of BASIC statements is executed.

The resultant type of expression must be the same as that of testexpression.

Multiple expression ranges can be used within a single Case clause. For example:

Case 1 To 10,12,15, Is > 40

Only the statement_block associated with the first matching expression will be executed.

A Select...End Select expression can also be represented with the If...Then expression. The use of the Select statement, however, may be more readable.

Example Sub Main()'This example uses the select .. case statement to output the'current operating system.OpSystem% = Basic.OSSelect Case OpSystem%Case 2

S$ = "Microsoft Windows"Case 3 to 8

S$ = "Unix"Case 10

S$ = "Apple Macintosh"Case 12

S$ = "DOS"Case Else

S$ = "Other"End SelectMbeMessageBox "This version of BASIC runs on: "+ S$

End Sub

statement_block Any group of BASIC statements

expressionlist Any of the following:expression [,expression]...expression to expressionis relational_operator expression

7-138 MicroStation BASIC Guide

Page 289: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 139 Friday, October 15, 1999 1:27 PM

SetSet object_var = object_expression

Set object_var = New object_type

Set object_var = Nothing

Descr. The Set statement assigns a value to an object variable.

The first syntax assigns the result of an expression to an object variable. This statement does not duplicate the object being assigned, but rather copies a reference of an existing object to an object variable.

The object_expression is an expression that evaluates to an object of the same type as the object_var.

With application-defined objects, Set performs additional processing. When the Set is performed, the application or extension that defines that object type is notified that a reference to an object is being made and destroyed. For example, the following statement informs the application or extension that a reference to object A is lost and a reference to object B is added:

Set A = B

In this way, the application can detect when an object is no longer being referenced and take appropriate action, such as destroying the physical object.

In the second syntax, the object variable is being assigned to a new instance of an existing object type. This syntax is only valid for application-defined objects.

At runtime, the application or extension that defines that object type is notified that a new object is being created and assigned. The application should respond by creating a new physical object (within the appropriate context) and returning a reference to that object which is immediately assigned to the variable being declared.

When an object created using the New keyword goes out of scope (i.e., the Sub or Function in which the variable is declared ends), the application is notified. The application can choose any appropriate action, such as destroying the physical object.

In the third syntax, the reserved keyword Nothing is used to make an object variable reference no object. At a later time, the

MicroStation BASIC Guide 7-139

Page 290: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 140 Friday, October 15, 1999 1:27 PM

object variable can be compared to Nothing to test if the object variable has been instantiated.

Example Sub Main()dim Document as objectdim Page as objectset Document = GetObject(“c:\resume.doc”)set page = Document.ActivePageMbeMessageBox page.name

End Sub

SetAttrSetAttr filename$, attribute%

Descr. The SetAttr command changes the attributes of the specified file to the given attribute. A runtime error results if the file cannot be found.

attribute can contain any combination of the following values:

The attributes can be combined using the + operator or the bitwise OR operator.

Example Sub Main()'This example creates a file and sets it's attributes to‘Read-Only and System.Open "Test2.Dat" For Output Access Write As # 1CloseMbeMessageBox "Current Attribute: " + Str$(GetAttr("Test2.Dat"))SetAttr "Test2.Dat",ebReadOnly OR ebSystemMbeMessageBox "Attribute set to: " + Str$(GetAttr("Test2.Dat"))

End Sub

Constant Value Includes...

ebNormal 0 Read-only, archive, subdir, none

ebReadOnly 1 Read-only files

ebHidden 2 Hidden files

ebSystem 4 System files

ebVolume 8 Volume label

ebDirectory 16 Sub-directories

ebArchive 32 Files that have changed since last backup

ebNone 64 Files with no attributes

7-140 MicroStation BASIC Guide

Page 291: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 141 Friday, October 15, 1999 1:27 PM

SgnSgn%(number)

Descr. Returns a value indicating if a number is less than, greater than, or equal to zero.

Returns 1 if number is greater than 0.Returns 0 if number is equal to 0.Returns -1 if number is less than 0.

The number parameter is a numeric expression of any type.

Example Sub Main()'This example tests the product of two numbers and displays'a message based on the sign of the result.A% = -100B% = 100C% = A * BSelect Case Sgn(C)

Case -1MbeMessageBox "The Product is Negative " + Str$(Sgn(C))

Case 0MbeMessageBox "The Product is Zero" + Str$(Sgn(C))

Case 1MbeMessageBox "The Product is Positive" + Str$(Sgn(C))

End SelectEnd Sub

SinSin#(angle#)

Descr. Returns the sine of a given angle.

angle is given in radians.

Example Sub Main()'Displays the Sine of PI/4 radians (45 degrees)C# = Sin(PI / 4)MbeMessageBox "The sine of 45 Degrees is: " + Str$(C)

End Sub

SleepSleep milliseconds&

Descr. This statement causes a macro to pause for a specified number of milliseconds.

Example Sub Main()'This example displays a message for two seconds.

MicroStation BASIC Guide 7-141

Page 292: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 142 Friday, October 15, 1999 1:27 PM

MbeWriteMessage "Waiting 2 seconds"Sleep(2000)MbeWriteMessage

End Sub

SlnSln#(Cost#, Salvage#, Life#)

Descr. The Sln function returns the Straight-Line Depreciation of an asset, assuming constant benefit from the asset.

The SLN of an asset is found by taking an estimate of its useful life in years, assigning values to each year, and adding up all the numbers.

The formula used to find the SLN of an asset is as follows:

(Cost - Salvage Value) / Useful Life

Sln requires the following parameters:

The unit of time used to express the useful life of the asset is the same unit of time used to express the period for which the depreciation is returned.

Example Sub Main()'This example calculates the straight line depreciation of an asset'which cost $10,000.00 and has a salvage value of $500.00 as scrap'after 10 years of service life.Dep# = Sln(10000.00,500.00,10)MbeMessageBox "The Annual depreciation is: " + Format$(Dep,"Currency")

End Sub

Space$Space$(NumSpaces%)

Descr. Returns a string containing the specified number of spaces.

NumSpaces must be between 0 and 32767.

Parameter Description

Cost This is a double-precision number representing the initial cost of the asset.

Salvage This is a double-precision number representing the estimated value of the asset at the end of its useful life.

Life This number represents the length of the assets useful life.

7-142 MicroStation BASIC Guide

Page 293: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 143 Friday, October 15, 1999 1:27 PM

Example Sub Main()'This example returns a string of 10 spaces and displays it.Ln$ = Space$(10)MbeMessageBox "Value of LN: =>" + LN + "<="

End Sub

SpcSpc(numspaces%)

Descr. The Spc function prints out the specified number of spaces. Spc can only be used with the Print and Print# statements.

numspaces specifies the number of spaces to be printed. It can be any value between 0 and 32767.

If a line width has been specified (using the Width statement), then the number of spaces is adjusted as follows:

numspaces% = numspaces% Mod width%

If the resultant number of spaces is greater than width - print_position, the number of spaces is recalculated as follows:

numspaces% = numspaces% - (width% - print_position)

These calculations have the effect of never allowing the spaces to overflow the line length. Furthermore, with a large value for column% and a small line width, the file pointer will never advance more than one line.

Example 'Displays 20 spaces between the arrowsPrint "20 Spaces:-->"; Spc(20); "<--"

SqrSqr#(number#)

Descr. Returns the square root of a given value.

number must be greater than or equal to 0.

Example Sub Main()'This example calculates the square root of the numbers from 1 to 10'and displays them.crlf$ = Chr$(13) + Chr$(10)Msg$ = NullFor X = 1 To 10

SX# = Sqr(X)

MicroStation BASIC Guide 7-143

Page 294: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 144 Friday, October 15, 1999 1:27 PM

Msg = Msg + Format$(X,"Fixed") + " - " + Format$(SX,"Fixed") + crlfNext xMbeMessageBox Msg

End Sub

StopStop

Descr. Suspends execution of the current macro, returning control to a debugger if one is present. If a debugger is not present, this command will have the same affect as end.

Example Sub Main()'The stop statement can be used for debugging. Here it is used'to stop execution when Z is randomly set to zeroFor X = 1 To 10

Z = Random(0,10)If Z = 0 Then StopY = X / Z

Next xEnd Sub

Str$Str$(number%)

Str$(number&)

Str$(number!)

Str$(number#)

Descr. Returns a string representation of the given number. The result is returned in floating point ‘E’ notation, if the result is very small or very large.

If number is negative, then the returned string will contain a leading minus sign. If number is positive, then the returned string will contain a leading space.

Singles are printed using only 7 significant digits. Doubles are printed using 15-16 significant digits.

Example Sub Main()'The Str$ function is used to display the value of a numeric variable.X# = 100.22MbeMessageBox Str$(X)

End Sub

7-144 MicroStation BASIC Guide

Page 295: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 145 Friday, October 15, 1999 1:27 PM

StrCompStrComp%(string1$, string2$ [, compare%])

Descr. Returns an Integer value indicating the result of comparing the two string arguments:

The StrComp function compares two strings and returns an integer indicating the result of the comparison. The comparison can be either case sensitive or case insensitive depending on the value of the optional compare parameter:

If compare is not specified, then the current Option Compare setting is used. If no Option Compare statement has been encountered, then Binary is used (i.e., string comparison is case sensitive).

Example Const crlf$ = Chr$(13) + Chr$(10)Sub Main()

'This example compares two strings and displays the results.'It illustrates that the function compares two strings to the'length of the shorter string in determining equivalency.Msg$ = NullA$ = "This string is UPPER and lower case"B$ = "This string is upper and lower case"C$ = "This string"D$ = "This string is upper and lower case characters"ABc = StrComp(A,B,0)Msg= Msg + "A and C (sensitive) : " + Format$(ABc,"True/False") + crlfABi = StrComp(A,B,1)Msg= Msg + "A and B (insensitive): " + Format$(ABi,"True/False") + crlfACi = StrComp(A,C,1)Msg= Msg + "A and C (insensitive): " + Format$(ACi,"True/False") + crlfBDi = StrComp(B,D,1)Msg= Msg + "B and D (sensitive) : " + Format$(BDi,"True/False") + crlfMbeMessageBox Msg

End Sub

0 string1$ = string2$

1 string1$ > string2$

-1 string1$ < string2$

0 case sensitive comparison

1 case insensitive comparison

MicroStation BASIC Guide 7-145

Page 296: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 146 Friday, October 15, 1999 1:27 PM

String$String$(number%, CharCode%)

String$(number%, str$)

Descr. Returns a string of length number consisting of a repetition of the specified filler character.

If CharCode is specified, then the character with this ANSI value will be used as the filler character.

If str$ is specified, then the first character of this string is used as the filler character.

Example Sub Main()'This example uses the string function to create a line of "=" signs‘the length of another string, and then displays the character string‘underlined with the generated string.A$ = "This string will appear underlined"B$ = String$(Len(A),"=")MbeMessageBox A + crlf + B

End Sub

Sub...End SubSub name[(parameter [As type]...)] [statements]End Sub

Descr. Declares a subroutine.

Parameters are passed to a subroutine by reference, meaning that any modifications to a passed parameter changes that variable in the caller. To avoid this, simply enclose variable names in parenthesis, as in the following example function calls:

UserSub 10,12,(j)

If a subroutine is not to receive a parameter by reference, then the optional ByVal keyword can be used:

Sub Test ByVal FileName As String[statements]

End Sub

A subroutine terminates when one of the following statements is encountered:

End SubExit Sub

7-146 MicroStation BASIC Guide

Page 297: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 147 Friday, October 15, 1999 1:27 PM

The name of the subroutine must follow BASIC naming conventions. It cannot include type declaration characters.

Subroutines can be recursive.

Example Sub Main()'This example uses a subroutine to calculate the area of a circleR! = 10PrintArea R

End SubSub PrintArea(R as single)

Area! = (R ^ 2) * PIMbeMessageBox "Area of circle with radius"+Str$(R) + " = " + Str$(Area)

End Sub

SYDSYD#(Cost#, Salvage#, Life#, Period#)

Descr. This function returns the Sum of Years' Digits depreciation of an asset over a specific period of time. The SYD of an asset is found by taking an estimate of its useful life in years, assigning values to each year, and adding up all the numbers.

The formula used to find the SYD of an asset is as follows:

(Cost - Salvage_Value) * Remaining_Useful_Life / SYD

SYD requires the following parameters:

Life and Period must be expressed in the same units. If Life is expressed in terms of months, then Period must also be expressed in terms of months to receive accurate results.

Example Sub Main()'An asset which cost $1,000.00 is depreciated over 10 years.‘The salvage value is $100.00 and the Sum of the years digit‘depreciation is shown for each year.For X = 1 To 10

Parameter Description

Cost This is a double-precision number representing the initial cost of the asset.

Salvage This is a double-precision number representing the estimated value of the asset at the end of its useful life.

Life This number represents the length of the assets useful life.

Period This number represents the period that the depreciation is to be calculated for. It cannot exceed the life of the asset.

MicroStation BASIC Guide 7-147

Page 298: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 148 Friday, October 15, 1999 1:27 PM

Dep# = SYD(1000,100,10,X)Msg$=Msg + "Year"+Str$(X)+" Dep: " + Format$(Dep,“Currency”)+ Chr$(13)

Next xMbeMessageBox Msg

End Sub

TabTab(column%)

Descr. The Tab function prints out the number of spaces necessary to reach a given column position. Tab can only be used with the Print and Print# statements.

column specifies the desired column position to advance to. It can be any value between 0 and 32767 inclusive.

Rule 1: If the current print position is less than or equal to column, then the number of spaces is calculated as:

column - print_position

Rule 2: If the current print position is greater than column, then column-1 spaces are printed on the next line.

If a line width is specified (using the Width statement), then the column position is adjusted as follows before applying the above two rules:

column = column Mod width%

Tab is useful for making sure that output begins at a given column position, regardless of the length of the data already printed on that line.

Example Sub Main()‘This example prints three column headers and three numbers‘aligned below the column headers.Print “Column1”; Tab(10); “Column2”; Tab(20); “Column3”Print Tab(3); “1”; Tab(14); “2”; Tab(24); “3”

End Sub

TanTan#(angle#)

Descr. Returns the tangent of an angle.

angle is given in radians.

7-148 MicroStation BASIC Guide

Page 299: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 149 Friday, October 15, 1999 1:27 PM

Example Sub Main()'This example computes tangent of PI/4 radians (45 degrees)C# = Tan(PI / 4)MbeMessageBox "The Tangent of 45 Degrees is: " + Str$(C)

End Sub

Time$Time$[()]

Time$ = newtime$

Descr. As a function, Time$ returns the system time as an 8 character string. As a statement, Time$ sets the system time to the time contained in the specified string.

The format of the time string is HH:MM:SS. A 24 hour clock is used.

Example This example illustrates use as a function.Sub Main()

'Returns the system time and displays it in a dialog boxTi$ = Time$Msg$ = "Time was: " + Ti + crlfTime$ = "10:30:54"Msg = Msg + "Time set to: " + Time$ + crlfTime$ = TiMsg = Msg + "Time restored to: " + Time$MbeMessageBox Msg

End Sub

Example This example illustrates use as a statement.Sub Main()

'Returns the system time and displays it in a dialog boxTi$ = Time$Msg$ = "Time was: " + Ti + crlfTime$ = "10:30:54"Msg = Msg + "Time set to: " + Time$ + crlfTime$ = TiMsg = Msg + "Time restored to: " + Time$MbeMessageBox Msg

End Sub

TimerTimer&

Descr. Returns the number of seconds that have elapsed since midnight.

Example Sub Main()'Displays the elapsed time between execution start and the

MicroStation BASIC Guide 7-149

Page 300: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 150 Friday, October 15, 1999 1:27 PM

‘time you clicked the Ok button on the first messageA& = TimerMbeMessageBox "Click the Ok button Please"B& = Timer - AMbeMessageBox "The elapsed Time was: " + Str$(B) + " seconds"

End Sub

TimeSerialTimeSerial#(hour%, minute%, second%)

Descr. Returns a double-precision number representing the given time with a date of zero. A Date of zero is equal to Dec 30, 1899

Example Sub Main()T1# = TimeSerial(10,22,30)T2# = TimeSerial(10,35,27)Tdif# = Abs (T1 - T2)MbeMessageBox "The Difference is: " + Format$(Tdif, "hh:mm:ss")

End Sub

TimeValueTimeValue#(time_string$)

Descr. Returns a double-precision number representing the time contained in the specified string argument.

This function interprets the passed time_string$ parameter looking for a valid time specification.

The time_string$ parameter can contain valid time items separated by time separators such as colon ‘:’ or period ‘.’.

Time strings can contain an optional date specification, but this is not used in the formation of the returned value.

If a particular time item is missing, then the missing time items are set to zero. For example, the string "10 pm" would be interpreted as "22:00:00".

Example Sub Main()'This example calculates the TimeValue of the current time and'Displays it in a dialog box.T1$ = “10:15”T2# = TimeValue(T1$)MbeMessageBox "The Timevalue of " + T1 + " is: " + Str$(T1)

End Sub

7-150 MicroStation BASIC Guide

Page 301: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 151 Friday, October 15, 1999 1:27 PM

Trim$Trim$(str$)

Descr. Returns the a copy of the passed string expression (str$) with leading and trailing spaces removed.

Example const crlf$ = chr$(13) + chr$(10)Sub Main()

'This example uses the Trim$ function to extract the non-blank part'of a string and display it:Tx$ = " This is Text "Te$ = Trim$(Tx)MbeMessageBox "Orig =>" + Tx + "<=" + crlf + "Trimmed =>" + Te + "<="

End Sub

TrueDescr. -1, used in conditionals and boolean expressions

Example Sub Main()'This example sets variable a to True and then tests to see if'(1) A is True; (2) if the True constant = -1; and (3) if A is'equal to -1 (True).a = Trueif ((A =True) and (True = -1) and (A = -1)) then

MbeMessageBox "A is True"Else

MbeMessageBox "A is False"End If

End Sub

TypeType username variable As type variable As type variable As type :End Type

Descr. The Type statement creates a structure definition which can then be used with the Dim statement to declare variables of that type. The username field specifies the name of the structure that is used later with the Dim statement.

Within a structure definition appear field descriptions in the format:

variable As type

MicroStation BASIC Guide 7-151

Page 302: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 152 Friday, October 15, 1999 1:27 PM

where variable is the name of a field of the structure, and type is the data type for that variable. Any fundamental data type or previously declared user-defined data type can be used within the structure definition (structures within structures are allowed). Only fixed arrays can appear within structure definitions.

Type can only appear outside of subroutine and function declarations.

Example 'This example displays the use of the Type statement to create a structure'representing the parts of a circle and assign values to them.Type Circ

Msg As StringRad As IntegerDia As IntegerAre As DoubleCir As Double

End TypeSub Main()

Dim Circle As CircCircle.Rad = 5Circle.Dia = Circle.Rad * 2Circle.Are = Circle.Rad ^ 2 * PiCircle.Cir = Circle.Dia * PiCircle.Msg = "The Area of the Circle is: " + Str$(Circle.Are)MbeMessageBox Circle.Msg

End Sub

UBoundUBound%(ArrayVariable() [, dimension%])

Descr. Returns the upper bound of the specified dimension of the specified array variable.

The first dimension (1) is assumed if dimension is not specified.

Example Sub Main()'This example dimensions two arrays and displays their upper boundsDim A(5 To 12)Dim B(2 To 100, 9 To 20)UBa = UBound(A)UBb = UBound(B,2)

MbeMessageBox "Upper Bnd A: " + Str$(UBa) + " Upper Bnd B: " + Str$(UBb)'This example uses Lbound and Ubound to dimension a dynamic array to'hold a copy of an array redimmed by the FileList statement.Dim FL$()FileList FL,"*.*"count = Ubound(FL)

7-152 MicroStation BASIC Guide

Page 303: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 153 Friday, October 15, 1999 1:27 PM

Redim NL$(Lbound(FL) To Ubound(FL))For X = 1 To count

NL(X) = FL(X)Next xMbeMessageBox "The last element of the new array is: " + NL(count)

End Sub

UCase$UCase$(str$)

Descr. Returns the upper case equivalent of the specified string.

Example Sub Main()'This example uses the UCase$ function to change a string from lower'to upper case.A1$ = "This string was lower case"A2$ = UCase$(A1)MbeMessageBox A2

End Sub

UnLockUnlock [#] filenumber% [,{record& | [start&] To end&}]

Descr. The Unlock statement unlocks a section of the specified file, allowing other processes access to that section of the file.

The filenumber parameter is a number that is used to refer to the open file—the number passed to the open statement.

For sequential files, the record, start and end parameters are ignored—the entire file is unlocked.

The section of the file is specified using one of the following:

The unlock range must be the same as that used by the Lock statement.

Syntax Description

<none> unlock the entire file (no record specification is given)

record unlock the specified record number (for Random files) or byte (for Binary files)

to end unlock from the beginning of the file to the specified record (for Random files) or byte (for Binary files)

start to end unlock the specified range of records (for Random files) or bytes (for Binary files)

MicroStation BASIC Guide 7-153

Page 304: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 154 Friday, October 15, 1999 1:27 PM

Example const crlf$ = chr$(13) + chr$(10)Sub Main()

'This example creates Test2.DAT and fills it with 10 string variable'records. These are displayed in a dialog box. The file is then'reopened for read/write and each record is Locked, modified,'rewritten and unlocked. The new records are then displayed in a'dialog box.A$ = "This is record number: "B$ = "0"Rec$ = ""Msg$ = ""Open "Test2.Dat" for random access write shared as #1For x% = 1 To 10

Rec = A + Str$(x)Lock #1,xPut #1,,RecUnlock #1,xMsg = Msg + Rec + crlf

Next xCloseMbeMessageBox "The Records are: " + crlf + MsgMsg = ""Open "Test2.Dat" For Random Access Read Write Shared As # 1For x = 1 to 10

Rec = Mid$(Rec,1,23) + Str$(11-x)Lock #1,x 'lock it for our usePut #1,x,Rec 'nobody's changed itUnLock #1,xMsg = Msg + Rec + crlf

Next xMbeMessageBox "The Records are: " + crlf + Msgclose

End Sub

ValVal#(number$)

Descr. Converts a given string expression to a number.

The number$ parameter can contain any of the following:

• Leading minus sign (for non hex or octal numbers only)

• Hexadecimal number in the format: &H<hex digits>

• Octal number in the format: &O<octal digits>

7-154 MicroStation BASIC Guide

Page 305: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 155 Friday, October 15, 1999 1:27 PM

• Floating point number, which can contain a decimal point and optional exponent

Spaces, tabs and linefeeds are ignored.

If number$ does not contain a number, then 0 is returned.

The Val function continues to read characters from the string up to the first non-numeric character.

Val always returns a double-precision floating point value. This value is forced to the data type of the assigned variable.

Example Sub Main()'This example inputs a number string from an MbeInputBox and converts‘it to a number variable.A$ = MbeInputBox$("Input a Number String")B# = Val(A)MbeMessageBox "The converted values is: " + Str$(B)

End Sub'The following table shows valid strings and their numeric equivalent:' "1 2 3" 123' "12.3" 12.3' "&HFFFF" -1' "&O77" 63' "12.345E-02" .12345

WeekdayWeekday%(serial#)

Descr. Returns the day of the week specified by the given date/time serial value. Sunday is 1, monday is 2, and so on.

Example Sub Main()'This example gets a date in an input box and displays'the day of the week and it's name for the date entered.Dim A$(7)A(1) = "SUNDAY"A(2) = "MONDAY"A(3) = "TUESDAY"A(4) = "WEDNESDAY"A(5) = "THURSDAY"A(6) = "FRIDAY"A(7) = "SATURDAY"Bd$ = MbeInputBox$("Please Enter Your Birthday")Dt = DateValue(Bd)Dw = WeekDay(Dt)

MicroStation BASIC Guide 7-155

Page 306: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 156 Friday, October 15, 1999 1:27 PM

MbeMessageBox "You were born on " + Str$(Dw) + ", which was a " + A(Dw)End Sub

While...WendWhile condition [statements]Wend

Descr. Repeats a statement or group of statements while a condition is TRUE.

Example Sub Main()'This example executes a While loop until the random number'generator returns a value of 1X% = 0Count% = 0While X <> 1 And Count < 500

X = Rnd(1)Count = Count + 1

WendMbeMessageBox "The loop executed " + Str$(count) + " times."

End Sub

Width#Width #filenumber%, newwidth%

Descr. The Width statement specifies the line width for sequential files opened in either Output or Append modes.

filenumber is a number that is used to refer to the open file—the number passed to the Open statement.

When a file is initially opened, there is no limit to line length. This command forces all subsequent output to the specified file to use the specified value as the maximum line length.

newwidth can be any integer from 0 to 255 inclusive. If newwidth is zero, no maximum line length is used.

Width affects output in the following manner: if the column position is greater than 1 and the length of the text to be written to the file causes the column position to exceed the current line width, then the data is written on the next line.

Width also affects output of the Print command when used with Tab and Spc functions.

7-156 MicroStation BASIC Guide

Page 307: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 157 Friday, October 15, 1999 1:27 PM

Example Sub Main()'See Print statement'This statement sets the maximum line width for file number 1 to 80'columnsWidth #1,80

End Sub

Word$Word$(text$, first%[, last%])

Descr. Returns a single word or sequence of words between first and last.

This function extracts words from a text source.

The first parameter specifies the first word in the sequence to return. If last is not specified, then only that word is returned. If last is specified, then all words between first and last will be returned, including all spaces, tabs and end-of-lines that occur between those words.

Words are separated by any non-alphanumeric characters such as spaces, tabs, end-of-lines and punctuation.

If first is greater than the number of words in text$, then an empty string is returned.

If last is greater than the number of words in text$, then all words from first to the end of text are returned.

Example Sub Main()'This example extracts two words from the string.A$ = "My last name is Williams, Stuart is my surname."C$ = Word$(A,5,6)MbeMessageBox "The extracted name is: " + C

End Sub

WordCountWordCount%(text$)

Descr. Returns the number of words in the specified text.

Words are separated by spaces, tabs and end-of-lines.

Example Sub Main()'This example counts the number of words in a particular stringA$ = "My last name is Williams, Stuart is my surname."

MicroStation BASIC Guide 7-157

Page 308: 48784209 Microstation Basic

600macro.bk : 607_A_Z.FRA Page 158 Friday, October 15, 1999 1:27 PM

D! = WordCount(A)MbeMessageBox "The String has " + Str$(D) + " words"

End Sub

Write #Write [#]filenumber% [, expressionlist]

Descr. This statement writes a list of expressions to a given sequential file.

The file referenced by filenumber must be opened in either Output or Append mode. filenumber is a number that is used to refer to the open file—the number passed to the Open statement.

Write outputs data items separated with commas. Strings are output enclosed within quotation marks. After writing each expression in the list, Write outputs an end-of-line.

Write can only be used with files opened in Output or Append modes.

Example const crlf$ = chr$(13) + chr$(10)Sub Main()

'This example opens a file for sequential write then writes ten'records into the file with the values 10..100. Then the file'is closed and re-opened for read and the records read with the'Input statement. The results are displayed in a dialog box.Open "Test2.Dat" For Output Access Write As #1For X% = 1 To 10

Y% = X * 10Write #1,X,Y

Next XClosePstr$ = ""Open "Test2.Dat" for input access read as #1For Y = 1 To 5

Input #1,A%,B%Pstr = Pstr + "Record " + Str$(A) + ": " + Str$(B) + crlf

Next YMbeMessageBox PstrClose

End Sub

Xorexpression1 Xor expression2

7-158 MicroStation BASIC Guide

Page 309: 48784209 Microstation Basic

A to Z Reference

Stan

dar

d B

ASI

C R

efer

ence

7

600macro.bk : 607_A_Z.FRA Page 159 Friday, October 15, 1999 1:27 PM

Descr. If both operands are relational, then Xor returns the logical exclusive Or of expression1 and expression2. In other words, Xor returns True only if both operands are not equal.

If both operands are numeric, the result is the bitwise Xor of the arguments.

If either of the operands is a floating point number, both operands are first converted to Longs, then a bitwise Xor is performed.

For numeric operands, bitwise Xor works as follows:

Example Const crlf = Chr$(13) + Chr$(10)Sub Main()

'This example builds a logic table for the XOR function & displays it.Msg$ = NullFor X = True To False

For Y = True To FalseZ = X Xor YMsg = Msg + Format$(X,"True/False") + " " + _

Format$(Y,"True/False") + " " +Format$(Z,"True/False") + crlf

Next yNext xMbeMessageBox Msg

End Sub

YearYear%(serial#)

Descr. Returns the year of the date encoded in the specified serial parameter. The value returned is (100 <= serial <= 9999) inclusive.

Example Sub Main()'This example returns the current Year in a dialog box.

Tdate$ = Date$TDay! = Year(DateValue(Tdate))MbeMessageBox "The current Year is: " + Str$(TDay)

End Sub

Bit in expression1

Bit in expression2

Bit in result

1 1 0

0 1 1

1 0 1

0 0 0

MicroStation BASIC Guide 7-159

Page 310: 48784209 Microstation Basic

A to Z Reference

600macro.bk : 607_A_Z.FRA Page 160 Friday, October 15, 1999 1:27 PM

7-160 MicroStation BASIC Guide

Page 311: 48784209 Microstation Basic

600macro.bk : 608_EXT.FRA Page 1 Friday, October 15, 1999 1:27 PM

8 MicroStation Extensions to BASIC

"extensio.pdf"

The keywords documented here are MicroStation-specific extensions to the standard BASIC language.

• State Object (see page 8-2)

• Element Object (see page 8-15)

• Element Set Objects (see page 8-62)

• Settings Object (see page 8-66)

• Design File Information Objects (see page 8-87)

• Current Transformation Object (see page 8-93)

• View Objects (see page 8-99)

• Reference File Objects (see page 8-108)

• Session Object (see page 8-116)

• C Expression Statements (see page 8-120)

• CAD Input Operations (see page 8-123)

• Dialog Box Statements (see page 8-145)

• MbeSqlda Object (see page 8-149)

• MbeTable Object (see page 8-152)

• MbeDatabase Object (see page 8-160)

• MbeDatabaseLink Object (see page 8-168)

• MbeDgnLevels Object (see page 8-172)

• MbeLevelGroup Object (see page 8-177)

• MbeNamedLevel Object (see page 8-181)

• Tag BASIC Extensions (see page 8-183)

• MbeTagSet Object (see page 8-185)

• MbeTagDef Object (see page 8-190)

• MbeTag Object (see page 8-196)

• MbeMacro Object (see page 8-202)

• Topology Objects (page 8-202) (GeoGraphics only)

• GbeTLayerPoint Object (page 8-205) (GeoGraphics only)

• GbeTLayerLine Object (page 8-207) (GeoGraphics only)

MicroStation BASIC Guide 8-1

Page 312: 48784209 Microstation Basic

State Object

600macro.bk : 608_EXT.FRA Page 2 Friday, October 15, 1999 1:27 PM

• GbeTLayerPolygon Object (page 8-209) (GeoGraphics only)

• GbeTLayerMixed Object (page 8-212) (GeoGraphics only)

• Category Object (page 8-214) (GeoGraphics only)

• Feature Object (page 8-218) (GeoGraphics only)

• Map Object (page 8-222) (GeoGraphics only)

• Project Object (page 8-226) (GeoGraphics only)

State Object

Properties and Methods Used to

MbeState.inputType (page 8-3) Returns information about the type of input that the user entered.

MbeState.getInputCommand (page 8-3) Get the command string entered by the user.

MbeState.getInputDataPoint (page 8-4) Get the coordinates and view of a data point entered by the user.

MbeState.getInputKeyin (page 8-4) Get the key-in string entered by the user.

MbeState.cmdResult (page 8-5) Get the result of input (data point, reset, etc.) submitted by the macro.

MbeState.errorMessages, MbeState.messages (page 8-6)

Enable or disable error/status messages that MicroStation displays to the user.

MbeState.noElementDisplay (page 8-6) Temporarily disable the display of graphics elements in views.

MbeState.parseAll (page 8-7) Tell MicroStation to parse or not parse all user key-ins for commands.

MbeState.measureResult1, MbeState.measureResult2 (page 8-7)

Access the results of the last MicroStation measure command.

MbeState.locateTolerance (page 8-8) Set the location tolerance that MicroStation uses.

MbeState.locateFileNum (page 8-9) Get the file number of an element that has been located by the user.

MbeState.locateHeaderFilePos (page 8-10) Get the file position of the complex header of the element that has been located by the user.

MbeState.locateComponentFilePos (page 8-10)

Get the file position of the component of the complex element nearest the data point used to locate an element.

MbeState.setLocateFileMask, MbeState.getLocateFileMask (page 8-10)

Set/determine which files are eligible for element location logic during command execution or fence processing by a macro.

MbeState.setLocateTypeMask, MbeState.getLocateTypeMask (page 8-11)

Set/determine which graphic element types are eligible for element location logic during command execution or fence processing by a macro.

8-2 MicroStation BASIC Guide

Page 313: 48784209 Microstation Basic

State Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 3 Friday, October 15, 1999 1:27 PM

MbeState.inputTypeMbeState.inputType

Descr. The MbeState.inputType property returns information about the type of input that the user entered. MbeState.inputType is a read-only property, and is valid only after a call to MbeGetInput. Its value will be one of the predefined constants MBE_CommandInput, MBE_DataPointInput, MBE_ResetInput or MBE_KeyinInput. It is typically used in an If statement or Select statement to control program flow based on input type. Once the input type is known, the macro can use one of the MbeState methods that return the user input details: MbeState.getInputCommand, MbeState.getInputDataPoint or MbeState.getInputKeyin.

Example MbeGetInput MBE_DataPointInput, MBE_ResetInputIf MbeState.inputType = MBE_DataPointInput Then

' Process data point hereElse

' Process reset hereEnd If

See also MbeGetInput, MbeState.getInputCommand, MbeState.getInputDataPoint, MbeState.getInputKeyin.

MbeState.getInputCommandstatus = MbeState.getInputCommand(commandString as String)

Descr. The MbeState.getInputCommand object function sets the commandString argument to the command string entered by the user. It is valid to call MbeState.getInputCommand only after calling MbeGetInput, and only when MbeState.inputType equals MBE_CommandInput.

Returns If the call to MbeState.getInputCommand is valid, the function returns MBE_Success. Otherwise, it returns MBE_WrongInputType (1101) and commandString is set to an empty string.

Example Dim cmdString$ as String...MbeGetInput MBE_DataPointInput, MBE_CommandInputIf MbeState.inputType = MBE_CommandInput Then

If MbeState.getInputCommand (cmdString$) = MBE_Success Then' Process Command here

MbeState.locatePropMask, MbeState.locatePropVal (page 8-13)

Limit elements eligible for user location and fence processing based on their properties.

MbeState.locateClassMask (page 8-14) Limit elements eligible for user location and fence processing based on their class.

Properties and Methods Used to

MicroStation BASIC Guide 8-3

Page 314: 48784209 Microstation Basic

State Object

600macro.bk : 608_EXT.FRA Page 4 Friday, October 15, 1999 1:27 PM

End IfElse

' Process data point hereEnd If

See also MbeGetInput, MbeState.inputType.

MbeState.getInputDataPointstatus = MbeState.getInputDataPoint(dataPoint as MbePoint [, view as _ Integer [, screenPoint as MbePoint]])

Descr. The MbeState.getInputDataPoint object function sets the dataPoint argument to the coordinates entered by the user and the optional view argument to the view in which the data point was entered. The optional screenPoint argument is set to the position of the data point in screen coordinates. The actual value of the screenPoint is of limited use. However, on comparing screenPoint from two different data points entered in the same view shows if the user has moved the input pointer significantly. It is valid to call MbeState.getInputDataPoint only after calling MbeGetInput, and only when MbeState.inputType equals MBE_DataPointInput.

Returns If the call to MbeState.getInputDataPoint is valid, the function returns MBE_Success. Otherwise, it returns MBE_WrongInputType (1101) and the dataPoint and view arguments are set to 0.

Example Dim dataPoint as MbePointDim view as Integer...MbeGetInput MBE_DataPointInput, MBE_CommandInputIf MbeState.inputType = MBE_DataPointInput Then

If MbeState.getInputDataPoint(dataPoint, view) = MBE_Success Then' Process Data point here

End IfElse

' Process command hereEnd If

See also MbeGetInput, MbeState.inputType.

MbeState.getInputKeyinstatus = MbeState.getInputKeyin(keyinString as String)

Descr. The MbeState.getInputKeyin object function sets keyinString to the string entered by the user. It is valid to call MbeState.getInputKeyin only after calling MbeGetInput, and only when MbeState.inputType equals MBE_KeyinInput.

Returns If the call to MbeState.getInputKeyin is valid, the function returns MBE_Success. Otherwise it returns MBE_WrongInputType (1101) and keyinString is set to an empty string.

8-4 MicroStation BASIC Guide

Page 315: 48784209 Microstation Basic

State Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 5 Friday, October 15, 1999 1:27 PM

Example Dim keyinString$ as String...MbeGetInput MBE_DataPointInput, MBE_KeyinInputIf MbeState.inputType = MBE_KeyinInput Then

If MbeState.getInputKeyin(keyinString$) = MBE_Success Then' Process Keyin here

End IfElse

' Process data point hereEnd If

See also MbeGetInput, MbeState.inputType.

MbeState.cmdResultMbeState.cmdResult

Descr. Upon return from a call to MbeSendDataPoint, MbeSendKeyin, MbeSendReset, MbeSendLastInput, MbeSendCommand, MbeRelocate or MbeLocateElement, the MbeState.cmdResult Integer property can be checked to determine the result of the input. Note that MbeState.cmdResult can be reliably checked only immediately following a call to one of the previously mentioned subroutines.

Common values of MbeState.cmdResult and their meanings are:

MBE_Success successful processing

MBE_ElementNotFound tried to locate element, but couldn’t

MBE_AcceptQuery element found, prompting “Accept/Reject”

MBE_UnknownCommand Command not recognized

MBE_3Donly 2D file, 3D command

MBE_RefFileNotFound Could not find reference file

MBE_ViewNotFound Named view could not be found

MBE_IllegalDefinition Data point resulted in illegal element def.

MBE_OffDesignPlane Data point put element off design plane

MBE_NeedChars Text data point before entering string

MBE_CellLibNotFound Could not find cell library

MBE_NoCellLibrary No cell library attached

MBE_NoOrigin No cell origin defined when creating cell

MBE_NoFenceActive Operation requires a fence, none active

MBE_EmptyFence No elements found within fence

MBE_BadCellName Invalid cell name when creating cell

MBE_CellExists Cell already in library on creating cell

MBE_CellNotFound Cell not found

MBE_NoActiveCell Attempt to place cell with no active cell

MBE_3DLib2DFile Attempt to create 3D cell in 2D library

MicroStation BASIC Guide 8-5

Page 316: 48784209 Microstation Basic

State Object

600macro.bk : 608_EXT.FRA Page 6 Friday, October 15, 1999 1:27 PM

Example Dim point as MbePoint...MbeSendInputDataPoint pointIf MbeState.cmdResult = MBE_AcceptQuery Then

' element found by MicroStation... (process here)

End If

See also MbeSendDataPoint, MbeSendKeyin, MbeSendReset, MbeSendCommand, MbeRelocate, MbeLocateElement.

MbeState.errorMessages, MbeState.messagesMbeState.errorMessagesMbeState.messages

Descr. The MbeState.errorMessages and MbeState.messages read/write Integer properties are used to enable and disable the messages that display to the user. Often, a macro will want to display its own messages in place of the usual MicroStation messages, and thus the MicroStation messages must be suppressed. To turn off all messages except error messages, set MbeState.messages to zero. To turn off error messages, set MbeState.errorMessages to zero. Any nonzero value enables MicroStation’s messages.

The effect of setting MbeState.errorMessages and MbeState.messages is permanent until it is changed by the macro (or another macro). Thus, it is wise to save the settings of these two properties before setting them and to restore them to their previous values as part of the exit code for a macro.

Example saveErrMsgs = MbeState.errorMessagessaveMsgs = MbeState.messages

MbeState.errorMessages = 0MbeState.messages = 0...MbeState.errorMessages = saveErrMsgsMbeState.messages = saveMsgs

MbeState.noElementDisplayMbeState.noElementDisplay

Descr. The MbeState.noElementDisplay read/write Integer property is used to temporarily disable the display of graphics elements to MicroStation views. To turn off element

MBE_CellDeleted Cell successfully deleted

MBE_CellNestError Cell nesting error (nests itself)

MBE_FileReadOnly Tried to write to read-only design file

MBE_InvalidRefOp Invalid reference file operation

8-6 MicroStation BASIC Guide

Page 317: 48784209 Microstation Basic

State Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 7 Friday, October 15, 1999 1:27 PM

display, set MbeState.noElementDisplay to any nonzero value. To turn element display back on, set MbeState.noElementDisplay to zero.

The effect of setting MbeState.noElementDisplay is permanent until it is changed by the macro. Since turning off element display affect MicroStation operation quite dramatically, it should be used with caution and always set back to zero as part the exit code for a macro.

Example MbeState.noElementDisplay = 1... ' do whatever operations are needed without element displayMbeState.noElementDisplay = 0

MbeState.parseAllMbeState.parseAll

Descr. The MbeState.parseAll read/write Integer property is used to direct MicroStation to try to parse user key-ins regardless of MicroStation state. For example, if MbeState.parseAll is nonzero, MicroStation parses all key-ins for commands even when it is prompting the user to enter text for the place text command.

Because there are separate BASIC extension statements for sending MicroStation commands and key-ins, this property is rarely needed by a macro, and it is recommended that it not be used.

The effect of setting MbeState.parseAll is permanent until it is changed by another macro. Thus it is wise to save the setting of the property before setting it and to restore it to its previous value as part of the exit code for a macro.

Example saveParseAll = MbeState.parseAllMbeState.parseAll = 0...MbeState.parseAll = saveParseAll

MbeState.measureResult1, MbeState.measureResult2MbeState.measureResult1

MbeState.measureResult2

Descr. The MbeState.measureResult1 and MbeState.measureResult2 read-only properties are of type Double and are used to access the results of the last MicroStation measure command. They are used when a macro sequences one of the measure commands and

MicroStation BASIC Guide 8-7

Page 318: 48784209 Microstation Basic

State Object

600macro.bk : 608_EXT.FRA Page 8 Friday, October 15, 1999 1:27 PM

needs access to the result. The following table shows the values placed in these two properties by MicroStation and the units of the values.

The MbeCurrentTransform.scalarFromUors object function can be used to transform the Measure Distance result to the macro units, if desired.

Example Dim area as DoubleDim perimeter as Double

... ' sequence the measure area command

area = MbeState.measureResult1perimeter = MbeState.measureResult2

MbeCurrentTransform.scalarFromUors

MbeState.locateToleranceMbeState.locateTolerance

Descr. The MbeState.locateTolerance read/write Integer object property is used to set the “location tolerance” that MicroStation uses. The location tolerance is the diameter, in screen pixels, of a circle surrounding the screen pointer location. When a MicroStation command asks the user to locate an element, an element that has any part drawn inside the location tolerance circle is considered for location.

The location tolerance is also used to determine when two points are “close enough” to be considered the same for MicroStation. Since the location tolerance is based on screen coordinates, this means that two points may be “close enough” when looking at a zoomed out view, but not “close enough” when looking at a magnified view. Occasionally this causes problems for macros that sequence commands like PLACE SHAPE, which assume the user meant to close a shape when the input point is “close enough” to the starting point. The problems surface in a zoomed out view, and can generally be prevented by setting MbeState.locateTolerance temporarily to zero and then setting it back to its original value when the operation is over.

Command measureResult1 measureResult2

Measure Angle AngleDegrees

not used

Measure Area Element

AreaSquare Master Units

PerimeterMaster Units

Measure Distance

DistanceUnits of Resolution

not used

Measure Length LengthMaster Units

not used

Measure Radius Primary RadiusMaster Units

Secondary RadiusMaster Units

Measure Volume VolumeCubic Master Units

Surface AreaSquare Master Units

8-8 MicroStation BASIC Guide

Page 319: 48784209 Microstation Basic

State Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 9 Friday, October 15, 1999 1:27 PM

The effect of setting MbeState.locateTolerance is permanent until it is changed by the macro (or another macro). Thus it is wise to save the settings of the property before setting it and restore it to its previous value as part of the exit code for a macro.

Example Sub drawOutline (origin as MbePoint, view as Integer, _totalWidth as Double, totalHeight as Double)

Dim point as MbePointDim saveTolerance as Integer

saveTolerance = MbeState.locateToleranceMbeState.locateTolerance = 0

point = originCall MbeSendCommand("PLACE SHAPE")Call MbeSendDataPoint(origin, view)point.x = origin.x + totalWidthCall MbeSendDataPoint(point, view)point.y = origin.y - totalHeightCall MbeSendDataPoint(point, view)point.x = origin.xCall MbeSendDataPoint(point, view)point.y = origin.yCall MbeSendDataPoint(point, view)MbeState.locateTolerance = saveTolerance

End Sub

MbeState.locateFileNumMbeState.locateFileNum

Descr. When an element has been located by the user (either as part of a command sequence or as a result of using the MbeStartLocate function in a Macro), the read-only properties locateFileNum, locateHeaderFilePos and locateComponentFilePos can be used to retrieve the file that the located element is in, the file position of the complex header, and file position of the component of the complex element that was nearest the data point used to locate the element. If the selected element is not complex, locateHeaderFilePos and locateComponentFilePos will be identical. If the MbeStartLocate function is used, the MbeElement.fromLocate is a better way to retrieve the element located than using MbeElement.fromFile with the MbeState.locateFileNum and MbeState.locateHeaderFilePos properties because it sets the current position in the element to the proper component element. MbeState.locateFileNum is of type Integer.

Example Dim element as New MbeElement...stat = element.fromFile(MbeState.locateHeaderFilePos, _

MbeState.locateFileNum)

See also MbeElement.fromLocate, MbeStartLocate.

MicroStation BASIC Guide 8-9

Page 320: 48784209 Microstation Basic

State Object

600macro.bk : 608_EXT.FRA Page 10 Friday, October 15, 1999 1:27 PM

MbeState.locateHeaderFilePosMbeState.locateHeaderFilePos

Descr. When an element has been located by the user (either as part of a command sequence or as a result of using the MbeStartLocate function in a Macro), the read-only properties locateFileNum, locateHeaderFilePos and locateComponentFilePos can be used to retrieve the file that the located element is in, the file position of the complex header, and file position of the component of the complex element that was nearest the data point used to locate the element. If the selected element is not complex, locateHeaderFilePos and locateComponentFilePos will be identical. If the MbeStartLocate function is used, the MbeElement.fromLocate is a better way to retrieve the element located than using MbeElement.fromFile with the MbeState.locateFileNum and MbeState.locateHeaderFilePos properties because it sets the current position in the element to the proper component element.

Example Dim element as New MbeElement...stat=element.fromFile(MbeState.locateHeaderFilePos,MbeState.locateFileNum)

See also MbeElement.fromLocate, MbeStartLocate.

MbeState.locateComponentFilePosMbeState.locateComponentFilePos

Descr. When an element has been located by the user (either as part of a command sequence or as a result of using the MbeStartLocate function in a Macro), the read-only properties locateFileNum, locateHeaderFilePos and locateComponentFilePos can be used to retrieve the file that the located element is in, the file position of the complex header, and file position of the component of the complex element that was nearest the data point used to locate the element. If the selected element is not complex, locateHeaderFilePos and locateComponentFilePos will be identical. If the MbeStartLocate function is used, the MbeElement.fromLocate is a better way to retrieve the element located than using MbeElement.fromFile with the MbeState.locateFileNum and MbeState.locateHeaderFilePos properties because it sets the current position in the element to the proper component element.

Example Dim element as New MbeElement...stat=element.fromFile(MbeState.locateComponentFilePos, _ MbeState.locateFileNum)

See also MbeElement.fromLocate, MbeStartLocate.

MbeState.setLocateFileMask, MbeState.getLocateFileMaskstat = MbeState.setLocateFileMask(fileArray() as Long)

stat = MbeState.setLocateFileMask()stat = MbeState.getLocateFileMask(fileArray() as Long)

8-10 MicroStation BASIC Guide

Page 321: 48784209 Microstation Basic

State Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 11 Friday, October 15, 1999 1:27 PM

Descr. When a macro sequences commands that either select an element (e.g., Rotate Element) or use a fence, the macro can specify which MicroStation files are eligible by setting a file mask using the setLocateFileMask object function. The file mask set using setLocateFileMask takes effect only for data points sent by the macro, and does not affect MicroStation operation after the macro exits.

The setLocateFileMask takes one optional argument that specifies, in the form of an array of 8 Longs, one bit for each file. The low-order bit of the first array element is for the master file, the next-lowest bit in the first array element is for the first reference file, etc. The low-order bit of the second array element is for reference file 32, and so on. If the fileArray argument is left off, any previous setting of the locate file mask is cleared, and the files searched for elements is left up to MicroStation.

If it is included, fileArray must be an array of Longs with 8 elements. If you are using Option Base 0 (the default) the correct Dim statement is:

Dim fileArray(7) as Long

If you are using Option Base 1, then the correct Dim statement is:

Dim fileArray(8) as Long

In either case you could be more specific:

Dim fileArray(1 to 8) as Long

The getLocateFileMask object function retrieves the file mask set by setLocateFileMask. If setLocateFileMask is not called or is called without its optional argument, every element of the fileArray retrieved by getLocateFileMask will be 0.

Returns Both functions return MBE_Success if successful or MBE_WrongDimension (801) if fileArray is dimensioned incorrectly.

Example Dim fileArray(1 to 8) as LongfileArray(1) = 255 ' select from master file and first 7 reference filesstat = MbeState.setLocateFileMask(fileArray)...stat = MbeState.getLocateFileMask(fileArray)fileArray(1) = fileArray(1) Or 256stat = MbeState.setLocateFileMask(fileArray)stat = MbeState.setLocateFileMask() ' clear locate mask

See also MbeState.setLocateTypeMask, MbeState.getLocateTypeMask, MbeState.locatePropMask, MbeState.locatePropVal, MbeState.locateClassMask.

MbeState.setLocateTypeMask, MbeState.getLocateTypeMaskstat = MbeState.setLocateTypeMask(typeArray() as Integer)

stat = MbeState.setLocateTypeMask()stat = MbeState.getLocateTypeMask(typeArray() as Integer)

MicroStation BASIC Guide 8-11

Page 322: 48784209 Microstation Basic

State Object

600macro.bk : 608_EXT.FRA Page 12 Friday, October 15, 1999 1:27 PM

Descr. When a Macro is sequencing commands that either select an element (e.g., Rotate Element) or use a fence, the Macro can specify which MicroStation graphic element types are eligible by setting a type mask using the setLocateTypeMask object function. The element type mask set using setLocateTypeMask takes effect only for data points sent by the macro, and does not affect MicroStation operation after the macro exits.

The setLocateTypeMask takes one optional argument that specifies, in the form of an array of 8 Integers, one bit for each graphics element type. The low-order bit of the first array element is for element type 1, the next-lowest bit in the first array element is element type 2, etc. The low-order bit of the second array element is for element type 17, and so on. If typeArray is left off, any previous setting of the locate type mask is cleared, and the types eligible for selection is left up to MicroStation.

typeArray must be an array of Integer with 8 elements. If you are using Option Base 0 (the default) the correct Dim statement is:

Dim typeArray(7)as Integer

If you are using Option Base 1, then the correct Dim statement is:

Dim typeArray(8) as Integer

In either case you could be more specific:

Dim typeArray(1 to 8) as Integer

The element type numbers are listed in the reference material for the MbeElement.type on page 8-29. The correct bit for a particular element can be set in BASIC using the following subroutine:

Example Sub setElemTypeBit(typeArray() as Integer, elemType as Integer)dim bitNum as Integerdim index as Integer

bitNum = (elemType-1) Mod 16index = LBound(typeArray) + (elemType-1) \ 16If bitNum = 15 Then

typeArray(index) = typeArray(index) Or -32768Else

typeArray(index) = typeArray(index) Or 2 ^ bitNumEnd If

End Sub

The getLocateTypeMask object function retrieves the type mask set by setLocateTypeMask. If setLocateTypeMask is not called or is called without its optional argument, every element of the typeArray retrieved by getLocateTypeMask will be 0.

Both functions return MBE_Success if successful, or MBE_WrongDimension if typeArray is dimensioned incorrectly.

Example Dim typeArray(1 to 8) as IntegersetElemTypeBit typeArray, MBE_Text ' select text

8-12 MicroStation BASIC Guide

Page 323: 48784209 Microstation Basic

State Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 13 Friday, October 15, 1999 1:27 PM

setElemTypeBit typeArray, MBE_TextNode ' select text nodessetElemTypeBit typeArray, MBE_CellHeader ' select cells

stat = MbeState.setLocateTypeMask(typeArray)...

stat = MbeState.getLocateTypeMask(typeArray)setElemTypeBit typeArray, MBE_Shape ' add shape elementsstat = MbeState.setLocateTypeMask(typeArray)stat = MbeState.setLocateTypeMask() ' clear locate type mask

See also MbeState.setLocateFileMask, MbeState.getLocateFileMask, MbeState.setLocateTypeMask, MbeState.getLocateTypeMask, MbeState.locateClassMask.

MbeState.locatePropMask, MbeState.locatePropValMbeState.locatePropMask

MbeState.locatePropVal

Descr. The MbeState.locatePropMask and MbeState.locatePropVal Integer properties are used together to limit the element eligible for user location and fence processing based on the element properties. The properties mask and value set using these object properties takes effect only for data points sent by the macro, and does not affect MicroStation operation after the macro exits.

The element properties are a group of bits in the element header that indicate locked status, new status, modified status, attributes present, view independent, hole or solid status, planar, and snappable. The bit name and meaning are summarized in the reference section for the MbeElement.properties object property.

To indicate that the value of a particular property should be used to determine locate eligibility, the corresponding bit in the MbeState.locatePropMask is set, and the corresponding bit in MbeState.locatePropVal is set to the desired value. For example, to locate only unlocked elements (without caring about the state of other properties bits), the following BASIC statements are used:

MbeState.locatePropMask = MBE_LockedProperty ' "locked" property relevantMbeState.locatePropVal = 0 ' want it to be zero.

To select only elements with user attributes present, the following BASIC statements are used:

MbeState.locatePropMask = MBE_AttributePropertyMbeState.locatePropVal = MBE_AttributeProperty

Combinations of property bits can be set by Oring different properties bits into locatePropMask and locatePropVal.

See also MbeState.setLocateFileMask, MbeState.getLocateFileMask, MbeState.setLocateTypeMask, MbeState.getLocateTypeMask, MbeState.locateClassMask.

MicroStation BASIC Guide 8-13

Page 324: 48784209 Microstation Basic

State Object

600macro.bk : 608_EXT.FRA Page 14 Friday, October 15, 1999 1:27 PM

MbeState.locateClassMaskMbeState.locateClassMask

Descr. The MbeState.locateClassMask Integer property is used to limit the element eligible for user location and fence processing based on the element class. The class mask set using this object property takes effect only for data points sent by the macro, and does not affect MicroStation operation after the macro exits.

Each graphics element has a class value associated with it. The element classes are summarized in the reference section for the MbeElement.class object property.

To indicate that a particular class of elements is eligible for location and fence operations, the corresponding bit in the MbeState.locateClassMask is set. If the MbeState.locateClassMask property is never assigned by a macro, then the selection of eligible classes is left to MicroStation. Regardless of whether the “primary” class bit is set or not, MicroStation allows selection of elements in the primary class. The bit in the mask for a class is set using the BASIC statement:

Example MbeState.locateClassMask = MbeState.locateClassMask Or 2 ^ (classNum-1)MbeState.locateClassMask = MbeState.locateClassMask Or 2 ^(MBE_DimClass-1)

See also MbeState.setLocateFileMask, MbeState.getLocateFileMask, MbeState.setLocateTypeMask, MbeState.getLocateTypeMask, MbeState.locatePropMask, MbeState.locatePropVal.

8-14 MicroStation BASIC Guide

Page 325: 48784209 Microstation Basic

Element Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 15 Friday, October 15, 1999 1:27 PM

Element Object

Properties and Methods Used to

MbeElement.addToFile (page 8-45) Add the MbeElement to the end of the master file.

MbeElement.appendDBLinkage (page 8-21)

Append database linkage to the element.

MbeElement.area (page 8-46) Get the area of the element at the current position.

MbeElement.attachActiveEntity (page 8-18)

Attach active entity to the element.

MbeElement.cellName (page 8-47) Get the name of the cell in the cell header at the current position.

MbeElement.changeAll (page 8-34) Control the scope of changes made to the MbeElement’s properties.

MbeElement.charHeight, MbeElement.charWidth (page 8-50)

Get the character (height/width) of the text, text node, or tag element at the current position.

MbeElement.class (page 8-36) Set the class of an element in the MbeElement or retrieve the class from the element at the current position.

MbeElement.color (page 8-35) Set the color of an element in the MbeElement or retrieve the color from the element at the current position.

MbeElement.componentFilePos (page 8-33)

Return the file position of the element at the current position.

MbeElement.deleteDBLinkage (page 8-21)

Delete linkage specified in MbeDatabaseLink object.

MbeElement.display (page 8-45) Display the MbeElement in one or more views.

MbeElement.extractDBLinkages (page 8-20)

Extract database attributes to MbeDatabaseLink array

MbeElement.fileNum (page 8-33) Return the file number from which the MbeElement originated.

MbeElement.filePos (page 8-33) Return the file position from which the MbeElement originated.

MbeElement.fileSize (page 8-30) Get the size of the entire MbeElement as it exists in the file.

MbeElement.firstElement (page 8-22) Set complex element position to the first element.

MbeElement.font (page 8-49) Get or set the font (by number) of one or all component text, text node or tag elements in the MbeElement.

MbeElement.fontName (page 8-49) Get or set the font (by name) of one or all component text, text node or tag elements in the MbeElement.

MbeElement.foundDBLinkages (page 8-19)

Test whether element has database attributes.

MbeElement.fromFile (page 8-31) Read an element from a master or reference file.

MbeElement.fromLocate (page 8-32) Read the last element located by a user (or a macro calling MbeStartLocate).

MicroStation BASIC Guide 8-15

Page 326: 48784209 Microstation Basic

Element Object

600macro.bk : 608_EXT.FRA Page 16 Friday, October 15, 1999 1:27 PM

MbeElement.getCellBox (page 8-48) Get the eight points that comprise the range box associated with the cell at the current position.

MbeElement.getCellLevels (page 8-48) Determine the levels occupied by the cell at the current position.

MbeElement.getCentroid (page 8-47) Get the centroid of the element at the current position.

MbeElement.getEndPoints (page 8-41) Get the start and end points of the graphics element at the current position.

MbeElement.getOrigin (page 8-38) Get the origin of the graphics element at the current position.

MbeElement.getPoints (page 8-39) Get an array of points that comprise the graphics element at the current position.

MbeElement.getRange (page 8-41) Get the range of the element at the current position.

MbeElement.getRotation (page 8-49) Get the rotation matrix for the element at the current position.

MbeElement.getString (page 8-52) Set the text string for the text element at the current position.

MbeElement.getTopOrigin (page 8-55) Get the center of the top circle of the cone element at the current position.

MbeElement.group (page 8-57) Set or retrieve the graphic group of the MbeElement.

MbeElement.headerElement (page 8-26)

Resets the current position to the header of the element at the current position.

MbeElement.internalSize (page 8-30) Get the size of the element at the current position as it exists in memory.

MbeElement.isComponent (page 8-29) Determine if the element at the current position is a component of a complex element.

MbeElement.isGraphics (page 8-29) Determine if the element at the current position is a graphics element.

MbeElement.isHeader (page 8-28) Determine if the element at the current position is a complex header.

MbeElement.justification (page 8-51) Get the justification of the text, text node or tag element at the current position.

MbeElement.level (page 8-34) Set the level of an element in the MbeElement or retrieve the level from the element at the current position.

MbeElement.lineSpacing (page 8-51) Get the character width and height of the text node element at the current position.

MbeElement.loadDAttributes (page 8-19)

Load displayable attribute text node.

MbeElement.move (page 8-42) Offset the coordinates of one or all elements in the MbeElement.

MbeElement.nextComponent (page 8-24)

Set element position to the next component under the current complex header.

MbeElement.nextElement (page 8-22) Set complex element position to the next element at the previous nest level.

Properties and Methods Used to

8-16 MicroStation BASIC Guide

Page 327: 48784209 Microstation Basic

Element Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 17 Friday, October 15, 1999 1:27 PM

MbeElement.perimeter (page 8-46) Get the perimeter of the element at the current position.

MbeElement.primaryAxis (page 8-53) Get or set the primary axis of the arc or ellipse element at the current position.

MbeElement.properties (page 8-37) Set or retrieve the properties bit flags of the component element at the current position.

MbeElement.publish (page 8-56) Publish the MbeElement for manipulation by C expression functions (rarely used).

MbeElement.reportDBLinkages (page 8-19)

Process database linkage and populate report rows.

MbeElement.reviewDBAttributes (page 8-18)

Review database attributes of the element.

MbeElement.rewrite (page 8-44) Rewrite the MbeElement at the file position from which it was read.

MbeElement.rotate (page 8-42) Rotate one or all elements in the MbeElement.

MbeElement.scale (page 8-43) Scale one or all elements in the MbeElement.

MbeElement.secondaryAxis (page 8-54)

Get or set the secondary axis of the arc or ellipse element at the current position.

MbeElement.setPoints (page 8-40) Set the points that make up the linear element at the current position.

MbeElement.setString (page 8-53) Set the text string for the text element at the current position.

MbeElement.startAngle (page 8-54) Get or set the start angle of the arc element at the current position.

MbeElement.style (page 8-35) Set the line style of an element in the MbeElement or retrieve the line style from the element at the current position.

MbeElement.sweepAngle (page 8-55) Get or set the sweep angle of the arc element at the current position.

MbeElement.thisComponent (page 8-27)

Get a handle to the current component or set the current component.

MbeElement.topRadius, MbeElement.bottomRadius (page 8-55)

Get the (top/bottom) radius of the cone element at the current position.

MbeElement.type (page 8-29) Get the type of the element at the current position.

MbeElement.volume (page 8-47) Get the volume of the element at the current position.

MbeElement.weight (page 8-36) Set the weight of an element in the MbeElement or retrieve the weight from the element at the current position.

MbeElement.isTagged (page 8-57) Decide whether the element has any tag attached.

MbeElement.tagId (page 8-57) Get the association ID of the element.

MbeElement.numTags (page 8-58) Get the number of tags attached to the element.

MbeElement.extractTags (page 8-58)

Get the array of tags attached to the element.

Properties and Methods Used to

MicroStation BASIC Guide 8-17

Page 328: 48784209 Microstation Basic

Element Object

600macro.bk : 608_EXT.FRA Page 18 Friday, October 15, 1999 1:27 PM

MbeElement.attachActiveEntityMbeElement.attachActiveEntity

Descr. The MbeElement.attachActiveEntity command links the graphic element with the active entity. The active entity must have been established with MicroStation FIND, CREATE ENTITY, DEFINE AE or ACTIVE ENTITY command. The database linkage that is created will be appended to existing attributes present on the element object. No existing linkages will be disturbed. If the linkage mode is NEW, the database server will copy the active entity and add a new record to the database. The MicroStation environment variable MS_LINKTYPE controls the linkage format.

Example Dim element as New MbeElementelement.attachActiveEntity... rewrite the element

See also MbeElement.reviewDBAttributes, MbeDatabase.showActiveEntity, MbeDatabase.defineActiveEntity.

MbeElement.reviewDBAttributesMbeElementMbeElement.reviewDBAttributes

Descr. The MbeElement.reviewDBAttributes command interactively reviews attribute linkages present on the element. The database server will execute the REVIEW SINGLE MicroStation command for the element linkages. If screen forms are activated, the entity's active screen form will be used. Otherwise, the SQL SELECT statement specified by the MicroStation command ACTIVE REVIEW will control attributes displayed for each linkage.

Example Dim element as New MbeElementelement.reviewDBAttributes

See also MbeElement.attachActiveEntity.

MbeElement.getMbeTag (page 8-58) Get MbeTag object from attribute element (type 37).

MbeElement.attachTag (page 8-59) Attach a tag to the element.

MbeElement.getNumLinkages (page 8-59)

get number of user attribute data linkages on element.

MbeElement.extractLinkage (page 8-59)

extract a user attribute data linkage from an element.

MbeElement.appendLinkage (page 8-60)

add a new user attribute data linkage to an element.

MbeElement.deleteLinkage (page 8-61)

delete a user attribute data linkage from an element.

Properties and Methods Used to

8-18 MicroStation BASIC Guide

Page 329: 48784209 Microstation Basic

Element Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 19 Friday, October 15, 1999 1:27 PM

MbeElement.reportDBLinkagesMbeElement.reportDBLinkages

Descr. The MbeElement.reportDBLinkages command processes database linkages on the MbeElement object. The database server will add one row to the corresponding report table for each occurrence of an attribute linkage. The MicroStation command ACTIVE REPORT defines the report table contents.

Subsequent calls to MbeElement.reportDBLinkages will accumulate additional rows in the report tables according to the attribute linkages present on the elements.

Example Dim element as New MbeElementelement.reportDBLinkages

See also MbeDatabase.reportOpen, MbeDatabase.reportClose.

MbeElement.loadDAttributesMbeElement.loadDAttributes

Descr. The MbeElement.loadDAttributes command loads a displayable attribute text node with attribute information from the database. The MbeElement object must be of type text node with a displayable attribute database linkage.

Existing text elements attached to the text node are replaced with the text strings reflecting the current database attribute contents. The screen form associated with the displayable attribute code of the text node's database linkage determines the text string format. The text string properties such as font, text size, line spacing and justification are taken from the text node.

Example Dim element as New MbeElementIf element.type = MBE_TextNode Then

If element.foundDBLinkages = MBE_Success Thenelement.loadDAttributes

End IfEnd If

See also MbeElement.foundDBLinkages.

MbeElement.foundDBLinkagesstat = MbeElement.foundDBLinkages()

Descr. The MbeElement.foundDBLinkages function tests to determine whether an element contains attribute data linkages that belong to the database server. Elements can

MicroStation BASIC Guide 8-19

Page 330: 48784209 Microstation Basic

Element Object

600macro.bk : 608_EXT.FRA Page 20 Friday, October 15, 1999 1:27 PM

contain many types of attribute data linkages that belong to either application programs or the database interface.

MbeElement.foundDBLinkages is a convenient way to determine whether the MbeElement contains at least one linkage that belongs to the database server.

Returns MbeElement.foundDBLinkages returns MBE_Success if the element has one or more linkages that belong to the database server and MBE_NoLinkage if no recognized linkages are present.

Example Dim inElem as New MbeElementDim lnk() as MbeDatabaseLinkDim numLinks as IntegerDim stat as IntegerIf inElem.foundDBLinkages = MBE_Success Then

...process linkagesEnd If

See also MbeElement.extractDBLinkages.

MbeElement.extractDBLinkagesstat = MbeElement.extractDBLinkages(link() as MbeDatabaseLink)

Descr. The MbeElement.extractDBLinkages function extracts an element's database linkages. Only the linkage types identified by MS_LINKTYPE will be recognized by this function.

link specifies a variable length array of MbeDatabaseLink objects which will be redimensioned to point to the array of the linkages found.

Returns MbeElement.extractDBLinkages returns MBE_Success if any existing linkages were successfully extracted. Otherwise, an error status is returned.

Example Dim inElem as New MbeElementDim lnk() as MbeDatabaseLinkDim numLinks as IntegerDim stat as IntegerIf inElem.foundDBLinkages = MBE_Success Then

If inElem.extractDBLinkages(lnk) = MBE_Success ThenFor iLink = LBound(lnk) To UBound(lnk)

If lnk(iLink).tableName = fromTable ThenCall rewriteLinkage(inElem, lnk(iLink))

End IfNext iLink

End IfEnd If

See also MbeElement.foundDBLinkages, MbeElement.appendDBLinkage, MbeElement.deleteDBLinkage.

8-20 MicroStation BASIC Guide

Page 331: 48784209 Microstation Basic

Element Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 21 Friday, October 15, 1999 1:27 PM

MbeElement.appendDBLinkagestat = MbeElement.appendDBLinkage(link as MbeDatabaseLink)

Descr. The MbeElement.appendDBLinkage function appends database attribute information present in the MbeDatabaseLink object link to the end of any existing attributes on the element. The linkType, tableName, entityNumber and mslink properties of the MbeDatabaseLink object must be set before passing it as a parameter for appendDBLinkages.

Returns MbeElement.appendDBLinkage returns MBE_Success if the linkage is successfully appended. Otherwise, an error status is returned.

Example Dim lnk as New MbeDatabaseLinkDim inElem as MbeElementlnk.tableName = tb.namelnk.entityNumber = tb.entityNumberlargestMslink = tb.largestMslinkIf inElem.appendDBLinkage(lnk) = MBE_Success Then

stat = inElem.rewrite()End If

See also MbeElement.extractDBLinkages, MbeElement.deleteDBLinkage, MbeDatabaseLink, MbeDatabaseLink.linkType, MbeDatabaseLink.tableName, MbeDatabaseLink.mslink.

MbeElement.deleteDBLinkagestat = MbeElement.deleteDBLinkage(link as MbeDatabaseLink)

Descr. The MbeElement.deleteDBLinkage function removes the database attribute linkage(s) matching to the properties set in the link parameter. If no properties are set by link, all database attributes will be stripped off.

No other types of user data linkages but database will be disturbed. The environment variable MS_LINKTYPE sets the types of linkages that the server processes.

Returns MbeElement.deleteDBLinkage returns MBE_Success if the attribute linkage(s) was successfully removed.

Example Sub RemoveAllOracleLinkages (inElem as MbeElement)Dim link as New MbeDatabaseLinklink.linkType = MBE_ORACLE_LinkageIf inElem.deleteDBLinkage (link) = MBE_Success Then

stat = inElem.rewrite ()End If

End Sub

See also MbeElement.extractDBLinkages, MbeElement.appendDBLinkage, MbeDatabaseLink, MbeDatabaseLink.linkType, MbeDatabaseLink.tableName, MbeDatabaseLink.entityNumber, MbeDatabaseLink.mslink.

MicroStation BASIC Guide 8-21

Page 332: 48784209 Microstation Basic

Element Object

600macro.bk : 608_EXT.FRA Page 22 Friday, October 15, 1999 1:27 PM

MbeElement.firstElementMbeElement.firstElement

Descr. The MbeElement.firstElement statement sets the current position within a complex MbeElement to the very first element. If MbeElement is a simple graphics element, there is only one element, so MbeElement.firstElement has no effect.

Example Dim element as New MbeElementDim filePos as Long

... ' figure out what element to operate on' read the elementfilePos = element.fromFile(filePos)

' two-pass processing requiredCall ProcessPass1(element)element.firstElementCall ProcessPass2(element)...

See also MbeElement.nextComponent, MbeElement.nextElement, MbeElement.thisComponent.

MbeElement.nextElementstat = MbeElement.nextElement

Descr. Whenever it is accessed, the MbeElement.nextElement read-only property does the following:

1. If the MbeElement is not complex, returns MBE_NoMoreElems (1217) and does not affect the current position.

2. If the element at the current position is a complex component, sets the current position to its header. If there is an element following that header at the same level as the header, sets the current position to that next element and returns MBE_Success. If there is no element following that header at the same nesting level, returns MBE_NoMoreElems (leaving the current position set to the header).

For illustration purposes, consider the following nested cell:

1 Cell Header (0)2 Line (1)3 Cell Header (1)4 Line String (2)5 Text Node (2)6 Text (3)7 Text (3)8 Ellipse (2)9 Shape (2)10 Arc(1)

8-22 MicroStation BASIC Guide

Page 333: 48784209 Microstation Basic

Element Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 23 Friday, October 15, 1999 1:27 PM

Where the numbers in parentheses indicate nesting level.

The following table shows the effect of accessing MbeElement.nextElement with current position set at each element of this complex element:

The MbeElement.nextElement object method is designed to be used in conjunction with MbeElement.nextComponent to traverse a complex MbeElement using a recursive subroutine. The example illustrates this technique.

Example '-----------------------------------------------------------------' Recursive subroutine to process a simple or complex element'-----------------------------------------------------------------Sub ProcessElement(inElem as MbeElement)

Dim gotNext as integer

Do' call func. to process individual element at current positionCall ProcessIndividualElem(inELem)

If inElem.isHeader <> 0 Then' if any components in complex, process them recursivelyIf inElem.nextComponent = MBE_Success Then

Call ProcessElement(inElem)End IfgotNext = inElem.nextElement

ElsegotNext = inElem.nextComponent

End IfLoop While gotNext = MBE_Success

End Sub

'-------------------------------------------------------------' Entry point'-------------------------------------------------------------Sub main

Current pos nextElement returns new current pos

1 (Cell Header) MBE_NoMoreElems 1 (CellHeader)

2 (Line) MBE_NoMoreElems 1 (CellHeader)

3 (Cell Header) MBE_NoMoreElems 1 (CellHeader)

4 (Line String) MBE_Success 10 (Arc)

5 (Text Node) MBE_Success 10 (Arc)

6 (Text) MBE_Success 8 (Ellipse)

7 (Text) MBE_Success 8 (Ellipse)

8 (Ellipse) MBE_Success 10 (Arc)

9 (Shape) MBE_Success 10 (Arc)

10 (Arc) MBE_NoMoreElems 1 (Cell Header)

MicroStation BASIC Guide 8-23

Page 334: 48784209 Microstation Basic

Element Object

600macro.bk : 608_EXT.FRA Page 24 Friday, October 15, 1999 1:27 PM

Dim element as New MbeElementDim filePos as Long

... ' figure out what element to process

filePos = element.fromFile(filePos) ' read element from fileCall ProcessElement(element) ' process element recursively

End Sub

See also MbeElement.nextComponent, MbeElement.thisComponent.

MbeElement.nextComponentstat = MbeElement.nextComponent

Descr. Whenever it is accessed, the MbeElement.nextComponent read-only property does the following:

1. If the MbeElement is not complex, returns MBE_NoMoreElems (1217) and does not affect the current position, which thus continues to point to the only element within the MbeElement.

2. If the element at the current position is a complex header, sets the current position to its first component element, if there is one. If there is no component element, MbeElement.nextComponent does not change the current position and returns MBE_NoMoreElems. If there is at least one component, the current position is updated to the first component and MbeElement.nextComponent returns MBE_Success.

3. If the element at the current position is not a complex header (it must therefore be a complex component), MbeElement.nextComponent attempts to set the current position to the next component sharing the same complex header. If there are no more such components, it returns MBE_NoMoreElems and the current position is not changed. Otherwise, the current position is updated and MbeElement.nextComponent returns MBE_Success.

For illustration purposes, consider the following nested cell:

1 Cell Header (0)2 Line (1)3 Cell Header (1)4 Line String (2)5 Text Node (2)6 Text (3)7 Text (3)8 Ellipse (2)9 Shape (2)10 Arc(1)

8-24 MicroStation BASIC Guide

Page 335: 48784209 Microstation Basic

Element Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 25 Friday, October 15, 1999 1:27 PM

Where the numbers in parentheses indicate the nesting level.

The following table shows the effect of accessing MbeElement.nextComponent with current position set at each element of this complex element:

The MbeElement.nextComponent object method is designed to be used in conjunction with MbeElement.nextElement to traverse a complex MbeElement using a recursive subroutine. The example illustrates this technique.

Example '-----------------------------------------------------------------' Recursive subroutine to process a simple or complex element'-----------------------------------------------------------------Sub ProcessElement(inElem as MbeElement)

Dim gotNext as integer

Do' call function to process individual element at' current positionCall ProcessIndividualElem (inELem)

If inElem.isHeader <> 0 Then' if any components in complex, process them recursivelyIf inElem.nextComponent = MBE_Success Then

Call ProcessElement(inElem)End IfgotNext = inElem.nextElement

ElsegotNext = inElem.nextComponent

End IfLoop While gotNext = MBE_Success

End Sub

'-------------------------------------------------------------' Entry point'-------------------------------------------------------------

Current pos nextComponent returnsnew current pos

1 (Cell Header) MBE_Success 2 (Line)

2 (Line) MBE_Success 3 (CellHeader)

3 (Cell Header) MBE_Success 4 (Line String)

4 (Line String) MBE_Success 5 (Text Node)

5 (Text Node) MBE_Success 6 (Text)

6 (Text) MBE_Success 7 (Text)

7 (Text) MBE_NoMoreElems 7 (Text)

8 (Ellipse) MBE_Success 9 (Shape)

9 (Shape) MBE_NoMoreElems 9 (Shape)

10 (Arc) MBE_NoMoreElems 10 (Arc)

MicroStation BASIC Guide 8-25

Page 336: 48784209 Microstation Basic

Element Object

600macro.bk : 608_EXT.FRA Page 26 Friday, October 15, 1999 1:27 PM

Sub mainDim element as New MbeElementDim filePos as Long

... ' figure out what element to process

filePos = element.fromFile(filePos) ' read element from fileCall ProcessElement(element) ' process element recursively

End Sub

See also MbeElement.nextElement, MbeElement.nextComponent.

MbeElement.headerElementstat = MbeElement.headerElement

Descr. Whenever it is accessed, the MbeElement.headerElement read-only property does the following:

1. If the MbeElement is not complex, or is not a complex component (i.e., is the “root” of the MbeElement), returns MBE_NotComplex (1218) and does not affect the current position.

2. Otherwise, sets the current position to the header of the element at the current position and returns MBE_SUCCESS.

For illustration purposes, consider the following nested cell:

1 Cell Header (0)2 Line (1)3 Cell Header (1)4 Line String (2)5 Text Node (2)6 Text (3)7 Text (3)8 Ellipse (2)9 Shape (2)10 Arc(1)

Where the numbers in parentheses indicate the nesting level.

The following table shows the effect of accessing MbeElement.nextElement with current position set at each element of this complex element:

Current posheaderElement returns new current pos

1 (Cell Header) MBE_NotComplex 1 (Cell Header)

2 (Line) MBE_Success 1 (Cell Header)

3 (Cell Header) MBE_Success 1 (Cell Header)

4 (Line String) MBE_Success 3 (Cell Header)

8-26 MicroStation BASIC Guide

Page 337: 48784209 Microstation Basic

Element Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 27 Friday, October 15, 1999 1:27 PM

Example Dim element as MbeElement...If element.headerElement = MBE_Success Then ... ' now current position is at header .End If

See also MbeElement.nextComponent, MbeElement.nextElement, MbeElement.thisComponent.

MbeElement.thisComponentMbeElement.thisComponent

Descr. The MbeElement.thisComponent read/write Integer property is used to mark a position within a complex MbeElement and return later to that position. For example, if a macro wanted to change the first text in a cell only if the next text had a certain characteristic, it could save the position of the first text it encountered and return to it if the next text matched the desired characteristics. When MbeElement.thisComponent is accessed, it returns a non-zero Integer “handle” that is used to identify the position within the complex. This “handle” has meaning only when MbeElement.thisComponent is assigned - the actual value cannot be used in any other context.

Example '-----------------------------------------------------------------' Recursive subroutine to find first text'-----------------------------------------------------------------Function FindFirstText(inElem as MbeElement) as Integer

Dim gotNext as integerDim firstTextPos As Integer

Do' call function that shows info for element at current positionIf inElem.type = MBE_Text Then

FindFirstText = inElem.thisComponentExit Function

End If

If inElem.isHeader <> 0 Then' process complex elements recursivelyIf inElem.nextComponent = MBE_Success Then

5 (Text Node) MBE_Success 3 (Cell Header)

6 (Text) MBE_Success 5 (Text Node)

7 (Text) MBE_Success 5 (Text Node)

8 (Ellipse) MBE_Success 3 (Cell Header)

9 (Shape) MBE_Success 3 (Cell Header)

10 (Arc) MBE_Success 1 (Cell Header)

Current posheaderElement returns

new current pos

MicroStation BASIC Guide 8-27

Page 338: 48784209 Microstation Basic

Element Object

600macro.bk : 608_EXT.FRA Page 28 Friday, October 15, 1999 1:27 PM

firstTextPos = FindFirstText (inElem)If firstTextPos <> 0 Then

FindFirstText = firstTextPosExit Function

End IfEnd IfgotNext = inElem.nextElement

ElsegotNext = inElem.nextComponent

End IfLoop While gotNext = MBE_Success

' if we get here, did not find textFindFirstText = 0

End Function

'-------------------------------------------------------------' Steps through every element in file, processes first text' element in every cell.'-------------------------------------------------------------Sub main

Dim element as New MbeElementDim filePos as LongDim firstTextPos as Integer

' read the first elementfilePos = element.fromFile (0)

Do While filePos >= 0If element.type = MBE_Cell Then

firstTextPos = FindFirstText(element)If firstTextPos <> 0 Then

element.thisComponent = firstTextPos' here is where we process the text element we foundCall ProcessFirstText(element)

End IfEnd IffilePos = element.fromFile(filePos + element.fileSize)

Loop End Sub

See also MbeElement.firstElement, MbeElement.nextElement, MbeElement.nextComponent.

MbeElement.isHeaderMbeElement.isHeader

Descr. The MbeElement.isHeader read-only property returns TRUE if the element at the current position of MbeElement is a complex header and FALSE otherwise. Complex header elements include MBE_CellHeader, MBE_TextNode, MBE_ComplexString,

8-28 MicroStation BASIC Guide

Page 339: 48784209 Microstation Basic

Element Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 29 Friday, October 15, 1999 1:27 PM

MBE_ComplexShape, MBE_Surface, MBE_Solid, MBE_BSplineSurface, MBE_BSplineCurve and MBE_RasterHeader.

Example Dim element as MbeElement...If element.isHeader <> 0 Then

... ' process complex elementEnd If

MbeElement.isComponentMbeElement.isComponent

Descr. The MbeElement.isComponent read-only property returns TRUE if the element at the current position of MbeElement is complex element component, FALSE otherwise.

Example Dim element as MbeElement...If element.isComponent <> 0 Then

... ' process component elementEnd If

MbeElement.isGraphicsMbeElement.isGraphics

Descr. The MbeElement.isGraphics read-only property returns 1 if the element at the current position of MbeElement is a graphics element and 0 if it is a non-graphics (control) element.

Example Dim element as MbeElement...If element.isGraphics <> 0 Then

... ' process graphics elementEnd If

MbeElement.typeMbeElement.type

The MbeElement.type read-only property returns the Integer type of the element at the current position. The graphics element types are:

MBE_CellLibraryHdr 1 MBE_BSplinePole 21

MBE_CellHeader 2 MBE_PointString 22

MBE_Line 3 MBE_Cone 23

MBE_LineString 4 MBE_BSplineSurface 24

MBE_Shape 6 MBE_BSplineBoundary 25

MicroStation BASIC Guide 8-29

Page 340: 48784209 Microstation Basic

Element Object

600macro.bk : 608_EXT.FRA Page 30 Friday, October 15, 1999 1:27 PM

Example Dim element as New MbeElement... ' get an element by some methodIf element.type = MBE_Text Then ... ' process complex elementEnd If

MbeElement.fileSizeMbeElement.fileSize

Descr. The MbeElement.fileSize read-only Long property returns the size, in bytes, that the entire (possibly complex) MbeElement occupies in the design file. This value can be used to step through the design file reading elements sequentially.

Example Dim element as MbeElementDim filePos as Long' step through every element in the filefilePos = element.fromFile (0)Do While filePos >= 0

ProcessElement(element)filePos = element.fromFile(filePos + element.fileSize)

Loop

See also MbeElement.internalSize.

MbeElement.internalSizeMbeElement.internalSize

Descr. The MbeElement.internalSize read-only Long property returns the size, in bytes, that the individual component element at the current position occupies in memory. On some platforms, an element is a different size on the disk from its internal size because

MBE_TextNode 7 MBE_BSplineKnot 26

MBE_Curve 11 MBE_BSplineCurve 27

MBE_ComplexString 12 MBE_BSplineWeight 28

MBE_ComplexShape 14 MBE_Dimension 33

MBE_Ellipse 15 MBE_SharedCellDefinition 34

MBE_Arc 16 MBE_SharedCell 35

MBE_Text 17 MBE_MultiLine 36

MBE_Surface 18 MBE_Tag 37

MBE_Solid 19 MBE_RasterHeader 87

MBE_RasterComponent 88

8-30 MicroStation BASIC Guide

Page 341: 48784209 Microstation Basic

Element Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 31 Friday, October 15, 1999 1:27 PM

some data items in an element must be aligned on byte boundaries appropriate to their data size.

Example Dim internalSize as LonginternalSize = element.internalSize

See also MbeElement.fileSize.

MbeElement.fromFilefilePos = MbeElement.fromFile(filePos as Long[, fileNum as Integer[, _mastFileUnits as Integer [, expandShared as Integer]]])

Descr. The MbeElement.fromFile object function attempts to read an MbeElement from either the master file or one of its reference files. The argument, filePos, is required to specify the file position of the MbeElement to be read from the file.

If the second (optional) argument, fileNum, is provided, it specifies whether to read the element from the master (fileNum = 0) or one of the reference files (fileNum = the reference file slot to read the element from). If fileNum is not provided, the MbeElement is read from the master file.

The third (optional) argument, mastFileUnits, is used only if the MbeElement is read from a reference file. It specifies whether to transform MbeElement read from the reference file to the coordinate system of the master file. Not providing the argument is the same as passing TRUE and thus transforming the MbeElement to master file coordinates, which is the recommended option.

The fourth (optional) argument, expandShared, specifies whether or not to expand shared cells, with TRUE indicating that they are to be expanded. Note that any changes that are made to the components of a shared cell cannot be written back to the design file. The default behavior if the argument is omitted is not to expand shared cells.

✍ If any optional argument is omitted, the arguments following it in the argument list must be omitted as well.

If successful, MbeElement.fromFile returns a Long that is the file position from which the element is read. The return value may differ from the filePos specified in the case that the element in the design file at filePos is a deleted element. Deleted elements cannot be retrieved from the design file using MbeElement.fromFile. Instead, the first non-deleted element following filePos is read. If filePos specifies a file position that does not correspond to the beginning of an element, MbeElement.fromFile returns -1.

If filePos points to a complex header, MbeElement.fromFile always reads the entire complex element. If filePos points to a complex component, MbeElement.fromFile will read it, but the usefulness of this is limited since you cannot modify a complex component and use MbeElement.rewrite to make a permanent change to the design.

There are a number of ways to determine a file position to use as input to MbeElement.fromFile. To process an entire design file, MbeElement.fromFile can read starting at 0 and use the return value from one call to MbeElement.fromFile and

MicroStation BASIC Guide 8-31

Page 342: 48784209 Microstation Basic

Element Object

600macro.bk : 608_EXT.FRA Page 32 Friday, October 15, 1999 1:27 PM

MbeElement.fileSize to calculate the filePos for the next call. The MbeElementSet object can be used to operate on sets of elements, and MbeDgnInfo.endOfFile can be saved before placing an element to retrieve the new element after sequencing a command.

Note that even though you can consider MbeElement.fromFile to be reading elements from the design file, in reality it retrieves the element from MicroStation’s element cache if the element is available in the cache. This yields a substantial performance benefit versus actual disk access.

Example Sub mainDim element as New MbeElementDim filePos as Long

' read the first elementfilePos = element.fromFile(0)

' step through every element in the fileDo While filePos >= 0

ProcessElement(element)filePos = element.fromFile(filePos + element.fileSize)

Loop End Sub

See also MbeElement.fileSize, MbeElement.fromLocate.

MbeElement.fromLocatefilePos=MbeElement.fromLocate([mastFileUnits as Integer _[,expandShared as Integer]])

Descr. The MbeElement.fromLocate object function attempts to read the last element that the user interactively located, either during the course of a MicroStation command or as a result of the macro calling MbeStartLocate.

The first (optional) argument, mastFileUnits, is used only if the element last located was in a reference file. It specifies whether to transform an MbeElement read from the reference file to the coordinate system of the master file. Not providing the argument is the same as passing TRUE and thus transforming the MbeElement to master file coordinates, which is the recommended option.

The second (optional) argument, expandShared, specifies whether or not to expand shared cells, with TRUE indicating that they are to be expanded. Note that any changes can be made to the components of a shared cell cannot be written back to the design file. The default behavior if the argument is omitted is not to expand shared cells.

If successful, MbeElement.fromLocate returns a Long that is the file position from which the previously located element is read. If the user has not previously located an element while the current master file has been active, MbeElement.fromLocate returns -1.

8-32 MicroStation BASIC Guide

Page 343: 48784209 Microstation Basic

Element Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 33 Friday, October 15, 1999 1:27 PM

If the element located is a complex, MbeElement.fromLocate retrieves the entire complex element and the current position in the MbeElement points to the actual component element that the user locate point selected.

Dim element as New MbeElement

MbeStartLocate... ' sequence user through selecting an element

' retrieve the element that the user locatedfilePos = element.fromLocate()If filePos >= 0 Then ... ' process the element End If

See also MbeStartLocate, MbeElement.fromFile.

MbeElement.filePosMbeElement.filePos

Descr. The MbeElement.filePos read-only Long property returns the file position from which the MbeElement originated.

Example Dim element as New MbeElementDim nextElemFilePos as Longstat = element.fromLocate()nextElemFilePos = element.filePos + element.fileSize

See also MbeElement.fileNum, MbeElement.componentFilePos.

MbeElement.componentFilePosMbeElement.componentFilePos

Descr. The MbeElement.componentFilePos read-only Long property returns the file position from which the component at the current position in the MbeElement originated.

Dim componentOffset as LongcomponentOffset = element.componentFilePos - element.filePos

See also MbeElement.fileNum, MbeElement.filePos.

MbeElement.fileNumMbeElement.fileNum

Descr. The MbeElement.fileNum read-only Integer property returns the file number from which the MbeElement originated.

Example Dim element as New MbeElementDim nextElemFilePos as Long

stat = element.fromLocate()

MicroStation BASIC Guide 8-33

Page 344: 48784209 Microstation Basic

Element Object

600macro.bk : 608_EXT.FRA Page 34 Friday, October 15, 1999 1:27 PM

nextElemFilePos = element.filePos + element.fileSizeelement.fromFile(nextElemFilePos, element.fileNum)

See also MbeElement.filePos, MbeElement.componentFilePos.

MbeElement.changeAllMbeElement.changeAll

Descr. The MbeElement.changeAll read/write Integer property controls whether changes to certain MbeElement properties affect only the element at the current position, or all valid component elements of the MbeElement. The properties for which the state of MbeElement.changeAll matters are those that are common to all graphics elements, including: level, color, style, weight, class and group; and the fontNum and fontName properties which are applied to all text and text node elements in a complex if MbeElement.changeAll is TRUE. The behavior of the MbeElement.move, MbeElement.rotate, and MbeElement.scale object functions are also affected by changeAll. The changeAll property is set to FALSE for a new MbeElement, but the state of changeAll is unaffected by reading a new element into an MbeElement.

Example Sub MatchLevel(elem1 as MbeElement, elem2 as MbeElement, _allComponents as integer)

' set changeAll property to change all component elements if desiredelem1.changeAll = allComponentselem1.level = elem2.level

End Sub

See also MbeElement.level, MbeElement.color, MbeElement.style, MbeElement.weight, MbeElement.class, MbeElement.group, MbeElement.font, MbeElement.fontName, MbeElement.move, MbeElement.rotate, MbeElement.scale.

MbeElement.levelMbeElement.level

Descr. The MbeElement.level read/write Integer property sets or retrieves the level of the MbeElement. When MbeElement.level is retrieved, it returns the level of the component element at the current position. When MbeElement.level is assigned, it sets the level of the component element at the current position if MbeElement.changeAll is FALSE, and the level of all components of the MbeElement if MbeElement.changeAll is TRUE. Any attempt to assign level to a value outside the range 1 to 63 results in an MBE_InvalidLevel (1202) runtime error. Any attempt to assign a level to a non-graphics (control) element or an element of type MBE_CellHeader results in an MBE_WrongElemType (1207) runtime error.

Example Sub MatchLevel(elem1 as MbeElement, elem2 as MbeElement, _allComponents as Integer)

' set changeAll property to change all component elements if desiredelem1.changeAll = allComponents

8-34 MicroStation BASIC Guide

Page 345: 48784209 Microstation Basic

Element Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 35 Friday, October 15, 1999 1:27 PM

elem1.level = elem2.levelEnd Sub

See also MbeElement.changeAll.

MbeElement.colorMbeElement.color

Descr. The MbeElement.color read/write Integer property sets or retrieves the color of the MbeElement. When MbeElement.color is retrieved, it returns the color of the component element at the current position. When MbeElement.color is assigned, it sets the color of the component element at the current position if MbeElement.changeAll is FALSE, and the color of all components of the MbeElement if MbeElement.changeAll is TRUE. Any attempt to assign color to a value outside the range 0 to 255 results in an MBE_InvalidColor (1203) runtime error. Any attempt to assign a color to a non-graphics (control) element results in an MBE_WrongElemType (1207) runtime error.

Example Sub MatchColor(elem1 as MbeElement, elem2 as MbeElement, _allComponents as Integer)

' set changeAll property to change all component elements if desiredelem1.changeAll = allComponentselem1.color = elem2.color

End Sub

See also MbeElement.changeAll.

MbeElement.styleMbeElement.style

Descr. The MbeElement.style read/write String property sets or retrieves the style of the MbeElement. When MbeElement.style is retrieved, it returns the style of the component element at the current position. When MbeElement.style is assigned, it sets the style of the component element at the current position if MbeElement.changeAll is FALSE, and the style of all components of the MbeElement if MbeElement.changeAll is TRUE. The style property is a String so a macro can use custom line styles. If a macro wants to set a line style by number, in can send the numeric string (i.e., “1” to set style 1). If an attempt is made to assign style that cannot be found, a runtime error MBE_InvalidStyle (1205) is generated. Any attempt to assign a style to a non-graphics (control) element results in an MBE_WrongElemType (1207) runtime error.

Example Sub MatchStyle(elem1 as MbeElement, elem2 as MbeElement, _allComponents as Integer)

' set changeAll property to change all component elements if desiredelem1.changeAll = allComponents

MicroStation BASIC Guide 8-35

Page 346: 48784209 Microstation Basic

Element Object

600macro.bk : 608_EXT.FRA Page 36 Friday, October 15, 1999 1:27 PM

elem1.style = elem2.styleEnd Sub

See also MbeElement.changeAll.

MbeElement.weightMbeElement.weight

Descr. The MbeElement.weight read/write Integer property sets or retrieves the line weight of the MbeElement. When MbeElement.weight is retrieved, it returns the line weight of the component element at the current position. When MbeElement.weight is assigned, it sets the line weight of the component element at the current position if MbeElement.changeAll is FALSE, and the weight of all components of the MbeElement if MbeElement.changeAll is TRUE. Any attempt to assign weight to a value outside the range 0 to 31 results in an MBE_InvalidWeight (1204) runtime error. Any attempt to assign a weight to a non-graphics (control) element results in an MBE_WrongElemType (1207) runtime error.

Example Sub MatchWeight(elem1 as MbeElement, elem2 as MbeElement, _allComponents as Integer)

' set changeAll property to change all component elements if desiredelem1.changeAll = allComponentselem1.weight = elem2.weight

End Sub

See also MbeElement.changeAll.

MbeElement.classMbeElement.class

Descr. The MbeElement.class read/write Integer property sets or retrieves the class of the MbeElement. When MbeElement.class is retrieved, it returns the class of the component element at the current position. When MbeElement.class is assigned, it sets the class of the component element at the current position if MbeElement.changeAll is FALSE, and the class of all components of the MbeElement if MbeElement.changeAll is TRUE. Any attempt to assign class to a value outside the range 0 to 15 results in an MBE_InvalidClass (1206) runtime error. Any attempt to assign a class to a non-graphics (control) element results in an MBE_WrongElemType (1207) runtime error.

Constants have been defined for the element classes that MicroStation recognizes:

MBE_PrimaryClass 0

MBE_PatternClass 1

MBE_ConstructionClass 2

MBE_DimensionClass 3

MBE_PrimaryRuleClass 4

8-36 MicroStation BASIC Guide

Page 347: 48784209 Microstation Basic

Element Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 37 Friday, October 15, 1999 1:27 PM

Example Sub MatchClass(elem1 as MbeElement, elem2 as MbeElement, _allComponents as Integer)

' set changeAll property to change all component elements if desiredelem1.changeAll = allComponentselem1.class = elem2.class

End Sub

See also MbeElement.changeAll.

MbeElement.propertiesMbeElement.properties

Descr. The MbeElement.properties read/write Integer property sets or retrieves the properties of the MbeElement. When MbeElement.properties is retrieved, it returns the properties of the component element at the current position. When MbeElement.properties is assigned, it sets the properties of the component element at the current position. Any attempt to assign properties to a non-graphics (control) element results in an MBE_WrongElemType (1207) runtime error.

The element properties are a group of bits in the element header that indicate locked status, new status, modified status, attributes present, view independent, hole or solid status, planar, and snappable. Generally, macros want to examine properties bits, and will rarely need to set them. To test for a particular property, retrieve the properties and AND with the desired property bit. To set a particular property, retrieve the properties, OR with the desired property, and assign the result. To clear a particular property, AND with NOT the property bit and assign the result.

These constants have been defined for the element properties bits:

Example Function isLocked(elem as MbeElement)If (elem.properties And MBE_LockedProp) <> 0 Then

MBE_PatternedLineClass 5

MBE_ConstRuleClass 6

PropertyMask Value

MBE_LockedProp 1

MBE_NewProp 2

MBE_ModifiedProp 4

MBE_AttributesProp 8

MBE_ViewIndProp 16

MBE_PlanarProp 32

MBE_NoSnapProp 64

MBE_HoleProp 128

MicroStation BASIC Guide 8-37

Page 348: 48784209 Microstation Basic

Element Object

600macro.bk : 608_EXT.FRA Page 38 Friday, October 15, 1999 1:27 PM

isLocked = TRUEElse

isLocked = FALSEEnd If

End Function

MbeElement.getOriginstat = MbeElement.getOrigin(origin as MbePoint)

Descr. The MbeElement.getOrigin object function retrieves an MbePoint that is the “origin” of the graphics element at the current position in the MbeElement. The function is valid for most, but not all graphics element types. The origin returned for each element type is as follows:

If the element at the current position is valid for getOrigin, the function returns MBE_Success. Otherwise it returns MBE_WrongElemType (1207).

Element Type Origin Definition

MBE_CellHeader Cell origin

MBE_Line Centroid

MBE_LineString Centroid

MBE_Shape Centroid

MBE_TextNode User origin

MBE_Curve Centroid

MBE_ComplexString Centroid

MBE_ComplexShape Centroid

MBE_Ellipse Center

MBE_Arc Center

MBE_Text User origin

MBE_BSplinePole First pole

MBE_PointString First point

MBE_Cone Bottom center

MBE_BSplineSurface Centroid

MBE_BSplineCurve Centroid

MBE_SharedCell Origin

MBE_MultiLine Centroid

MBE_Tag User origin

8-38 MicroStation BASIC Guide

Page 349: 48784209 Microstation Basic

Element Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 39 Friday, October 15, 1999 1:27 PM

Example ' scale selected element about its originDim element as New MbeElementDim origin as MbePointMbeStartLocate... ' sequence user through selecting an element' retrieve the element that the user locatedfilePos = element.fromLocate()' find the originIf element.getOrigin(origin) = MBE_Success Then

' start the SCALE commandMbeSendCommand “SCALE”' locate the element at its originCall MbeLocateElement(element.filePos, element.filePos, _

element.fileNum, origin)' should have found it, but double checkIf MbeState.cmdResult = MBE_AcceptQuery Then

MbeSendDataPoint(origin) ' accept (point doesn’t matter)End If' get out of SCALE commandMbeSendCommand "NULL"

End If

See also MbeElement.getPoints.

MbeElement.getPointsstat = MbeElement.getPoints(points() as MbePoint)

Descr. The MbeElement.getPoints object function retrieves an array of type MbePoint that contains the points that comprise the graphics element at the current position. The function is valid for element types MBE_Line, MBE_LineString, MBE_Shape, MBE_Curve, MBE_BSplinePole, MBE_PointString and MBE_MultiLine. If the element at the current position is valid for getPoints, the function returns MBE_Success. Otherwise it returns MBE_WrongElemType (1207).

The function redimensions the points array argument, so the macro must pass it a variable-length array. The array is redimensioned by the function to points (0 to numpoints-1); if the macro needs to calculate the number of points it can do so using UBound(points) - Lbound(points) + 1.

Example Sub ShowPoints(element as MbeElement)Dim points() as MbePointDim iPoint as Integer

If element.getPoints(points) = MBE_Success Thenprint “Number of Points : “;UBound(points) - LBound(points) + 1For iPoint = LBound(points) To UBound(points)

print “x :";points(iPoint).x;" y:";points(iPoint).y;print " z:";points(iPoint).z

MicroStation BASIC Guide 8-39

Page 350: 48784209 Microstation Basic

Element Object

600macro.bk : 608_EXT.FRA Page 40 Friday, October 15, 1999 1:27 PM

Next iPointEnd If

End Sub

See also MbeElement.getOrigin.

MbeElement.setPointsstat = MbeElement.setPoints(points() as MbePoint [,numPoints as Integer])

Descr. The MbeElement.setPoints object function sets the points that make up the linear element as the current position within the MbeElement. The function is valid for element types MBE_Line, MBE_LineString, MBE_Shape, MBE_Curve and MBE_MultiLine. If numPoints is supplied, then that specifies the number of points to use from the points array, otherwise the UBound and LBound of points are used to compute the number of points. The function can change the number of points in a linear graphics element. An MBE_Line is changed to an MBE_LineString if the number of points is greater than 2, while an MBE_LineString is changed to an MBE_Line if the number of points is equal to 2.

Note that the changes are made to the MbeElement in memory only. To make the changes permanent, the MbeElement.rewrite function is used.

points must be a single-dimensioned array, and, if numPoints is specified, it must contain at least numPoints MbePoints, or MBE_WrongDimension (801) is returned. If the number of points is less than 2, MBE_NotEnoughPoints (1212) is returned, and if the number of points is greater than 101, MBE_TooManyPoints (1213) is returned. If any of the points specified are off the design plane, the function returns MBE_OffDesignPlane (1211). If an element that is invalid for the function is specified, the function returns MBE_WrongElemType (1207).

Example Dim points() as MbePointsDim element as New MbeElement... ' get element somehowIf element.getPoints(points) = MBE_Success Then

If Ubound(points) - Lbound(points) > 3 Thenpoints(2).x = points(1).xIf element.setPoints (points) <> MBE_Success Then

print “could not set points”End If

End IfEnd If

See also MbeElement.getOrigin.

8-40 MicroStation BASIC Guide

Page 351: 48784209 Microstation Basic

Element Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 41 Friday, October 15, 1999 1:27 PM

MbeElement.getEndPointsstat = MbeElement.getEndPoints(startPoint [, endPoint])

Descr. The MbeElement.getEndPoints object function retrieves the start and end points of the graphics element at the current position in the MbeElement. startPoint retrieves the starting point as an MbePoint, while the second (optional) argument retrieves the end point as an MbePoint. The function is valid for element types MBE_Line, MBE_LineString, MBE_Shape, MBE_Curve, MBE_BSplinePole, MBE_PointString, MBE_Arc, MBE_Ellipse, MBE_ComplexString, MBE_ComplexShape and MBE_MultiLine. If the element at the current position is valid for getEndPoints, the function returns MBE_Success. Otherwise it returns MBE_WrongElemType (1207).

For closed elements, the start and end points are the same.

Example Dim element as MbeElement, startPoint as MbePoint, endPoint as MbePoint... ' get element from somewhereIf element.getEndPoints(startPoint, endPoint) = MBE_Success Then

... ' process end pointsEnd If

See also MbeElement.getOrigin, MbeElement.getPoints.

MbeElement.getRangestat = MbeElement.getRange(range as MbeRange)

Descr. The MbeElement.getRange object function retrieves an MbeRange that contains the range of the element at the current position within the MbeElement. The range retrieved indicates the upper and lower boundaries of the element in the x, y and z directions in the design file. The values are returned in design file units (not in master units). The element range is generally of limited use to a macro. The getRange function returns an integer that is set to MBE_Success unless the element passed is corrupt.

The MbeRange type is defined as follows:

Type MbeRangexLow as LongyLow as LongzLow as LongxHigh as LongyHigh as LongzHigh as Long

End Type

Example Dim range as MbeRange, element as New MbeElement... Get an element

stat = element.getRange(range)

MicroStation BASIC Guide 8-41

Page 352: 48784209 Microstation Basic

Element Object

600macro.bk : 608_EXT.FRA Page 42 Friday, October 15, 1999 1:27 PM

MbeElement.movestat = MbeElement.move(distance as MbePoint)

Descr. The MbeElement.move object function offsets the element at the current position within the MbeElement by the distance specified, unless MbeElement.changeAll is TRUE, in which case the entire complex element is moved, rather than just the component. The move function works on any graphics element type except those that are inherently components of a complex element (i.e., MBE_BSplineKnot). If attempts are made to move such elements, MBE_WrongElemType (1207) is returned, otherwise MBE_Success.

✍ Changes are made to the element descriptor in memory only. To make the changes permanent, MbeElement.rewrite is used.

Example Dim element as New MbeElement, distance as MbePoint... Get an elementdistance.x = 4.2distance.y = -1.2distance.z = 0stat = element.move (distance)

See also MbeElement.rotate, MbeElement.scale, MbeElement.rewrite, MbeElement.addToFile.

MbeElement.rotatestat = MbeElement.rotate(rotateZ as Double [, rotateY as Double [, _rotateX as Double [, origin as MbePoint]]])

stat = MbeElement.rotate(rMatrix(0 to 2, 0 to 2) as Double, _[origin as MbePoint])

Descr. The MbeElement.rotate object function rotates the element at the current position within the MbeElement by the rotating angles specified in radians, unless MbeElement.changeAll is TRUE, in which case the entire complex element is rotated, rather than just the component. Considering the first declaration of MbeElement.rotate, in its simplest form, only the first argument is given, which specifies the rotation about the Z axis. The second and third optional arguments specify the rotations around the Y and X axes, respectively. The fourth optional argument specifies a point to rotate the element about. Most of the time origin is needed, otherwise the element is rotated about the coordinate system origin. This is rarely the desired result. The second legal declaration of MbeElement.rotate illustrates the ability to accept a rotation matrix in the form of a 3-dimensional array of Doubles. This is the form already returned by the MbeElement.getRotation method, (refer to the second example). The rotate function works on any graphics element type except those that are inherently components of a complex element (i.e.,

8-42 MicroStation BASIC Guide

Page 353: 48784209 Microstation Basic

Element Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 43 Friday, October 15, 1999 1:27 PM

MBE_BSplineKnot). If an attempt is made to rotate such an element, MBE_WrongElemType (1207) is returned, otherwise the function returns MBE_Success.

Note that the changes are made to the element descriptor in memory only. To make the changes permanent, the MbeElement.rewrite object function is used.

Example Dim element as New MbeElement, origin as MbePoint... Get an elementIf element.getOrigin(origin) = MBE_Success Then

If element.rotate(PI/4, 0.0, 0.0, origin) = MBE_Success Thenstat = element.rewrite()

End IfEnd If

Example Dim cellElem As MbeElement, origin As MbePointDim rMatrix(0 To 2, 0 To 2) As Double’ Set up a matrix to do a 90 degree rotation.rMatrix(0,0) = 0.0rMatrix(0,1) = -1,0rMatrix(0,2) = 0.0

rMatrix(1,0) = 1.0rMatrix(1,1) = 0.0rMatrix(1,2) = 0.0

rMatrix(2,0) = 0.0rMatrix(2,1) = 0.0rMatrix(2,2) = 1.0

... Get a cell elementIf cellElem.getOrigin(origin) = MBE_Success Then

If cellElem.rotate(rMatrix, origin) = MBE_Success Thenstat = element.rewrite()

End IfEnd If

See also MbeElement.move, MbeElement.scale, MbeElement.rewrite, MbeElement.addToFile.

MbeElement.scalestat = MbeElement.scale (scaleX as Double [, scaleY as Double [, _scaleZ as Double [, origin as MbePoint]]])

Descr. The MbeElement.scale object function scales the element at the current position within the MbeElement by the scale factors specified, unless MbeElement.changeAll is TRUE, in which case the entire complex element is scaled, rather than just the component. In its simplest form, only the first argument is given, which specifies the scale factor in the X direction. The second and third optional arguments specify the scale factors in the Y and X axes, respectively, which are assumed to be 1.0 if not specified. The fourth optional argument specifies a point to scale the element about. Most of the time the origin argument is needed, because otherwise the element is scaled about the

MicroStation BASIC Guide 8-43

Page 354: 48784209 Microstation Basic

Element Object

600macro.bk : 608_EXT.FRA Page 44 Friday, October 15, 1999 1:27 PM

coordinate system origin, which is rarely the desired result. The scale function works on any graphics element type except those that are inherently components of a complex element (i.e., MBE_BSplineKnot). If an attempt is made to scale such an element, MBE_WrongElemType (1207) is returned, otherwise MBE_Success is returned.

In Visual Basic, the method name scaleElem must be used instead of scale. See Appendix A for more information on OLE Automation.

Note that the changes are made to the element descriptor in memory only. To make the changes permanent, the MbeElement.rewrite object function is used.

Dim element as New MbeElement, origin as MbePoint... Get an elementIf element.getOrigin(origin) = MBE_Success Then

If element.scale(1.4, 1.4, 1.0, origin) = MBE_Success Thenstat = element.rewrite()

End IfEnd If

See also MbeElement.move, MbeElement.rotate, MbeElement.rewrite, MbeElement.addToFile, MbeElement.changeAll, "Appendix A".

MbeElement.rewritestat = MbeElement.rewrite([filePos [, eraseOld as Integer [, _drawNew as Integer]]])

Descr. The MbeElement.rewrite object function rewrites the MbeElement at the file position from which it was read. If filePos is provided, it returns the file position at which the element was rewritten. If the optional eraseOld argument is specified, it controls whether the existing element is erased before replacing it in the file. Similarly, drawNew controls whether the changed element is displayed after it is written to the design file. Both arguments are assumed to be TRUE if they are not provided.

The possible errors that can arise when trying to rewrite an element are:

Example Dim element as New MbeElement, origin as MbePoint... Get an elementIf element.getOrigin(origin) = MBE_Success Then

If element.rotate(PI/4, 0.0, 0.0, origin) = MBE_Success Then

MBE_DiskFull (61) disk is full.

MBE_AccessDenied (70) file is read only.

MBE_CantRewrite (1208) element in reference file

MBE_ComplexComponent (1215) element is not an entire complex

MBE_WriteInhibit (1216) write to file stopped by MDL application

MBE_BadElement (1219) element corrupted

8-44 MicroStation BASIC Guide

Page 355: 48784209 Microstation Basic

Element Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 45 Friday, October 15, 1999 1:27 PM

stat = element.rewrite()End If

End If

See also MbeElement.addToFile.

✍ Do not try to rewrite a deleted element.

MbeElement.addToFilestat = MbeElement.addToFile([filePos as Long [, drawNew as Integer]])

Descr. The MbeElement.addToFile object function adds the MbeElement to the end of the master file. If filePos is provided, it returns the file position at which the element was written. If drawNew is specified, it controls whether the changed element is displayed after it is written to the .dgn file. Not specifying drawNew is the same as passing TRUE.

The possible errors that can arise when trying to add an element to the file are:

Example Dim element as New MbeElement, origin as MbePoint... Get an element' rotate the element and put the modified copy at the end of the fileIf element.getOrigin(origin) = MBE_Success Then

If element.rotate(PI/4, 0.0, 0.0, origin) = MBE_Success Thenstat = element.addToFile()

End IfEnd If

See also MbeElement.rewrite.

MbeElement.displayMbeElement.display [drawMode as Integer[, viewMask as Integer]]

Descr. The MbeElement.display statement displays the MbeElement in one or more views. If drawMode is provided, it specifies the drawing mode to use. Possible values are MBE_NormalDraw, Mbe_Erase or Mbe_Hilite. If the argument is omitted, MBE_NormalDraw is assumed. viewMask controls which views the MbeElement is displayed in. If the low order bit is a 1, the element is displayed to view 1, if the next

MBE_DiskFull (61) disk is full.

MBE_AccessDenied (70) file is read only.

MBE_ComplexComponent (1215) element is not an entire complex.

MBE_WriteInhibit (1216) write to file stopped by MDL application.

MBE_BadElement (1219) element corrupted.

MicroStation BASIC Guide 8-45

Page 356: 48784209 Microstation Basic

Element Object

600macro.bk : 608_EXT.FRA Page 46 Friday, October 15, 1999 1:27 PM

bit is a 1, the element is displayed to view 2, and so on. If viewMask is omitted, the MbeElement is displayed in all views.

Example Dim element as New MbeElement... Get an element' hilite the element in views 1, 2, and 3element.display MBE_Hilite, 7

MbeElement.areaMbeElement.area

Descr. The MbeElement.area read-only property returns the area of the element at the current position within the MbeElement as a Double. The element must be closed. The units depend on the current coordinate system that the macro has established using the MbeCurrentTransform object (by default, it is square master units). The property is valid for element types MBE_Shape, MBE_Curve, closed MBE_BSplineCurve, MBE_Ellipse, MBE_ComplexShape and MBE_CellHeader that represent grouped hole orphan cells. If the element at the current position is not closed and therefore does not have a valid area, the function returns 0.

Example Dim element as New MbeElement, area as Double... Get an element' find the area of the elementarea = element.areaIf area <> 0.0 Then ... ' can use area in calculationsEnd If

MbeElement.perimeterMbeElement.perimeter

Descr. The MbeElement.perimeter read-only property returns the perimeter of the element at the current position within the MbeElement as a Double. The element must be closed. The units depend on the current coordinate system that the macro has established using the MbeCurrentTransform object (by default, it is master units). The property is valid for element types MBE_Shape, MBE_Curve, closed MBE_BSplineCurve, MBE_Ellipse, MBE_ComplexShape and MBE_CellHeader that represent grouped hole orphan cells. If the element at the current position is not closed and therefore does not have a valid perimeter, the function returns 0.

Example Dim element as New MbeElement, perimeter as Double... Get an element' find the perimeter of the elementperimeter = element.perimeterIf perimeter <> 0.0 Then ... ' can use perimeter in calculationsEnd If

8-46 MicroStation BASIC Guide

Page 357: 48784209 Microstation Basic

Element Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 47 Friday, October 15, 1999 1:27 PM

MbeElement.volumeMbeElement.volume

Descr. The MbeElement.volume read-only property returns the volume of the element at the current position within the MbeElement as a Double. The element must be a volume-enclosing element. The units depend on the current coordinate system that the macro has established using the MbeCurrentTransform object (by default, it is cubic master units). The property is valid for MBE_Solid, MBE_Surface, and closed MBE_BSplineSurface elements. If the element at the current position does not have a valid volume, the function returns 0.

Example Dim element as New MbeElement, area as Double... Get an element' find the volume of the elementvolume = element.volumeIf volume <> 0.0 Then ... ' can use volume in calculationsEnd If

MbeElement.getCentroidstat = MbeElement.getCentroid(centroid as MbePoint)

Descr. The MbeElement.getCentroid object function returns the centroid of the element at the current position within the MbeElement as a Double. The centroid can be calculated for most elements, exceptions being those that are inherently components of a complex element (i.e., MBE_BSplineKnot). The units depend on the current coordinate system that the macro has established using the MbeCurrentTransform object (by default, the centroid is returned in master units). If the element at the current position does not have a valid centroid, the function returns MBE_WrongElemType (1207).

Example Dim element as New MbeElement, centroid as MbePoint... Get an element' find the centroid of the elementIf element.getCentroid (centroid) = MBE_Success Then ... ' can use centroid in calculationsEnd If

MbeElement.cellNameMbeElement.cellName

Descr. The MbeElement.cellName read-only String property returns the name of the cell in the cell header at the current position within the MbeElement. The property is valid for MBE_CellLibraryHeader, MBE_CellHeader, MBE_SharedCell and

MicroStation BASIC Guide 8-47

Page 358: 48784209 Microstation Basic

Element Object

600macro.bk : 608_EXT.FRA Page 48 Friday, October 15, 1999 1:27 PM

MBE_SharedCellDefinition elements. If the element at the current position is not one of these types, an MBE_WrongElemType (1207) runtime error is generated.

Example Dim element as New MbeElement, cellName as String... Get an elementIf element.type = MBE_CellHeader Or element.type = MBE_SharedCell Then cellName = element.cellNameEnd If

MbeElement.getCellLevelsstat = MbeElement.getCellLevels(levelMask() as Integer)

Descr. The MbeElement.getCellLevels object function retrieves an array of type Integer that contains the levels that are occupied by the cell. The function is valid for MBE_CellLibraryHeader, MBE_CellHeader, MBE_SharedCell and MBE_SharedCellDefinition elements. If the element at the current position is one of these types, the function returns MBE_Success. Otherwise it returns MBE_WrongElemType (1207). The function redimensions the levelMask array argument to levelMask (0 to 3), so the macro must pass a variable-length array. The low bit of levelMask(0) corresponds to level 1, the next bit to level 2, etc.

Example Dim element as New MbeElementDim levelMask() as Integer

If element.getCellLevels(levelMask) = MBE_Success Then ... process level maskEnd If

MbeElement.getCellBoxstat = MbeElement.getCellBox(rangeBox, as MbePoint)

Descr. The MbeElement.getCellBox object function retrieves the eight points that comprise the range box associated with the cell. The cell range box differs from the range of the element in that it is oriented in the coordinate system of the cell and thus is not necessarily orthogonal to the .dgn file coordinate system. When a cell is selected using MicroStation’s element selection tool, element handles are placed at the eight points returned by this function (the first four in a 2D file). The function is valid for MBE_CellHeader, MBE_SharedCell and MBE_SharedCellDefinition elements. If the element at the current position is one of these types, MBE_Success is returned, otherwise MBE_WrongElemType (1207). The function redimensions the rangeBox array argument to rangeBox (0 to 7), so the macro must pass a variable-length array.

Example Dim element as New MbeElement, rangeBox() as MbePointIf element.getCellBox (rangeBox) = MBE_Success Then ... process range boxEnd If

8-48 MicroStation BASIC Guide

Page 359: 48784209 Microstation Basic

Element Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 49 Friday, October 15, 1999 1:27 PM

MbeElement.getRotationstat = MbeElement.getRotation(rotMatrix(0 to 2)(0 to 2) as Double)

Descr. The MbeElement.getRotation object function retrieves the rotation matrix for the element at the current position within the MbeElement, returning MBE_Success if it is able to return the rotation matrix. The rotMatrix argument must be a 3 x 3 two-dimensional array - the dimensions can be (0 to 2) or (1 to 3), depending on the macro programmer’s preference. If rotMatrix is not correctly dimensioned, the function returns Mbe_WrongDimension (801). The function is valid for MBE_CellHeader, MBE_SharedCell, MBE_SharedCellDefinition, MBE_Ellipse, MBE_Arc, MBE_Text, MBE_TextNode, MBE_Tag and MBE_Cone elements. If the element at the current position is not one of these types, the function returns MBE_WrongElemType (1207).

Example Dim element as New MbeElement, rotation(1 to 3,1 to 3) as DoubleIf element.getRotation(rotation) = MBE_Success Then ... process rotationEnd If

MbeElement.fontMbeElement.font

Descr. The MbeElement.font read/write Integer property sets or retrieves the font of MBE_Text, MBE_TextNode or MBE_Tag elements. When MbeElement.font is retrieved, it returns the font of the component element at the current position. When MbeElement.font is assigned, it sets the font of the MBE_Text, MBE_TextNode or MBE_Tag element at the current position if MbeElement.changeAll is FALSE, and the font of all MBE_Text, MBE_TextNode and MBE_Tag elements within the MbeElement if MbeElement.changeAll is TRUE. On retrieval or assignment with MbeElement.changeAll = FALSE, an MBE_WrongElemType (1207) runtime error is generated if the element at the current position is not a valid type.

Dim element as New MbeElement

... Get an elementelement.changeAll = FALSE

Select Case element.typeCase MBE_Text, MBE_TextNode, MBE_Tag

' change all font 4’s into font 1’sIf element.font = 4 Then element.font = 1

Case Elsefont = -1

End Select

See also MbeElement.fontName, MbeElement.changeAll.

MbeElement.fontNameMbeElement.fontName

MicroStation BASIC Guide 8-49

Page 360: 48784209 Microstation Basic

Element Object

600macro.bk : 608_EXT.FRA Page 50 Friday, October 15, 1999 1:27 PM

Descr. The MbeElement.fontName read/write String property sets or retrieves the font of MBE_Text, MBE_TextNode or MBE_Tag elements. When MbeElement.fontName is retrieved, it returns the font of the component element at the current position. When MbeElement.fontName is assigned, it sets the font of the MBE_Text, MBE_TextNode or MBE_Tag element at the current position if MbeElement.changeAll is FALSE, and the font of all MBE_Text, MBE_TextNode and MBE_Tag elements within the MbeElement if MbeElement.changeAll is TRUE. If the font specified on assignment isn’t found in symbology resource files, MBE_FontNotFound (1209) runtime error is generated. On retrieval or assignment with MbeElement.changeAll=FALSE, MBE_WrongElemType (1207) runtime error is generated if the element at the current position is not a valid type.

Dim element as New MbeElement

... Get an elementelement.changeAll = FALSE

Select Case element.typeCase MBE_Text, MBE_TextNode, MBE_Tag

If element.fontName = “ENGINEERING” Thenelement.fontName = “WORKING”

End IfCase Else

font = -1End Select

See also MbeElement.font, MbeElement.changeAll.

MbeElement.charHeight, MbeElement.charWidthMbeElement.charHeight

MbeElement.charWidth

Descr. The MbeElement.charHeight and MbeElement.charWidth read-only Double properties retrieve the character height and width of the MBE_Text, MBE_TextNode or MBE_Tag element at the current position within the MbeElement. If the element at the current position is not one of these types, an MBE_WrongElemType (1207) runtime error is generated.

Example Dim element as New MbeElement, charWidth as Double, charHeight as Double... Get an element

Select Case element.typeCase MBE_Text, MBE_TextNode, MBE_Tag ' get the character height and width charHeight = element.charHeight charWidth = element.charWidthCase Else font = -1End Select

8-50 MicroStation BASIC Guide

Page 361: 48784209 Microstation Basic

Element Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 51 Friday, October 15, 1999 1:27 PM

MbeElement.lineSpacingMbeElement.lineSpacing

Descr. The MbeElement.lineSpacing read-only Double property retrieves the line spacing of the MBE_TextNode element at the current position within the MbeElement. If the element at the current position is not one of an MBE_TextNode, an MBE_WrongElemType (1207) runtime error is generated.

Example Dim element as New MbeElement, lineSpacing as Double... Get an element

If element.type = MBE_TextNode Then lineSpacing = element.lineSpacingEnd If

MbeElement.justificationMbeElement.justification

Descr. The MbeElement.justification read-only Integer property retrieves the justification of an MBE_Text, MBE_TextNode or MBE_Tag element at the current position within the MbeElement. If the element at the current position is not one of these three types, an MBE_WrongElemType (1207) runtime error is generated.

The possible value for justification are:

Example Dim element as New MbeElement, justification as Integer... Get an element

Select Case element.typeCase MBE_Text, MBE_TextNode, MBE_Tag

MBE_LeftTop 0

MBE_LeftCenter 1

MBE_LeftBottom 2

MBE_LeftMarginTop 3 (Text nodes only)

MBE_LeftMarginCenter 4 (Text nodes only)

MBE_LeftMarginBottom 5 (Text nodes only)

MBE_CenterTop 6

MBE_CenterCenter 7

MBE_CenterBottom 8

MBE_RightMarginTop 9 (Text nodes only)

MBE_RightMarginCenter 10 (Text nodes only)

MBE_RightMarginBottom 11 (Text nodes only)

MBE_RightTop 12

MBE_RightCenter 13

MBE_RightBottom 14

MicroStation BASIC Guide 8-51

Page 362: 48784209 Microstation Basic

Element Object

600macro.bk : 608_EXT.FRA Page 52 Friday, October 15, 1999 1:27 PM

' get the justification justification = element.justificationCase Else justification = -1End Select

MbeElement.getStringstat=MbeElement.getString(elemText as String [,numEDFields as Integer[, _enterDataFields() as MbeEDField ]])

Descr. The MbeElement.getString function retrieves the text string for the MBE_Text element at the current position within the MbeElement. Optionally, the number of “Enter Data” fields and the starting position and length of those Enter Data fields can be returned by numEDFields and enterDataFields. The MbeEDField predefined data type is as follows:

Type MbeEDFieldstart as Integerlength as Integerjustification as Integer

End Type

Valid values for justification are -1, 0, 1. These values relate to left, center and right justification, respectively. If enterDataFields is included, MbeElement.getString redimensions the array passed in to (0 to numEDFields-1), so the macro must pass a variable-length array for this argument. If the element at the current position is not MBE_Text, the function returns MBE_WrongElemType (1207).

Example Dim element as New MbeElement, elemText as StringDim numEDFields as Integer, EDFields() as MbeEDField... Get element somehow

If element.type = MBE_Text ThenIf element.getString(elemText,numEDFields,EDFields)=MBE_Success Then' fill in second EDField, if text has right characteristics

If (numEDFields > 3) ThenIf EDFields(2).start = 8 And EDFields(2).length = 3 Then

Mid$(elemText, 8, 3) = “BJB”If element.setString(elemText,numEDFields,EDFields) _<> MBE_Success Then

MbeWriteError(“Unable to change string”)End If

End IfEnd If

End IfEnd If

See also MbeElement.setString.

8-52 MicroStation BASIC Guide

Page 363: 48784209 Microstation Basic

Element Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 53 Friday, October 15, 1999 1:27 PM

MbeElement.setStringstat = MbeElement.setString (elemText as String [,numEDFields as Integer, _ enterDataFields() as MbeEDField ])

Descr. The MbeElement.setString object function sets the text string for the MBE_Text element at the current position within the MbeElement. Optionally, the number of “Enter Data” fields and the starting position and length of those Enter Data fields can be set using the optional numEDFields and enterDataFields arguments. See MbeElement.getString for the definition of the MbeEDField predefined data type. If numEDFields and enterDataFields are both included, MbeElement.setString sets the enter data fields within the MBE_Text element. enterDataFields must be a one-dimensional array with at least numEDFields entries. If either condition is not met, the function returns Mbe_WrongDimension (801) If the element at the current position is not MBE_Text, the function returns MBE_WrongElemType (1207).

Example Dim element as New MbeElement, elemText as StringDim numEDFields as Integer, EDFields() as MbeEDField... Get element somehow

If element.type = MBE_Text Then If element.getString(elemText, numEDFields, EDFields) = MBE_Success Then ' fill in second EDField, if text has right characteristics If (numEDFields > 3) Then If EDFields(2).start = 8 And EDFields(2).length = 3 Then Mid$(elemText, 8, 3) = “BJB” If element.setString(elemText, numEDFields, EDFields) _ <> MBE_Success Then MbeWriteError (“Unable to change string”) End If End If End If End IfEnd If

See also MbeElement.getString.

MbeElement.primaryAxisMbeElement.primaryAxis

Descr. The MbeElement.primaryAxis read/write Double property retrieves or sets the primary axis of the MBE_Arc or MBE_Ellipse element at the current position within the MbeElement. The primary axis of an ellipse or arc is the axis aligned with the X axis of

MicroStation BASIC Guide 8-53

Page 364: 48784209 Microstation Basic

Element Object

600macro.bk : 608_EXT.FRA Page 54 Friday, October 15, 1999 1:27 PM

the ellipse or arc coordinate system. If the element at the current position is not one of these two types, an MBE_WrongElemType (1207) runtime error is generated.

Example Dim element as New MbeElement, newAxis as Double... Get an element' make the arc into a circular arc, ellipse into a circleIf element.type = MBE_Arc Or element.type = MBE_Ellipse Then If element.primaryAxis <> element.secondaryAxis Then newAxis = (element.primaryAxis + element.secondaryAxis) / 2.0 element.primaryAxis = newAxis element.secondaryAxis = newAxis End IfEnd If

See also MbeElement.secondaryAxis, MbeElement.startAngle, MbeElement.sweepAngle.

MbeElement.secondaryAxisMbeElement.secondaryAxis

Descr. The MbeElement.secondaryAxis read/write Double property retrieves or sets the secondary axis of the MBE_Arc or MBE_Ellipse element at the current position within the MbeElement. The secondary axis of an ellipse or arc is the axis aligned with the Y axis of the ellipse or arc coordinate system. If the element at the current position is not one of these two types, an MBE_WrongElemType (1207) runtime error is generated.

Example Dim element as New MbeElement, newAxis as Double... Get an element' make the arc into a circular arc, ellipse into a circleIf element.type = MBE_Arc Or element.type = MBE_Ellipse Then If element.primaryAxis <> element.secondaryAxis Then newAxis = (element.primaryAxis + element.secondaryAxis) / 2.0 element.primaryAxis = newAxis element.secondaryAxis = newAxis End IfEnd If

See also MbeElement.primaryAxis, MbeElement.startAngle, MbeElement.sweepAngle.

MbeElement.startAngleMbeElement.startAngle

The MbeElement.startAngle read/write Double property retrieves or sets the starting angle in radians of an MBE_Arc element at the current position within the MbeElement. The start angle of an arc is the starting angle for theta while drawing the arc according to the formula X = A cos (theta), Y = B sin (theta), where A is the primary axis and B is the secondary axis. If the element at the current position is not an MBE_Arc, an MBE_WrongElemType (1207) runtime error is generated.

8-54 MicroStation BASIC Guide

Page 365: 48784209 Microstation Basic

Element Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 55 Friday, October 15, 1999 1:27 PM

Example Dim element as New MbeElement, arcAngle as Double... Get an elementIf element.type=MBE_Arc Then arcAngle=element.startAngle End If

See also MbeElement.sweepAngle, MbeElement.primaryAxis, MbeElement.secondaryAxis.

MbeElement.sweepAngleMbeElement.sweepAngle

Descr. The MbeElement.sweepAngle read/write Double property sets the sweep angle in radians for an MBE_Arc element at the current position within the MbeElement. The sweep angle of an arc is the angle through which theta traverses while drawing the arc starting at its start angle according to the formula X = A cos (theta), Y = B sin (theta), where A is the primary axis and B is the secondary axis. If the element at the current position is not an MBE_Arc, an MBE_WrongElemType (1207) runtime error is generated.

Example Dim element as New MbeElement, arcAngle as Double... Get an elementIf element.type=MBE_Arc Then arcAngle=element.startAngle End If

See also MbeElement.primaryAxis, MbeElement.secondaryAxis, MbeElement.startAngle.

MbeElement.topRadius, MbeElement.bottomRadiusMbeElement.topRadius

MbeElement.bottomRadius

Descr. The MbeElement.topRadius and MbeElement.bottomRadius read-only Double properties retrieve the top and bottom radii of the MBE_Cone element at the current position within the MbeElement. If the element at the current position is not an MBE_Cone, an MBE_WrongElemType (1207) runtime error is generated.

Example Dim element as New MbeElement, topRadius as Double, bottomRadius as Double... Get an elementIf element.type = MBE_Cone Then topRadius = element.topRadius bottomRadius = element.bottomRadiusEnd If

See also MbeElement.getOrigin, MbeElement.getTopOrigin.

MbeElement.getTopOriginstat = MbeElement.getTopOrigin(origin as MbePoint)

Descr. The MbeElement.getTopOrigin object function retrieves an MbePoint that is the center of the top circle of the MBE_Cone at the current position in the MbeElement. If the

MicroStation BASIC Guide 8-55

Page 366: 48784209 Microstation Basic

Element Object

600macro.bk : 608_EXT.FRA Page 56 Friday, October 15, 1999 1:27 PM

element at the current position is not an MBE_Cone, MBE_WrongElemType (1207) runtime error is generated. The base center of MBE_Cone is retrieved by MbeElement.getOrigin.

Example Dim element as New MbeElement, topOrigin as MbePoint, botOrigin as MbePointIf element.type = MBE_Cone Then stat = element.getOrigin (botOrigin) stat = element.getTopOrigin (topOrigin)End If

See also MbeElement.getOrigin.

MbeElement.publishMbeElement.publish publishName as String

Descr. The MbeElement.publish object method publishes the underlying structure for an MbeElement so that it can be accessed using MbeCExpression routines. This facility is rarely needed by macro programmers, but is provided for instances where MbeElement methods do not provide an interface to some aspect of the MbeElement. Effective use of MbeElement.publish requires a good working knowledge of C and MDL (MicroStation Development Language). BASIC MbeElement objects are implemented using MDL element descriptors, so an understanding of element descriptor concept is also needed. When the MbeElement.publish statement is executed, the name supplied becomes the variable name for a C structure defining an MbeElement. That name can then be used by MbeCExpression functions to access structure members. Accessible members of a C structure that represent an MbeElement are:

Using MbeElement.publish and MbeCExpression requires extreme caution. None of the safeguards that are in place when you access the MbeElement through the BASIC object interface are in place when you use this technique.

Example Dim element as New MbeElement, nodeNumber as Long, filePos as Long' read the first elementfilePos = element.fromFile (0)element.publish "elem"

' Find text node number 8 in the master fileDo While filePos >= 0 print "element type "; element.type If element.type = MBE_TextNode Then nodeNum = MbeCExpressionLong _ ("elem.currentPosition->el.text_node_2d.nodenumber") If nodeNum = 8 Then End Do

long filePos file position

int fileNum file number

int globalChanges “changeAll” property

MSElementDescr *currentPosition current position

MSElementDescr *elemDP element descriptor

8-56 MicroStation BASIC Guide

Page 367: 48784209 Microstation Basic

Element Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 57 Friday, October 15, 1999 1:27 PM

End If filePos = element.fromFile(filePos + element.fileSize)LoopIf filePos >= 0 Then ' Do interrupted - found text node number 8 ... process it hereEnd If

See also MbeCExpressionLong, MbeCExpressionDouble, MbeCExpressionString.

MbeElement.groupMbeElement.group

Descr. The MbeElement.group read/write Integer property sets or retrieves the graphic group of the MbeElement. When MbeElement.group is retrieved, it returns the graphic group of the component element at the current position. When MbeElement.group is assigned, it sets the graphic group of component element at the current position if MbeElement.changeAll is FALSE, and the level of all components of the MbeElement if MbeElement.changeAll is TRUE. Any attempt to assign a graphic group to a non-graphics (control) element results in an ERR_WRONGELEMENTTYPE (1207) runtime error.

Example Sub MatchGroup(el1 as MbeElement, el2 as MbeElement, allComps as Integer)' set changeAll property to change all component elements if desiredel1.changeall = allCompsel1.group = el2.group

End Sub

See also MbeElement.changeAll, MbeDgnInfo.graphicGroup, MbeDgnInfo.nextGraphicGroup.

MbeElement.isTaggedDescr. MbeElement.isTagged is a read only integer property which decides whether the

element has any tags attached. It returns either 1 (tagged) or 0 (not tagged).

Example Sub ShowTagInfo(inElem as MbeElement)if inElem.isTagged = 1 then call printTaggedInfo(inElem) end if

End sub

See also MbeElement.attachTag, MbeElement.numTags, MbeElement.tagId.

MbeElement.tagIdDescr. MbeElement.tagId is a read only property of type Long that returns the unique

association ID for the element. It returns 0 if the element is not tagged.

Example if inElem.tagId=0 then call AssociateElement(inElem) end ifEnd sub

See also MbeElement.attachTag, MbeElement.isTagged, MbeElement.numTags.

MicroStation BASIC Guide 8-57

Page 368: 48784209 Microstation Basic

Element Object

600macro.bk : 608_EXT.FRA Page 58 Friday, October 15, 1999 1:27 PM

MbeElement.numTagsDescr. MbeElement.numTags is a read only integer property which returns the number of tags

attached to the element. It returns 0 if it is not tagged.

Example Sub ProcessTags(inElem as MbeElement)if inElem.isTagged = 1 then

for idx = 0 to idx = inElem.numTags 1...next idx

end ifEnd sub

See also MbeElement.attachTag, MbeElement.isTagged.

MbeElement.extractTagsstat = MbeElement.extractTags(tagArray() as MbeTag)

Descr. MbeElement.extractTags creates an array of MbeTag objects for each tag attached to the element. tagArray specifies a variable length array of MbeTag objects which will be redimensioned according the number tag attachments. MbeElement.extractTags returns MBE_Success if either the tags are extracted successfully or the element has no tags attached. Otherwise, an error code is returned.

Example Sub printTaggedInfo(inElem as MbeElement)dim tagArray() as MbeTagif inElem.isTagged = 1 then

total = inElem.numTagsif inElem.extractTags(tagArray) = MBE_Success then

for idx = 0 to total -1call printTag(tagArray(idx))next idx

end ifend if

End Sub

See also MbeElement.attachTag, MbeElement.getMbeTag.

MbeElement.getMbeTagstat = MbeElement.getMbeTag(tag as MbeTag)

Descr. MbeElement.getMbeTag creates an MbeTag object from an attribute element (type 37). tag specifies the MbeTag object to be created from the element. MbeElement.getMbeTag returns MBE_Success if the MbeTag object extracted successfully from the element. It returns MBE_WrongElemType if the element is not an attribute element (type 37).

Example Sub printTagInfo(inElem as MbeElement)dim tag as new MbeTag

8-58 MicroStation BASIC Guide

Page 369: 48784209 Microstation Basic

Element Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 59 Friday, October 15, 1999 1:27 PM

if inElem.getMbeTag(tag)=MBE_Success then‘print tag properties

end ifEnd Sub

See also MbeElement.attachTag, MbeElement.extractTags.

MbeElement.attachTagstat = MbeElement.attachTag(tag as MbeTag)stat = MbeElement.attachTag(tag as MbeTag, doNotWrite as integer)

Descr. MbeElement.attachTag attaches the tag specified by an MbeTag object to the element. If doNotWrite is not passed or its value is FALSE then the attribute element (type 37) is also written to the design file. tag specifies the MbeTag object containing the tag information to be attached. MbeElement.attachTag returns MBE_Success if the tag is attached successfully to the element. Otherwise, it returns an error code.

Example Sub tagElement(count as Long, inElem as MbeElement)Dim tag as new MbeTagtag.setName = "set0001"'tag element count tag.name = "elemnum"tag.value = Str$ (count)stat = inElem.attachTag(tag)

End Sub

See also MbeElement.getMbeTag, MbeTag.value, MbeTag.setName, MbeTag.name.

MbeElement.getNumLinkagesnumLinkages%=MbeElement.getNumLinkages(linkageId as Long)

Descr. MbeElement.getNumLinkages returns the number of user attribute data linkages on the element matching the linkage signature of linkageId.

Example ’ An application-specific linkage Id must be obtained from Bentley Systems.’ Do not use the Id shown below in this example as it is for demonstration’ purposes only and might conflict with already existing linkages.Const demoLinkageId=43797Dim numLinkages As Integer, element As New MbeElement... get an elementnumLinkages=element.getNumLinkages(demoLinkageId)

MbeElement.extractLinkagestatus&=MbeElement.extractLinkage(linkageData As <almost any type>, _linkageId As Long [, nthLink As Integer])

MicroStation BASIC Guide 8-59

Page 370: 48784209 Microstation Basic

Element Object

600macro.bk : 608_EXT.FRA Page 60 Friday, October 15, 1999 1:27 PM

Descr. MbeElement.extractLinkage obtains a copy of a user attribute data linkage from an element and makes it accessible in a BASIC variable. linkageData can be any data type except Single and Object. Contents of the variable are filled in from a user attribute data linkage. The signature for the new linkage is given by linkageId. nthLink specifies the linkage to extract in cases of multiple linkages on the element matching linkageId. If nthLink is not provided, the first linkage matching linkageId is extracted. Regardless of platform, user attribute data copied from the element automatically is converted from .dgn file format (packed little-endian) to native memory format. Attention is needed when extracting BASIC String variables (or String members of User Defined Types). Although linkageData is filled in by MbeElement.extractLinkage, it is first used as a template on interpreting the format of the linkage data on the element. When that data includes a char array, the corresponding String variable must be pre-sized to match the char data’s size. String variables are pre-sized by assigning a value to it. The example below may be considered an inverse to that in MbeElement.appendLinkage.

Example ’ An application-specific linkage Id must be obtained from Bentley Systems.’ Do not use the Id shown below in this example as it is for demonstration’ purposes only and might conflict with already existing linkages.Const demoLinkageId=43797Type FurnitureType

partId As Longdescription As String ’Must be padded to 32 characters

End TypeSub MainDim status As Long, element As New MbeElement, chair As FurnitureType’String variables must be initialized to their expected sizechair.description=space$(32)... get an element’extract the first demolinkage

status=element.extractLinkage(chair, demoLinkageId)End sub

MbeElement.appendLinkagestatus&=MbeElement.appendLinkage(linkageData As <almost any type>, _linkageId As Int)

Descr. MbeElement.appendLinkage appends a new user attribute data linkage to an element. linkageData can be any BASIC data type except Single and Object. Contents of the variable are appended to the element as a user attribute data linkage. The signature of the new linkage is provided by linkageId. Regardless of platform, the BASIC variable’s contents will be converted to .dgn file format (packed little-endian). Attention is needed when the BASIC variable is a String variable or a User Defined Type containing a String member. String variables have no predefined sizes, they are sized to fit data as needed. Char arrays in user attribute data linkages must be a fixed size to be extracted properly at a later time. The solution is padding the String variable to desired size before appending to the element. Consider a user attribute data linkage

8-60 MicroStation BASIC Guide

Page 371: 48784209 Microstation Basic

Element Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 61 Friday, October 15, 1999 1:27 PM

consisting of 32 chars needs to be appended to an element. PadString, below can be used to pad the String variable to the desired size.

Example ’ An application-specific linkage Id must be obtained from Bentley Systems.’ Do not use the Id shown below in this example as it is for demonstration’ purposes only and might conflict with already existing linkages.Const demoLinkageId=43797Type FurnitureType

partId As Longdescription As String ’Must be padded to 32 characters

End TypeFunction PadString(theString As String, padSize As Integer) As String

PadString=theString+space$(padSize-len(theString))End FunctionSub Main

Dim status As Long, element As New MbeElement, chair As FurnitureTypechair.partId=512chair.description=PadString("arm chair", 32)

... get an elementstatus=element.appendLinkage(chair, demoLinkageId)End sub

MbeElement.deleteLinkagenumDelete%=MbeElement.deleteLinkage(linkageId [, nthLink])

Descr. MbeElement.deleteLinkage deletes one or more user attribute data linkages matching the linkage signature of linkageId, from an element. nthLink (optional) specifies which linkage to delete from the element. This only applies when more than one linkage matching linkageId exists on the element. If nthLink is not provided, the first linkage encountered (matching linkageId) is deleted. To delete all linkages matching linkageId, specify -1 for nthLink. MbeElement.deleteLinkage returns number of linkages deleted.

Example ’ An application-specific linkage Id must be obtained from Bentley Systems.’ Do not use the Id shown below in this example as it is for demonstration’ purposes only and might conflict with already existing linkages.Const demoLinkageId=43797Dim numDeleted as Integer, element as New MbeElement... get an element’ delete the 2nd linkage on the element.numDeleted=element.deleteLinkage(demoLinkageId, 2)

See also MbeElement.getNumLinkages, MbeElement.extractLinkage, MbeElement.appendLinkage.

MicroStation BASIC Guide 8-61

Page 372: 48784209 Microstation Basic

Element Set Object

600macro.bk : 608_EXT.FRA Page 62 Friday, October 15, 1999 1:27 PM

Element Set Object

MbeElementSet.fromSelectionSetstat = MbeElementSet.fromSelectionSet([discard])

Descr. The MbeElementSet.fromSelectionSet object function populates the MbeElementSet object from the user selection set, if there is one. If discard is set to a nonzero value, the user selection set is discarded after it is transferred to the object, which is convenient if the macro wants to sequence a MicroStation command that works on a selection set, giving individualized inputs for every element in the selection set (e.g., the scaletxt.bas example shown below). If MbeElementSet.fromSelectionSet is called for an MbeElementSet object that has previously been populated by a call to either MbeElementSet.fromSelectionSet or MbeElementSet.fromFence, the existing set members are discarded before getting the new members.

The MbeElementSet.fromSelectionSet function returns MBE_Success if there is a selection set, and MBE_NoSelectionSet (1301) if there is no user selection set active.

Example Sub mainDim elemSet as New MbeElementSetDim elem as New MbeElementDim setMember as MbeSetMemberDim point as MbePointDim filePos as LongDim fileNum as IntegerDim saveGGLk as IntegerDim saveMsgs as Integer

' turn off graphic group locksaveGGLk = MbeSettings.graphGroupLockMbeSettings.graphGroupLock = 0

' turn off messagessaveMsgs = MbeState.messagesMbeState.messages = 0

' get element set from either selection set or fence

Properties and Methods Used To

MbeElementSet.fromSelectionSet (page 8-62)

Populate the MbeElementSet object from the currently defined selection set, if one exists.

MbeElementSet.fromFence (page 8-63) Populate the MbeElementSet object from the currently defined fence, if one exists.

MbeElementSet.getFirst (page 8-64) Get file information on the first selection set member (returned as type MbeSetMember).

MbeElementSet.getNext (page 8-64) Retrieve information on the next selection set member.

MbeElementSet.clear (page 8-65) Free all memory associated with the MbeElementSet.

8-62 MicroStation BASIC Guide

Page 373: 48784209 Microstation Basic

Element Set Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 63 Friday, October 15, 1999 1:27 PM

If elemSet.fromSelectionSet (1) <> MBE_Success ThenIf elemSet.fromFence() <> MBE_Success Then

MbeWriteStatus "No fence or selection set"Else

MbeWriteStatus "Processing Fence"End If

ElseMbeWriteStatus "Processing Selection Set"

End If

' set an undo mark so we can go back MbeSendCommand "MARK"

status = elemSet.getFirst(setMember)' process each graphic group memberDo While status = MBE_Success

filePos = elem.fromFile(setMember.filePos, setMember.fileNum)If elem.type = MBE_Text Then

If elem.getOrigin(point) = MBE_Success ThenMbeSendCommand "SCALE"MbeLocateElement setMember.filePos,_

elem.componentFilePos, setMember.fileNum, pointIf MbeState.cmdResult = MBE_AcceptQuery Then

MbeSendDataPoint point

' cancel scale, as accept point may' select another elemMbeSendCommand "NULL"

End IfEnd If

End Ifstatus = elemSet.getNext (setMember)

Loop

' clear selection setelemSet.clear

' restore graphic group lock and messagesMbeSettings.graphGroupLock = saveGGLkMbeState.messages = saveMsgs

End Sub

See also MbeElementSet.fromFence, MbeElementSet.clear.

MbeElementSet.fromFencestat = MbeElementSet.fromFence([allowLocked])

Descr. The MbeElementSet.fromFence object function populates the MbeElementSet object from a fence, if there is one. If allowLocked is set to a non-zero value, elements from reference files and elements in the master file with the locked bit set are included in the MbeElementSet. If allowLocked is omitted or zero, only unlocked elements in the

MicroStation BASIC Guide 8-63

Page 374: 48784209 Microstation Basic

Element Set Object

600macro.bk : 608_EXT.FRA Page 64 Friday, October 15, 1999 1:27 PM

master file are included. If fence clip lock is on, the elements that overlap the fence boundary are clipped at the boundary and the appropriate clipped portion of the element becomes part of the element set.

If MbeElementSet.fromFence is called for an MbeElementSet object that has previously been populated by a call to MbeElementSet.fromSelectionSet or MbeElementSet.fromFence, the existing set members are discarded before getting the new members.

The MbeElementSet.fromFence function returns MBE_Success if there is a fence active, and MBE_NoFence (1302) if no fence is defined.

See also MbeElementSet.fromFence, MbeElementSet.clear; For an example see MbeElementSet.fromSelectionSet.

MbeElementSet.getFirststat = MbeElementSet.getFirst(setMember as MbeSetMember)

Descr. The MbeElementSet.getFirst object function retrieves the first member from the MbeElementSet. The element set members are returned as type MbeSetMember, which is a predefined type as follows:

Type MbeElementSetfilePos as LongfileNum as Integer

End Type

The MbeElementSet.getFirst function returns MBE_Success if there is at least one member in the set, and MBE_NoMoreInset (1304) if the set is empty despite an attempt to get a set from a fence or selection set, and MBE_MustGetFromUser (1303) if neither MbeElementSet.fromSelectionSet nor MbeElementSet.fromFence was successfully called to populate the set.

See also MbeElementSet.getNext; For an example see MbeElementSet.fromSelectionSet.

MbeElementSet.getNextstat = MbeElementSet.getNext(setMember as MbeSetMember)

Descr. The MbeElementSet.getFirst object function retrieves the next member from the MbeElementSet. The element set members are returned as type MbeSetMember, which is a predefined type as follows:

Type MbeElementSetfilePos as LongfileNum as Integer

End Type

The MbeElementSet.getFirst function returns MBE_Success if there is another member in the set, and MBE_NoMoreInset (1304) if there are no more members. If

8-64 MicroStation BASIC Guide

Page 375: 48784209 Microstation Basic

Element Set Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 65 Friday, October 15, 1999 1:27 PM

neither MbeElementSet.fromSelectionSet nor MbeElementSet.fromFence has been successfully called, MbeElementSet.getNext returns MBE_MustGetFromUser (1303).

See also MbeElementSet.getFirst; For an example see MbeElementSet.fromSelectionSet.

MbeElementSet.clearMbeElementSet.clear

Descr. The MbeElementSet.clear object method discards the MbeElementSet members and returns the memory used by the element set to the system. It is good programming practice to call MbeElementSet.clear as soon as the set processing is complete. If a macro uses an MbeElementSet and fails to call MbeElementSet.clear, the clear is automatically performed when the MbeElementSet object goes out of scope or when the macro exits, whichever comes first.

See also MbeElementSet.fromFence; For an example see MbeElementSet.fromSelectionSet.

MicroStation BASIC Guide 8-65

Page 376: 48784209 Microstation Basic

Settings Object

600macro.bk : 608_EXT.FRA Page 66 Friday, October 15, 1999 1:27 PM

Settings Object

Properties and Methods Used To

MbeSettings.angle (page 8-67) Set or retrieve the active angle.

MbeSettings.areaMode (page 8-68) Set or retrieve the active area mode (Solid or Hash).

MbeSettings.axisAngle (page 8-68) Set or retrieve the increment angle for Axis Lock.

MbeSettings.axisOrigin (page 8-68) Set or retrieve the origin angle for Axis Lock.

MbeSettings.capMode (page 8-69) Set or retrieve the active cap mode for making capped (open) surfaces or uncapped surfaces (treated as solids).

MbeSettings.cell (page 8-69) Set or retrieve the active cell name.

MbeSettings.class (page 8-69) Set or retrieve the active class.

MbeSettings.color (page 8-70) Set or retrieve the active color number.

MbeSettings.colorName (page 8-70) Set or retrieve the active color by name.

MbeSettings.currentGraphicGroup (page 8-71)

Set or retrieve the current graphic group number.

MbeSettings.fillColor (page 8-71) Set or retrieve the active fill color.

MbeSettings.fillMode (page 8-71) Set or retrieve the active fill mode.

MbeSettings.font (page 8-72) Set or retrieve the active font by number

MbeSettings.fontName (page 8-72) Set or retrieve the active font by name.

MbeSettings.gridReferences (page 8-72) Set or retrieve the number of grid points between grid reference crosses.

MbeSettings.gridUnits (page 8-73) Set or retrieve the spacing between grid points.

MbeSettings.level (page 8-73) Set or retrieve the active level.

MbeSettings.lineStyle (page 8-74) Set or retrieve the active line style.

MbeSettings.lineStyleName (page 8-74) Set or retrieve the active line style name.

MbeSettings.lineTerminator (page 8-74) Set or retrieve the active line terminator (cell name).

MbeSettings.nodeJustification (page 8-75) Set or retrieve the active text node justification.

MbeSettings.patternAngle1 (page 8-75) Set or retrieve the pattern angle 1 as a double in radians.

MbeSettings.patternAngle2 (page 8-75) Set or retrieve the pattern angle 2 as a double in radians.

MbeSettings.patternCell (page 8-76) Set or retrieve the active pattern cell name.

MbeSettings.setPatternDelta (page 8-76) Set the active pattern component offsets.

MbeSettings.getPatternDelta (page 8-77) Retrieve the active pattern component offsets.

MbeSettings.patternScale (page 8-77) Set or retrieve the active pattern scale factor.

MbeSettings.point (page 8-77) Set or retrieve the active point cell name.

MbeSettings.setScale (page 8-78) Set the active scale.

MbeSettings.getScale (page 8-78) Retrieve the active scale.

MbeSettings.tagIncrement (page 8-78) Set or retrieve the active tag increment.

MbeSettings.terminatorScale (page 8-79) Set or retrieve the active line terminator scale.

8-66 MicroStation BASIC Guide

Page 377: 48784209 Microstation Basic

Settings Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 67 Friday, October 15, 1999 1:27 PM

MbeSettings.angleMbeSettings.angle

Descr. The MbeSettings.angle read/write property sets or retrieves the active angle as a Double in radians.

Example Dim oldAngle as DoubleoldAngle = MbeSettings.angleMbeSettings.angle = PI/4 ' set active angle to 45 degrees...MbeSettings.angle = oldAngle

MbeSettings.textHeight (page 8-79) Set or retrieve the active text height.

MbeSettings.textWidth (page 8-79) Set or retrieve the active text width.

MbeSettings.textLineLength (page 8-80) Set or retrieve the active text line length.

MbeSettings.textLineSpacing (page 8-80) Set or retrieve the active text line spacing.

MbeSettings.textJustification (page 8-80) Set or retrieve the active text justification.

MbeSettings.weight (page 8-81) Set or retrieve the active line weight.

MbeSettings.associationLock (page 8-81) Set or retrieve the Association Lock state (on or off).

MbeSettings.axisLock (page 8-82) Set or retrieve the Axis Lock state (on or off).

MbeSettings.boresiteLock (page 8-82) Set or retrieve the Boresite Lock state (on or off).

MbeSettings.cellStretchLock (page 8-82) Set or retrieve the cell stretch lock state (on or off).

MbeSettings.constructionPlaneLock (page 8-83)

Set or retrieve the Construction Plane Lock state (on or off).

MbeSettings.depthLock (page 8-83) Set or retrieve the Depth Lock state (on or off).

MbeSettings.graphGroupLock (page 8-83) Set or retrieve the Graphic Group Lock state (on or off).

MbeSettings.gridLock (page 8-84) Set or retrieve the Grid Lock state (on or off).

MbeSettings.fenceClip (page 8-84) Turn fence clipping on or off.

MbeSettings.fenceOverlap (page 8-84) Set or retrieve the fence overlap lock state (controls how elements that overlap the fence are processed).

MbeSettings.fenceVoid (page 8-85) Set or retrieve the fence void lock state (controls how elements outside the fence are processed).

MbeSettings.levelLock (page 8-85) Set or retrieve the Level Lock state (determines whether located elements should be limited to the active level).

MbeSettings.selectionSetLock (page 8-85) Set or retrieve the selection set lock state (controls whether MicroStation commands will operate on elements in selection sets).

MbeSettings.snapLock (page 8-86) Set or retrieve the Snap Lock state.

MbeSettings.textNodeLock (page 8-86) Set or retrieve the Text Node Lock state.

MbeSettings.settingErr (page 8-86) Determine the status of the last attempt to set or retrieve one of the properties of the MbeSettings system object.

Properties and Methods Used To

MicroStation BASIC Guide 8-67

Page 378: 48784209 Microstation Basic

Settings Object

600macro.bk : 608_EXT.FRA Page 68 Friday, October 15, 1999 1:27 PM

MbeSettings.areaModeMbeSettings.areaMode

Descr. The MbeSettings.areaMode read/write Integer property sets or retrieves the active area mode as an Integer. MbeSettings.areaMode is set to 0 for Solid and 1 for Hole. If an attempt is made to set MbeSettings.areaMode to a value other than 0 or 1, it is not set and MbeSettings.settingErr is set to TRUE.

Example Dim oldAreaMode as IntegeroldAreaMode = MbeSettings.areaModeMbeSettings.areaMode = 0 ' set active areaMode to Solid...MbeSettings.areaMode = oldAreaMode ' restore old areaMode

See also MbeSettings.settingErr.

MbeSettings.axisAngleMbeSettings.axisAngle

Descr. The MbeSettings.axisAngle read/write property sets or retrieves the increment angle for axis lock. For example, if MbeSettings.axisAngle is PI/4 (45 degrees), the axis lock will lock at 0, 45, 90,... degrees. The property is a Double measured in radians.

Example Dim oldAxisAngle as DoubleoldAxisAngle = MbeSettings.axisAngleMbeSettings.axisAngle = PI/4 ' set axis angle to 45 degrees...MbeSettings.axisAngle = oldAxisAngle

See also MbeSettings.axisOrigin.

MbeSettings.axisOriginMbeSettings.axisOrigin

Descr. The MbeSettings.axisOrigin read/write property sets or retrieves the origin angle for axis lock. For example, if MbeSettings.axisOrigin is PI/4 (45 degrees) and MbeSetting.axisAngle is PI/2 (90 degrees), the axis lock will lock at 45, 135, 225... degrees. The property is a Double measured in radians.

Example Dim oldAxisOrigin as DoubleDim oldAxisAngle as Double

oldAxisOrigin = MbeSettings.axisOrigin' save existing settingsoldAxisAngle = MbeSettings.axisAngle

MbeSettings.axisOrigin = PI/4 ' set axis origin to 45 degreesMbeSettings.axisAngle = PI/2 ' and axis angle to 90 degrees...

8-68 MicroStation BASIC Guide

Page 379: 48784209 Microstation Basic

Settings Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 69 Friday, October 15, 1999 1:27 PM

MbeSettings.axisOrigin = oldAxisOrigin MbeSettings.axisAngle = oldAxisAngle

See also MbeSettings.axisOrigin.

MbeSettings.capModeMbeSettings.capMode

Descr. The MbeSettings.capMode read/write property sets or retrieves the active cap mode as an Integer. MbeSettings.capMode is set to 0 to make uncapped surfaces (treated as open surfaces) and 1 for capped surfaces (treated as solids). If an attempt is made to set MbeSettings.capMode to a value other than 0 or 1, it is not set and MbeSettings.settingErr is set to TRUE.

Example Dim oldCapMode as IntegeroldCapMode = MbeSettings.capModeMbeSettings.capMode = 1 ' set active capMode to Closed...MbeSettings.capMode = oldCapMode ' restore old capMode

See also MbeSettings.settingErr.

MbeSettings.cellMbeSettings.cell

Descr. The MbeSettings.cell read/write property sets or retrieves the active cell as a String. If an attempt is made to set MbeSettings.cell to a cell not found in any of the cell libraries in the search path, the active cell is not changed and MbeSettings.settingErr is set to TRUE.

Example Dim oldCell as StringoldCell = MbeSettings.cellMbeSettings.cell = “AC12R2” ' set active cellIf MbeSettings.settingErr = 0 Then ... ' Use new active cell MbeSettings.cell = oldCell ' restore old cellEnd If

See also MbeSettings.settingErr.

MbeSettings.classMbeSettings.class

Descr. The MbeSettings.class read/write property sets or retrieves the active class as an Integer. If an attempt is made to set MbeSettings.class to a number outside the range 0 through 15, it is not set and MbeSettings.settingErr is set to TRUE. The

MicroStation BASIC Guide 8-69

Page 380: 48784209 Microstation Basic

Settings Object

600macro.bk : 608_EXT.FRA Page 70 Friday, October 15, 1999 1:27 PM

reference for MbeElement.class includes a discussion of the meanings of class values.

Example Dim oldClass as IntegeroldClass = MbeSettings.classMbeSettings.class = MBE_ConstructionClass ' set class to construction...MbeSettings.class = oldClass ' restore old class

See also MbeSettings.settingErr.

MbeSettings.colorMbeSettings.color

Descr. The MbeSettings.color read/write property sets or retrieves the active color as an Integer. If an attempt is made to set MbeSettings.color to a number outside the range 0 - 255, it is not set and MbeSettings.settingErr is set to TRUE.

Example Dim oldColor as IntegeroldColor = MbeSettings.colorMbeSettings.color = 12 ' set active color to 12...MbeSettings.color = oldColor ' restore old color

See also MbeSettings.settingErr, MbeSettings.colorName.

MbeSettings.colorNameMbeSettings.colorName

Descr. The MbeSettings.colorName read/write property sets or retrieves the active color as a string. If the active color does not have a name, the string will contain the numeric value of the color on retrieval. The colorName on assignment can be a numeric string as well. If an attempt is made to set MbeSettings.colorName to a string that does not contain a valid color, the active color is unchanged and MbeSettings.settingErr is set to TRUE

Example Dim oldColorName as StringoldColorName = MbeSettings.colorNameMbeSettings.colorName = “Brown” ' set active color to Brown...MbeSettings.colorName = oldColorName ' restore old color

See also MbeSettings.settingErr, MbeSettings.color.

8-70 MicroStation BASIC Guide

Page 381: 48784209 Microstation Basic

Settings Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 71 Friday, October 15, 1999 1:27 PM

MbeSettings.currentGraphicGroupMbeSettings.currentGraphicGroup

Descr. The MbeSettings.currentGraphicGroup read/write property sets or retrieves the active graphic group as a Long. The active graphic group is the graphic group that MicroStation assigns to newly created elements. If an attempt is made to set MbeSettings.currentGraphicGroup to a number outside the range 0 through 65535, it is unchanged and MbeSettings.settingErr is set to TRUE. MbeSettings.currentGraphicGroup should be always be set to 0 when a macro exits.

Example ' set the current graphic group to the next available graphic groupMbeSettings.currentGraphicGroup = MbeDgnInfo.nextGraphicGroup' place elements that go into the graphic group...' put current graphic group back to zeroMbeSettings.currentGraphicGroup = 0

See also MbeSettings.settingErr, MbeDgnInfo.graphicGroup, MbeDgnInfo.nextGraphicGroup.

MbeSettings.fillColorMbeSettings.fillColor

Descr. The MbeSettings.fillColor read/write property sets or retrieves the active fill color as an Integer. If MbeSettings.fillColor is set to -1, the active color is used for the fill color. If MbeSettings.fillMode is set to 0, closed elements are not filled and fillColor is irrelevant.

Dim oldFillColor as Integer

Example oldFillColor = MbeSettings.fillColorMbeSettings.fillColor = 5 ' set to fill elements with color 5...MbeSettings.fillColor = oldFillColor ' restore old fill color

See also MbeSettings.settingErr, MbeSettings.fillMode.

MbeSettings.fillModeMbeSettings.fillMode

Descr. The MbeSettings.fillMode read/write property sets or retrieves the active fill mode as an Integer. MbeSettings.fillMode is set to 0 to make unfilled closed elements and 1 to make filled elements. If an attempt is made to set MbeSettings.fillmode to a number other than 0 or 1, it is not changed and MbeSettings.settingErr is set to TRUE.

Dim oldFillMode as Integer

MicroStation BASIC Guide 8-71

Page 382: 48784209 Microstation Basic

Settings Object

600macro.bk : 608_EXT.FRA Page 72 Friday, October 15, 1999 1:27 PM

Example oldFillMode = MbeSettings.fillModeMbeSettings.fillMode = 1 ' set to fill elements...MbeSettings.fillMode = oldFillMode ' restore old fillMode

See also MbeSettings.settingErr, MbeSettings.fillColor.

MbeSettings.fontMbeSettings.font

Descr. The MbeSettings.font read/write property sets or retrieves the active font as an Integer. If the an attempt is made to set MbeSettings.font to a number that is outside the range 0 to 255, or there is no font with the specified number, the active font is unchanged and MbeSettings.settingErr is set to TRUE.

Example Dim oldFont as IntegeroldFont = MbeSettings.fontMbeSettings.font = 1 ' set active font to 1...MbeSettings.font = oldFont ' restore old font

See also MbeSettings.settingErr.

MbeSettings.fontNameMbeSettings.fontName

Descr. The MbeSettings.fontName read/write property sets or retrieves the active font as a String. If an attempt is made to set MbeSettings.fontName to a font that cannot be found, the active font is unchanged and MbeSettings.settingErr is set to TRUE.

Example Dim oldFontName as StringoldFontName = MbeSettings.fontNameMbeSettings.fontName = “Italics” ' set active font...MbeSettings.fontName = oldFontName ' restore old font

See also MbeSettings.settingErr.

MbeSettings.gridReferencesMbeSettings.gridReference

Descr. The MbeSettings.gridReference read/write property sets or retrieves the number of grid points between grid reference crosses. For example, if MbeSettings.gridReference is 12, there is one reference grid cross drawn for every

8-72 MicroStation BASIC Guide

Page 383: 48784209 Microstation Basic

Settings Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 73 Friday, October 15, 1999 1:27 PM

12 grid points. The property is of type Integer. When it is changed, the grid is redrawn in all views where it is turned on.

Example Dim oldGridReference as IntegeroldGridReference = MbeSettings.gridReferenceMbeSettings.gridReference = 12 ' grid crosses every 12 grid points...MbeSettings.gridReference = oldGridReference

See also MbeSettings.gridUnits.

MbeSettings.gridUnitsMbeSettings.gridUnits

Descr. The MbeSettings.gridUnits read/write property sets or retrieves the spacing between grid points. For example, if MbeSettings.gridUnits is 10.0, there are 10 master units between grid points. The property is a Double measured in master units (or the current units if the MbeCurrentTransform object methods have been used to change units). If an attempt is made to set MbeSettings.gridUnits to a value less than zero, it is unchanged and MbeSettings.settingErr is set to TRUE. When it is changed, the grid is redrawn in all views where it is turned on.

Example Dim oldGridUnits as DoubleoldGridUnits = MbeSettings.gridUnitsMbeSettings.gridUnits = 10.0 ' set grids every 10 master units...MbeSettings.gridUnits = oldGridUnits

See also MbeSettings.gridReferences.

MbeSettings.levelMbeSettings.level

Descr. The MbeSettings.level read/write property sets or retrieves the active level as an Integer. If an attempt is made to set MbeSettings.level to a value outside of the range 1 to 63, the active level is unchanged and MbeSettings.settingErr is set to TRUE.

Example Dim oldLevel as IntegeroldLevel = MbeSettings.levelMbeSettings.level = 20 ' set active level to 20...MbeSettings.level = oldLevel ' restore old level

See also MbeSettings.settingErr.

MicroStation BASIC Guide 8-73

Page 384: 48784209 Microstation Basic

Settings Object

600macro.bk : 608_EXT.FRA Page 74 Friday, October 15, 1999 1:27 PM

MbeSettings.lineStyleMbeSettings.lineStyle

Descr. The MbeSettings.lineStyle read/write property sets or retrieves the active line style as an Integer. If an attempt is made to set MbeSettings.lineStyle to a value outside of the range 0 to 7, the active line style is unchanged and MbeSettings.settingErr is set to TRUE. For setting or retrieving custom line styles, MbeSettings.lineStyleName is used.

Example Dim oldLineStyle as IntegeroldLineStyle = MbeSettings.lineStyleMbeSettings.lineStyle = 3 ' set active line style to 3...MbeSettings.lineStyle = oldLineStyle ' restore old line style

See also MbeSettings.settingErr, MbeSettings.lineStyleName.

MbeSettings.lineStyleNameMbeSettings.lineStyleName

Descr. The MbeSettings.lineStyleName read/write property sets or retrieves the active line style name as a String. On assignment, if the line style name specified is not found, MbeSettings.settingErr is set to TRUE and the active line style is unchanged.

Example Dim oldLineStyleName as StringoldLineStyleName = MbeSettings.lineStyleNameMbeSettings.lineStyleName = “CENTER”' set active line style to CENTER...MbeSettings.lineStyleName = oldLineStyleName ' restore old line style

See also MbeSettings.settingErr, MbeSettings.lineStyle.

MbeSettings.lineTerminatorMbeSettings.lineTerminator

Descr. The MbeSettings.lineTerminator read/write property sets or retrieves the active line terminator as a String. If an attempt is made to set MbeSettings.lineTerminator to a cell not found in any of the cell libraries in the search path, the active line terminator is not changed and MbeSettings.settingErr is set to TRUE.

Example Dim oldLineTerminator as StringoldLineTerminator = MbeSettings.lineTerminatorMbeSettings.lineTerminator = “ARROW” ' set active lineTerminator...MbeSettings.lineTerminator = oldLineTerminator ' restore old lineTerminator

See also MbeSettings.settingErr, MbeSettings.terminatorScale.

8-74 MicroStation BASIC Guide

Page 385: 48784209 Microstation Basic

Settings Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 75 Friday, October 15, 1999 1:27 PM

MbeSettings.nodeJustificationMbeSettings.nodeJustification

Descr. The MbeSettings.nodeJustification read/write property sets or retrieves the active text node justification as an Integer. The text node justification is used to position multiline text elements relative to the user’s insertion point. If an attempt is made to set the node justification to a value outside of the range 0 to 14, it is not set, and MbeSettings.settingErr is set to TRUE. For a list of the defined constants for node justification, see the reference description of MbeElement.justification.

Example Dim oldNodeJustification as IntegeroldNodeJustification = MbeSettings.nodeJustificationMbeSettings.nodeJustification = MBE_CenterCenter...MbeSettings.nodeJustification = oldNodeJustification' restore old node just

See also MbeSettings.settingErr, MbeSettings.textJustification.

MbeSettings.patternAngle1MbeSettings.patternAngle1

Descr. The MbeSettings.patternAngle1 read/write property retrieves or sets pattern angle 1 as a Double measured in radians. Pattern angle 1 is used as the rotation angle for the cells in patterning and for the angle of the hatch lines and the first set of crosshatch lines.

Example Dim oldAngle as DoubleoldAngle = MbeSettings.patternAngle1MbeSettings.patternAngle1 = PI/4 ' set pattern angle 1 to 45 degrees...MbeSettings.patternAngle1 = oldAngle ' restore old angle

See also MbeSettings.patternAngle2, MbeSettings.setPatternDelta, MbeSettings.patternScale.

MbeSettings.patternAngle2MbeSettings.patternAngle2

Descr. The MbeSettings.patternAngle2 read/write property retrieves or sets pattern angle 1 as a Double measured in radians. Pattern angle 2 is used as the angle of the second set of crosshatch lines

Example Dim oldAngle as DoubleoldAngle = MbeSettings.patternAngle2MbeSettings.patternAngle2 = -PI/4 ' set pattern angle 2 to -45 degrees

MicroStation BASIC Guide 8-75

Page 386: 48784209 Microstation Basic

Settings Object

600macro.bk : 608_EXT.FRA Page 76 Friday, October 15, 1999 1:27 PM

...MbeSettings.patternAngle2 = oldAngle ' restore old angle

See also MbeSettings.patternAngle1, MbeSettings.setPatternDelta, MbeSettings.patternScale.

MbeSettings.patternCellMbeSettings.patternCell

Descr. The MbeSettings.patternCell read/write property sets or retrieves the active pattern cell as a String. If an attempt is made to set MbeSettings.patternCell to a cell not found in any of the cell libraries in the search path, the active pattern cell is not changed and MbeSettings.settingErr is set to TRUE.

Example Dim oldPatternCell as StringoldPatternCell = MbeSettings.patternCellMbeSettings.patternCell = “BRICK” ' set pattern cell...MbeSettings.patternCell = oldPatternCell ' restore old pattern cell

See also MbeSettings.settingErr, MbeSettings.patternAngle1, MbeSettings.setPatternDelta, MbeSettings.patternScale.

MbeSettings.setPatternDeltaMbeSettings.patternDelta(deltas as MbePoint)

Descr. The MbeSettings.getPatternDelta object function sets the active pattern deltas. For convenience, the function groups the deltas together as type MbePoint. The deltas.x value corresponds to the distance between pattern components in the x direction of a coordinate system rotated by MbeSettings.patternAngle1, and the deltas.y corresponds to the distance between crosshatch lines in the other direction. The deltas.z value is not used and will always be set to zero. It returns MBE_Success if the delta values are greater than zero, and an error code otherwise.

Example Dim oldDeltas as MbePointDim newDeltas as MbePoint

stat = MbeSettings.getPatternDelta(oldDeltas)newDelta.x = 2.0newDelta.y = 1.5stat = MbeSettings.setPatternDelta(newDeltas)...stat = MbeSettings.setPatternDelta(oldDeltas) ' restore old deltas

See also MbeSettings.getPatternDelta, MbeSettings.patternAngle1, MbeSettings.patternAngle2, MbeSettings.patternCell, MbeSettings.patternScale, MbeSettings.setPatternDelta.

8-76 MicroStation BASIC Guide

Page 387: 48784209 Microstation Basic

Settings Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 77 Friday, October 15, 1999 1:27 PM

MbeSettings.getPatternDeltastat = MbeSettings.getPatternDelta(deltas as MbePoint)

Descr. The MbeSettings.getPatternDelta object function retrieves the active pattern deltas. For convenience, the function returns them grouped together as type MbePoint. It always returns MBE_Success, so there is no point in checking the return value.

See also MbeSettings.patternAngle1, MbeSettings.patternAngle2, MbeSettings.patternCell, MbeSettings.patternScale; For an example see MbeSettings.setPatternDelta.

MbeSettings.patternScaleMbeSettings.patternScale

Descr. The MbeSettings.patternScale read/write property sets or retrieves the pattern scale, which is the scale factor used for cells in area and linear patterning. The property is a Double. If an attempt is made to set MbeSettings.patternScale to a value less than or equal to zero or greater than 100,000, the pattern scale is unchanged and MbeSettings.settingErr is set to TRUE.

Example Dim oldPatternScale as DoubleoldPatternScale = MbeSettings.patternScaleMbeSettings.patternScale = 2.0...MbeSettings.patternScale = oldPatternScale

See also MbeSettings.settingErr, MbeSettings.patternAngle1, MbeSettings.patternCell, MbeSettings.setPatternDelta.

MbeSettings.pointMbeSettings.point

Descr. The MbeSettings.point read/write property sets or retrieves the active point cell as a String. If an attempt is made to set MbeSettings.point to a cell not found in any of the cell libraries in the search path, the active point is not changed and MbeSettings.settingErr is set to TRUE.

Example Dim oldPointCell as StringoldPointCell = MbeSettings.pointMbeSettings.point = “MANHOL” ' set active point...MbeSettings.point = oldPointCell ' restore old point cell

See also MbeSettings.settingErr.

MicroStation BASIC Guide 8-77

Page 388: 48784209 Microstation Basic

Settings Object

600macro.bk : 608_EXT.FRA Page 78 Friday, October 15, 1999 1:27 PM

MbeSettings.setScaleMbeSettings.setScale(scale as MbePoint)

Descr. The MbeSettings.setScale object function sets the active scale. For convenience, the function groups the scale factors together as type MbePoint. The scale.x value corresponds to the active scale in the x direction, scale.y the active scale in the y direction, and scale.z the active scale in the z direction. If an attempt is made to set any of the three scale factors to a value less than or equal to zero or greater than 100,000, the function fails and returns an error code of 1 or otherwise MBE_SUCCESS.

Example Dim oldScale as MbePointDim newScale as MbePoint

stat = MbeSettings.setScale(oldScale)newScale.x = 1.5newScale.y = 1.5newScale.z = 1.5stat = MbeSettings.setScale(newScale)...stat = MbeSettings.setScale(oldScale) ' restore old scale

See also MbeSettings.setScale.

MbeSettings.getScalestat = MbeSettings.getScale(scale as MbePoint)

Descr. The MbeSettings.getScale object function retrieves the scales. For convenience, the function returns them grouped together as type MbePoint. It always returns MBE_Success.

See also MbeSettings.setScale.

MbeSettings.tagIncrementMbeSettings.tagIncrement

Descr. The MbeSettings.tagIncrement read/write property sets or retrieves the active tag increment as an Integer. The tag increment is used in the Copy and Increment Text and Enter Data field commands. If an attempt is made to set MbeSettings.tagIncrement to a value outside of the range 1 to 1000, the active tag increment is unchanged MbeSettings.settingErr is set to TRUE.

Example Dim oldIncrement as IntegeroldIncrement = MbeSettings.tagIncrementMbeSettings.tagIncrement = 2 ' set tag increment to 2...MbeSettings.tagIncrement = oldIncrement ' restore old tag increment

See also MbeSettings.settingErr.

8-78 MicroStation BASIC Guide

Page 389: 48784209 Microstation Basic

Settings Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 79 Friday, October 15, 1999 1:27 PM

MbeSettings.terminatorScaleMbeSettings.terminatorScale

Descr. The MbeSettings.terminatorScale read/write property sets or retrieves the active line terminator scale as a Double. If an attempt is made to set MbeSettings.terminatorScale to a value less than or equal to zero or greater than 100,000, the terminator scale is unchanged and MbeSettings.settingErr is set to TRUE.

Example Dim oldTerminatorScale as DoubleoldTerminatorScale = MbeSettings.terminatorScaleMbeSettings.terminatorScale = 0.5 ' set line terminator scale...MbeSettings.terminatorScale = oldTerminatorScale ' restore previous value

See also MbeSettings.settingErr, MbeSettings.lineTerminator.

MbeSettings.textHeightMbeSettings.textHeight

Descr. The MbeSettings.textHeight read/write property sets or retrieves the active text height. The property is a Double measured in master units (or the current units if the MbeCurrentTransform object methods have been used to change units). If an attempt is made to set it too large, it is not set, and MbeSettings.settingErr is set to TRUE.

Example Dim oldTextHeight as DoubleoldTextHeight = MbeSettings.textHeightMbeSettings.textHeight = 0.25...MbeSettings.textHeight = oldTextHeight

See also MbeSettings.settingErr, MbeSettings.textWidth.

MbeSettings.textWidthMbeSettings.textWidth

Descr. The MbeSettings.textWidth read/write property sets or retrieves the active text width. The property is a Double measured in master units (or the current units if the MbeCurrentTransform object methods have been used to change units). If an attempt is made to set it too large, it is not set, and MbeSettings.settingErr is set to TRUE.

Example Dim oldTextWidth as DoubleoldTextWidth = MbeSettings.textWidthMbeSettings.textWidth = 0.20...MbeSettings.textWidth = oldTextWidth

See also MbeSettings.settingErr, MbeSettings.textHeight.

MicroStation BASIC Guide 8-79

Page 390: 48784209 Microstation Basic

Settings Object

600macro.bk : 608_EXT.FRA Page 80 Friday, October 15, 1999 1:27 PM

MbeSettings.textLineLengthMbeSettings.textLineLength

Descr. The MbeSettings.textLineLength read/write property sets or retrieves the active text line length as an Integer. The text line length is used to determine where to automatically “wrap” text in the place text command. If an attempt is made to set MbeSettings.textLineLength to a value outside of the range 1 to 255, the active text line length is unchanged and MbeSettings.settingErr is set to TRUE.

Example Dim oldLineLength as IntegeroldLineLength = MbeSettings.textLineLengthMbeSettings.textLineLength = 80 ' set for 80 column text lines...MbeSettings.textLineLength = oldlineLength

See also MbeSettings.settingErr.

MbeSettings.textLineSpacingMbeSettings.textLineSpacing

Descr. The MbeSettings.textLineSpacing read/write property sets or retrieves the active text line spacing. This is the spacing between lines in a text node created by entering multiline text. The property is a Double measured in master units (or the current units if the MbeCurrentTransform object methods have been used to change units). If an attempt is made to set the text spacing less than or equal to zero or too large, it is not set, and MbeSettings.settingErr is set to TRUE.

Example Dim oldTextSpacing as DoubleoldTextSpacing = MbeSettings.textLineSpacingMbeSettings.textLineSpacing = 0.15...MbeSettings.textLineSpacing = oldTextSpacing

See also MbeSettings.settingErr, MbeSettings.textLineLength.

MbeSettings.textJustificationMbeSettings.textJustification

Descr. The MbeSettings.textJustification read/write property sets or retrieves the active text justification as an Integer. The text justification is used to position single line text elements relative to the user’s insertion point. If an attempt is made to set MbeSettings.textJustification to a value other than 0, 1,2, 6, 7, 8, 12, 13 or 14, the active text justification is unchanged, and MbeSettings.settingErr is set to TRUE. For

8-80 MicroStation BASIC Guide

Page 391: 48784209 Microstation Basic

Settings Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 81 Friday, October 15, 1999 1:27 PM

a list of the defined constants for text justification, see the reference description of MbeElement.justification.

Example Dim oldTextJustification as IntegeroldTextJustification = MbeSettings.textJustificationMbeSettings.textJustification = MBE_LeftTop...MbeSettings.textJustification = oldTextJustification

See also MbeSettings.settingErr, MbeSettings.nodeJustification.

MbeSettings.weightMbeSettings.weight

Descr. The MbeSettings.weight read/write property sets or retrieves the active line weight as an Integer. If an attempt is made to set MbeSettings.weight to a value outside of the range 0 to 31, the active line weight is unchanged, and MbeSettings.settingErr is set to TRUE.

Example Dim oldLineWeight as IntegeroldLineWeight = MbeSettings.weightMbeSettings.weight = 1 ' set active weight to 1...MbeSettings.weight = oldLineWeight ' restore old weight

See also MbeSettings.settingErr.

MbeSettings.associationLockMbeSettings.associationLock

Descr. The MbeSettings.associationLock read/write property sets or retrieves the association lock as an Integer. Setting MbeSettings.associationLock to any non-zero value turns association lock on, and setting it to zero turns association lock off.

Example Dim oldAssociationLock as IntegeroldAssociationLock = MbeSettings.associationLockMbeSettings.associationLock = 0 ' turn off association lock...MbeSettings.associationLock = oldAssociationLock

MicroStation BASIC Guide 8-81

Page 392: 48784209 Microstation Basic

Settings Object

600macro.bk : 608_EXT.FRA Page 82 Friday, October 15, 1999 1:27 PM

MbeSettings.axisLockMbeSettings.axisLock

Descr. The MbeSettings.axisLock read/write property sets or retrieves the axis lock as an Integer. Setting MbeSettings.axisLock to any nonzero value turns axis lock on, and setting it to zero turns axis lock off.

Example Dim oldAxisLock as IntegeroldAxisLock = MbeSettings.axisLockMbeSettings.axisLock = 1 ' turn on axis lock...MbeSettings.axisLock = oldAxisLock ' restore axis lock

See also MbeSettings.axisOrigin, MbeSettings.axisAngle.

MbeSettings.boresiteLockMbeSettings.boresiteLock

Descr. The MbeSettings.boresiteLock read/write property sets or retrieves the boresite lock as an Integer. Setting MbeSettings.boresiteLock to any nonzero value turns boresite lock on, and setting it to zero turns boresite lock off.

Example Dim oldBoresiteLock as IntegeroldBoresiteLock = MbeSettings.boresiteLockMbeSettings.boresiteLock = 1 ' turn on boresite lock...MbeSettings.boresiteLock = oldBoresiteLock ' restore boresite lock

MbeSettings.cellStretchLockMbeSettings.cellStretchLock

Descr. The MbeSettings.cellStretchLock read/write property sets or retrieves the cell stretch lock, which affects the behavior of cells straddling a fence when the Fence Stretch command is used. Setting MbeSettings.cellStretchLock to any nonzero value turns cell stretch lock on, and setting it to zero turns it off.

Example Dim oldCellStretchLock as IntegeroldCellStretchLock = MbeSettings.cellStretchLockMbeSettings.cellStretchLock = 1 ' turn on cell stretch lock...MbeSettings.cellStretchLock = oldCellStretchLock

8-82 MicroStation BASIC Guide

Page 393: 48784209 Microstation Basic

Settings Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 83 Friday, October 15, 1999 1:27 PM

MbeSettings.constructionPlaneLockMbeSettings.ConstructionPlaneLock

Descr. The MbeSettings.constructionPlaneLock read/write property sets or retrieves the construction plane lock as an Integer. Setting MbeSettings.ConstructionPlaneLock to any nonzero value turns the lock on, and setting it to zero turns it off.

Example Dim oldPlaneLock as IntegeroldPlaneLock = MbeSettings.ConstructionPlaneLockMbeSettings.constructionPlaneLock = 1 ' turn on ConstructionPlane lock...MbeSettings.constructionPlaneLock = oldPlaneLock

MbeSettings.depthLockMbeSettings.depthLock

Descr. The MbeSettings.depthLock read/write property sets or retrieves the depth lock as an Integer. When depth lock is on and the user snaps to an element in a 3D file, the input data point is projected onto the active depth for the input view before it is processed. If depth lock is off, the input data point is the point on the element that was snapped to. Setting MbeSettings.depthLock to any nonzero value turns it on, and setting it to zero turns depth lock off.

Example Dim oldDepthLock as IntegeroldDepthLock = MbeSettings.depthLockMbeSettings.depthLock = 1 ' turn on depth lock...MbeSettings.depthLock = oldDepthLock ' restore depth lock

MbeSettings.graphGroupLockMbeSettings.graphGroupLock

Descr. The MbeSettings.graphGroupLock read/write property sets or retrieves the graphic group lock as an Integer. Setting MbeSettings.graphGroupLock to any nonzero value turns it on, and setting it to zero turns graphic group lock off.

Example Dim oldGroupLock as IntegeroldGroupLock = MbeSettings.graphGroupLockMbeSettings.graphgroupLock = 0 ' turn off graphic group lock...MbeSettings.graphGroupLock = oldGroupLock ' restore graphic group lock

MicroStation BASIC Guide 8-83

Page 394: 48784209 Microstation Basic

Settings Object

600macro.bk : 608_EXT.FRA Page 84 Friday, October 15, 1999 1:27 PM

MbeSettings.gridLockMbeSettings.gridLock

Descr. The MbeSettings.gridLock read/write property sets or retrieves the grid lock as an Integer. Setting MbeSettings.gridLock to any nonzero value turns grid lock on, and setting it to zero turns grid lock off.

Example Dim oldGridLock as IntegeroldGridLock = MbeSettings.gridLockMbeSettings.gridLock = 1 ' turn on grid lock...MbeSettings.gridLock = oldGridLock ' restore grid lock

See also MbeSettings.gridUnits, MbeSettings.gridReferences.

MbeSettings.fenceClipMbeSettings.fenceClip

Descr. The MbeSettings.fenceClip read/write property sets or retrieves the fence clip lock as an Integer. Setting MbeSettings.fenceClip to any nonzero value turns fence clipping on, and setting it to zero turns fence clipping off.

Example Dim oldFenceClip as IntegeroldFenceClip = MbeSettings.fenceClipMbeSettings.fenceClip = 1 ' turn on fence clipping...MbeSettings.fenceClip = oldFenceClip ' restore fence clipping

See also MbeSettings.fenceOverlap, MbeSettings.fenceVoid.

MbeSettings.fenceOverlapMbeSettings.fenceOverlap

Descr. The MbeSettings.fenceOverlap read/write property sets or retrieves the fence overlap lock as an Integer. Setting MbeSettings.fenceOverlap to any nonzero value causes fences to process any graphic elements that overlap the fence, while setting it to zero causes fences to process only graphic elements that are completely inside the fence. When MbeSettings.fenceClip is TRUE, the setting of MbeSettings.fenceOverlap is irrelevant. When MbeSettings.fenceVoid is TRUE and MbeSettings.fenceOverlap is FALSE, all graphics elements except those completely within the fence are processed.

Example Dim oldFenceOverlap as IntegeroldFenceOverlap = MbeSettings.fenceOverlapMbeSettings.fenceOverlap = 1 ' turn on fence overlap...MbeSettings.fenceOverlap = oldFenceOverlap ' restore fence overlap

See also MbeSettings.fenceClip, MbeSettings.fenceVoid.

8-84 MicroStation BASIC Guide

Page 395: 48784209 Microstation Basic

Settings Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 85 Friday, October 15, 1999 1:27 PM

MbeSettings.fenceVoidMbeSettings.fenceVoid

Descr. The MbeSettings.fenceVoid read/write property sets or retrieves the fence void lock as an Integer. Setting MbeSettings.fenceVoid to any nonzero value causes fence commands to process graphic elements outside the fence, while setting it to zero causes fence commands to process graphics element inside the fence.

Example Dim oldFenceVoid as IntegeroldFenceVoid = MbeSettings.fenceVoidMbeSettings.fenceVoid = 1 ' process elements outside fence...MbeSettings.fenceVoid = oldFenceVoid ' restore fence void mode

See also MbeSettings.fenceClip, MbeSettings.fenceOverlap.

MbeSettings.levelLockMbeSettings.levelLock

Descr. The MbeSettings.levelLock read/write property sets or retrieves the level lock as an Integer. When level lock is on, the user can locate for manipulation only elements on the active level. Setting MbeSettings.levelLock to any nonzero value turns it on, and setting it to zero turns level lock off.

Example Dim oldLevelLock as IntegeroldLevelLock = MbeSettings.levelLockMbeSettings.levelLock = 1 ' turn on level lock...MbeSettings.levelLock = oldLevelLock ' restore it

MbeSettings.selectionSetLockMbeSettings.selectionSetLock

Descr. The MbeSettings.selectionSetLock read/write property sets or retrieves the selection set lock as an Integer. When selection set lock is off, MicroStation commands will not operate on selection sets - the user must locate elements for modification interactively. Setting MbeSettings.selectionSetLock to any nonzero value turns it on, and setting it to zero turns it off.

Example Dim oldSetLock as IntegeroldSetLock = MbeSettings.selectionSetLockMbeSettings.selectionSetLock = 0 ' turn off selection set lock...MbeSettings.selectionSetLock = oldSetLock

MicroStation BASIC Guide 8-85

Page 396: 48784209 Microstation Basic

Settings Object

600macro.bk : 608_EXT.FRA Page 86 Friday, October 15, 1999 1:27 PM

MbeSettings.snapLockMbeSettings.snapLock

Descr. The MbeSettings.snapLock read/write property sets or retrieves the snap lock as an Integer. Setting MbeSettings.snapLock to any nonzero value turns snap lock on, and setting it to zero turns snap lock off.

Example Dim oldSnapLock as IntegeroldSnapLock = MbeSettings.snapLockMbeSettings.snapLock = 1 ' turn on snap lock...MbeSettings.snapLock = oldSnapLock ' restore snap lock

MbeSettings.textNodeLockMbeSettings.textNodeLock

Descr. The MbeSettings.textNodeLock read/write property sets or retrieves the text node lock as an Integer. When text node lock is on, text can only be placed by attaching it to an existing text node. Setting MbeSettings.textNodeLock to any nonzero value turns text node lock on, and setting it to zero turns it off.

Example Dim oldNodeLock as IntegeroldNodeLock = MbeSettings.TextNodeLockMbeSettings.textNodeLock = 1 ' turn on text node lock...MbeSettings.textNodeLock = oldNodeLock

MbeSettings.settingErrMbeSettings.settingErr

Descr. The MbeSettings.settingErr read-only property reveals whether or not the last attempt to retrieve or set one of the MbeSettings properties was successful or not. Since MbeSettings.settingErr is set for each property retrieval or assignment, it must be checked after the statement that retrieves or sets the property but before another MbeSettings property is accessed.

Example Function setLevelFunc(userSpecifiedLevel as Integer) ' userSpecifiedLevel obtained from user keyin ' Don’t know whether it is valid or not MbeSettings.level = userSpecifiedLevel If MbeSettings.settingErr <> MBE_Success Then Call MbeWriteError(“Level out of range - reenter”) setLevelFunc = 1 Else setLevelFunc = 0 ' acceptable level End IfEnd Function

8-86 MicroStation BASIC Guide

Page 397: 48784209 Microstation Basic

Design File Information Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 87 Friday, October 15, 1999 1:27 PM

Design File Information Object

MbeDgnInfo.dgnFileNameMbeDgnInfo.dgnFileName

Descr. The MbeDgnInfo.dgnFileName read-only String property returns absolute pathname of the currently active design file.

Example Dim designFile as StringdesignFile = MbeDgnInfo.dgnFileName

Properties and Methods Used To

MbeDgnInfo.dgnFileName (page 8-87)

Return the full file name of the current design file.

MbeDgnInfo.dgn3D (page 8-88) Determine if the current design file is 3D.

MbeDgnInfo.dgnFileReadOnly (page 8-88)

Determine if the current design file is opened for read-only access.

MbeDgnInfo.endOfFile (page 8-88) Return the file position of the end of file marker in the current design file.

MbeDgnInfo.masterUnitName (page 8-88)

Set or retrieve the name of the master units used by the current design file.

MbeDgnInfo.subUnitName (page 8-89)

Set or retrieve the name of the sub units used by the current design file.

MbeDgnInfo.uorPerSub (page 8-89) Set or retrieve the number of units of resolution (UORs) per sub unit in the current design file.

MbeDgnInfo.subPerMaster (page 8-90)

Set or retrieve the number of sub-units per master unit in the current design file.

MbeDgnInfo.getGlobalOrigin (page 8-90)

Retrieve the global origin of the design file.

MbeDgnInfo.graphicGroup (page 8-90)

Retrieve the graphic group number that will be used the next time a graphic group is created.

MbeDgnInfo.nextGraphicGroup (page 8-91)

Retrieve and reserve the next available graphic group number.

MbeDgnInfo.cellFileName (page 8-91)

Return the full file name of the cell library attached to the attached design file.

MbeDgnInfo.cell3D (page 8-91) Determine if the attached cell library is 3D.

MbeDgnInfo.cellFileReadOnly (page 8-92)

Determine if the attached cell library is a read-only file.

MicroStation BASIC Guide 8-87

Page 398: 48784209 Microstation Basic

Design File Information Object

600macro.bk : 608_EXT.FRA Page 88 Friday, October 15, 1999 1:27 PM

MbeDgnInfo.dgn3DMbeDgnInfo.dgn3D

Descr. The MbeDgnInfo.dgn3D read-only Integer property returns 1 if the currently active design file is 3D and 0 if it is 2D.

Example If MbeDgnInfo.dgn3D <> 0 Then Call MbeSendCommand(“PLACE CONE”)Else Call MbeWriteError(“Operation valid for 3D file only”)End If

MbeDgnInfo.dgnFileReadOnlyMbeDgnInfo.dgnFileReadOnly

Descr. The MbeDgnInfo.dgnFileReadOnly read-only Integer property returns 1 if the currently active design file is opened for read-only access and 0 if it is writable.

Example If MbeDgnInfo.dgnFileReadOnly = 0 Then Call MbeSendCommand(“PLACE LINE”)Else Call MbeWriteError(“Cannot perform operation on Read-only design file”)End If

MbeDgnInfo.endOfFileMbeDgnInfo.endOfFile

Descr. The MbeDgnInfo.endOfFile read-only Long property returns the file position of the end of file marker in the active design file.

Example Dim endOfFilePos as LongDim newElem as New MbeElementendOfFilePos = MbeDgnInfo.endOfFileMbeSendCommand “Place line”Call MbeSendDataPoint(0.0, 0.0, 0.0, 1)Call MbeSendDataPoint(10.0, 10.0, 10.0, 1)If newElem.fromFile(endOfFilePos) == MBE_Success Then ... ' Process element just created hereEnd If

MbeDgnInfo.masterUnitNameMbeDgnInfo.masterUnitName

Descr. The MbeDgnInfo.masterUnitName read/write property sets or retrieves the master unit name of the currently active design file. The master unit name is an abbreviation limited to two characters. Although this String property can be set, it is not

8-88 MicroStation BASIC Guide

Page 399: 48784209 Microstation Basic

Design File Information Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 89 Friday, October 15, 1999 1:27 PM

recommended. If an attempt is made to set MbeDgnInfos.masterUnitName to a string longer than two characters, a run-time error MBE_StringTooLong (1401) is generated.

Example Dim oldUnitName as String

oldUnitName = MbeDgnInfo.masterUnitNameMbeDgnInfo.masterUnitName = “ft”...MbeDgnInfo.masterUnitName = oldUnitName

MbeDgnInfo.subUnitNameMbeDgnInfo.subUnitName

Descr. The MbeDgnInfo.subUnitName read/write property sets or retrieves the sub unit name of the currently active design file. The sub unit name is an abbreviation limited to two characters. Although this String property can be set, it is not recommended. If an attempt is made to set MbeDgnInfo.subUnitName to a string longer than two characters, a run-time error MBE_StringTooLong (1401) is generated.

Example Dim oldUnitName as String

oldUnitName = MbeDgnInfo.subUnitNameMbeDgnInfo.subUnitName = “in”...MbeDgnInfo.subUnitName = oldUnitName

MbeDgnInfo.uorPerSubMbeDgnInfo.uorPerSub

Descr. The MbeDgnInfo.uorPerSub read/write property sets or retrieves the number of units of resolution (or positional units) per subunit. The property is a Long. Although this property can be set, it is not recommended, since changing its value indiscriminately resizes every graphics element in the design file. Since coordinates that are passed to and from MicroStation BASIC extensions are (by default) in design file master units, it is seldom necessary for a BASIC program to access MbeDgnInfo.uorPerSub, and even more seldom necessary for a BASIC program to change it.

Example Dim oldUorPerSub as Long

oldUorPerSub = MbeDgnInfo.uorPerSubMbeDgnInfo.uorPerSub = oldUorPerSub / 2...MbeDgnInfo.uorPerSub = oldUorPerSub

MicroStation BASIC Guide 8-89

Page 400: 48784209 Microstation Basic

Design File Information Object

600macro.bk : 608_EXT.FRA Page 90 Friday, October 15, 1999 1:27 PM

MbeDgnInfo.subPerMasterMbeDgnInfo.subPerMaster

Descr. The MbeDgnInfo.subPerMaster read/write property sets or retrieves the number of subunits per master unit. The property is a Long. Although this property can be set, it is not recommended, since changing its value indiscriminately resizes every graphics element in the design file. Since coordinates that are passed to and from MicroStation BASIC extensions are (by default) in design file master units, it is seldom necessary for a BASIC program to access MbeDgnInfo.subPerMaster, and even more seldom necessary for a BASIC program to change it.

Example Dim oldSubPerMaster as Long

oldSubPerMaster = MbeDgnInfo.subPerMasterMbeDgnInfo.subPerMaster = oldSubPerMaster * 2...MbeDgnInfo.subPerMaster = oldSubPerMaster

✍ The four properties MbeDgnInfo.masterUnitName, MbeDgnInfo.subUnitName, MbeDgnInfo.uorPerSub and MbeDgnInfo.subPerMaster change the size or meaning of the design file untis. They are interdependent and should not be set without a thorough consideration of the effect of the changes.

MbeDgnInfo.getGlobalOriginstat = MbeDgnInfo.getGlobalOrigin(globalOrg as MbePoint)

Descr. The MbeDgnInfo.getGlobalOrigin object function retrieves the global origin of the design file. The global origin is an offset that is applied to the position of every graphics element in the design file. It is typically used to set the position of the design file in a larger plane (for example, in a state plane coordinate system). A macro must use the ACTIVE ORIGIN MicroStation command to change the global origin. The MbeDgnInfo.getGlobalOrigin object function always returns MBE_Success.

Example Dim globalOrg as MbePoint

stat = MbeDgnInfo.getGlobalOrigin(globalOrg)

MbeDgnInfo.graphicGroupMbeDgnInfo.graphicGroup

Descr. The MbeDgnInfo.graphicGroup read-only Long property retrieves the next graphic group number that will be assigned to a graphic group when a MicroStation command that creates a graphics group is executed (e.g., GROUP ADD).

Example Dim graphGroup as Long

graphGroup = MbeDgnInfo.graphGroup

See also MbeDgnInfo.nextGraphicGroup, MbeSettings.currentGraphicGroup.

8-90 MicroStation BASIC Guide

Page 401: 48784209 Microstation Basic

Design File Information Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 91 Friday, October 15, 1999 1:27 PM

MbeDgnInfo.nextGraphicGroupMbeDgnInfo.nextGraphicGroup

Descr. The MbeDgnInfo.nextGraphicGroup read-only Long property retrieves the next graphic group number that will be assigned to a graphic group. It differs from MbeDgnInfo.graphicGroup in that it reserves the graphic group number that is returned for the macro’s exclusive use. To reserve the graphic group, it increments the internal counter, so that the next graphic group retrieved using MbeDgnInfo.graphicGroup or MbeDgnInfo.nextGraphicGroup will be one higher. A typical use of MbeDgnInfo.nextGraphicGroup is to get a graphic group number to use with MbeSettings.currentGraphicGroup.

' set the current graphic group to the next available graphic groupMbeSettings.currentGraphicGroup = MbeDgnInfo.nextGraphicGroup

' place elements that go into the graphic group...' put current graphic group back to zeroMbeSettings.currentGraphicGroup = 0

See also MbeDgnInfo.graphicGroup, MbeSettings.currentGraphicGroup.

MbeDgnInfo.cellFileNameMbeDgnInfo.cellFileName

Descr. The MbeDgnInfo.cellFileName read-only String property returns the absolute pathname of the currently attached cell library.

Example Dim cellFile as StringcellFile = MbeDgnInfo.cellFileName

MbeDgnInfo.cell3DMbeDgnInfo.cell3D

Descr. The MbeDgnInfo.cell3D read-only Integer property returns 1 if the currently attached cell library is 3D and 0 if it is 2D.

Example If MbeDgnInfo.dgn3D <> 0 And MbeDgnInfo.cell3D <> 0 ThenCall MbeSendCommand(“CREATE CELL NEWCELL”)

ElseCall MbeWriteError(“Cannot create cell: 2D library / 3D file”)

End If

MicroStation BASIC Guide 8-91

Page 402: 48784209 Microstation Basic

Design File Information Object

600macro.bk : 608_EXT.FRA Page 92 Friday, October 15, 1999 1:27 PM

MbeDgnInfo.cellFileReadOnlyMbeDgnInfo.cellFileReadOnly

Descr. The MbeDgnInfo.cellFileReadOnly read-only Integer property returns 1 if the currently attached cell library is opened for read-only access and 0 if it is writable.

Example If MbeDgnInfo.cellFileReadOnly = 0 ThenCall MbeSendCommand(“CREATE CELL”)

ElseCall MbeWriteError(“Cannot create cell: library read only”)

End If

8-92 MicroStation BASIC Guide

Page 403: 48784209 Microstation Basic

Current Transformation Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 93 Friday, October 15, 1999 1:27 PM

Current Transformation Object

MbeCurrentTransform.masterUnitsMbeCurrentTransform.masterUnits

Descr. The MbeCurrentTransform.masterUnits object method initializes the macro’s coordinate transform such that all geometric properties it retrieves or sets are in the master unit coordinates of the design file. This is the default coordinate transform when a macro is started, so if a macro simply wants to use master units, it has no need of this (or any other) MbeCurrentTransform method. If the macro changes the coordinate system using one of the other MbeCurrentTransform methods, however, MbeCurrentTransform.masterUnits is very useful for going back to the default

Properties and Methods Used to

MbeCurrentTransform.masterUnits (page 8-93) Initialize the macro’s coordinate transform to reflect master unit coordinates of the design file.

MbeCurrentTransform.dgnUnits (page 8-95) Initialize the macro’s coordinate transform to reflect design file units (UORs).

MbeCurrentTransform.moveOrigin (page 8-96) Translate the origin of the macro’s coordinate system in terms of the current coordinate system.

MbeCurrentTransform.moveOriginWorld (page 8-96)

Translate the origin of the macro’s coordinate system in terms of design file coordinates (UORs).

MbeCurrentTransform.rotate (page 8-96) Rotate the macro’s coordinate system about its origin.

MbeCurrentTransform.fromView (page 8-97) Match the macro’s coordinate system to that of a specific view.

MbeCurrentTransform.scale (page 8-97) Scale the macro’s coordinate system.

MbeCurrentTransform.scalarToUors (page 8-97)

Scale a value that is relative to the macro’s current coordinate system into the design file coordinate system (UORs).

MbeCurrentTransform.scalarFromUors (page 8-98)

Scale a value that is relative to the macro’s current coordinate system into the design file coordinate system (UORs).

MbeCurrentTransform.pointToUors (page 8-98)

Transform a point specified in the macro’s current coordinate system to the design file coordinate system.

MbeCurrentTransform.pointFromUors (page 8-98)

Transform a point specified in the design file coordinate system to the macro’s current coordinate system.

MicroStation BASIC Guide 8-93

Page 404: 48784209 Microstation Basic

Current Transformation Object

600macro.bk : 608_EXT.FRA Page 94 Friday, October 15, 1999 1:27 PM

coordinate system. The following example illustrates many of the MbeCurrentTransform object methods:

Example ' Example of using MbeCurrentTransform object'---------------------------------------------------------------' DrawShape '---------------------------------------------------------------Sub DrawShape(origin as MbePoint, view as Integer, _ totalWidth as Double, totalHeight as Double) Dim point as MbePoint point = origin Call MbeSendCommand("PLACE SHAPE") Call MbeSendDataPoint (origin, view) point.x = origin.x + totalWidth Call MbeSendDataPoint(point, view) point.y = origin.y - totalHeight Call MbeSendDataPoint(point, view) point.x = origin.x Call MbeSendDataPoint(point, view) point.y = origin.y Call MbeSendDataPoint(point, view)End Sub'---------------------------------------------------------------' Main - entry point'---------------------------------------------------------------Sub Main Dim origin as MbePoint Dim moveDist as MbePoint Dim uorPoint as MbePoint Dim view as Integer Dim saveLocTol as Integer

' set locate tolerance to 0 so PLACE SHAPE works at any zoom level saveLocTol = MbeState.locateTolerance MbeState.locateTolerance = 0

Call MbeSendCommand("NULL") Call MbeWritePrompt("Enter Center Point")

' wait for data or reset Call MbeGetInput(MBE_DataPointInput , MBE_ResetInput) ' reset aborts, data point gives upper left corner If MbeState.inputType = MBE_ResetInput Then Exit Sub ElseIf MbeState.inputType = MBE_DataPointInput Then stat = MbeState.getInputDataPoint(origin, view) End If

' we need the origin point in a fixed coordinate system, use Uors uorPoint = origin MbeCurrentTransform.pointToUors uorPoint

8-94 MicroStation BASIC Guide

Page 405: 48784209 Microstation Basic

Current Transformation Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 95 Friday, October 15, 1999 1:27 PM

' set up current transform from the view the data point was in MbeCurrentTransform.fromView view

' set coordinate system origin to the input point MbeCurrentTransform.moveOriginWorld uorPoint

' set origin to 0,0,0 since we set up our coordinate system origin.x = 0 : origin.y = 0 : origin.z = 0 moveDist.x = 12.0 : moveDist.y = 0.0 : moveDist.z = 0.0

For iCol = 1 to 4 For iPat = 1 To 8 Call DrawShape(origin, view, 5.0, 2.0) MbeCurrentTransform.rotate PI/4 Next iPat MbeCurrentTransform.moveOrigin moveDist MbeCurrentTransform.scale 1.1 Next iCol

MbeState.locateTolerance = saveLocTol

' return to master units (don't really have to do this here ' since we're done, but if we had more to do we'd have to) MbeCurrentTransform.masterUnits

End Sub

See also MbeCurrentTransform.dgnUnits.

MbeCurrentTransform.dgnUnitsMbeCurrentTransform.dgnUnits

Descr. The MbeCurrentTransform.dgnUnits object method initializes the macro’s coordinate transform such that all geometric properties it retrieves or sets are in the design file units, also known as Units Of Resolution (UOR). It is rare that a macro finds it convenient to use MbeCurrentTransform.dgnUnits to work in UORs, but transforming points to and from the design file coordinate system is convenient because it functions as a convenient fixed coordinate system in which to store points when changing the coordinate system using one of the MbeCurrentTransform object methods.

Example MbeCurrentTransform.dgnUnits... ' some manipulations in UORsMbeCurrentTransform.masterUnits... ' back to master units.

See also MbeCurrentTransform.masterUnits, MbeCurrentTransform.scalarToUors, MbeCurrentTransform.pointFromUors.

MicroStation BASIC Guide 8-95

Page 406: 48784209 Microstation Basic

Current Transformation Object

600macro.bk : 608_EXT.FRA Page 96 Friday, October 15, 1999 1:27 PM

MbeCurrentTransform.moveOriginMbeCurrentTransform.moveOrigin moveDistance as MbePoint

Descr. The MbeCurrentTransform.moveOrigin object method moves the origin of the coordinate system by changing the MbeCurrentTransform appropriately. moveDistance specifies distances in the current coordinate system. Sometimes specifying the distance in the current coordinate system is advantageous (i.e., when you have set the coordinate system to align with a view and want to move the origin in the view coordinate system) and sometimes it is a disadvantage. For the latter situation, the MbeCurrentTransform.moveOriginWorld object method is provided, which takes distances specified in the (unchanging) design file coordinate system.

See also MbeCurrentTransform.moveOriginWorld, For an example see MbeCurrentTransform.masterUnits.

MbeCurrentTransform.moveOriginWorldMbeCurrentTransform.moveOriginWorld moveDistance as MbePoint

Descr. The MbeCurrentTransform.moveOriginWorld object method moves the origin of the coordinate system by changing the MbeCurrentTransform appropriately. moveDistance specifies distances in the design file coordinate system. Specifying the distances in the design file coordinate system is an advantage when you have a specific point to which you want to move the origin (i.e., when you want to move it to a user’s input point after having rotated the coordinate system or matched it to a view). Since the design file coordinate system does not change when the MbeCurrentTransform object methods are invoked, a point can be converted to design coordinates (using MbeCurrentTransform.pointToUors) and saved, the MbeCurrentTransform methods can be used to change the coordinate system, and the saved point converted back to the new coordinate system, to yield the same physical point.

See also MbeCurrentTransform.moveOrigin, MbeCurrentTransform.pointToUors, For an example see MbeCurrentTransform.masterUnits.

MbeCurrentTransform.rotateMbeCurrentTransform.rotate _

rotateZ as Double[, rotateY as Double[, rotateX as Double]]

Descr. The MbeCurrentTransform.rotate object method rotates the coordinate system about its current origin. rotateZ is required and represents the rotation about the current Z axis. rotateY and rotateX are optional and specify rotation about the Y and Z axes, respectively. If they are not specified, the coordinate system rotates only about the Z axis.

See also MbeCurrentTransform.fromView, For an example see MbeCurrentTransform.masterUnits.

8-96 MicroStation BASIC Guide

Page 407: 48784209 Microstation Basic

Current Transformation Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 97 Friday, October 15, 1999 1:27 PM

MbeCurrentTransform.fromViewMbeCurrentTransform.fromView view as Integer

Descr. The MbeCurrentTransform.fromView object method matches the rotation of the current coordinate transformation to that of the specified view. After the statement, the X and Y axes of the macro’s coordinate system align with horizontal and vertical in the view.

See also MbeCurrentTransform.rotate, For an example see MbeCurrentTransform.masterUnits.

MbeCurrentTransform.scaleMbeCurrentTransform.scale _

scaleX as Double[, scaleY as Double[, scaleZ as Double]]

Descr. The MbeCurrentTransform.scale object method scales the coordinate system according to scaleX, scaleY and scaleZ. The optional scaleY and scaleZ arguments are seldom used, since if they are omitted, the coordinate system is scaled in each direction by scaleX, which is the recommended practice.

In Visual Basic, the method name scaleTrans must be used instead of scale. See Appendix A for more information on OLE Automation.

See also For an example see MbeCurrentTransform.masterUnits, "Appendix A".

MbeCurrentTransform.scalarToUorsMbeCurrentTransform.scalarToUors value as Double

Descr. The MbeCurrentTransform.scalarToUors object method scales the Double specified in the value argument by the conversion factor from the current coordinate system to design coordinates (UORs).

Example Dim axis as Double... ' get an arc or ellipse elementdistance = element.primaryAxisMbeCurrentTransform.scalarToUors axis... ' use axis in UOR’s for some calculation

See also MbeCurrentTransform.scalarFromUors.

MicroStation BASIC Guide 8-97

Page 408: 48784209 Microstation Basic

Current Transformation Object

600macro.bk : 608_EXT.FRA Page 98 Friday, October 15, 1999 1:27 PM

MbeCurrentTransform.scalarFromUorsMbeCurrentTransform.scalarFromUors value as Double

Descr. The MbeCurrentTransform.scalarFromUors object method scales the Double specified by value by the conversion factor from design coordinates (UORs) to the current coordinate system.

Example Dim result as Double... ' sequence measure distance commandresult = MbeState.measureResult1MbeCurrentTransform.scalarFromUors result... ' result now scaled for use in our macro.

See also MbeCurrentTransform.scalarToUors.

MbeCurrentTransform.pointToUorsMbeCurrentTransform.pointToUors point as MbePoint

Descr. The MbeCurrentTransform.pointToUors object method transforms the MbePoint specified by point from the current coordinate system to design coordinates (UORs).

See also MbeCurrentTransform.pointFromUors, MbeCurrentTransform.moveOriginWorld; For an example see MbeCurrentTransform.masterUnits.

MbeCurrentTransform.pointFromUorsMbeCurrentTransform.pointFromUors point as MbePoint

Descr. The MbeCurrentTransform.pointFromUors object method transforms the MbePoint specified by point from design coordinates (UORs) to the current coordinate system.

Example Dim origin as MbePointDim view as Integer

... ' get origin and view from the userIf MbeState.getInputDataPoint(origin, view)MbeCurrentTransform.pointToUors origin ' get point into dgn unitsMbeCurrentTransform.fromView view ' change to view coordinate systemMbeCurrentTransform.pointFromUors origin ' get point into new coord system

See also MbeCurrentTransform.pointFromUors.

8-98 MicroStation BASIC Guide

Page 409: 48784209 Microstation Basic

View Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 99 Friday, October 15, 1999 1:27 PM

View Object

MbeViews(index)MbeViews(index)

Descr. MbeViews(index) retrieves the MbeView object associated with the index view, with the view 1 corresponding to index = 1. The properties of the MbeView object so

Properties and Methods Used to

MbeView.active (page 8-100) Determine if the view (corresponding to the MbeView object) is active.

MbeView.screenNum (page 8-101) Determine which screen the view is on.

MbeView.fastCurve (page 8-101) Set or retrieve the fast curve state of the view.

MbeView.noText (page 8-101) Turn on or off text display for the view.

MbeView.slowFont (page 8-102) Turn on slow (correct) fonts or the fast font for the view.

MbeView.lineWeight (page 8-102) Set or retrieve whether line weights are displayed in the view.

MbeView.pattern (page 8-102) Set or retrieve whether elements of the pattern class are displayed in the view.

MbeView.textNode (page 8-103) Set or retrieve whether text node elements are displayed in the view.

MbeView.enterDataField (page 8-103) Set or retrieve whether enter data fields of text elements are displayed in the view.

MbeView.grid (page 8-103) Set or retrieve whether grid points are displayed in the view.

MbeView.levelSymbology (page 8-103)

Set or retrieve whether level symbology display is in use for the view.

MbeView.construction (page 8-104) Set or retrieve whether construction class elements display in the view.

MbeView.dimension (page 8-104) Set or retrieve whether dimension class elements display in the view.

MbeView.areaFill (page 8-105) Set or retrieve whether area fills are displayed in the view.

MbeView.refBoundary (page 8-105) Set or retrieve whether reference file boundaries are displayed in the view.

MbeView.fastRefClip (page 8-105) Set or retrieve whether reference files are clipped to their boundary rectangle.

MbeView.deferApply (page 8-105) Control whether changes to view display parameters causes an immediate redraw of the view.

MbeView.update (page 8-106) Immediately redraw the view.

MbeView.getLevels (page 8-106) Determine which master file levels are on for the view.

MbeView.levelsOn, MbeView.levelsOff (page 8-107)

Turn on or off master file levels in the view.

MicroStation BASIC Guide 8-99

Page 410: 48784209 Microstation Basic

View Object

600macro.bk : 608_EXT.FRA Page 100 Friday, October 15, 1999 1:27 PM

retrieved can be directly referenced, or an MbeView object can be declared and Set to MbeViews(index). The example below demonstrates both methods.

Example Dim view as MbeViewDim iView as Integer

' Turn on areafill, slow font, and turn off grid in all active viewsFor iView = 1 to MBE_MaxViews If MbeViews(iView).active <> 0 Then Set view = MbeViews(iView) view.deferApply = 1 ' defer actual changes to avoid multiple updates view.areaFill = 1 view.slowFont = 1 view.grid = 0 view.deferApply = 0 view.update ' update to see the changes End IfNext iView

MbeView.activeMbeView.active

Descr. The MbeView.active read-only property returns an Integer that is nonzero if the view to which MbeView refers is active.

Example Dim iView as Integer

For iView = 1 to MBE_MaxViews If MbeViews(iView).active <> 0 Then ... Process view End IfNext iView

8-100 MicroStation BASIC Guide

Page 411: 48784209 Microstation Basic

View Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 101 Friday, October 15, 1999 1:27 PM

MbeView.screenNumMbeView.screenNum

Descr. The MbeView.screenNum read-only property returns an Integer that is the screen that the view to which the MbeView refers is on.

Example Dim viewsOnScreen(0 to 1) as IntegerDim iView as IntegerDim screenNum as Integer' Count views active on each screenFor iView = 1 to MBE_MaxViews If MbeViews(iView).active <> 0 Then screenNum = MbeViews(iView).screenNum viewsOnScreen(screenNum) = viewsOnScreen(screenNum) + 1 End IfNext iView

MbeView.fastCurveMbeView.fastCurve

Descr. The MbeView.fastCurve read/write integer property sets or retrieves the fast curve state for the view to which MbeView refers. If the property is assigned, and the new value differs from the present state, and MbeView.deferApply is FALSE, the view is updated to reflect the new state of the fast curve flag.

Example Dim view as MbeView

' Turn on fast curve for view 2MbeViews(2).fastCurve = 1

See also MbeView.deferApply.

MbeView.noTextMbeView.noText

Descr. The MbeView.noText read/write integer property sets or retrieves whether text is displayed in the view to which MbeView refers. If the property is assigned, and the new value differs from the present state, and MbeView.deferApply is FALSE, the view is updated to reflect the new state of text display.

Example Dim view as MbeView

' Turn off text in view 1MbeViews(1).noText = 1

See also MbeView.deferApply.

MicroStation BASIC Guide 8-101

Page 412: 48784209 Microstation Basic

View Object

600macro.bk : 608_EXT.FRA Page 102 Friday, October 15, 1999 1:27 PM

MbeView.slowFontMbeView.slowFont

Descr. The MbeView.slowFont read/write integer property sets or retrieves whether text is displayed in the correct fonts or the fast font in the view to which MbeView refers. If the property is assigned, and the new value differs from the present state, and MbeView.deferApply is FALSE, the view is updated to reflect the new state of text display.

Example Dim view as MbeView

' set up slow font in view 3 to match view 1MbeViews(3).slowFont = MbeViews(1).slowFont

See also MbeView.deferApply.

MbeView.lineWeightMbeView.lineWeight

Descr. The MbeView.lineWeight read/write integer property sets or retrieves whether line weights are displayed in the view to which MbeView refers. If the property is assigned, and the new value differs from the present state, and MbeView.deferApply is FALSE, the view is updated to reflect the new state of line weight display.

Example Dim iView as Integer

' Turn on line weight in all viewsFor iView = 1 to MBE_MaxViews MbeViews(iView).lineWeight = 1Next iView

See also MbeView.deferApply.

MbeView.patternMbeView.pattern

Descr. The MbeView.pattern read/write integer property sets or retrieves whether elements of the pattern class are displayed in the view to which MbeView refers. If the property is assigned, and the new value differs from the present state, and MbeView.deferApply is FALSE, the view is updated to reflect the new state of pattern display.

Example Dim iView as Integer

' Turn off pattern display in all viewsFor iView = 1 to MBE_MaxViews MbeViews(iView).pattern = 0Next iView

See also MbeView.deferApply.

8-102 MicroStation BASIC Guide

Page 413: 48784209 Microstation Basic

View Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 103 Friday, October 15, 1999 1:27 PM

MbeView.textNodeMbeView.textNode

Descr. The MbeView.textNode read/write Integer property sets or retrieves whether text node elements are displayed in the view to which MbeView refers. If the property is assigned, and the new value differs from the present state, and MbeView.deferApply is FALSE, the view is updated to reflect the new state of text node display.

Example ' Turn off text node display in view 1MbeViews(1).textNode = 0

See also MbeView.deferApply.

MbeView.enterDataFieldMbeView.enterData

Descr. The MbeView.enterDataField read/write Integer property sets or retrieves whether enter data fields in text elements are displayed in the view to which MbeView refers. If the property is assigned, and the new value differs from the present state, and MbeView.deferApply is FALSE, the view is updated to reflect the new state of enter data display.

Example ' Turn on enter data field display in view 3MbeViews(3).enterData = 1

See also MbeView.deferApply.

MbeView.gridMbeView.grid

Descr. The MbeView.grid read/write Integer property sets or retrieves whether the grid is displayed in the view to which MbeView refers. If the property is assigned, and the new value differs from the present state, and MbeView.deferApply is FALSE, the view is updated to reflect the new state of grid display.

Example ' Turn off grid display in view 4MbeViews(4).grid = 0

See also MbeView.deferApply, MbeSettings.gridUnits, MbeSettings.gridReferences.

MbeView.levelSymbologyMbeView.levelSymbology

Descr. The MbeView.levelSymbology read/write Integer property sets or retrieves whether level symbology display is turned on in the view to which MbeView refers. If the property is assigned, and the new value differs from the present state, and

MicroStation BASIC Guide 8-103

Page 414: 48784209 Microstation Basic

View Object

600macro.bk : 608_EXT.FRA Page 104 Friday, October 15, 1999 1:27 PM

MbeView.deferApply is FALSE, the view is updated to reflect the new state of level symbology display.

Example ' Turn on level symbology in all viewsFor iView = 1 to MBE_MaxViews MbeViews(iView).levelSymbology = 1Next iView

See also MbeView.deferApply.

MbeView.constructionMbeView.construction

Descr. The MbeView.construction read/write Integer property sets or retrieves whether elements of the construction class are displayed in the view to which MbeView refers. If the property is assigned, and the new value differs from the present state, and MbeView.deferApply is FALSE, the view is updated to reflect the new state of construction display.

Example Dim iView as Integer

' Turn off construction display in all viewsFor iView = 1 to MBE_MaxViews MbeViews(iView).construction = 0Next iView

See also MbeView.deferApply.

MbeView.dimensionMbeView.dimension

Descr. The MbeView.dimension read/write Integer property sets or retrieves whether elements of the dimension class are displayed in the view to which MbeView refers. If the property is assigned, and the new value differs from the present state, and MbeView.deferApply is FALSE, the view is updated to reflect the new state of dimension display.

Example Dim iView as Integer

' Turn off dimension display in all viewsFor iView = 1 to MBE_MaxViews MbeViews(iView).dimension = 0Next iView

See also MbeView.deferApply.

8-104 MicroStation BASIC Guide

Page 415: 48784209 Microstation Basic

View Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 105 Friday, October 15, 1999 1:27 PM

MbeView.areaFillMbeView.areaFill

Descr. The MbeView.areaFill read/write Integer property sets or retrieves whether area fills are displayed in the view to which MbeView refers. If the property is assigned, and the new value differs from the present state, and MbeView.deferApply is FALSE, the view is updated to reflect the new state of area fill display.

Example ' Turn on area fill in view 6MbeViews(6).areaFill = 1

See also MbeView.deferApply.

MbeView.refBoundaryMbeView.refBoundary

Descr. The MbeView.refBoundary read/write Integer property sets or retrieves whether reference file boundaries are displayed in the view to which MbeView refers. If the property is assigned, and the new value differs from the present state, and MbeView.deferApply is FALSE, the view is updated to reflect the new state of reference file boundary display.

Example ' Turn off reference file boundary display in view 1MbeViews(1).refBoundary = 0

See also MbeView.deferApply.

MbeView.fastRefClipMbeView.fastRefClip

Descr. The MbeView.fastRefClip read/write Integer property sets or retrieves whether reference files are clipped to their boundary rectangle (fast clipping) in the view to which MbeView refers. If the property is assigned, and the new value differs from the present state, and MbeView.deferApply is FALSE, the view is updated to reflect the new state of reference file clipping.

Example ' Turn on fast reference file clipping view 2MbeViews(2).fastRefClip = 1

See also MbeView.deferApply.

MbeView.deferApplyMbeView.deferApply

Descr. The MbeView.deferApply read/write Integer property controls whether changes to view display parameters cause an immediate redraw of the view to which the MbeView refers. If MbeView.deferApply is TRUE, then the changes made to viewing parameters do not take effect until the next time the view is updated (either by the user or using

MicroStation BASIC Guide 8-105

Page 416: 48784209 Microstation Basic

View Object

600macro.bk : 608_EXT.FRA Page 106 Friday, October 15, 1999 1:27 PM

the MbeView.update statement). If MbeView.deferApply is FALSE, any change to the view display flags causes a redraw of the view. By default, MbeView.deferApply is set to FALSE for all views. Set MbeView.deferApply to TRUE before making multiple changes to the view display flags to avoid multiple redraws.

Example Dim view as MbeViewDim iView as Integer

' Turn on areafill, slow font, and turn off grid in all active viewsFor iView = 1 to MBE_MaxViews

If MbeViews(iView).active <> 0 ThenSet view = MbeViews(iView)

view.deferApply = 1 'defer actual changes to'avoid multiple updates

view.areaFill = 1view.slowFont = 1view.grid = 0view.deferApply = 0view.update ' update to see the changes

End IfNext iView

MbeView.updateMbeView.update

Descr. The MbeView.update statement causes the view to which MbeView refers to immediately redraw.

Example ' redraw view 2MbeViews(2).update

MbeView.getLevelsstat = MbeView.getLevels(levelArray() as Integer)

Descr. The MbeView.getLevels object function retrieves a level mask that shows which master file levels are on for the view to which MbeView refers. The macro should call MbeView.getLevels with a variable-sized array for levelArray, which the function will redimension to levelArray(0 to 3). The low bit of levelArray(0) is 1 if level 1 is on and zero if it is off, the next lowest bit indicates the state of level 2, etc. Similarly the low bit of levelArray(1) gives the state of level 17, and so on. The function returns

8-106 MicroStation BASIC Guide

Page 417: 48784209 Microstation Basic

View Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 107 Friday, October 15, 1999 1:27 PM

MBE_Success if the levels are successfully retrieved, or an error code if levelArray cannot be redimensioned.

Example Dim view as MbeViewDim levelArray() as Integerview = MbeViews(1)If view.getLevels(levelArray) <> MBE_Success Then MbeWriteStatus “Error getting levels”Else ... ' process levels in levelArrayEnd If

See also MbeView.levelsOn, MbeView.levelsOff.

MbeView.levelsOn, MbeView.levelsOffstat = MbeView.levelsOn(levelArray() as Integer)

stat = MbeView.levelsOff(levelArray() as Integer)

Descr. The MbeView.levelsOn and MbeView.levelsOff object functions turn on or off master file levels in the view to which MbeView refers. levelArray must be a four-element Integer array. For MbeView.levelsOn, the levels for which corresponding bits are 1 are turned on, and for MbeView.levelsOff, the levels for which corresponding bits are 1 are turned off. For both functions, the display state of the levels corresponding to zero bits is unchanged. The bits map to levels as described for MbeView.getLevels. The functions return MBE_Success if the levels are successfully manipulated, and Mbe_WrongDimensions (801) if levelArray is not a four-element Integer array.

When levels are turned on or off, if MbeView.deferApply is FALSE, the elements in the affected levels are immediately drawn (or erased).

Example Dim view as MbeView

Dim levelsOn(0 to 3) as IntegerDim levelsOff(0 to 3) as Integer

view = MbeViews(1)

levelsOn(0) = 31 ' Turn on levels 1 through 5levelsOff(0) = 992 ' Turn off levels 6 through 10

If view.levelsOn(levelsOn) <> MBE_Success Then MbeWriteStatus “Error turning levels on”End If

If view.levelsOff(levelsOff) <> MBE_Success Then MbeWriteStatus “Error turning levels off”End If

MicroStation BASIC Guide 8-107

Page 418: 48784209 Microstation Basic

Reference File Object

600macro.bk : 608_EXT.FRA Page 108 Friday, October 15, 1999 1:27 PM

Reference File Object

The properties and methods listed below in this table refer to an MbeRefFile object and the reference slot to which it refers.

Properties and Methods Used To

MbeRefFiles.maxRefFiles (page 8-109)

Determine the maximum number of reference files that can be attached to the master file.

MbeRefFiles(index) (page 8-109) Returns an individual MbeRefFile object corresponding to the reference file slot identified by index. This slot may or may not have a reference file attached to it.

MbeRefFile.active (page 8-109) Determine if a reference file is attached to the reference file slot.

MbeRefFile.notFound (page 8-110) Determine if the reference file named in the reference file slot was found.

MbeRefFile.display (page 8-110) Set or retrieve the display state of the reference file slot.

MbeRefFile.locate (page 8-110) Set or retrieve the locate state of the reference file slot.

MbeRefFile.snap (page 8-111) Set or retrieve the snap state for the reference file slot.

MbeRefFile.plot (page 8-111) Set or retrieve the plot state for the reference file slot.

MbeRefFile.scaleLineStyle (page 8-111)

Set or retrieve the flag that determines if line styles are scaled for the reference file slot

MbeRefFile.fileName (page 8-112) Retrieve the full file name of the reference file attached to the reference file slot.

MbeRefFile.attachName (page 8-112)

Retrieve the attachment name of the reference file attached to the reference file slot.

MbeRefFile.logical (page 8-113) Set or retrieve the logical name of the reference file attached to the reference file slot.

MbeRefFile.description (page 8-113) Set or retrieve the description of the reference file attached to the reference file slot.

MbeRefFile.scale (page 8-113) Return the ratio of master file master units to reference file master units for the reference file attached to the reference file slot.

MbeRefFile.getLevels (page 8-114) Determine which levels are turned on in a particular view for the reference file slot.

MbeRefFile.levelsOn, MbeRefFile.levelsOff (page 8-114)

Turn on/off specific levels in a view for the reference file slot.

MbeRefFile.saveSettings (page 8-115)

Make any MbeRefFile changes for a given reference file slot permanent by saving them to the master design file.

8-108 MicroStation BASIC Guide

Page 419: 48784209 Microstation Basic

Reference File Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 109 Friday, October 15, 1999 1:27 PM

MbeRefFiles.maxRefFilesMbeRefFiles.maxRefFiles

Descr. The MbeRefFiles.maxRefFiles read-only property returns an Integer that is the maximum number of reference files that can be attached to a master file. This number is set by the user in the User Preferences dialog box.

Dim iRef as Integer

For iRef = 1 to MbeRefFiles.maxRefFiles If MbeRefFiles(iRef).active <> 0 Then ... ' process reference file End IfNext iRef

MbeRefFiles(index)MbeRefFiles(index)

Descr. MbeRefFiles(index)retrieves the MbeRefFile object associated with the index reference file attachment, with the first reference file attachment corresponding to index = 1. The properties of the MbeRefFile object so retrieved can be directly referenced, or an MbeRefFile object can be declared and Set to MbeRefFiles(index). The example below demonstrates both methods.

Example Dim refFile as MbeRefFileDim iRef as Integer

' Turn on display for all active reference files that MicroStation foundFor iRef = 1 to MbeRefFiles.maxRefFiles

If MbeRefFiles(iRef).active <> 0 ThenSet refFile = MbeRefFiles(iRef)If refFile.notFound = 0 Then

refFile.display = 1End If

End IfNext iRef

MbeRefFile.activeMbeRefFile.active

Descr. The MbeRefFile.active read-only property returns an Integer that is nonzero if the reference file slot that MbeRefFile refers to has a reference file attached.

Example Dim iRef as IntegerFor iRef = 1 to MbeRefFiles.maxRefFiles

If MbeRefFiles(iRef).active <> 0 Then... Process reference file

End IfNext iRef

MicroStation BASIC Guide 8-109

Page 420: 48784209 Microstation Basic

Reference File Object

600macro.bk : 608_EXT.FRA Page 110 Friday, October 15, 1999 1:27 PM

MbeRefFile.notFoundMbeRefFile.notFound

Descr. The MbeRefFile.active read-only integer property returns an Integer that is nonzero if the file named in the reference slot to which MbeRefFile refers could not be found by MicroStation.

Example Dim refFile as MbeRefFileDim iRef as Integer

For iRef = 1 to MbeRefFiles.maxRefFilesrefFile = MbeRefFiles(iRef)If (refFile.active <> 0) And (refFile.notFound <> 0) Then

MbeWriteError "could not find " &refFile.attachNameEnd If

Next iRef

MbeRefFile.displayMbeRefFile.display

Descr. The MbeRefFile.display read/write Integer property sets or retrieves the display state for the reference file slot to which MbeRefFile refers.

Example Dim refFile as MbeRefFile' Turn on display of reference file 2refFile = MbeRefFiles(2)

If refFile.active <> 0 ThenrefFile.display = 1

End If

See also MbeRefFile.saveSettings.

MbeRefFile.locateMbeRefFile.locate

Descr. The MbeRefFile.locate read/write Integer property sets or retrieves the locate state for the reference file slot to which MbeRefFile refers.

Example Dim iRef as Integer' Turn on locate for all active reference fileFor iRef = 1 to MbeRefFiles.maxRefFiles

If MbeRefFiles(iRef).active <> 0 ThenMbeRefFiles(iRef).locate = 1

End IfNext iRef

See also MbeRefFile.saveSettings.

8-110 MicroStation BASIC Guide

Page 421: 48784209 Microstation Basic

Reference File Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 111 Friday, October 15, 1999 1:27 PM

MbeRefFile.snapMbeRefFile.snap

Descr. The MbeRefFile.snap read/write Integer property sets or retrieves the snap state for the reference file slot to which MbeRefFile refers.

Example Dim iRef as Integer' Turn off snap for all active reference fileFor iRef = 1 to MbeRefFiles.maxRefFiles

If MbeRefFiles(iRef).active <> 0 ThenMbeRefFiles(iRef).snap = 0

End IfNext iRef

See also MbeRefFile.saveSettings.

MbeRefFile.plotMbeRefFile.plot

Descr. The MbeRefFile.plot read/write Integer property sets or retrieves the plot state (whether the attached reference file should appear in plots) for the reference file slot to which MbeRefFile refers.

Example Dim refFile as MbeRefFileDim iRef as Integer

' Turn on plot for all reference file that are displayedFor iRef = 1 to MbeRefFiles.maxRefFiles

refFile = MbeRefFiles(iRef)If (refFile.active <> 0) And (refFile.display <> 0) ThenendifrefFile.plot = 1

Next iRef

See also MbeRefFile.saveSettings.

MbeRefFile.scaleLineStyleMbeRefFile.plot

Descr. The MbeRefFile.scaleLineStyle read/write Integer property sets or retrieves the state of scaling line styles for the reference file slot to which MbeRefFile refers.

Example Dim refFile as MbeRefFileDim iRef as Integer

' Turn on scaleLineStyle for all plotted reference filesFor iRef = 1 to MbeRefFiles.maxRefFiles refFile = MbeRefFiles(iRef) If (refFile.active <> 0) And (refFile.plot <> 0) Then refFile.scaleLineStyles = 1

MicroStation BASIC Guide 8-111

Page 422: 48784209 Microstation Basic

Reference File Object

600macro.bk : 608_EXT.FRA Page 112 Friday, October 15, 1999 1:27 PM

End IfNext iRef

See also MbeRefFile.saveSettings.

MbeRefFile.fileNameMbeRefFile.fileName

Descr. The MbeRefFile.fileName read-only String property retrieves the full file name of the reference file for the slot to which MbeRefFile refers. This property is valid only if MbeRefFile.notFound is FALSE.

Example Dim refFile as MbeRefFileDim iRef as Integer

' turn off display for all ref. files that are attachments of master fileFor iRef = 1 to MbeRefFiles.maxRefFiles refFile = MbeRefFiles(iRef) If (refFile.active <> 0) And (refFile.notFound = 0) Then If StrComp(refFile.fileName, MbeDgnInfo.dgnFileName) = 0 Then refFile.display = 0 End If End IfNext iRef

See also MbeRefFile.attachName.

MbeRefFile.attachNameMbeRefFile.attachName

Descr. The MbeRefFile.attachName read-only String property retrieves the name by which the reference file for the slot to which MbeRefFile refers is attached.

Example Function attachedAs (refFile as MbeRefFile, name as String) If refFile.active <> 0 Then If StrComp (refFile.attachName, name) = 0 Then attachedAs = 1 End If End IfEnd Function

See also MbeRefFile.logical, MbeRefFile.description.

8-112 MicroStation BASIC Guide

Page 423: 48784209 Microstation Basic

Reference File Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 113 Friday, October 15, 1999 1:27 PM

MbeRefFile.logicalMbeRefFile.logical

Descr. The MbeRefFile.logical read/write String property sets or retrieves the logical name of the reference file to which MbeRefFile refers.

Example Function logicalNameIs(refFile as MbeRefFile, name as String) If refFile.active <> 0 Then If StrComp(refFile.logicalName, name) = 0 Then logicalNameIs = 1 End If End IfEnd Function

See also MbeRefFile.attachName, MbeRefFile.description.

MbeRefFile.descriptionMbeRefFile.description

Descr. The MbeRefFile.description read/write String property sets or retrieves the description of the reference file to which MbeRefFile refers.

Example Sub showDescription(iRef as Integer) Dim refFile as MbeRefFile refFile = MbeRefFiles(iRef) If refFile.active <> 0 Then MbeWriteStatus “ref file description is “ & refFile.description Else MbeWriteError “reference file not active” End IfEnd Sub

See also MbeRefFile.attachName, MbeRefFile.logical.

MbeRefFile.scaleMbeRefFile.scale

Descr. The MbeRefFile.scale read-only property returns a Double that is the ratio of master file master units to reference file master units for the reference file to which MbeRefFile refers.

Example Dim refScale as DoublerefScale = MbeRefFiles.scale

MicroStation BASIC Guide 8-113

Page 424: 48784209 Microstation Basic

Reference File Object

600macro.bk : 608_EXT.FRA Page 114 Friday, October 15, 1999 1:27 PM

MbeRefFile.getLevelsstat = MbeRefFile.getLevels(levelArray() as Integer, viewNum as Integer)

Descr. The MbeRefFile.getLevels object function retrieves a level mask that shows which levels are on for the view specified by viewNum for the reference file to which MbeRefFile refers. The macro should call MbeRefFile.getLevels with a variable-sized array for levelArray, which the function will redimension to levelArray(0 to 3). The low bit of levelArray(0) is 1 if level 1 is on and zero if it is off, the next lowest bit indicates the state of level 2, etc. Similarly, the low bit of levelArray(1) gives the state of level 17, and so on. The function returns MBE_Success if the levels are successfully retrieved, and MBE_InvalidView (1501) if the view is outside the range 1-8 or MBE_InvalidRefFile (1601) if the reference file is not active.

Example Dim refFile as MbeRefFileDim levelArray() as Integer

Set refFile = MbeRefFiles(1)

If refFile.getLevels (levelArray, 1) <> MBE_Success Then MbeWriteStatus "Error getting ref levels"Else ' process reference levels in levelArray ...End If

See also MbeRefFile.levelsOn, MbeRefFile.levelsOff.

MbeRefFile.levelsOn, MbeRefFile.levelsOffstat = MbeRefFile.levelsOn(levelArray() as Integer, viewNum as Integer)

stat = MbeRefFile.levelsOff(levelArray() as Integer, viewNum as Integer)

Descr. The MbeRefFile.levelsOn and MbeRefFile.levelsOn object functions turn on or off levels in the view specified by viewNum for the reference file to which MbeRefFile refers. levelArray must be a four-element Integer array. For MbeRefFile.levelsOn, the levels for which corresponding bits are 1 are turned on, and for MbeRefFile.levelsOff, the levels for which corresponding bits are 1 are turned off. For both functions the state of the levels for which the corresponding bits are zero is unchanged. The bits map to levels as described for MbeRefFile.getLevels. The functions return MBE_Success if the levels are successfully manipulated, and MBE_InvalidView (1501) if the view is out of range, MBE_InvalidRefFile (1601) if the reference file is not active, or Mbe_WrongDimensions (801) if levelArray is not a four-element Integer array.

When levels are turned on or off, the reference file graphics elements in the levels affected are drawn (or erased) immediately to the view specified.

Dim refFile as MbeRefFile

Dim levelsOn(0 to 3) as IntegerDim levelsOff(0 to 3) as Integer

refFile = MbeRefFiles(1)

8-114 MicroStation BASIC Guide

Page 425: 48784209 Microstation Basic

Reference File Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 115 Friday, October 15, 1999 1:27 PM

levelsOn(0) = 31 ' Turn on levels 1 through 5levelsOff(0) = 992 ' Turn off levels 6 through 10

If refFile.levelsOn (levelsOn, 1) <> MBE_Success Then MbeWriteStatus “Error turning levels on”End If

If refFile.levelsOff (levelsOff, 1) <> MBE_Success Then MbeWriteStatus “Error turning levels off”End If

See also MbeRefFile.saveSettings.

MbeRefFile.saveSettingsstat = MbeRefFile.saveSettings([overrideUserPref])

Descr. The MbeRefFile.saveSettings object function saves, to the master file reference file attachment, the changes to the reference file made through the MbeRefFile properties and functions. If this function is not called for a particular reference file object, then any changes made through the MbeRefFile properties and functions are “temporary” and will be reset to their saved settings the next time the master file is entered.

If the optional overrideUserPref argument is zero or omitted, the function first checks the state of the “Save Settings to Save Changes” user preference. If this preference is TRUE, it indicates that the user wishes to save reference file manipulations only when the MicroStation “Save Settings” operation is performed. In that case mbeRefFile.saveSettings returns MBE_RefSaveDeferred (1602) without actually saving the new settings. If overrideUserPref is nonzero, or the “Save Settings to Save Changes” preference is FALSE, the new settings are saved.

The MbeRefFile.saveSettings function returns MBE_Success if the settings are successfully saved and MBE_InvalidRefFile (1601) if the reference file to which MbeRefFile refers is not active.

Example Dim refFile as MbeRefFileDim status as Integer

refFile = MbeRefFiles(1)status = refFile.saveSettings()If status = 1602 Then MbeWriteStatus “Not saving new ref file settings”Else If status = MBE_Success Then MbeWriteStatus “Ref settings saved”Else MbeWriteError “Could not save ref file settings”End If

MicroStation BASIC Guide 8-115

Page 426: 48784209 Microstation Basic

Session Object

600macro.bk : 608_EXT.FRA Page 116 Friday, October 15, 1999 1:27 PM

Session Object

MbeSession.msProductMbeSession.msProduct

Descr. The MbeSession.msProduct read-only property returns an Integer code specifying which product within the MicroStation family that the macro is beginning executed by. Possible codes include:

Example Select Case MbeSession.msProductCase MBE_MicroStation ... ' MicroStation specific actionCase MBE_MSPowerDraft ... ' PowerDraft specific codeCase MBE_MSReview Then ... ' MS Review codeCase Else MbeWriteError “Unrecognized MicroStation product”End Select

See also MbeSession.msVersion, MbeSession.msPlatform.

Properties and Methods Used to

MbeSession.msProduct (page 8-116) Determine which product in the MicroStation family is executing the macro.

MbeSession.msPlatform (page 8-117)

Determine on which platform the macro is being executed.

MbeSession.msVersion (page 8-117) Return the version string of the product on which the macro is being run.

MbeSession.language (page 8-118) Returns the name of the language in which MicroStation prompts and dialog boxes are being displayed.

MbeSession.numScreens (page 8-118)

Return the number of display screens to which MicroStation has access.

MbeSession.canSwapScreen (page 8-119)

Determine if the SWAP command can be used to switch to another logical screen.

MbeSession.elapsedTime (page 8-119)

Return the elapsed time in seconds since the MicroStation session was started.

Product Constant Value

MicroStation MBE_MicroStation 10

MicroStation Review MBE_MSReview 30

MicroStation MBE_MSPowerDraft 50

8-116 MicroStation BASIC Guide

Page 427: 48784209 Microstation Basic

Session Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 117 Friday, October 15, 1999 1:27 PM

MbeSession.msPlatformMbeSession.msPlatform

Descr. The MbeSession.msPlatform read-only property returns an Integer code specifying which hardware platform the macro is beginning executed on. Since MicroStation takes care of most differences between platforms for macros, most do not need to know what platform they are running on. Possible codes include:

Example Select Case MbeSession.msPlatformCase MBE_PlatformPC

... ' DOS specific codeCase MBE_PlatformIntelNT, MBE_PlatformAlphaNT

... ' Windows NT specific codeCase MBE_PlatformClipperEV, MBE_PlatformClipperX

... ' Clix specific codeCase MBE_PlatformSparc, MBE_PlatformHP700, MBE_PlatformSGI, _

MBE_PlatformRS6000... ' Other unix specific code

Case MBE_PlatformMac, MBE_PlatformPowerMac... ' Mac specific code

Case ElseMbeWriteError “unrecognized MS Platform”

End Select

See also MbeSession.msVersion, MbeSession.msProduct.

MbeSession.msVersionMbeSession.msVersion

Descr. The MbeSession.msVersion read-only property returns a String containing the full four-digit version specifier for the product the macro is running on. This string is in the

Platform Constant Value

PC-DOS MBE_PlatformPC 1

Clipper EnvV MBE_PlatformClipperEV 21

Clipper X MBE_PlatformClipperX 22

Macintosh MBE_PlatformMac 3

PowerMac MBE_PlatformPowerMac 14

Sparc MBE_PlatformSparc 4

HP700 MBE_PlatformHP700 6

SGI MBE_PlatformSGI 7

RS6000 MBE_PlatformRS6000 9

Intel WinNT MBE_PlatformIntelNT 10

Alpha WinNT MBE_PlatformAlphaNT 11

MicroStation BASIC Guide 8-117

Page 428: 48784209 Microstation Basic

Session Object

600macro.bk : 608_EXT.FRA Page 118 Friday, October 15, 1999 1:27 PM

format “aa.bb.cc.dd”, where aa is the 2-digit major version number, bb is the 2-digit minor version number, cc is the 2-digit revision number, and dd is the 2-digit build number. Most macros need not be concerned with the version of MicroStation they are running on, and in any case usually only the major version number is significant.

Example Dim version as StringDim majorVers as IntegerDim minorVers as Integer

version = MbeSession.msVersion

majorVers = Val (Word$ (version, 1, 1))minorVers = Val (Word$ (version, 2, 2))If majorVers <> 5 Then

MbeWriteError “Wrong MicroStation Version”Exit Sub

End If

If minorVers < 4 ThenMbeWriteError “Need newer MicroStation”Exit Sub

End If

See also MbeSession.msProduct, MbeSession.msPlatform.

MbeSession.languageMbeSession.language

Descr. The MbeSession.language read-only property returns a String containing the name of the language that the MicroStation prompts and dialog boxes are displayed in.

Example Dim language as Stringlanguage = MbeSession.language

MbeSession.numScreensMbeSession.numScreens

Descr. The MbeSession.numScreens read-only property returns an Integer that is the number of display screens that MicroStation has access to.

Example If MbeSession.numScreens < 2 Then... ' open views only one screen

Else... ' open views on both screens

End If

See also MbeSession.canSwapScreen.

8-118 MicroStation BASIC Guide

Page 429: 48784209 Microstation Basic

Session Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 119 Friday, October 15, 1999 1:27 PM

MbeSession.canSwapScreenMbeSession.canSwapScreen

Descr. The MbeSession.canSwapScreen read-only property returns an Integer that is nonzero if the MicroStation “SWAP” command can be used to swap to another logical screen and zero if there is only one logical screen.

Example If (MbeSession.numScreens < 2) And (MbeSession.canSwapScreen = 0) Then... ' open views only one screen

Else... ' open views on both screens

End If

See also MbeSession.numScreens.

MbeSession.elapsedTimeDescr. The MbeSession.elapsedTime function returns the elapsed time, in seconds, since the

MicroStation session was started. It returns the time in the maximum resolution that it can get from the system, which varies from platform to platform. The primary use of this function is for timing operations in MicroStation.

Example Sub mainDim startTime As DoubleDim endTime As DoublestartTime = MbeSession.elapsedTime’ (some compute intensive operation goes here)Print "The operation took "; endTime - startTime; "seconds to complete"End sub

MicroStation BASIC Guide 8-119

Page 430: 48784209 Microstation Basic

C Expression Statements

600macro.bk : 608_EXT.FRA Page 120 Friday, October 15, 1999 1:27 PM

C Expression Statements

MbeCExpressionLongMbeCExpressionLong (expression as String) as Long

Descr. The MbeCExpressionLong function attempts to evaluate the C expression specified in the expression argument and return the result as a Long. This function has two purposes:

1. It can provide access to variables published (using the MbeCExpression_ functions) by MDL applications.

2. It provides access to MicroStation internal variables in the rare instances where there is no interface to them available through the BASIC extensions.

Effective use of MbeCExpressionLong requires a good working knowledge of C and MDL (MicroStation Development Language). It should be used with extreme caution, since none of the safeguards provided by the BASIC interface are in place when it is used.

If the MbeCExpression given cannot be evaluated because the variable it references is not found, an MBE_VariableNotFound (1702) runtime error is generated.

If the MbeCExpression evaluates to a C double, structure or pointer, an MBE_VariableWrongType (24) runtime error is generated.

Otherwise, the function returns the value of the C long, int, short, unsigned short or char expression, promoted to a Long variable if necessary.

✍ Assignments to published C variables can be made by making the expression argument an assignment statement.

Example Dim nextNodeNum as LongnextNodeNum = MbeCExpressionLong (“tcb->canode”)

See also MbeCExpressionDouble, MbeCExpressionString, MbeElement.publish.

MbeCExpressionDoubleMbeCExpressionDouble(expression as String) as Double

Statements Used to

MbeCExpressionLong (page 8-120) Evaluate C expression and return result as a Long.

MbeCExpressionDouble (page 8-120) Evaluate C expression and return result as a Double.

MbeCExpressionString (page 8-121) Evaluate C expression and return result as a String.

8-120 MicroStation BASIC Guide

Page 431: 48784209 Microstation Basic

C Expression Statements

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 121 Friday, October 15, 1999 1:27 PM

Descr. The MbeCExpressionDouble function attempts to evaluate the C expression specified in the expression argument and return the result as a Double. This function has two purposes:

1. It can provide access to variables published (using the MbeCExpression_ functions) by MDL applications.

2. It provides access to MicroStation internal variables in the rare instances where there is no interface to them available through the BASIC extensions.

Effective use of MbeCExpressionDouble requires a good working knowledge of C and MDL (MicroStation Development Language). It should be used with extreme caution, since none of the safeguards provided by the BASIC interface are in place when it is used.

If the MbeCExpression given cannot be evaluated because the variable it references is not found, an MBE_VariableNotFound (1702) runtime error is generated.

If the MbeCExpression evaluates to a C structure or pointer, an MBE_VariableWrongType (24) runtime error is generated.

Otherwise, the function returns the value of the C double, long, int, short, unsigned short or char expression, promoted to a Double variable if necessary.

✍ Assignments to published C variables can be made by making the expression argument an assignment statement.

Example Dim trueNorthAzimuth as DoubletrueNorthAzimuth = MbeCExpressionDouble(“tcb->azimuth”)

See also MbeCExpressionLong, MbeCExpressionString, MbeElement.publish.

MbeCExpressionStringMbeCExpressionString(expression as String) as String

Descr. The MbeCExpressionString function attempts to evaluate the C expression specified in the expression argument and return the result as a String. This function has two purposes:

1. It can provide access to variables published (using the MbeCExpression_ functions) by MDL applications.

2. It provides access to MicroStation internal variables in the rare instances where there is no interface to them available through the BASIC extensions.

Effective use of MbeCExpressionString requires a good working knowledge of C and MDL (MicroStation Development Language). It should be used with extreme caution, since none of the safeguards provided by the BASIC interface are in place when it is used.

MicroStation BASIC Guide 8-121

Page 432: 48784209 Microstation Basic

C Expression Statements

600macro.bk : 608_EXT.FRA Page 122 Friday, October 15, 1999 1:27 PM

If the MbeCExpression given cannot be evaluated because the variable it references is not found, an MBE_VariableNotFound (1702) runtime error is generated.

If the MbeCExpression evaluates to a C char pointer, the string is returned in the output variable.

If the MbeCExpression evaluates to a C structure or other type of pointer, an MBE_VariableWrongType (24) runtime error is generated.

If the MbeCExpression evaluates to a C double, long, int, short, unsigned short or char expression, the value is formatted into a string and returned.

✍ Assignments to published C variables can be made by making the expression argument an assignment statement.

Example Dim altLibraryName as StringaltLibraryName = MbeCExpressionString("tcb->altLibraryName")

See also MbeCExpressionLong, MbeCExpressionDouble, MbeElement.publish.

8-122 MicroStation BASIC Guide

Page 433: 48784209 Microstation Basic

CAD Input Operations

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 123 Friday, October 15, 1999 1:27 PM

CAD Input OperationsThe statements documented in this section allow a BASIC macro to access the fundamental drawing capabilities of MicroStation.

Statements and Functions Used to

MbeGetInput (page 8-124) Obtain a data point, Reset, key-in, or command from the user.

MbePoint (page 8-125) Definition of a point in the design plane/cube.

MbeSendAppMessage (page 8-125) Send an application-defined string to the indicated task.

MbeSetAppVariable (page 8-125) Set the value of a variable belonging to a dialog box item of an MDL task.

MbeSetScaledAppVar (page 8-126) Set the value of a variable belonging to dialog box item that represents a coordinate or a distance.

MbeSendCommand (page 8-127) Activate a command.

MbeSendDataPoint (page 8-127) Send a data point to the active command.

MbeSendDragPoints (page 8-128) Send starting and ending data points with a drag between the two.

MbeSendLastInput (page 8-129) Send the last input from MbeGetInput to MicroStation for processing.

MbeSendKeyin (page 8-129) Send a key-in to the active command.

MbeSendReset (page 8-129) Send a Reset to the active command.

MbeSendTentPoint (page 8-129) Send a tentative point to the active command.

MbeWriteCommand (page 8-130) Display a string as the command name in the status bar.

MbeWriteError (page 8-130) Display a string as an error message in the status bar.

MbeWriteMessage (page 8-131) Display a string in the message field of the status bar.

MbeWritePrompt (page 8-131) Display a prompt in the status bar.

MbeWriteStatus (page 8-131) Display a string in the status field of the status bar.

MbeRelocate (page 8-131) Relocate an element that was located by macro using the MbeStartLocate.

MbeStartLocate (page 8-132) Allow the macro to control the element location process.

MbeLocateElement (page 8-139) Locate a specific element in the master file or an attached reference file.

MbeScalarFromString (page 8-141) Parse a string, subject to the macro’s current coordinate system, into a scalar value.

MbePointFromString (page 8-141) Parse a string, subject to the macro’s coordinate system, into a point in the design plane/cube.

MbeAngleFromString (page 8-141) Parse a string, subject to the macro’s current coordinate system, into an angle specified in radians.

MbeStringFromScalar (page 8-142) Format a scalar value in the macro’s current coordinate system into a string.

MicroStation BASIC Guide 8-123

Page 434: 48784209 Microstation Basic

CAD Input Operations

600macro.bk : 608_EXT.FRA Page 124 Friday, October 15, 1999 1:27 PM

MbeGetInputMbeGetInput inputType as Integer[, inputType as Integer[, inputType as Integer[, inputType as Integer]]]

Descr. This statement waits for the user to enter the desired input.

The inputType parameter can be one or more of the following:

If the user selects a primitive command when MbeGetInput is not waiting for a command, an MBE_ReceivedCommand (1102) runtime error is generated.

Example Sub main()'After prompting, wait for either a data point or a reset

MbeStringFromPoint (page 8-142) Format a point in the macro’s current coordinate system into a string.

MbeStringFromAngle (page 8-143) Format an angle in the macro’s current coordinate system into a string.

MbeGetConfigVar (page 8-143) Get the value of a configuration variable.

MbeFindFile (page 8-143) Find a file matching a given list of file name components and/or configuration variable directory specifications.

MbeStartDefaultCommand (page 8-144)

Start the default MicroStation command.

Constant Description

MBE_CommandInput This integer constant, whose value is 1, is used when getting input from the user.

MBE_DataPointInput This integer constant, whose value is 2, is used when getting input from the user.

MBE_KeyinInput This integer constant, whose value is 4, is used when getting input from the user.

MBE_ResetInput This integer constant, whose value is 3, is used when getting input from the user.

inputType Meaning

MBE_DataPointInput Wait for a data point

MBE_ResetInput Wait for a reset

MBE_KeyinInput Wait for a keyin

MBE_CommandInput Wait for a command

Statements and Functions Used to

8-124 MicroStation BASIC Guide

Page 435: 48784209 Microstation Basic

CAD Input Operations

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 125 Friday, October 15, 1999 1:27 PM

MbeWritePrompt "Accept/Reject"MbeGetInput MBE_DataPointInput, MBE_ResetInput

End Sub

MbePointType MbePoint

x As Doubley As Doublez AS Double

End Type

Descr. This structure defines a point in the design plane/cube.

The coordinates are specified in the current coordinate system.

Example Sub main()Dim point as MbePoint' Set the coordinatespoint.x = 5.5#point.y = -2.25#point.z = 1000#' Send the point to the active commandMbeSendDataPoint point, 1%

End Sub

MbeSendAppMessageMbeSendAppMessage task as Integer, string as Integer

Descr. This statement sends the message in string$ to the indicated task. The format of the message is defined by task.

This statement is output by the macro generator when the user’s actions cannot be adequately described by commands and application variables.

Example Sub Main' Send message to update the Text EditorMbeSendAppMessage "MGDSHOOK", "TextEdit A text string"

End Sub

MbeSetAppVariableMbeSetAppVariable task as String, varName as String, value as String

ORMbeSetAppVariable task as Long,varName as Long,value as Long[,mask as Long]

MicroStation BASIC Guide 8-125

Page 436: 48784209 Microstation Basic

CAD Input Operations

600macro.bk : 608_EXT.FRA Page 126 Friday, October 15, 1999 1:27 PM

✍ In OLE Automation, a function call of this form uses the function name MbeSetAppVariableInteger instead of MbeSetAppVariable.

ORMbeSetAppVariable task as String, varName as String, value as Double

✍ In OLE Automation, a function call of this form uses the function name MbeSetAppVariableReal instead of MbeSetAppVariable.

Both MbeSetAppVariableReal and MbeSetAppVariableInteger are only available in OLE Automation

Descr. This statement sets varName$ to the specified value. The variables are associated with a task’s dialog box items.

The optional mask parameter is used when the associated dialog item displays only part of the underlying variable’s value.

Example Sub main()'Clear the variable for underlining textMbeSetAppVariable "MGDSHOOK","tcb->textUnderline",0&,1&

'Set the radius of the arcs when placing "smart" linesMbeSetAppVariable "SMRTLINE","smrtlineInfo.radius",70000#

End Sub

See also Appendix A

MbeSetScaledAppVarMbeSetScaledAppVar task as String, varName as String, value as Long

ORMbeSetScaledAppVar task as String, varName as String, value as Double

Descr. Like MbeSetAppVariable, this statement sets varName, a variable associated with a task’s dialog box item, to the specified value. Unlike MbeSetAppVariable, the variables represent coordinates or distances and the values are specified in the current coordinate system.

Example Sub main()MbeSendCommand "PLACE CIRCLE RADIUS"

'Set the radius of the circle to 5.5 mMbeSetScaledAppVar "MGDSHOOK", "tcb->arc_radius", 5.5#MbeSendDataPoint 10#, -3.25#, 0.0#, 1&

End Sub

8-126 MicroStation BASIC Guide

Page 437: 48784209 Microstation Basic

CAD Input Operations

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 127 Friday, October 15, 1999 1:27 PM

MbeSendCommandMbeSendCommand cmdString as String

Descr. This statement activates the command cmdString$ using its corresponding key-in string cmdString$.

Example Sub main()MbeSendCommand "PLACE SMARTLINE"

End Sub

MbeSendDataPointMbeSendDataPoint x as Double, y as Double, z as Double _[, view as Long [, qualifier as Long]]

ORMbeSendDataPoint point as MbePoint [, view as Long [, qualifier as Long]]

Descr. This statement sends a data point to the active command.

The x, y and z parameters in the first syntax and the point parameter in the second syntax specify the data point coordinates. Using the first syntax, the coordinates are specified individually in master units. Using the second syntax, the coordinates are specified through an MbePoint structure.

The optional view parameter specifies the view to which the data point is directed. Commands that work with views, for example, WINDOW AREA and SET FILL ON, need this information. Views are numbered from 1 to 8.

The optional qualifier parameter specifies what, if any, qualifiers are associated with the data points. The Selection Tool makes use of this qualifier:

✍ Only the second form of this function call is supported in OLE Automation. See Appendix A for more information on OLE Automation.

Example Sub main()Dim point As MbePoint'Send a data point.MbeSendDataPoint -1000.5#, 0.58#, 0#

'Send a data point for view 5 using an MbePointpoint.x = 100#

1 Toggle the selection of an element. Interactively, this is generally done by holding down the <Ctrl> key.

MicroStation BASIC Guide 8-127

Page 438: 48784209 Microstation Basic

CAD Input Operations

600macro.bk : 608_EXT.FRA Page 128 Friday, October 15, 1999 1:27 PM

point.y = 50#point.z = -88#MbeSendDataPoint point, 5%

End Sub

See also Appendix A.

MbeSendDragPointsMbeSendDragPoints x1 as Double, y1 as Double, z1 as Double, _x2 as Double, y2 as Double, z2 as Double[,view as Long[,qualifier as Long]]

ORMbeSendDragPoints point1 as MbePoint, _point2 as MbePoint[,view as Long[,qualifier as Long]]

Descr. This statement sends data point information to the active command as if the user pressed and held the data button while moving the mouse (or pointer).

The x1, y1 and z1 parameters in the first syntax and the point1 parameter in the second syntax specify the coordinates where the data button was pressed down. The x2, y2 and z2 parameters in the first syntax and the point2 parameter in the second syntax specify where the data button was released. Using the first syntax, the coordinates are specified individually in master units. Using the second syntax, the coordinates are specified through MbePoint structures.

The optional view parameter specifies the view to which the data point information is directed.

The optional qualifier parameter specifies what, if any, qualifiers are associated with the data point information. The Selection Tool makes use of the qualifiers which are:

✍ Only the second form of this function call is supported in OLE Automation. See Appendix A for more information on OLE Automation.

Example Sub main()Dim point1 As MbePoint, point2 As MbePoint'Send data point information.MbeSendDragPoints -1000#, -507.5#, 0#, 0.8875#, -200.5#, 0#

1 Toggle the selection of the elements enclosed by the dynamic rectangle.

3 Toggle the selection of the elements enclosed by and overlapping the dynamic rectangle.

8-128 MicroStation BASIC Guide

Page 439: 48784209 Microstation Basic

CAD Input Operations

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 129 Friday, October 15, 1999 1:27 PM

'Send data point information using MbePoints, include a qualifierpoint1.x = 200.456#point1.y = 55.350#point1.z = 0#point2.x = 95.2#point2.y = 176.806#point2.z = 0#MbeSendDragPoints point1, point2, 1%, 1%

End Sub

See also Appendix A.

MbeSendLastInputMbeSendLastInput

Descr. This statement sends the last input from MbeGetInput to MicroStation for processing.

Sub main()MbeStartLocateMbeGetInput MBE_DataPointInput, MBE_ResetInputMbeSendLastInput

End Sub

MbeSendKeyinMbeSendKeyin string as String

Descr. This statement sends the key-in string$ to the active command.

Example Sub main()'Send a "yes" response to a promptMbeSendKeyin "yes"

End Sub

MbeSendResetMbeSendReset

Descr. This statement sends a reset to the active command.

Example Sub main()MbeReset

End Sub

MbeSendTentPointMbeSendTentPoint x as Double, y as Double, z as Double [,view as Integer]

MicroStation BASIC Guide 8-129

Page 440: 48784209 Microstation Basic

CAD Input Operations

600macro.bk : 608_EXT.FRA Page 130 Friday, October 15, 1999 1:27 PM

ORMbeSendTentPoint point as MbePoint [,view as Integer]

Descr. This statement sends a tentative point to the active command.

The x, y and z parameters in the first syntax and the point parameter in the second syntax specify the tentative point coordinates. Using the first syntax, the coordinates are specified individually in master units. Using the second syntax, the coordinates are specified through an MbePoint structure.

The optional view parameter specifies the view to which the tentative point is directed. Views are numbered from 1 to 8.

✍ Only the second form of this function call is supported in OLE Automation. See Appendix A for more information on OLE Automation.

Example Sub main()Dim point As MbePoint'Send a tentative point.MbeSendTentPoint -1000.5#, 0.58#, 0#

'Send a tentative point for view 5 using an MbePointpoint.x = 100#point.y = 50#point.z = -88#MbeSendTentPoint point, 5%

End Sub

See also Appendix A.

MbeWriteCommandMbeWriteCommand [string as String]

Descr. This statement displays the given string as the command name in the status bar.

If a string is not specified, the command name area is cleared.

Example Sub main()MbeWriteCommand "Place Widget"

End Sub

MbeWriteErrorMbeWriteError [string as String]

8-130 MicroStation BASIC Guide

Page 441: 48784209 Microstation Basic

CAD Input Operations

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 131 Friday, October 15, 1999 1:27 PM

Descr. This statement displays the given error message in the status bar.

If a string is not specified, the error message is cleared.

Example Sub main()MbeWriteError "Element not found"

End Sub

MbeWriteMessageMbeWriteMessage [string as String]

Descr. This statement displays the given message string in the status bar.

If a string is not specified, the message area is cleared.

Example Sub main()MbeWriteMessage "Current position MARKed"

End Sub

MbeWritePromptMbeWritePrompt [string as String]

Descr. This statement displays the given prompt string in the status bar.

If a string is not specified, the prompt message is cleared.

Example Sub main()MbeWritePrompt "Enter origin"

End Sub

MbeWriteStatusMbeWriteStatus [string as String]

Descr. This statement displays the given status string in the status bar.

If a string is not specified, the status area is cleared.

Example Sub main()MbeWriteStatus "Type=LINE, Level=5"

End Sub

MbeRelocateMbeRelocate [point as MbePoint [, view as Integer]]

MicroStation BASIC Guide 8-131

Page 442: 48784209 Microstation Basic

CAD Input Operations

600macro.bk : 608_EXT.FRA Page 132 Friday, October 15, 1999 1:27 PM

Descr. MbeRelocate relocates the element that was located by the macro using the MbeStartLocate function. If the optional point and view arguments are provided, they become the user entered data point and view, respectively. If the optional arguments are omitted, the data point and view that were entered during the MbeStartLocate user interaction is used. The effect of calling MbeRelocate to a MicroStation command that is prompting to locate an element is as if the user entered a data point (at point and view) and located the exact same element that was located during the MbeStartLocate user interaction (regardless of whether point and view would have resulted in MicroStation locating the previously located element or not).

The usefulness of this statement is that MbeStartLocate can be used to gain more control over the element location process than is possible when a MicroStation command is active. When an acceptable element is found, the macro starts a MicroStation command that requires an element to be located and calls MbeRelocate.

See also MbeStartLocate; For an example, see MbeLocateElement.

MbeStartLocateMbeStartLocate [wantPrompts as Integer [, wantHilite as Integer [, _allowComponents as Integer [, continueLocate as Integer[, _elemTypes() as Integer [, levelMask() as Integer [, _classMask() as Integer [, propVal as Integer[, _propMask as Integer ]]]]]]]]]

Descr. MbeStartLocate starts a special command within MicroStation that gives a macro a higher degree of control over the element selection process than is possible by simply sequencing a command that requires an element location by the user (some control in the latter situation is available by using the MbeState.locate* properties). All nine arguments to MbeStartLocate are optional, but if any argument is omitted, all of the arguments that follow it must be omitted as well. The arguments and their meanings are as follows:

wantMsgs - If 1, MicroStation prompts to locate the element. If 0, the macro must supply its own messages. The default is 1.

wantHilite - If 1, MicroStation hilites the located element. If 0, the macro must hilite the selected element (using MbeElement.display) if it wants it hilited. The default is 1.

allowComponents - If 1, the outermost element header is considered to be located, and MbeState.locateComponentFilePos will always be the same as MbeState.locateHeaderFilePos. If 0, allows the component element to be located, and MbeState.locateComponentFilePos points to it, while MbeState.locateHeaderFilePos points to the outermost header. If 2, MbeState.locateComponentFilePos points to the inner header and MbeState.locateHeaderFilePos points to the outermost header. The default is 0.

continueLocate - If continueLocate is 1, MicroStation starts looking for an element to locate at the position following the last located element. The default is 0.

8-132 MicroStation BASIC Guide

Page 443: 48784209 Microstation Basic

CAD Input Operations

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 133 Friday, October 15, 1999 1:27 PM

elemTypes - a bit map containing one bit for each element type. If the bit is 1, the corresponding element is eligible for locate, otherwise it is not. The low bit of elemTypes(0) corresponds to element type 1, the next bit corresponds to element type 2, etc. The array must be one-dimensional, and can have from 1 to 8 entries. If the array is smaller than 8 entries, all of the entries beyond those provided are assumed to be zero (the element types are disabled). If this argument is not provided, all element types are eligible.

levelMask - a bit map containing one bit for each level. If the bit is 1, elements on the corresponding level are eligible for locate, otherwise they are not. The low bit of levelMask(0) corresponds to level 1, the next bit corresponds to level 2, etc. The array must be one-dimensional, and can have from 1 to 4 entries. If the array is smaller than 4 entries, all of the entries beyond those provided are assumed to be zero (the levels are disabled). If this argument is not provided, elements on all levels are eligible.

classMask - a bit map containing one bit for each element class. If the bit is 1, elements of the corresponding class are eligible for locate, otherwise they are not. The low bit of classMask corresponds to class 0 (primary class) which cannot be turned off. The next bit corresponds to class 1, etc. The MicroStation element classes are discussed in the MbeElement.class reference. If classMask is omitted, all classes are allowed.

propVal and propMask - The arguments are used together to limit the elements eligible for location based on the element properties. The element properties are a group of bits in the element header that indicate locked status, new status, modified status, attributes present, view independent, hole or solid status, planar, and snappable. The bit name and meaning are summarized in the reference section for the MbeElement.properties. To indicate that the value of a particular property should be used to determine locate eligibility, the corresponding bit in the propMask argument is set, and the corresponding bit in the propVal argument is set to the desired value. For example, to locate only unlocked elements (without caring about the state of other properties bits), propMask is set to MBE_LockedProperty and propVal is set to 0. If these arguments are omitted, no filtering is done on element properties.

Example of element location techniquesThis example uses a number of the MicroStation Basic Extension element location techniques. It performs a simple manipulation on selected elements, but this same technique can be used to implement a more sophisticated manipulation. Similarly, while the filtering during the element selection logic is simple, the technique can be readily extended.

This example looks complicated because it emulates all of the behavior that MicroStation exhibits when it locates elements:

• When you reject an element that is hilited, it keeps looking around the data point for more elements that have not been processed.

MicroStation BASIC Guide 8-133

Page 444: 48784209 Microstation Basic

CAD Input Operations

600macro.bk : 608_EXT.FRA Page 134 Friday, October 15, 1999 1:27 PM

• When you select an element and accept it with a point that is close to the selection point, it looks for more elements around the same point, skipping elements already processed.

• When you select an element and accept it with a point that is not close to the selection point, it uses the accept point to begin looking for more elements to process.

• In addition, it provides a step that filters elements so that only elements that are acceptable to the program are presented to the user for acceptance or rejection.

'---------------------------------------------------------------' Main subroutine'---------------------------------------------------------------Sub main

Dim saveColor as IntegerDim saveWeight as IntegerDim saveMsgs as IntegerDim elemSet as New MbeElementSet

' set up for manipulation by saving the old settings and' setting new onessaveColor = MbeSettings.colorsaveWeight = MbeSettings.weightsaveMsgs = MbeState.messages

' set MicroStation to a neutral stateMbeSendCommand "NULL"

' get rid of any selection setIf elemSet.fromSelectionSet(1) = MBE_Success Then

elemSet.clearEnd If

MbeSettings.color = 3MbeSettings.weight = 3MbeState.messages = 0

locate_selectElementsToModify

MbeWriteStatus "Leaving locate function"' Clear the messagesMbeSettings.color = saveColorMbeSettings.weight = saveColorMbeState.messages = saveMsgs

MbeWritePromptMbeWriteCommand

End Sub'---------------------------------------------------------------' locate_selectElementsToModify - solicits user for elements

8-134 MicroStation BASIC Guide

Page 445: 48784209 Microstation Basic

CAD Input Operations

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 135 Friday, October 15, 1999 1:27 PM

' to modify and manipulates them.'---------------------------------------------------------------Sub locate_selectElementsToModify

Dim elem as New MbeElementDim filePos as LongDim point as MbePointDim acceptPoint as MbePointDim acceptScreenPt as MbePointDim firstScreenPt as MbePointDim stat as IntegerDim view as IntegerDim acceptView as IntegerDim continueLocate as IntegerDim haveAcceptPoint as Integer

continueLocate = FALSEhaveAcceptPoint = FALSE

Do' Display messagesCall locate_displayPrompts()

' Start locating an element, don't put out msgs,' don't hilite when found, don't allow components,' continue locate from previous element if appropriate.MbeStartLocate 0, 0, 0, continueLocate

' If accepted element or continuing from a reset ' send the previously entered point.If haveAcceptPoint Or continueLocate Then

Call MbeSendDataPoint(acceptPoint, acceptView)continueLocate = FALSE

' If previous element accepted, future comparisons are to' accept pointIf haveAcceptPoint Then

haveAcceptPoint = FALSEpoint = acceptPointview = acceptViewfirstScreenPt = acceptScreenPt

End IfElse

' Wait for a data point or a resetMbeGetInput MBE_DataPointInput, MBE_ResetInput

' If user resets, exit the loop.If MbeState.inputType = MBE_ResetInput Then

Exit Do

' On a data point, retrieve the point for future use, then' send it through to be processed.

MicroStation BASIC Guide 8-135

Page 446: 48784209 Microstation Basic

CAD Input Operations

600macro.bk : 608_EXT.FRA Page 136 Friday, October 15, 1999 1:27 PM

ElseIf MbeState.inputType = MBE_DataPointInput Thenstat=MbeState.getInputDataPoint(point, view,firstScreenPt)MbeSendLastInput

End IfEnd If

' If we found an element, check for acceptabilityIf MbeState.cmdResult = MBE_AcceptQuery Then

' if we did not find a line, keep resetting until' either we find one or we run out of candidatesDo

filePos = elem.fromLocate()If locate_isElementAcceptable(elem) Then

' located an acceptable element - hilite itelem.display MBE_Hilite

' prompt the user to accept or reject itMbeWritePrompt "Accept / Reject"

' get data to accept, reset to rejectMbeGetInput MBE_DataPointInput, MBE_ResetInput

If MbeState.inputType = MBE_DataPointInput Then' on Data pnt, accept element and modify itstat = MbeState.getInputDataPoint( _acceptPoint, acceptView, acceptScreenPt)Call locate_manipulateElement(point, view)

' continue locating if accept' point near first pointcontinueLocate=locate_pointsCloseEnough( _acceptScreenPt, firstScreenPt)haveAcceptPoint = TRUE

Else' user rejected it - continue looking around' the same point by continuing the locate' operation in the loop.elem.display MBE_NormalDrawacceptPoint = pointacceptView = viewcontinueLocate = TRUE

End IfExit Do

Else' found element but it’s not acceptable' to our filter.' Send resets to the locate logic to cause it to' retrieve the next closest element in range

8-136 MicroStation BASIC Guide

Page 447: 48784209 Microstation Basic

CAD Input Operations

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 137 Friday, October 15, 1999 1:27 PM

MbeSendResetIf MbeState.cmdResult = MBE_ElementNotFound Then

Call locate_elementUnacceptableExit Do

End IfEnd If

Loop While elem.type <> MBE_LineElseIf MbeState.cmdResult = MBE_ElementNotFound Then MbeWriteError "Element Not Found"Else print "unexpected MbeState.cmdResult of "; MbeState.cmdResultEnd If

Loop

End Sub

'---------------------------------------------------------------'locate_pointsCloseEnough - returns TRUE if points roughly 'within the locate tolerance, FALSE otherwise'---------------------------------------------------------------Function locate_pointsCloseEnough(point1 as MbePoint, point2 as MbePoint)as Integer

If Abs (point1.x - point2.x) + Abs (point1.y - point2.y) _ < MbeState.LocateTolerance Then

locate_pointsCloseEnough = TRUEEnd If

End Function

'---------------------------------------------------------------' locate_manipulateElement - performs the actual manipulation' on the selected element. This manipulation sequences commands’ and uses the MbeRelocate subroutine to make the command work’ on the previously selected element'---------------------------------------------------------------Sub locate_manipulateElement(point as MbePoint, view as Integer)

Dim elem as New MbeElementDim filePos as Long

' turn off graphics while changing elementMbeState.noElementDisplay = 1

' start change color and relocate elementMbeSendCommand "CHANGE COLOR"MbeRelocate point, viewMbeSendDataPoint point, view

' start change weight and relocate elementMbeSendCommand "CHANGE WEIGHT"

MicroStation BASIC Guide 8-137

Page 448: 48784209 Microstation Basic

CAD Input Operations

600macro.bk : 608_EXT.FRA Page 138 Friday, October 15, 1999 1:27 PM

MbeRelocate point, viewMbeSendDataPoint point, view

' Relocate the manipulated element to reset the "locate' context." If we continue the locate (first we will ' continue with the next element ), set the command so' the data point sent by MbeRelocate doesn't change the' weight of an element that may have been selected by ' sending the accept data point to the CHANGE WEIGHT command.' This section could have been shortened by substituting ' MbeRelocate for the above MbeSendDataPoint, but this looks' a bit confusing).MbeSendCommand "LOCELE"MbeRelocate point, view

MbeState.noElementDisplay = 0

' get the element to redraw it with its new symbologyfilePos = elem.fromLocate()elem.display MBE_NormalDraw

' set MicroStation to a neutral state.MbeSendCommand "NULL"

End Sub

'---------------------------------------------------------------' locate_isElementAcceptable - returns TRUE if element passes ' filter criteria and FALSE otherwise.'---------------------------------------------------------------Function locate_isElementAcceptable(elem as MbeElement) as Integer

If elem.type = MBE_Line Thenlocate_isElementAcceptable = TRUE

End IfEnd Function

'---------------------------------------------------------------' locate_elementUnacceptable - reports an error saying that' no acceptable element was located.'---------------------------------------------------------------Sub locate_elementUnacceptable

MbeWriteStatus "Only lines allowed"End Sub

'---------------------------------------------------------------' locate_displayPrompts - tell the user what to identify'---------------------------------------------------------------Sub locate_displayPrompts

MbeWriteCommand "Locate Test "

8-138 MicroStation BASIC Guide

Page 449: 48784209 Microstation Basic

CAD Input Operations

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 139 Friday, October 15, 1999 1:27 PM

MbeWritePrompt "Identify line"End Sub

See also MbeStartLocate, MbeLocateElement.

MbeLocateElementMbeLocateElement filePos as Long [, componentFilePos as Long [, _fileNum as Integer [, point as MbePoint [, _view as Integer [, componentIndex]]]]]

Descr. MbeLocateELement directs MicroStation to locate the element specified by the arguments. filePos is required, and specifies the file position of the outermost header of the element to be located. The remaining arguments are all optional, but if any are is omitted, all the arguments following must be omitted. The optional arguments have the following meanings:

componentFilePos - the file position of the component element that is to be located. If omitted, this is taken to be the same as filePos.

fileNum - the design file from which the element is to be located. The default is 0, meaning the master file. Other values denote reference files by attachment number.

point, view - if the point and view arguments are included, they are considered to be the point entered by the user to locate the specified element, regardless of whether point and view would have resulted in MicroStation locating the specified element or not. If the arguments are omitted, the last data point entered by the user is used.

componentIndex - this argument is valid only if a multiline element is being located, and it represents the line number within the multiline that is to be located.

The effect of calling MbeLocateELement when a MicroStation command is prompting to locate an element is as if the user entered a data point (at point and view) and located the element specified in the call.

The usefulness of this statement is that when a macro discovers an element that it wants to process (using an MbeElementSet object or reading the elements sequentially), it can start the appropriate MicroStation command to perform the manipulation, and use MbeLocateElement to direct the command to work on the desired element.

Example Sub mainDim elemSet as New MbeElementSetDim elem as New MbeElementDim setMember as MbeSetMemberDim point as MbePointDim filePos as LongDim fileNum as IntegerDim saveGGLk as IntegerDim saveMsgs as Integer

' turn off graphic group lock

MicroStation BASIC Guide 8-139

Page 450: 48784209 Microstation Basic

CAD Input Operations

600macro.bk : 608_EXT.FRA Page 140 Friday, October 15, 1999 1:27 PM

saveGGLk = MbeSettings.graphGroupLockMbeSettings.graphGroupLock = 0

' turn off messagessaveMsgs = MbeState.messagesMbeState.messages = 0

' get element set from either selection set or fenceIf elemSet.fromSelectionSet(1) <> MBE_Success Then

If elemSet.fromFence() <> MBE_Success ThenMbeWriteStatus "No fence or selection set"

ElseMbeWriteStatus "Processing Fence"

End IfElse

MbeWriteStatus "Processing Selection Set"End If

' set an undo mark so we can go back MbeSendCommand "MARK"

status = elemSet.getFirst(setMember)' process each graphic group memberDo While status = MBE_Success

filePos = elem.fromFile(setMember.filePos, setMember.fileNum)If elem.type = MBE_Text Then

If elem.getOrigin(point) = MBE_Success ThenMbeSendCommand "SCALE"MbeLocateElement setMember.filePos, _elem.componentFilePos, setMember.fileNum, pointIf MbeState.cmdResult = MBE_AcceptQuery Then

MbeSendDataPoint point

' cancel scale, as accept point' may select another elemMbeSendCommand "NULL"

End IfEnd If

End Ifstatus = elemSet.getNext (setMember)

Loop

' clear selection setelemSet.clear

' restore graphic group lock and messagesMbeSettings.graphGroupLock = saveGGLkMbeState.messages = saveMsgs

End Sub

See also MbeStartLocate, MbeLocateElement.

8-140 MicroStation BASIC Guide

Page 451: 48784209 Microstation Basic

CAD Input Operations

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 141 Friday, October 15, 1999 1:27 PM

MbeScalarFromStringstat = MbeScalarFromString(value as Double, inString as String)

Descr. MbeScalarFromString parses a string of any form accepted by MicroStation to specify a scalar value (a distance, for example) and converts it to the current coordinate system of the macro (design file master units by default). The inString argument supplies the string and the output is stored in the value argument. The function returns MBE_Success if the string was successfully parsed and MBE_CantParseString (1100) if it could not parse the string. This also means that if you enter a null string, you will get the point (0, 0, 0).

Example Dim distance as DoubleDim distString as String

... ' get distString from userIf MbeScalarFromString(distance, distString) = MBE_Success Then

' can use distance hereEnd If

See also MbePointFromString, MbeAngleFromString, MbeStringFromScalar.

MbePointFromStringstat = MbePointFromString(point as MbePoint, inString as String)

Descr. MbeScalarFromString parses a string of any form accepted by MicroStation to specify a point, and converts it to a point in the current coordinate system of the macro (design file master units by default). The inString argument supplies the string and the output is stored in the point argument. The function returns MBE_Success if the string was successfully parsed and MBE_CantParseString (1100) if it could not parse the string. If the parsed string omits any of X, Y, or Z, the corresponding member of the point MbePoint will be zero. For example, if inString is “4.2,,5.7”, then point.x = 4.2, point.y = 0, and point.z = 5.7.

✍ If inString is null, then point is: (0, 0, 0).

Example Dim point as MbePointDim pntString as String' get pntString from user... If MbePointFromString(point, pntString) = MBE_Success Then

' can use point hereEnd If

See also MbeScalarFromString, MbeAngleFromString, MbeStringFromPoint.

MbeAngleFromStringstat = MbeAngleFromString(angle as Double, inString as String)

MicroStation BASIC Guide 8-141

Page 452: 48784209 Microstation Basic

CAD Input Operations

600macro.bk : 608_EXT.FRA Page 142 Friday, October 15, 1999 1:27 PM

Descr. MbeScalarFromString parses a string of any form accepted by MicroStation to specify an angle, and converts it to an angle in radians as a Double. The inString argument supplies the string and the output is stored in the angle argument. The function returns MBE_Success if the string was successfully parsed and MBE_CantParseString (1100) if it could not parse the string.

Example Dim angle as DoubleDim angString as String' get angString from user...If MbeAngleFromString(angle, angString) = MBE_Success Then

' can use angle hereEnd If

See also MbeScalarFromString, MbePointFromString, MbeStringFromAngle.

MbeStringFromScalarstat = MbeStringFromScalar(outString as String, value as Double)

Descr. MbeStringFromScalar formats a scalar value in the macro’s current coordinate system (design file master units by default) into a string suitable for display to the user. The format is determined by the settings in MicroStation’s Coordinate Readout dialog. The function returns MBE_Success, except in the rare instance that it runs out of memory creating the output string, in which case it returns MBE_OutOfMemory (7).

Example Dim distance as DoubleDim distString as String' calculate a distance...If MbeStringFromScalar(distString, distance) = MBE_Success Then

MbeWriteStatus “distance is “ & distStringEnd If

See also MbeStringFromPoint, MbeStringFromAngle, MbeScalarFromString.

MbeStringFromPointstat = MbeStringFromPoint(outString as String, point as MbePoint)

Descr. MbeStringFromPoint formats point in the macro’s current coordinate system (design file master units by default) into a string suitable for display to the user. The format is determined by the settings in MicroStation’s Coordinate Readout dialog. The function returns MBE_Success, except in the rare instance that it runs out of memory creating the output string, in which case it returns MBE_OutOfMemory (7).

Example Dim point as MbePointDim pntString as String' extract point from element...

8-142 MicroStation BASIC Guide

Page 453: 48784209 Microstation Basic

CAD Input Operations

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 143 Friday, October 15, 1999 1:27 PM

If MbeStringFromPoint(pntString, point) = MBE_Success ThenMbeWriteStatus “point is “ & pntString

End If

See also MbeStringFromScalar, MbeStringFromAngle, MbeStringFromAngle, MbePointFromString.

MbeStringFromAnglestat = MbeStringFromAngle(outString as String, angle as Double)

Descr. MbeStringFromAngle formats the angle in radians into a string suitable for display to the user. The format is determined by the settings in MicroStation’s Coordinate Readout dialog. The function returns MBE_Success, except in the rare instance that it runs out of memory creating the output string, in which case it returns MBE_OutOfMemory (7).

Example Dim angle as DoubleDim angString as String' calculate an angle...If MbeStringFromAngle (angString, angle) = MBE_Success Then

MbeWriteStatus “angle is “ & angStringEnd If

See also MbeStringFromPoint, MbeStringFromScalar, MbeAngleFromString.

MbeGetConfigVarstring = MbeGetConfigVar(cfgVarName as String)

Descr. MbeGetConfigVar function returns the expansion of the configuration variable specified by cfgVarName. If cfgVarName is not in the configuration variable table, an empty string is returned. Configuration variables are used by MicroStation to specify directories and files, and in some cases to specify operational parameters. They are modified using the Configuration Variables dialog box.

Example Dim defaultDgnDir as StringdefaultDgnDir = MbeGetConfigVar("MS_DEF")

See also MbeFindFile, "Environ$".

MbeFindFilestat = MbeFindFile(fileName as String, inputName as String [, _cfgVarName as String [, extension as String ]])

Descr. MbeFindFile attempts to find the specified file. The fileName argument is set to the name of the file if it is found. inputName specifies the file as a user might enter it. It must include the root filename, and it can optionally include a directory or a

MicroStation BASIC Guide 8-143

Page 454: 48784209 Microstation Basic

CAD Input Operations

600macro.bk : 608_EXT.FRA Page 144 Friday, October 15, 1999 1:27 PM

configuration variable specifying a directory, and/or an extension. If inputName includes a directory or extension, they will not be overridden by the other arguments in trying to find the file. The filename components included in the inputName argument are used first in searching for the file.

The optional cfgVarName argument can be used to specify a configuration variable that specifies one or more directories to search for the file. Alternatively, it can specify a directory, but in that case the directory specification must be appropriate to the operating system MicroStation is running on, and must including the trailing path separator character.

The optional extension argument can be used to specify a default extension for the file that is used if no extension is provided in inputName.

MbeFindFile returns MBE_Success if the file is found and MBE_FileNotFound (53) otherwise.

Example Dim cellLibrary as StringIf MbeFindFile(cellLibrary, "arch2d", "MS_CELL", ".cell") = MBE_SuccessThen

MbeSendCommand("ATTACH LIBRARY " & cellLibrary)End If

See also MbeFindFile.

MbeStartDefaultCommandMbeStartDefaultCommand

Descr. This statement starts the default command - generally the ElementSelection tool.

Use the statement to return MicroStation to a known state at the end of a macro.

Example Submain()' Restart the Element Selection tool...MbeStartDefaultCommand

EndSub

8-144 MicroStation BASIC Guide

Page 455: 48784209 Microstation Basic

Dialog Box Statements

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 145 Friday, October 15, 1999 1:27 PM

Dialog Box Statements

MbeFileOpen, MbeFileCreateMbeFileOpen as Long (filename as String [,suggest as String, _filter as String,directory as String,title as String])

MbeFileCreate as Long (filename as String [,suggest as String, _filter as String,directory as String,title as String])

Descr. The MbeFileOpen and MbeFileCreate functions lets the user conveniently choose a file (through a dialog box) for opening or creating. They return MBE_Success if the user chose a file name and clicked the OK button. It returns 1 if the user clicked the Cancel button, or an error if the dialog box could not be opened. Upon successful return, the filename argument will contain the name of the file to be opened or created.

suggest suggests a filename for opening or creating a file. It displays in the text field of the dialog. If a directory is attached to the filename, this argument serves as the default directory and the directory argument is ignored. This argument should normally be an empty string when it is called for opening files.

filter contains the filter to use for determining which files to include in the file list. It is useful for limiting files displayed to a particular type. Simple wild carding is allowed. An asterisk (*) matches any string and a question mark (?) matches any single character. If filter is an empty string, the filter string will match all files (*.*).

directory contains the directory where the selection process starts, but can also be an environment variable. In the latter case, the directory associated with the variable is used. This argument can be overwritten with the suggest argument. If directory is an empty string, the current working directory will be used.

Statement and Functions Used to

MbeFileOpen, MbeFileCreate (page 8-145)

Obtain a file name using the standard MicroStation file Open dialog box.

MbeMessageBox (page 8-146) Display a message in a dialog box using one of a variety of icons or pushbutton configurations.

MbeInputBox (page 8-147) Solicit string input from a user.

MbeSelectBox (page 8-147) Display a list of items in a dialog box and obtain a selection of one of the items in the list.

MbeOpenModalDialog (page 8-148) Open a customized dialog box that was previously generated for the macro using the Dialog Builder.

MicroStation BASIC Guide 8-145

Page 456: 48784209 Microstation Basic

Dialog Box Statements

600macro.bk : 608_EXT.FRA Page 146 Friday, October 15, 1999 1:27 PM

title contains the title of the dialog box.

Example suggest$ = "junk.bas"filter$ = "*.bas"directory$ = "MS_MACRO"title$ = "Choose a Macro File to Open"filename$ = ""

status = MbeFileOpen(filename$, suggest$, filter$, directory$, title$)If status = MBE_Success Then

button = MbeMessageBox("Selected filename is (" + filename$ + ").")Else

button = MbeMessageBox("File not selected.")End If

MbeMessageBoxstat=MbeMessageBox(msg as String [,type as Long])

Descr. The MsgBox function displays the message contained in msg in a dialog box with a set of predefined buttons and optional alert icon. The msg string can contain new line characters to separate lines in the message. Long lines in the message are automatically word-wrapped to the next line. The function returns a Long which button was selected. The following values are valid:

The type parameter may be used to specify which pushbuttons and which icon (if any) should be displayed. The defaults button is the OK button. The following values are valid:

type is also used to specify an icon in the dialog to be displayed with the message. The default behavior is “no icon”. The following values may be stored in type along with the button specification using the OR operator:

Constant Value Description

MBE_BUTTON_OK 3 OK was pressed.

MBE_BUTTON_CANCEL 4 Cancel was pressed.

MBE_BUTTON_YES 6 Yes was pressed.

MBE_BUTTON_NO 7 No was pressed.

Constant Value Description

MBE_OKBox 1 Display OK button only.

MBE_OKCancelBox 3 Display OK and Cancel buttons.

MBE_YesNoBox 12 Display Yes and No buttons.

MBE_YesNoCancelBox 14 Display Yes, No and Cancel buttons.

8-146 MicroStation BASIC Guide

Page 457: 48784209 Microstation Basic

Dialog Box Statements

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 147 Friday, October 15, 1999 1:27 PM

returns one of the following values:

If status = MBE_Success Thenbutton = MbeMessageBox ("Success. Press OK to continue.")

Elsebutton = MbeMessageBox ("Error found. Continue processing?",

MBE_YesNoBox or MBE_QuestionIcon)If button = MBE_BUTTON_NO Then

’ Statements to abort processing...End If

End If

MbeInputBoxstring = MbeInputBox(prompt as String [,defaultText as String, _title as String])

Descr. The MbeInputBox method prompts the user for input into a text field in the Input dialog box. It returns the text contained in the text field when the user clicks the OK button. If the user cancels the dialog box, an empty string is returned.

prompt can contain multiple lines, each separated with a newline character (Chr$(10)).

defaultText may be used to specify an initial entry in the input text field.

title specifies the text that appears in the dialog box’s title bar. If title is not specified, then no title appears in the dialog box’s title bar.

See also MbeSelectBox.

MbeSelectBoxMbeSelectBox as Integer(prompt as String, items as String(), _title as String)

Constant Value Description

MBE_CriticalIcon 256 Display “stop” icon.

MBE_QuestionIcon 512 Display “question mark” icon.

MBE_InfoIcon 1024 Display “information” icon.

MBE_WarningIcon 2048 Display “exclamation point” icon.

MicroStation BASIC Guide 8-147

Page 458: 48784209 Microstation Basic

Dialog Box Statements

600macro.bk : 608_EXT.FRA Page 148 Friday, October 15, 1999 1:27 PM

Descr. The MbeSelectBox method displays a dialog box containing a list of items. If the user selects an item and clicks the OK button, the index of that item is returned. An index value of -1 is returned if the user clicks the Cancel button.

prompt is provided to instruct the user to select an item from the list. It appears directly above the list in the dialog box.

items is used to construct the selection list. It must be a single dimension array of strings.

title specifies the text that appears in the dialog box’s title bar. If title is not specified, then no title appears in the dialog box’s title bar.

See also MbeInputBox.

MbeOpenModalDialogMbeOpenModalDialog as Long (dialogId as Long [,timeout as Integer _[timeoutButton as Integer]])

Descr. The MbeOpenModalDialog method is used to display a customized dialog box designed by the user. It returns one of the following standard button values or a user-defined button value (a positive integer >= 1000).

If the custom dialog could not be loaded, -1 is returned as the button value.

dialogId is the identifier of the custom dialog to be displayed.

The optional timeout parameter specifies the number of seconds that the dialog is to remain on the screen before being closed automatically. If not supplied, the dialog remains on the screen until the user dismisses it.

Constant Value

MBE_BUTTON_APPLY 1

MBE_BUTTON_OK 3

MBE_BUTTON_CANCEL 4

MBE_BUTTON_DEFAULT 5

MBE_BUTTON_YES 6

MBE_BUTTON_NO 7

MBE_BUTTON_RETRY 8

MBE_BUTTON_STOP 9

8-148 MicroStation BASIC Guide

Page 459: 48784209 Microstation Basic

Dialog Box Statements

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 149 Friday, October 15, 1999 1:27 PM

The optional timeoutButton parameter is used to set the button value associated with a custom dialog that was dismissed because the timeout value is MBE_BUTTON_OK, (this only applies if the timeout parameter was supplied and a timeout occured).

MicroStation BASIC Guide 8-149

Page 460: 48784209 Microstation Basic

MbeSqlda Object

600macro.bk : 608_EXT.FRA Page 150 Friday, October 15, 1999 1:27 PM

MbeSqlda Object

MbeSqlda.numColumnsMbeSqlda.numColumns

Descr. MbeSqlda.numColumns is a read only Integer property which gets the total number of fields available in MbeSqlda object.

See also MbeSqlda.column.

MbeSqlda.columnMbeSqlda.column(index as Integer)

Descr. MbeSqlda.column is a read-only String property which retrieves the index field name from the MbeSqlda object.

index must be greater than or equal to 0 and less than MbeSqlda.numColumns.

Example sub listAllColumns(dim sqlda as new MbeSqlda)dim iCol as IntegerFor iCol=0 To iCol=sqlda.numColumns-1

print sqlda.column(iCol)Next iCol

end sub

See also MbeSqlda.numColumns.

MbeSqlda.valueMbeSqlda.value(index as Integer)

Statement and Functions Used to

MbeSqlda.numColumns (page 8-150) Get total number of fields.

MbeSqlda.column (page 8-150) Get the field name.

MbeSqlda.value (page 8-150) Get the field value.

MbeSqlda.type (page 8-151) Get the field type.

MbeSqlda.length (page 8-151) Get the field length.

MbeSqlda.isNull (page 8-151) Get whether null is allowed.

MbeSqlda.scale (page 8-152) Get the scale portion of the field.

MbeSqlda.precision (page 8-152) Get total chars in a field.

MbeSqlda.getIndex (page 8-152) Get index for a field name.

8-150 MicroStation BASIC Guide

Page 461: 48784209 Microstation Basic

MbeSqlda Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 151 Friday, October 15, 1999 1:27 PM

Descr. MbeSqlda.value is a read-only String property which retrieves the index field value from the MbeSqlda object.

index must be greater than or equal to 0 and less than MbeSqlda.numColumns.

Example Function getMslink(sqlda as MbeSqlda) as Longdim iCol as IntegerFor iCol=0 To iCol=sqlda.numColumns-1

If sqlda.column(iCol)="mslink" Or sqlda.column(iCol)="MSLINK" ThengetMslink=var(sqlda.value(iCol))exit for

End IfNext iColEnd Function

See also MbeSqlda.numColumns, MbeSqlda.column, MbeTable.recordFirst, MbeTable.recordNext.

MbeSqlda.typeMbeSqlda.type(index as Integer)

Descr. MbeSqlda.type is a read-only String property which retrieves the index field type from the MbeSqlda object. MbeSqlda.type can be one of the following values: MBE_DBChar, MBE_DBInteger, MBE_DBNumber, MBE_DBDate, MBE_DBRaw or MBE_DBBinary.

index must be greater than or equal to 0 and less than MbeSqlda.numColumns.

See also MbeSqlda.numColumns.

MbeSqlda.lengthMbeSqlda.length(index as Integer)

Descr. MbeSqlda.length is a read-only Integer property which retrieves the length of the index field value from the MbeSqlda object. MbeSqlda.length is significant only where MbeSqlda.type(index) is MBE_DBCHAR and returns zero for all other type fields.

index must be greater than or equal to 0 and less than MbeSqlda.numColumns.

See also MbeSqlda.numColumns, MbeSqlda.type.

MbeSqlda.isNullMbeSqlda.isNull(index as Integer)

Descr. MbeSqlda.isNull is a read-only boolean property which returns TRUE or FALSE depending on if nulls are allowed in index field of the MbeSqlda object.

index must be greater than or equal to 0 and less than MbeSqlda.numColumns.

See also MbeSqlda.numColumns, MbeSqlda.value.

MicroStation BASIC Guide 8-151

Page 462: 48784209 Microstation Basic

MbeSqlda Object

600macro.bk : 608_EXT.FRA Page 152 Friday, October 15, 1999 1:27 PM

MbeSqlda.scaleMbeSqlda.scale(index as Integer)

Descr. MbeSqlda.scale is a read-only Integer property which returns the maximum number of digits after the decimal for the index field of the MbeSqlda object.

index must be greater than or equal to 0 and less than MbeSqlda.numColumns.

See also MbeSqlda.numColumns, MbeSqlda.type.

MbeSqlda.precisionMbeSqlda.precision(index as Integer)

Descr. MbeSqlda.precision is a read-only Integer property which returns the maximum number of characters in the number field at index field position of the MbeSqlda object.

index must be greater than or equal to 0 and less than MbeSqlda.numColumns.

See also MbeSqlda.numColumns, MbeSqlda.type, MbeSqlda.scale.

MbeSqlda.getIndexMbeSqlda.getIndex(fieldname as String)

Descr. MbeSqlda.getIndex is a read-only Integer property which returns the position of the field having name fieldname in MbeSqlda object.

index must be greater than or equal to 0 and less than MbeSqlda.numColumns.

See also MbeSqlda.column, MbeSqlda.type.

8-152 MicroStation BASIC Guide

Page 463: 48784209 Microstation Basic

MbeTable Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 153 Friday, October 15, 1999 1:27 PM

MbeTable Object

MbeTable.nameMbeTable.name

Descr. MbeTable.name is a read/write String property which sets or retrieves the name of the MbeTable object. This should be set before using any other methods of the MbeTable object.

Example Sub setTableName(tb as MbeTable, tbName as String)tb.name=tbName

end sub

See also MbeTable.create.

MbeTable.criteriaMbeTable.criteria

Descr. MbeTable.criteria is a read/write String property which sets or retrieves the current selection criteria for MbeTable.object.

A valid MbeTable.criteria must be of the formats:

Statement and Functions Used to

MbeTable.name (page 8-153) Get or set the table object name.

MbeTable.criteria (page 8-153) Get or set the selection criteria.

MbeTable.largestMslink (page 8-154) Get the largest MSLINK key.

MbeTable.entityNumber (page 8-154) Get the entity number for the table.

MbeTable.activeReview (page 8-154) Get or set review filter.

MbeTable.reportTable (page 8-155) Get or set report table.

MbeTable.describe (page 8-156) Describes the table.

MbeTable.recordFirst (page 8-156) Get the first record.

MbeTable.recordLast (page 8-157) Get the last record.

MbeTable.recordNext (page 8-157) Get next record in the table.

MbeTable.recordInsert (page 8-158) Insert a row in the table.

MbeTable.recordUpdate (page 8-158) Update the specified row.

MbeTable.recordDelete (page 8-159) Delete the specified row.

MbeTable.copy (page 8-159) Makes a duplicate table structure.

MbeTable.create (page 8-159) Create a new table.

MbeTable.drop (page 8-160) Drop the table from database.

MicroStation BASIC Guide 8-153

Page 464: 48784209 Microstation Basic

MbeTable Object

600macro.bk : 608_EXT.FRA Page 154 Friday, October 15, 1999 1:27 PM

"[column(s)][,expr][where condition]"

’-select only firstname and lastname where mslink is greater than 5

tb.criteria="firstname, lastname where mslink > 5"

’-select all fields where lastName is ’Smith’

tb.criteria="where lastName=’Smith’"

’-select all fields with no condition

tb.criteria=""

See also MbeTable.name, MbeTable.recordFirst.

MbeTable.largestMslinkMbeTable.largestMslink

Descr. MbeTable.largestMslink is a read-only property of type Long and retrieves the highest MSLINK key of the table in the MbeTable.object.

Example Sub defineActiveEntity(tb as MbeTable)dim db as New MbeDatabaseIf db.activeEntity <> tb.entityNumber Then

db.defineActiveEntity tb.name, tb.largestMslinkEndif

end sub

See also MbeTable.entityNumber, MbeDatabase.activeEntity.

MbeTable.entityNumberMbeTable.entityNumber

Descr. MbeTable.entityNumber is a read-only Integer property which retrieves the entity number for the table in the MbeTable object.

Example Sub defineActiveEntity(tb as MbeTable)dim db as New MbeDatabaseIf db.activeEntity <> tb.entityNumber Then

db.defineActiveEntity tb.name, tb.largestMslinkEndif

end sub

See also MbeTable.largestMslink, MbeDatabase.activeEntity.

MbeTable.activeReviewMbeTable.activeReview

8-154 MicroStation BASIC Guide

Page 465: 48784209 Microstation Basic

MbeTable Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 155 Friday, October 15, 1999 1:27 PM

Descr. MbeTable.activeReview is a read/write String property which sets or retrieves the SQL SELECT statement used for attribute review operations for the table in MbeTable object. MbeTable.activeReview is equivalent to the MicroStation ACTIVE_REVIEW key-in (RA=).

Example If tb.activeReview="" ThenreviewString="select mslink, mapname from " + tb.nametb.activeReview=reviewString

Endif

See also MbeElement.rewrite.

MbeTable.reportTableMbeTable.reportTable

Descr. MbeTable.reportTable is a read/write String property which sets or retrieves the report table name used during FENCE REPORT operations for the table in MbeTable object.

Example If tb.reportTable="" ThenreviewString="select mslink, mapname from " + tb.namett.reportTable="parcel_tab"Endif

See also MbeElement.reportDBLinkages, MbeDatabase.reportOpen.

MbeTable.fenceFilterMbeTable.fenceFilter

Descr. MbeTable.activeReview is a read/write String property which sets or retrieves the SQL SELECT statement specifying a subset of the table in MbeTable object. The fence filter limits all fence operations to only those elements which meet the database criteria expressed by this SELECT statement.

Example If tb.fenceFilter="" ThenfilterString="select ownername, mslink from " + tb.nametb.fenceFilter=filterStringEndif

See also MbeElement.review.

MicroStation BASIC Guide 8-155

Page 466: 48784209 Microstation Basic

MbeTable Object

600macro.bk : 608_EXT.FRA Page 156 Friday, October 15, 1999 1:27 PM

MbeTable.describestat = MbeTable.describe(sqlda as MbeSqlda)

Descr. The MbeTable.describe method describes the structure of the underlying table in MbeTable object. A new MbeSqlda object should be passed to the function to receive the table structure.

Example Sub profileTable(table as String)Dim tb as New MbeTableDim sqlda as New MbeSqldaDim idx as Integertb.name=tableIf tb.describe(sqlda) = MBE_Success Then

For idx=0 To sqlda.numColumns -1Call processFields(sqlda.column(idx))

Next idxEnd If

end Sub

See also MbeSqlda.numColumns, MbeSqlda.column, MbeDatabase.describe.

MbeTable.recordFirststat = MbeTable.recordFirst(sqlda as MbeSqlda)

Descr. The MbeTable.recordFirst method retrieves the first record from the table according to the criteria set in the MbeTable object. A new MbeSqlda object should be passed to the function to receive query result.

Example Sub getFirstSmith(table as String)Dim tb as New MbeTableDim sqlda as New MbeSqldaDim idx as Integertb.name=table

’--- create a querytb.criteria="where lastName=’Smith’"If tb.recordFirst(sqlda)=MBE_Success Then

’--- output the resultprint tab(2);"First Name:";sqlda.value(0);tab(44);"mslink:";sqlda.value(2)

End IfEnd sub

See also MbeSqlda.numColumns, MbeSqlda.value, MbeTable.recordLast, MbeTable.recordNext.

8-156 MicroStation BASIC Guide

Page 467: 48784209 Microstation Basic

MbeTable Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 157 Friday, October 15, 1999 1:27 PM

MbeTable.recordLaststat = MbeTable.recordLast(sqlda as MbeSqlda)

Descr. The MbeTable.recordLast method retrieves the last record from the table query according to the criteria set in the MbeTable object. A new MbeSqlda object should be passed to the function to receive query result.

Example Sub getLastSmith(table as String)Dim tb as New MbeTableDim sqlda as New MbeSqldaDim idx as Integertb.name=table

’--- create a querytb.criteria="where lastName=’Smith’"If tb.recordLast(sqlda)=MBE_Success Then

’--- output the resultprint tab(2);"First Name:";sqlda.value(0);tab(44);"mslink:";sqlda.value(2)

End IfEnd sub

See also MbeSqlda.value, MbeTable.recordFirst, MbeTable.recordNext.

MbeTable.recordNextstat = MbeTable.recordNext(sqlda as MbeSqlda)

Descr. The MbeTable.recordNext method retrieves the Next record from the table according to the criteria set in the MbeTable object. A new MbeSqlda object should be passed to the function to receive query result. MbeTable.recordFirst should be called before the first MbeTable.recordNext.

Example Sub getAllSmiths(table as String)Dim tb as New MbeTableDim sqlda as New MbeSqldaDim idx as Integertb.name=table’--- create a querytb.criteria="where lastName=’Smith’"If tb.recordFirst(sqlda)=MBE_Success Then’--- output the result

Doprint tab(2);"First Name:";sqlda.value(0);tab(44);"mslink:";sqlda.value(2)

Loop while tb.recordNext(sqlda)=MBE_QueryNotFinishedEnd If

End subReturn

MicroStation BASIC Guide 8-157

Page 468: 48784209 Microstation Basic

MbeTable Object

600macro.bk : 608_EXT.FRA Page 158 Friday, October 15, 1999 1:27 PM

MbeTable.recordNext returns MBE_QueryNotFinished if there is more to retrieve and returns MBE_QueryFinished when query is finished.

See also MbeSqlda.value, MbeTable.recordLast, MbeTable.recordFirst.

MbeTable.recordInsertstat=MbeTable.recordInsert insertString as String

Descr. The MbeTable.recordInsert command inserts a row to the table in the MbeTable object. MbeTable.recordInsert needs a string argument with the column values to be inserted. It can be a list of values separated by commas or list of columns and their values separated with a ‘values’ clause.

Example Sub insertThreeRecords(table as String)Dim tb as New MbeTabletbname = tabletb.recordInsert "'Michael', 'Smith',1"tb.recordInsert "mslink, firstname, lastname values 2, 'Tim', 'Best'"tb.recordInsert "firstname,lastname, mslink values 'Matt','Smith', 3"

end sub

See also MbeTable.recordDelete, MbeTable.recordUpdate.

MbeTable.recordUpdateMbeTable.recordUpdate mslink as long, updateList as String

Descr. The MbeTable.recordUpdate command updates the row specified by the mslink value passed. MbeTable.recordUpdate needs two arguments. mslink is a Long specifying the row to change and updateList a string containing columns and values to changed.

Example Sub renameSmithToJohn(table as String)Dim tb as New MbeTableDim mslink as longtb.name = tabletb.criteria = "where lastName = 'Smith'"If tb.recordFirst(sqlda) = MBE_Success Then

Domslink = val(sqlda.value(2))tb.recordUpdate mslink, “lastname = ‘John’”

Loop while tb.recordNext(sqlda) = MBE_SuccessEnd If

end sub

See also MbeTable.recordInsert, MbeTable.recordDelete.

8-158 MicroStation BASIC Guide

Page 469: 48784209 Microstation Basic

MbeTable Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 159 Friday, October 15, 1999 1:27 PM

MbeTable.recordDeleteMbeTable.recordDelete mslink as Long

Descr. The MbeTable.recordDelete command deletes the row specified by the mslink value passed.

Example Sub removeAllMedlocks(table as String)Dim tb as New MbeTableDim sqlda as New MbeSqldaDim mslink as long

tb.name = tabletb.criteria = "where lastName = 'Jones'"

If tb.recordFirst(sqlda) = MBE_Success Then Do

mslink = val(sqlda.value(2))tb.recordDelete mslink

Loop while tb.recordNext(sqlda) = MBE_SuccessEnd If

end sub

See also MbeTable.recordInsert, MbeTable.recordUpdate.

MbeTable.copyMbeTable.copy newTableName as String

Descr. The MbeTable.copy command creates a new table with the same structure as the existing table in the MbeTable object. Rows for the existing table are not copied into the new table.

Example Sub copyTable(newTableName as String)Dim tb as New MbeTabletb.name = tabletb.copy newTableName

end sub

See also MbeTable.create, MbeTable.recordInsert.

MbeTable.createMbeTable.create columnsList as String

Descr. The MbeTable.create command creates a new table with the column list specified. columnList defines the columns and optional column constraints of the table. Refer to your Database manuals for more information on CREATE TABLE syntax.

Example Sub createTable (tableName as String)Dim tb as New MbeTable

MicroStation BASIC Guide 8-159

Page 470: 48784209 Microstation Basic

MbeTable Object

600macro.bk : 608_EXT.FRA Page 160 Friday, October 15, 1999 1:27 PM

tb.name = tableNametb.create "firstname char(20), lastname char(20), mslink int"

end sub

See also MbeTable.drop, MbeTable.recordInsert.

MbeTable.dropMbeTable.drop

Descr. The MbeTable.drop method removes the table in MbeTable object and all its data from the database.

Example Sub dropTable (tableName as String)Dim tb as New MbeTabletb.name = tableNametb.drop

end sub

See also MbeTable.create.

8-160 MicroStation BASIC Guide

Page 471: 48784209 Microstation Basic

MbeDatabase Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 161 Friday, October 15, 1999 1:27 PM

MbeDatabase Object

MbeDatabase.name MbeDatabase.name

Descr. MbeDatabase.name is a read/write String property which sets or retrieves the database name. It extracts the active database name if no name is set for the MbeDatabase object.

Example Sub databaseConnect(dbName as String)Dim db as New MbeDatabaseIf db.name = “” Then

db.name = dbNamedb.connect

Statement and Functions Used to

MbeDatabase.name (page 8-161) Get or set database name.

MbeDatabase.activeEntity (page 8-162) Get the current active entity.

MbeDatabase.mslink (page 8-162) Get MSLINK key field of a record.

MbeDatabase.errorText (page 8-162) Get detailed text for an error code.

MbeDatabase.describe (page 8-163) Retrieves table names in an array.

MbeDatabase.connect (page 8-163) Connect the database to MS

MbeDatabase.disconnect (page 8-163) Disconnect the database.

MbeDatabase.defineActiveEntity (page 8-164)

Define AE from an SQL statement

MbeDatabase.showActiveEntity (page 8-164)

Shows current AE if any.

MbeDatabase.editActiveEntity (page 8-164)

Let user edit the AE if any.

MbeDatabase.modeCommit (page 8-165) Set database commit mode.

MbeDatabase.modeConfirm (page 8-165)

Get or set the confirmation mode.

MbeDatabase.modeDelete (page 8-165) Get or set the database rows delete mode.

MbeDatabase.modeForms (page 8-166) Get or set screen forms mode.

MbeDatabase.modeLinkage (page 8-166) Get or set the linkage mode (new, duplicate, etc.)

MbeDatabase.dAType (page 8-167) Get or set the active displayable attribute type.

MbeDatabase.reportOpen (page 8-167) Initializes all report tables.

MbeDatabase.reportClose (page 8-167) Close the report tables.

MicroStation BASIC Guide 8-161

Page 472: 48784209 Microstation Basic

MbeDatabase Object

600macro.bk : 608_EXT.FRA Page 162 Friday, October 15, 1999 1:27 PM

End Ifend sub

See also MbeDatabase.connect.

MbeDatabase.activeEntityMbeDatabase.activeEntity

Descr. MbeDatabase.activeEntity is a read only Integer property which returns the current active entity number if defined any and else returns 0.

Example Sub defineActiveEntity(tb as MbeTable)dim db as New MbeDatabaseIf db.activeEntity <> tb.entityNumber Then

db.defineActiveEntity tb.name, tb.largestMslinkEnd If

end sub

See also MbeDatabase.mslink, MbeDatabase.defineActiveEntity, MbeTable.entityNumber.

MbeDatabase.mslink MbeDatabase.mslink

Descr. MbeDatabase.mslink is a read only Integer property which returns the MSLINK key field of the current active entity record.

Example Sub defineActiveEntity(tb as MbeTable)dim db as New MbeDatabaseIf db.activeEntity = tb.entityNumber Then

If db.mslink <> tb.largestMslink Then db.defineActiveEntity tb.name, tb.largestMslinkEnd If

End Ifend sub

See also MbeDatabase.activeEntity, MbeDatabase.defineActiveEntity, MbeTable.entityNumber.

MbeDatabase.errorTextstat = MbeDatabase.errorText(errorDescr as String, errorCode as Integer)

Descr. The MbeDatabase.errorText method retrieves a detailed description in errorDescr for the errorCode.

Returns MbeDatabase.errorText returns MBE_Success if errorCode is a valid database error.

Example Sub handleDBError(errorCode as integer)dim db as New MbeDatabase

8-162 MicroStation BASIC Guide

Page 473: 48784209 Microstation Basic

MbeDatabase Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 163 Friday, October 15, 1999 1:27 PM

dim txt as StringIf db.errorText(txt, errorCode) = MBE_Success Then

MbeMessageBox(txt)End If

end sub

MbeDatabase.describenumTables = MbeDatabase.describe(tableArray() as String)

Descr. The MbeDatabase.describe function retrieves names of all the tables in the database and puts them in a dynamically allocated string array, tableArray.

Returns MbeDatabase.describe returns numTables an Integer which specifies the total number of tables available in tableArray.

Example Sub processAllTables(db as MbeDatabase)dim tabArray() as Stringdim numTables as Integerdim idx as integernumTables = db.describe(tabArray)If numTables <> 0 Then

For idx =0 To numTables -1processTable(tabArray(idx))

Next idxEnd If

end sub

See also MbeTable.name, MbeTable.describe.

MbeDatabase.connectMbeDatabase.connect connectString

Descr. The MbeDatabase.connect command connects the database to MicroStation. If no argument is supplied, it will try to connect using the MbeDatabase.name if it is set. MbeDatabase.connect is equivalent to DB=<schema> or |CONNECT commands in MicroStation.

See also MbeDatabase.disconnect, MbeTable.name.

MbeDatabase.disconnectMbeDatabase.disconnect

Descr. The MbeDatabase.disconnect method disconnects the database from MicroStation. MbeDatabase.disconnect is equivalent to |DISCONNECT key-in in MicroStation.

See also MbeDatabase.connect, MbeDatabase.name.

MicroStation BASIC Guide 8-163

Page 474: 48784209 Microstation Basic

MbeDatabase Object

600macro.bk : 608_EXT.FRA Page 164 Friday, October 15, 1999 1:27 PM

MbeDatabase.defineActiveEntityMbeDatabase.defineActiveEntity Select_Statement as StringMbeDatabase.defineActiveEntity Insert_Statement as StringMbeDatabase.defineActiveEntity tablename as String, mslink as longMbeDatabase.defineActiveEntity tablename as String

Descr. The MbeDatabase.defineActiveEntity command defines a new active entity using the parameters passed.

Select_Statement is an SQL SELECT statement. If the SELECT statement returns multiple rows the first one is used as the basis for the active entity. This case is equivalent to the MicroStation FIND (FI=) key-in.

Insert_Statement is an SQL INSERT statement with no mslink field as MicroStation will automatically assign an mslink when a linkage is created. This case is equivalent to MicroStation ACTIVE ENTITY (AE=) key-in.

If a tablename and a mslink value are passed, MbeDatabase.defineActiveEntity is equivalent to FI = select * from tablename where mslink = mslink command.

If only tablename is passed it will try to define active entity using ‘FI= select * from tablename ‘ command.

See also MbeElement.attachActiveEntity, MbeDatabase.showActiveEntity, MbeDatabase.editActiveEntity, MbeDatabase.modeLinkage.

MbeDatabase.showActiveEntityMbeDatabase.showActiveEntity

Descr. The MbeDatabase.showActiveEntity method displays the active entity if defined one. The active entity is the target row to which graphics elements will be linked.

MbeDatabase.showActiveEntity is equivalent to the MicroStation SHOW AE key-in.

See also MbeElement.attachActiveEntity, MbeDatabase.defineActiveEntitym, MbeDatabase.editActiveEntitym, MbeDatabase.activeEntitym, MbeDatabase.mslink, MbeDatabase.modeLinkage.

MbeDatabase.editActiveEntityMbeDatabase.editActiveEntity

Descr. The MbeDatabase.editActiveEntity method displays the active entity and allows editing of the individual fields.

The active entity is the target row to which graphics elements will be linked. If the active linkage mode (MbeDatabase.modeLinkage) is DUPLICATE, the active entity represents an actual table row and edits are written directly to the database.

If the linkage mode is NEW, the active entity is a prototype row, and edits are written in-memory only.

8-164 MicroStation BASIC Guide

Page 475: 48784209 Microstation Basic

MbeDatabase Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 165 Friday, October 15, 1999 1:27 PM

MbeDatabase.editActiveEntity equivalent to the MicroStation EDIT AE key-in.

See also MbeElement.attachActiveEntity, MbeDatabase.defineActiveEntity, MbeDatabase.showActiveEntity, MbeDatabase.activeEntity, MbeDatabase.mslink, MbeDatabase.modeLinkage.

MbeDatabase.modeCommitMbeDatabase.modeCommit = autoCommitMode as Integer

Descr. MbeDatabase.modeCommit is a write only boolean property which controls when a transaction-capable database commits work. Most RDBMSs (Oracle, Informix, Ingres) support the concept of transactions. A transaction is a unit of work which must be committed in its entirety before being posted to the database.

Normally, the MicroStation database interfaces immediately commit each SQL statement as it is processed. Applications which require greater control over database operations can turn off automatic commits.

Work performed since the last COMMIT may be undone by submitting a ROLLBACK.

See also MbeTable.recordInsert, MbeTable.recordUpdate, MbeTable.recordDelete.

MbeDatabase.modeConfirmMbeDatabase.modeConfirm = confirmRows as IntegerconfirmRows = MbeDatabase.modeConfirm

Descr. MbeDatabase.modeConfirm is a read/write boolean property which controls when MicroStation prompts for confirmation on a database operation which requires selecting a graphics element with an existing linkage. The DEFINE AE and ATTACH DA commands require selecting a graphics element which may contain more than one linkage. If there are multiple linkages and confirmRows is TRUE, MicroStation will prompt for confirmation of the row in the SQL Window. If confirmRows is FALSE, the first linkage on the element will be selected.

MbeDatabase.modeConfirm is equivalent to the MicroStationSET CONFIRM (ON | OFF) key-in.

MbeDatabase.modeDeleteMbeDatabase.modeDelete = deleteRows as Integer

Descr. MbeDatabase.modeDelete is a write only boolean property which controls whether database rows linked to graphics elements are deleted when the graphics element is deleted or the linkages are detached. deleteRows is TRUE when linked rows are to be

MicroStation BASIC Guide 8-165

Page 476: 48784209 Microstation Basic

MbeDatabase Object

600macro.bk : 608_EXT.FRA Page 166 Friday, October 15, 1999 1:27 PM

deleted during graphics delete and detach linkage operations. A value of FALSE means delete and detach operations have no effect on linked rows.

MbeDatabase.modeDelete is equivalent to the MicroStation SET DELETE (ON | OFF) key-in.

See also MbeElement.attachActiveEntity.

MbeDatabase.modeFormsMbeDatabase.modeForms = useForms as IntegeruseForms = MbeDatabase.modeForms

Descr. MbeDatabase.modeForms is a read/write boolean property which controls when MicroStation uses screen forms for attribute review and editing. If useForms is TRUE then the screen forms defined in MSCATALOG for each entity is used for attribute review. If useForms is FALSE then the SQL Window dialog box is used.

MbeDatabase.modeForms is equivalent to the MicroStation SET FORMS (ON | OFF) key-in.

See also MbeDatabase.showActiveEntity, MbeDatabase.editActiveEntity.

MbeDatabase.modeLinkageMbeDatabase.modeLinkage = mode as String

Descr. MbeDatabase.modeLinkage is a write only String property which sets the active database linkage mode. The linkage mode controls how and when MicroStation adds new rows to the database. When linkages are attached to graphics elements and when elements are copied, MicroStation uses the linkage mode to determine when to add new rows to the database.

Descr. The argument mode is a character string which specifies the linkage mode. The string may be one of the following values:

MbeDatabase.modeLinkage is equivalent to the MicroStation key-inACTIVE LINK (NEW | DUPLICATE | INFORMATION | NONE). Changing the linkage mode will clear the active entity.

See also MbeDatabase.defineActiveEntity, MbeElement.attachActiveEntity.

String Value Description

"new" each element is linked to a different row

"duplicate" many elements may be linked to the same row

"information" like duplicate mode but don't contribute to reports

"none" no linkages possible

8-166 MicroStation BASIC Guide

Page 477: 48784209 Microstation Basic

MbeDatabase Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 167 Friday, October 15, 1999 1:27 PM

MbeDatabase.dATypeMbeDatabase.dAType = daCode as IntegerdACode = MbeDatabase.dAType

Descr. MbeDatabase.dAType is a read/write Integer property which sets the active displayable attribute type. The displayable attribute type is used when MicroStation builds a displayable attribute linkage for a text node during the ATTACH DA command. The displayable attribute type is an index into the displayable attribute table defined for each entity in MSCATALOG.

daType is an integer value between 1 and 255 that maps to a row in a displayable attributes table. The displayable attribute format may be either an SQL SELECT statement or a screen form.

MbeDatabase.dAType is equivalent to a MicroStation ACTIVE DATYPE (DA=) key-in.

See also MbeElement.loadDAttributes.

MbeDatabase.reportOpenMbeDatabase.reportOpen

Descr. The MbeDatabase.reportOpen command initializes the report tables in the database to prepare for report generation. The report table contents, as defined by the MicroStation command ACTIVE REPORT, are deleted.

Subsequent calls to MbeElement.reportDBLinkages will accumulate rows in the report tables according to the attribute linkages present on the elements.

See also MbeElement.reportDBLinkages, MbeDatabase.reportClose, MbeTable.reportTable.

MbeDatabase.reportCloseMbeDatabase.reportClose

Descr. The MbeDatabase.reportClose command closes report tables in the database after report generation. The MicroStation command ACTIVE REPORT defines the report table names.

Subsequent reporting operations must be preceded by MbeDatabase.reportOpen.

See also MbeElement.reportDBLinkages, MbeDatabase.reportOpen, MbeTable.reportTable.

MicroStation BASIC Guide 8-167

Page 478: 48784209 Microstation Basic

MbeDatabaseLink Object

600macro.bk : 608_EXT.FRA Page 168 Friday, October 15, 1999 1:27 PM

MbeDatabaseLink ObjectThe MbeDatabaseLink object represents the linkage between graphics and database.

The first step in using an MbeDatabaseLink object is to declare the object and allocate space for it using either of the following BASIC constructs:

Dim link as New MbeDatabaseLink

or

Dim link as MbeDatabaseLinkSet link = New MbeDatabaseLink

You can call the MbeDatabaseLink object variable anything you want in your program. In this example we use link as the variable name. Either of these constructs establishes a name for an MbeDatabaseLink object and allocates memory.

The following extensions are provided for querying and manipulating MbeDatabaseLink object.

Statement and Functions Used to

MbeDatabaseLink.dAType (page 8-169)

Get or set displayable attribute type.

MbeDatabaseLink.entityNumber (page 8-169)

Get or set entity number of the linkage.

MbeDatabaseLink.isInformation (page 8-169)

Get or set information, modified, remote, or user property bit of the linkage.

MbeDatabaseLink.linkClass (page 8-170)

Get or set linkage class.

MbeDatabaseLink.linkSize (page 8-170)

Retrieves size in words of the database link.

MbeDatabaseLink.linkType (page 8-170)

Get or set type of database linkage.

MbeDatabaseLink.mslink (page 8-171) Get or set MSLINK value of a linkage

MbeDatabaseLink.tableName (page 8-171)

Get or set the associated table name.

8-168 MicroStation BASIC Guide

Page 479: 48784209 Microstation Basic

MbeDatabaseLink Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 169 Friday, October 15, 1999 1:27 PM

MbeDatabaseLink.dATypeMbeDatabaseLink.dAType

Descr. MbeDatabaseLink.dAType is a read/write Integer property which sets or retrieves the displayable attribute type if any are associated with the linkage object.

See also MbeElement.extractDBLinkages, MbeElement.appendDBLinkage, MbeElement.deleteDBLinkage, MbeDatabase.dAType.

MbeDatabaseLink.entityNumberMbeDatabaseLink.entityNumber

Descr. MbeDatabaseLink.entityNumber is a read/write Integer property which sets or retrieves the entity number for the database table associated with the linkage object. User must set either or both of the tableName or entityNumber properties of the linkage object before appending the linkage to the graphics element using MbeElement.appendDBLinkage extension.

See also MbeElement.extractDBLinkages, MbeElement.appendDBLinkage, MbeElement.deleteDBLinkage, MbeTable.entityNumber, MbeDatabaseLink.tableName.

MbeDatabaseLink.isInformationDescr. This is the read/write boolean property which sets or retrieves the property bit on the

database attribute link.

See also MbeElement.extractDBLinkages.

MbeDatabaseLink.isModifiedDescr. This is the read/write boolean property which sets or retrieves the modify bit on the

database attribute link.

See also MbeElement.extractDBLinkages.

MbeDatabaseLink.isRemoteDescr. This is the read/write boolean property which sets or retrieves the remote bit on the

database attribute link.

See also MbeElement.extractDBLinkages.

MicroStation BASIC Guide 8-169

Page 480: 48784209 Microstation Basic

MbeDatabaseLink Object

600macro.bk : 608_EXT.FRA Page 170 Friday, October 15, 1999 1:27 PM

MbeDatabaseLink.isUserLinkDescr. This is the read/write boolean property which sets or retrieves the user bit on the

database attribute link.

See also MbeElement.extractDBLinkages.

MbeDatabaseLink.linkClassMbeDatabaseLink.linkClass

Descr. MbeDatabaseLink.linkClass is a read/write Integer property which sets or retrieves the the linkage class of the database link.

See also MbeElement.extractDBLinkages.

MbeDatabaseLink.linkSizeMbeDatabaseLink.linkSize

Descr. MbeDatabaseLink.linkSize is a read only Integer property which retrieves the size of the database link in words.

See also MbeElement.extractDBLinkages.

MbeDatabaseLink.linkTypeMbeDatabaseLink.linkType

Descr. MbeDatabaseLink.linkType is a read/write Integer property which sets or retrieves the type of database linkage associated with the linkage object. MbeDatabaseLink.linkType can be any of the following values: MBE_ORACLE_Linkage, MBE_INFORMIX_Linkage, MBE_RIS_Linkage, MBE_DMRS_Linkage, MBE_ODBC_Linkage, MBE_XBASE_Linkage, MBE_DBASE_Linkage, MBE_SYBASE_Linkage or MBE_INGRES_Linkage.

Example Sub changeOracleLinksToODBC(lnk as MbeDatabaseLink)If lnk.type = MBE_ORACLE_Linkage Then

lnk.type = MBE_ODBC_LinkageEnd If

end sub

See also MbeElement.extractDBLinkages, MbeElement.appendDBLinkage, MbeElement.deleteDBLinkage.

8-170 MicroStation BASIC Guide

Page 481: 48784209 Microstation Basic

MbeDatabaseLink Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 171 Friday, October 15, 1999 1:27 PM

MbeDatabaseLink.mslink MbeDatabaseLink.mslink

Descr. MbeDatabaseLink.mslink is a read/write Integer property which sets or retrieves the MSLINK key value associated with the linkage object MbeDatabaseLink.

Example Sub validateLinkage(lnk as MbeDatabaseLink)Dim table as New MbeTableDim largestMslink as Longtable.name = lnk.tableNamelargestMslink = table.largestMslinklnk.mslink > largestMsLink Then

lnk.mslink = largestMsLinkEnd If

end sub

See also MbeElement.extractDBLinkages, MbeElement.appendDBLinkage, MbeElement.deleteDBLinkage.

MbeDatabaseLink.tableNameMbeDatabaseLink.tableName

Descr. MbeDatabaseLink.tableName is a read/write String property which sets or retrieves the database table name associated with the linkage object. User must set either or both the tableName and/or entityNumber properties of the linkage object before appending the linkage to the graphics element using MbeElement.appendDBLinkage extension.

Example Sub changeFeatureToParcel(lnk as MbeDatabaseLink)Dim table as New MbeTableIf lnk.tableName = “features” Then

table.name = “parcel”lnk.tableName = table.namelnk.entityNumber = table.entityNumber

End Ifend sub

See also MbeElement.extractDBLinkages, MbeElement.appendDBLinkage, MbeElement.deleteDBLinkage, MbeDatabaseLink.entityNumber.

MicroStation BASIC Guide 8-171

Page 482: 48784209 Microstation Basic

MbeDgnLevels Object

600macro.bk : 608_EXT.FRA Page 172 Friday, October 15, 1999 1:27 PM

MbeDgnLevels Object

MbeDgnLevels.rootGroupDescr. The MbeDgnLevels.rootGroup read-only property returns the MbeLevelGroup object

corresponding to the root of the current level structure. Its name cannot be modified.

Example Dim rootGroup As MbeLevelGroupset rootGroup = MbeDgnLevels.rootGroup

MbeDgnLevels.numGroupsDescr. The MbeDgnLevels.numGroups read-only Integer property returns the number of

groups in the current level structure.

Example Dim numGroups As IntegernumGroups = MbeDgnLevels.numGroups

Properties and Methods Used to

MbeDgnLevels.rootGroup (page 8-172) return the MbeLevelGroup object corresponding to the root of the current level structure.

MbeDgnLevels.numGroups (page 8-172) return the number of groups in the current level structure.

MbeDgnLevels.numNamedLevels (page 8-173)

return the number of named levels in the current level structure.

MbeDgnLevels.getGroup (page 8-173) retrieve the MbeLevelGroup corresponding to the specified name.

MbeDgnLevels.getLevel (page 8-173) retrieve the MbeNamedLevel corresponding to the specified name.

MbeDgnLevels.freeGroups (page 8-173) clear the current level group structures.

MbeDgnLevels.freeAll (page 8-174) clear the current level structure, including all level name and level group definitions.

MbeDgnLevels.loadGroupsFromFile (page 8-174)

load the only the level group definitions from the resource file specified.

MbeDgnLevels.loadLevelsFromFile (page 8-174)

load only the level name definitions from the resource file specified.

MbeDgnLevels.loadAllFromFile (page 8-175)

load the level name and level group definitions from the resource file specified.

MbeDgnLevels.saveGroupsToFile (page 8-175)

save the level group definitions to the resource file specified.

MbeDgnLevels.saveLevelsToFile (page 8-175)

save the level name definitions to the resource file specified.

MbeDgnLevels.saveAllToFile (page 8-176)

save the level name and level group definitions to the resource file specified.

8-172 MicroStation BASIC Guide

Page 483: 48784209 Microstation Basic

MbeDgnLevels Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 173 Friday, October 15, 1999 1:27 PM

MbeDgnLevels.numNamedLevelsDescr. The MbeDgnLevels.numNamedLevels read-only Integer property returns the number of

named levels in the current level structure.

Example Dim numNamedLevels As IntegernumNamedLevels = MbeDgnLevels.numNamedLevels

MbeDgnLevels.getGroupstat = MbeDgnLevels.getGroup(levelGroup As MbeLevelGroup, groupName As String)

Descr. MbeDgnLevels.getGroup retrieves the MbeLevelGroup corresponding to the named specified in groupName.

If more than one level group in the level structure has the name groupName, the method returns MBE_DuplicateLevelGroup. If no groups named groupName exist, the method returns MBE_InvalidLevelGroup.

Example Dim levelGroup As MbeLevelGroupIf MbeDgnLevels.getGroup (levelGroup, “furn/equip”) = MBE_Success Then levelGroup.deleteGroupEnd If

MbeDgnLevels.getLevelstat=MbeDgnLevels.getLevel(namedLevel As MbeNamedLevel, levelName As String)

Descr. MbeDgnLevels.getLevel retrieves the MbeNamedLevel corresponding to the name specified in levelName.

If more than one named level having the specified name exists in the level structure, the method returns MBE_DuplicateLevelName. If no levels having the specified name exist, the method returns MBE_InvalidLevelName.

Example Dim namedLevel As MbeNamedLevelIf MbeDgnLevels.getLevel(namedLevel, “STAIR”) = MBE_Success Then

namedLevel.deleteLevelEnd If

MbeDgnLevels.freeGroupsDescr. MbeDgnLevels.freeGroups clears the current level group structures.

✍ The level name definitions are not cleared; they remain active.

MicroStation BASIC Guide 8-173

Page 484: 48784209 Microstation Basic

MbeDgnLevels Object

600macro.bk : 608_EXT.FRA Page 174 Friday, October 15, 1999 1:27 PM

MbeDgnLevels.freeLevelsDescr. MbeDgnLevels.freeLevels clears the current level name structures.

✍ The level group definitions are not cleared; they remain active.

MbeDgnLevels.freeAllDescr. MbeDgnLevels.freeAll clears the current level structure, including all level name and

level group definitions. No level names or level groups are active after this method is called.

MbeDgnLevels.loadGroupsFromFilestat = MbeDgnLevels.loadGroupsFromFile(fileName As String)

Descr. MbeDgnLevels.loadGroupsFromFile loads the only the level group definitions from the resource file specified by fileName. The full file specification is passed in fileName.

Loading level group definitions from a resource file overrides the level group definitions contained in the design file.

The method returns MBE_CantLoadLevelsFromFile if the level group definitions are not successfully loaded.

Example If MbeDgnLevel.loadGroupsFromFile (“c:\ustation\wsmod\arch\data\aiaplumb.lvl”) = MBE_Success Then

Call ShowLevelGroupDefinitions()End If

MbeDgnLevels.loadLevelsFromFilestat = MbeDgnLevels.loadLevelsFromFile(fileName As String)

Descr. MbeDgnLevels.loadLevelsFromFile loads only the level name definitions from the resource file specified by fileName. The full file specification is passed in fileName.

Loading the level name definitions from a resource file overrides the level name definitions contained in the design file.

The method returns MBE_CantLoadLevelsFromFile if the level name definitions are not successfully loaded.

Example If MbeDgnLevels.loadLevelsFromFile (“c:\ustation\wsmod\arch\data\aiaplumb.lvl) = MBE_Success Then

Call ShowLevelNameDefinitions()End If

8-174 MicroStation BASIC Guide

Page 485: 48784209 Microstation Basic

MbeDgnLevels Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 175 Friday, October 15, 1999 1:27 PM

MbeDgnLevels.loadAllFromFilestat = MbeDgnLevels.loadAllFromFile(fileName As String)

Descr. MbeDgnLevels.loadAllFromFile loads the level name and level group definitions from the resource file specified by fileName. The full file specification is passed in fileName.

Loading the level name and level group definitions from a resource file overrides the level structure contained in the design file.

The method returns MBE_CantLoadLevelsFromFile if the level structure is not successfully loaded.

Example If MbeDgnLevels.loadAllFromFile (“c:\ustation\wsmod\arch\data\aiaplumb.lvl”) = MBE_Success Then

Call ShowLevelStructure()End If

MbeDgnLevels.saveGroupsToFilestat = MbeDgnLevels.saveGroupsToFile(fileName As String)

Descr. MbeDgnLevels.saveGroupsToFile saves only the level group definitions to the resource file specified by fileName. The full file specification is passed in fileName.

The method returns MBE_CantSaveLevelsToFile if the level group definitions are not successfully saved.

Example If MbeDgnLevels.saveGroupsToFile (“c:\ustation\data\mygroups.lvl”) = MBE_Success Then

MbeDgnLevels.freeGroupsEnd If

MbeDgnLevels.saveLevelsToFilestat = MbeDgnLevels.saveLevelsToFile(fileName As String)

Descr. MbeDgnLevels.saveLevelsToFile saves only the level name definitions to the resource file specified by fileName. The full file specification is passed in fileName.

The method returns MBE_CantSaveLevelsToFile if the level name definitions are not successfully saved.

Example If MbeDgnLevels.saveLevelsToFile(“c:\ustation\data\mylevels.lvl”) = MBE_Success Then

MbeDgnLevels.freeLevelsEnd If

MicroStation BASIC Guide 8-175

Page 486: 48784209 Microstation Basic

MbeDgnLevels Object

600macro.bk : 608_EXT.FRA Page 176 Friday, October 15, 1999 1:27 PM

MbeDgnLevels.saveAllToFilestat = MbeDgnLevels.saveAllToFile(fileName As String)

Descr. MbeDgnLevels.saveAllToFile saves the level name and level group definitions to the resource file specified by fileName. The full file specification is passed in fileName.

The method returns MBE_CantSaveLevelsToFile if the level structure is not successfully saved.

Example If MbeDgnLevels.saveAllToFile(“c:\ustation\data\mystruct.lvl”) = MBE_Success Then

MbeDgnLevels.freeAllEnd If

8-176 MicroStation BASIC Guide

Page 487: 48784209 Microstation Basic

MbeLevelGroup Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 177 Friday, October 15, 1999 1:27 PM

MbeLevelGroup Object

MbeLevelGroup.groupNameDescr. The MbeLevelGroup.groupName String property sets or retrieves the name identifying

the level group in the current level structure. Group names are limited to 16 characters in length.

✍ The groupName of the “root” group (MbeDgnLevels.rootGroup) cannot be changed.

Example Dim groupName As StringDim levelGroup As MbeLevelGroupIf MbeDgnLevels.getGroup(levelGroup, “furn/equip”) = MBE_Success Then

levelGroup.groupName = “furniture”End If

MbeLevelGroup.getLevelsstat = MbeLevelGroup.getLevels(namedLevels() As MbeNamedLevel)

Descr. MbeLevelGroup.getLevels retrieves an array of type MbeNamedLevel that contains objects corresponding to all the named levels immediately belonging to the level group.

The method returns MBE_InvalidLevelGroup if the level group is not valid in the current level structure.

Example Dim levelGroup As MbeLevelGroupDim namedLevels() As MbeNamedLevel

Properties and Methods Used to

MbeNamedLevel.levelNumber (page 8-181)

set or retrieve the MicroStation number of the named level.

MbeNamedLevel.levelName (page 8-181)

set or retrieve the level name of the named level.

MbeNamedLevel.levelComment (page 8-182)

set or retrieve the comment associated with the named level.

MbeNamedLevel.getParentGroup (page 8-182)

retrieve an object of type MbeLevelGroup corresponding to the level group containing the current named level.

MbeNamedLevel.getLevelMask (page 8-182)

retrieve a level mask corresponding to the named level.

MbeNamedLevel.deleteLevel (page 8-183)

delete the level name definition from the current level structure.

MicroStation BASIC Guide 8-177

Page 488: 48784209 Microstation Basic

MbeLevelGroup Object

600macro.bk : 608_EXT.FRA Page 178 Friday, October 15, 1999 1:27 PM

Dim iLevel As IntegerIf MbeDgnLevels.getGroup(levelGroup, “furn/equip”) = MBE_Success Then

If levelGroup.getLevels (namedLevels) = MBE_Success ThenFor iLevel = LBound (namedLevels) to UBound (namedLevels)

Print namedLevels(iLevel).levelNameNext iLevelEnd If

End If

MbeLevelGroup.getDescendentLevelsstat = MbeLevelGroup.getDescendentLevels(namedLevels() As MbeNamedLevel)

Descr. MbeLevelGroup.getDescendentLevels retrieves an array of type MbeNamedLevel that contains objects corresponding to all the named levels contained by the level group or any level groups descending from the current level group.

The method returns MBE_InvalidLevelGroup if the level group is not valid in the current level structure.

Example Dim levelGroup As MbeLevelGroupDim namedLevels() As MbeNamedLevelDim iLevel As IntegerIf MbeDgnLevels.getGroup(levelGroup, “furn/equip”) = MBE_Success Then

If levelGroup.getDescendentLevels(namedLevels) = MBE_Success ThenFor iLevel = LBound (namedLevels) to UBound (namedLevels) Print namedLevels(iLevel).levelNameNext iLevel

End IfEnd If

MbeLevelGroup.getDescendentGroupsstat = MbeLevelGroup.getDescendentGroups(subGroups() As MbeLevelGroup)

Descr. MbeLevelGroup.getDescendentGroups retrieves an array of type MbeLevelGroup that contains the objects corresponding to all the level groups descending from the current level group.

The method returns MBE_InvalidLevelGroup if the level group is not valid in the current level structure.

Example Dim rootGroup As MbeLevelGroupDim levelGroups() As MbeLevelGroupDim iGroup As Integerset rootGroup = MbeDgnLevels.rootGroupIf rootGroup.getDescendentGroups(levelGroups) = MBE_Success Then

For iGroup = LBound (levelGroups) to UBound (levelGroups)

8-178 MicroStation BASIC Guide

Page 489: 48784209 Microstation Basic

MbeLevelGroup Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 179 Friday, October 15, 1999 1:27 PM

Print levelGroups(iGroup).groupNameNext iGroup

End If

MbeLevelGroup.getParentGroupstat = MbeLevelGroup.getParentGroup (parentGroup As MbeLevelGroup)

Descr. MbeLevelGroup.getParentGroup retrieves and object of type MbeLevelGroup corresponding to the level group containing the current level group.

✍ The “root” group has no parent.

The method returns MBE_RootGroupHasNoParent if it is called from the root level from object. If the parent group does not exist in the level structure, the function returns MBE_InvalidLevelGroup.

Example Sub ShowParentName(levelGroup As MbeLevelGroup)Dim parentGroup As MbeLevelGroupIf levelGroup.getParentGroup(parentGroup) = MBE_Success Then

Print “Parent Group Name : “;parentGroup.groupNameEnd If

End Sub

MbeLevelGroup.getLevelMaskstat = MbeLevelGroup.getLevelMask(levelMask() As Integer)

Descr. MbeLevelGroup.getLevelMask retrieves a level mask that shows which levels belong in the level group. The levelMask argument must be a four-element Integer array.

The method returns an error code if the array is the wrong dimension.

Example Dim levelMask (0 to 3) As IntegerDim levelGroup As MbeLevelGroupDim view As MbeViewview = MbeViews(1)If MbeDgnLevels.getGroup(levelGroup, “furn/equip”) = MBE_Success Then

If levelGroup.getLevelMask(levelMask) = MBE_Success Thenview.levelsOn(levelMask)

End IfEnd If

MicroStation BASIC Guide 8-179

Page 490: 48784209 Microstation Basic

MbeLevelGroup Object

600macro.bk : 608_EXT.FRA Page 180 Friday, October 15, 1999 1:27 PM

MbeLevelGroup.deleteGroupDescr. MbeLevelGroup.deleteGroup deletes the level group from the current level structure.

Descendent groups will be deleted unless FALSE is specified.

Example Dim levelGroup As MbeLevelGroupIf MbeDgnLevels.getGroup(levelGroup, “notes/ref”) = MBE_Success Then

levelGroup.deleteGroupEnd If

MbeLevelGroup.addGroupstat = MbeLevelGroup.addGroup(subGroupName As String)

Descr. MbeLevelGroup.addGroup adds a level group definition as a descendant of the current level group. The subGroupName String argument is limited to 16 characters in length and specifies the name to be assigned to the new level group.

The method returns MBE_InvalidLevelGroup if the level group is not valid in the current level structure.

Example Dim rootGroup As MbeLevelGroupset rootGroup = MbeDgnLevels.rootGroupstat = rootGroup.addGroup(“notes”)If stat = MBE_Success Then

Print “Group Added”End If

MbeLevelGroup.addLevelstat=MbeLevelGroup.addLevel(levelName As String, levelNumber As Integer, _ [levelComment As String])

Descr. MbeLevelGroup.addLevel adds a named level definition in the current level structure. The named level immediately belongs to the current level group.

The levelName String argument is limited to 16 characters in length and specifies the name for the definition. The MicroStation number of the new level is passed in levelNumber. The optional levelComment String argument is limited to 32 characters in length.

The function returns an error code if the level name definition cannot be added.

Example Dim rootGroup As MbeLevelGroupset rootGroup = MbeDgnLevels.rootGroupstat = rootGroup.addLevel(“revisions”)If stat = MBE_Success Then

8-180 MicroStation BASIC Guide

Page 491: 48784209 Microstation Basic

MbeNamedLevel Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 181 Friday, October 15, 1999 1:27 PM

Print “Level Added”End If

MbeNamedLevel Object

MbeNamedLevel.levelNumberDescr. The MbeNamedLevel.levelNumber Integer property sets or retrieves the MicroStation

number of the named level.

Example Dim levelNumber As IntegerDim namedLevel As MbeNamedLevelIf MbeDgnLevels.getLevel(namedLevel, “revisions”) = MBE_Success Then

levelNumber = namedLevel.levelNumberEnd If

MbeNamedLevel.levelNameDescr. The MbeNamedLevel.levelName Integer property sets or retrieves the level name of

the named level.

Example Dim namedLevel As MbeNamedLevelIf MbeDgnLevels.getLevel(namedLevel, “revisions”) = MBE_Success Then

namedLevel.levelName = “notes/rev”End If

Properties and Methods Used to

MbeNamedLevel.levelNumber (page 8-181)

set or retrieve the MicroStation number of the named level.

MbeNamedLevel.levelName (page 8-181)

set or retrieve the level name of the named level.

MbeNamedLevel.levelComment (page 8-182)

set or retrieve the comment associated with the named level.

MbeNamedLevel.getParentGroup (page 8-182)

retrieve an object of type MbeLevelGroup corresponding to the level group containing the current named level.

MbeNamedLevel.getLevelMask (page 8-182)

retrieve a level mask corresponding to the named level.

MbeNamedLevel.deleteLevel (page 8-183)

delete the level name definition from the current level structure.

MicroStation BASIC Guide 8-181

Page 492: 48784209 Microstation Basic

MbeNamedLevel Object

600macro.bk : 608_EXT.FRA Page 182 Friday, October 15, 1999 1:27 PM

MbeNamedLevel.levelCommentDescr. The MbeNamedLevel.levelComment String property sets or retrieves the comment

associated with the named level.

Example Dim namedLevel As MbeNamedLevelDim levelComment As StringIf MbeDgnLevels.getLevel(namedLevel, “revisions”) = MBE_Success Then

levelComment = namedLevel.levelCommentEnd If

MbeNamedLevel.getParentGroupstat = MbeNamedLevel.getParentGroup (parentGroup As MbeLevelGroup)

Descr. MbeNamedLevel.getParentGroup retrieves an object of type MbeLevelGroup corresponding to the level group containing the current named level.

If the parent group does not exist in the level structure, the function returns MBE_InvalidLevelGroup.

Example Sub ShowParentName(namedLevel As MbeNamedLevel) Dim parentGroup As MbeLevelGroup If namedLevel.getParentGroup(parentGroup) = MBE_Success Then

Print “Parent Group Name : “;parentGroup.groupNameEnd If

End Sub

MbeNamedLevel.getLevelMaskstat = MbeNamedLevel.getLevelMask(levelMask() As Integer)

Descr. MbeNamedLevel.getLevelMask retrieves a level mask corresponding to the named level. The levelMask argument must be a four-element Integer array.

The function returns an error code if the array is the wrong dimension.

Example Dim levelMask (0 to 3) As IntegerDim namedLevel As MbeNamedLevelDim view As MbeViewview = MbeViews(1)If MbeDgnLevels.getLevel(namedLevel, “revisions”) = MBE_Success Then

If namedLevel.getLevelMask(levelMask) = MBE_Success Thenview.levelsOn(levelMask)

End IfEnd If

8-182 MicroStation BASIC Guide

Page 493: 48784209 Microstation Basic

MbeNamedLevel Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 183 Friday, October 15, 1999 1:27 PM

MbeNamedLevel.deleteLevelDescr. MbeNamedLevel.deleteLevel deletes the level name definition from the current level

structure.

Example Dim namedLevel As MbeNamedLevelIf MbeDgnLevels.getLevel(namedLevel, “revisions”) = MBE_Success Then

namedLevel.deleteLevelEnd If

MicroStation BASIC Guide 8-183

Page 494: 48784209 Microstation Basic

Tag BASIC Extensions

600macro.bk : 608_EXT.FRA Page 184 Friday, October 15, 1999 1:27 PM

Tag BASIC Extensions

MbeNumberOfTagSetsnum = MbeNumberOfTagSets()num = MbeNumberOfTagSets(fileNum as Integer)

Descr. MbeNumberOfTagSets returns the number of tagsets found in the design file. If the optional argument, fileNum, is provided, it specifies whether to find the count for the master (fileNum = 0) or one of the reference files (fileNum = the reference file slot to read the element from). If fileNum is not provided, MbeNumberOfTagSets is calculated for the master file.

Example Dim num as Integer‘ count total tagsets in the masternum = MbeNumberOfTagSets()‘ count total tagsets for the first ref. filenum = MbeNumberOfTagSets(1)

See also MbeGetTagSetNames, MbeTagSet.getTagDefNames.

MbeGetTagSetNamesnum = MbeGetTagSetNames(setNames as String())num = MbeGetTagSetNames(setNames as String(), fileNum as Integer)

Descr. MbeGetTagSetNames retrieves a sorted array of tagset names found in the design file. If the optional argument, fileNum, is provided, it specifies whether to find the tagset names for the master (fileNum = 0) or one of the reference files (fileNum = the reference file slot to read the element from). If fileNum is not provided,

Properties and Methods Used to

MbeNumberOfTagSets (page 8-184) get number of tagsets present in the specified design file.

MbeGetTagSetNames (page 8-184) get an array of tagset names present in the specified design file.

8-184 MicroStation BASIC Guide

Page 495: 48784209 Microstation Basic

Tag BASIC Extensions

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 185 Friday, October 15, 1999 1:27 PM

MbeGetTagSetNames retrieves the names for the master file. MbeGetTagSetNames returns the number of tagsets found in the specified file.

Example Dim numMaster as IntegerDim numRef as IntegerDim setsMaster as String()Dim setsRef as String()‘ get tagset names for the masternumMaster = MbeGetTagSetNames(setsMaster)‘ count total tagsets for the first ref. filenumRef = MbeGetTagSetNames(setsRef, 1)

See also MbeNumberOfTagSets, MbeTagSet.numTagDefs.

MicroStation BASIC Guide 8-185

Page 496: 48784209 Microstation Basic

MbeTagSet Object

600macro.bk : 608_EXT.FRA Page 186 Friday, October 15, 1999 1:27 PM

MbeTagSet Object

MbeTagSet.nameMbeTagSet.name

Descr. MbeTagSet.name is a read/write String property which sets or retrieves the name of the tagset object. MbeTagSet.name should be set before calling other MbeTagSet methods.

Example Dim tagset as new MbeTagSet'set tagset propertiestagset.name = "set0001"

See also MbeTagSet.getTagDefNames, MbeTagDef.name.

MbeTagSet.reportNameMbeTagSet.reportName

Descr. MbeTagSet.reportName is a read/write String property which sets or retrieves the name of the ASCII report file. MbeTagSet.reportName should be set before calling MbeTagSet.generateReport if no fileName argument is provided there.

Example Dim tagset as new MbeTagSet'set tagset properties

Properties and Methods Used to

MbeTagSet.name (page 8-186) get or set the tagset name.

MbeTagSet.reportName (page 8-186)

get or set name of the report file for the tagset.

MbeTagSet.fileNum (page 8-187) get or set the file number associated with the tagset.

MbeTagSet.numTagDefs (page 8-187)

get total number of tag definitions in the set.

MbeTagSet.getTagDefNames (page 8-187)

get a sorted array of tag names found in the set.

MbeTagSet.add (page 8-188) add a new tagset to the design file.

MbeTagSet.update (page 8-188) update the set and its report names.

MbeTagSet.delete (page 8-188) delete the tagset from master design file.

MbeTagSet.getTagDef (page 8-189)

det the MbeTagDef object for the specified tag from the tagset.

MbeTagSet.generateReport (page 8-189)

generate an ASCII report file for the tagset.

MbeTagSet.deleteInstances (page 8-190)

delete attribute elements for for all or the specified definition of the tagset.

8-186 MicroStation BASIC Guide

Page 497: 48784209 Microstation Basic

MbeTagSet Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 187 Friday, October 15, 1999 1:27 PM

...tagset.reportName = "c:\\tt"

See also MbeTagSet.generateReport.

MbeTagSet.fileNumMbeTagSet.FileNum

Descr. MbeTagSet.FileNum is a read/write Integer property which sets or retrieves the file number associated with tagset. By default, MbeTagSet.FileNum points to the master design file.

Example Dim tagset as new MbeTagSet'check whether the tagset is read from masterif tagset.fileNum = 0 then

‘update tagsetend if

See also MbeTagSet.add, MbeTagSet.update, MbeTagSet.delete.

MbeTagSet.numTagDefsnum = MbeTagSet.numTagDefs

Descr. MbeTagSet.numTagDefs is a read only Integer property which retrieves the total number of tag definitions found in the tagset.

Example Dim tagset as new MbeTagSettagset.name = “myset”'check tagset myset has any tags definedif tagset.numTagDefs > 0 then

‘process tagsend if

See also MbeTagSet.getTagDefNames, MbeTagDef.add.

MbeTagSet.getTagDefNamesnum = MbeTagSet.getTagDefNames(tagNames as String())

Descr. MbeTagSet.getTagDefNames retrieves a sorted array of tags defined in the tagset. MbeTagSet.getTagDefNames returns the number of tags found in the tagset.

Example dim tagset as new MbeTagSetdim tagNames() as stringnum = tagset.getTagDefNames(tagNames)

See also MbeTagSet.numTagDefs.

MicroStation BASIC Guide 8-187

Page 498: 48784209 Microstation Basic

MbeTagSet Object

600macro.bk : 608_EXT.FRA Page 188 Friday, October 15, 1999 1:27 PM

MbeTagSet.addstat = MbeTagSet.add()

Descr. MbeTagSet.add adds a new tagset to the design file. MbeTagSet.add returns MBE_Success if the tagset is added successfully, MBE_InvalidTagSet if the MbeTagSet.name property is not set and a different error code otherwise.

Example Dim tagset as new MbeTagSet'set tagset propertiestagset.name = "set0001"stat = tagset.add()

See also MbeTagSet.delete, MbeTagDef.add.

MbeTagSet.updatestat = MbeTagSet.update(newName as string)stat = MbeTagSet.update(newName as string, newReport as string)

Descr. MbeTagSet.update updates the tagset with a new name and report file. newName specifies the new name for the tagset. The second (optional) argument, newReport is the new report file name. If newReport is not provided, MbeTagSet.update does not change the report file name for the tagset.

MbeTagSet.update returns MBE_Success if the tagset is updated successfully, MBE_InvalidTagSet if the MbeTagSet.name property is not set and a different error code otherwise.

Example Dim tagset as new MbeTagSet'set tagset propertiestagset.name = "set0001"stat = tagset.update(“set0002”)

See also MbeTagSet.add, MbeTagDef.update.

MbeTagSet.deletestat = MbeTagSet.delete()

Descr. MbeTagSet.delete deletes the tagset from design file. User should delete the tag instances if any using MbeTagSet.deleteInstances before calling this.

MbeTagSet.delete returns MBE_Success if the tagset is deleted successfully, MBE_InvalidTagSet if the MbeTagSet.name property is not set and a different error code otherwise.

Example Dim tagset as new MbeTagSet'set tagset properties

8-188 MicroStation BASIC Guide

Page 499: 48784209 Microstation Basic

MbeTagSet Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 189 Friday, October 15, 1999 1:27 PM

tagset.name = "set0001"stat = tagset.delete()

See also MbeTagSet.deleteInstances, MbeTagDef.delete.

MbeTagSet.getTagDefstat = MbeTagSet.getTagDef(tagDef as MbeTagDef, tagName as string)

Descr. MbeTagSet.getTagDef creates an MbeTagDef object tagDef for the specified tag name tagName if it is available in the tagset.

MbeTagSet.getTagDef returns MBE_Success if tagName is a valid tag name for the tagset, MBE_InvalidTagSet if the MbeTagSet.name property is not set and a different error code otherwise.

Example Dim tagset as new MbeTagSetDim tagdef as new MbeTagDef'set tagset propertiestagset.name = "set1"‘check whether set1 contains tag1if tagset.getTagDef(tagdef, “tag1”) = MBE_Success then

‘process tagend if

See also MbeTagDef.add, MbeTagSet.numTagDefs.

MbeTagSet.generateReportstat= MbeTagSet.generateReport()stat= MbeTagSet.generateReport(reportMode as Integer)stat= MbeTagSet.generateReport(reportMode as Integer, tagList as String())stat=MbeTagSet.generateReport(reportMode as Integer, tagList as String(),

fileName as String)

Descr. MbeTagSet.generateReport generates an ASCII report file for the tagset. MbeTagSet.reportName must be set to a valid file path before calling this function.

The optional reportMode argument takes MBE_TagReportAll or MBE_TagReportTagged values. If reportMode is not specified it assumes MBE_TagReportTagged and reports only tagged elements.

The optional tagList argument specifies an array of column names for the report. They can be either tag names or tag types that MicroStation supports (i.e., $color for element color, $type for element type, etc.).

MicroStation BASIC Guide 8-189

Page 500: 48784209 Microstation Basic

MbeTagSet Object

600macro.bk : 608_EXT.FRA Page 190 Friday, October 15, 1999 1:27 PM

The optional fileName argument specifies the fully-qualified filename where the report will be generated. This is useful if the path exceeds the 12 characters that MbeTagSet.reportName can contain. If provided, fileName is used instead of reportName for generating the report. tagList can be a zero length array if you want to specify fileName but not tagList.

MbeTagSet.generateReport returns MBE_Success if the report is generated successfully, MBE_InvalidTagSet if the MbeTagSet.name or MbeTagSet.reportName properties are not set or a different error code otherwise.

Example Dim tagset as new MbeTagSetDim columns as string()tagset.name = “set1”tagset.reportName = "c:\\tt"‘set columns to tag namescolumns(0) = "tag1"columns(1) = "tag2"columns(2) = "tag3"stat = tagset.generateReport(MBE_TagReportTagged, columns)

See also MbeTagSet.reportName.

MbeTagSet.deleteInstancesstat = MbeTagSet.deleteInstances()stat = MbeTagSet.deleteInstances(tagName as string)

Descr. MbeTagSet.deleteInstances deletes all the attribute instances (type 37) of the tag specified by tagName from the design file. If the optional argument tagName is not provided, it deletes instances of all tags in the tagset.

MbeTagSet.deleteInstances returns MBE_Success tag elements are deleted successfully, MBE_InvalidTagSet if the MbeTagSet.name property is not set or a different error code otherwise.

Example Dim tagset as new MbeTagSet'set tagset propertiestagset.name = "set1"‘delete instances of tag1if tagset.deleteInstances(“tag1”) = MBE_Success then

‘now delete the tag definitionend if

See also MbeElement.attachTag, MbeTagDef.add.

8-190 MicroStation BASIC Guide

Page 501: 48784209 Microstation Basic

MbeTagDef Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 191 Friday, October 15, 1999 1:27 PM

MbeTagDef Object

MbeTagDef.nameMbeTagDef.name

Descr. MbeTagDef.name is a read/write String property which sets or retrieves the name of the tag definition object. MbeTagDef.name should be set before calling most of MbeTagDef methods.

Example Dim tagdef as new MbeTagDef'set tag definition propertiestagdef.setName = “set1”tagdef.name = "tag1"‘insert the tag to set1stat = tagdef.add()

See also MbeTagSet.name, MbeTagDef.setName.

Properties and Methods Used to

MbeTagDef.name (page 8-191) get or set tag name.

MbeTagDef.setName (page 8-192) get or set the parent tagset name.

MbeTagDef.prompt (page 8-192) get ot set the prompt string used for Dialog operations.

MbeTagDef.style (page 8-192) get ot set the text style for creating tag element.

MbeTagDef.tagType (page 8-193) get or set the data type of the tag.

MbeTagDef.defaultValue (page 8-193)

get or set the default value for the tag.

MbeTagDef.isHidden (page 8-194)

get or set the display mode of the tag.

MbeTagDef.isConstant (page 8-194)

get or set the constant mode of the tag.

MbeTagDef.tagId (page 8-194) get the unique ID associated with the tag definition.

MbeTagDef.add (page 8-195) add the tag definition to the tagset.

MbeTagDef.update (page 8-195) update the properties of tag definition.

MbeTagDef.delete (page 8-196) drop the definition from the tagset.

MicroStation BASIC Guide 8-191

Page 502: 48784209 Microstation Basic

MbeTagDef Object

600macro.bk : 608_EXT.FRA Page 192 Friday, October 15, 1999 1:27 PM

MbeTagDef.setNameMbeTagDef.setName

Descr. MbeTagDef.setName is a read/write String property which sets or retrieves name of the tagset which contains the tag definition object. MbeTagDef.setName should be set before calling most of MbeTagDef methods.

Example Dim tagdef as new MbeTagDef'set tag definition propertiestagdef.setName = “set1”tagdef.name = "tag1"‘insert the tag to set1stat = tagdef.add()

See also MbeTagSet.name, MbeTagDef.name, MbeTagDef.add.

MbeTagDef.promptMbeTagDef.prompt

Descr. MbeTagDef.prompt is a read/write String property which sets or retrieves the prompt string used while editing the attributes in MicroStation dialog interface.

Example Dim tagdef as new MbeTagDef'set tag definition propertiestagdef.setName = "set1"tagdef.name = "name"tagdef.prompt = “What is your name?”‘insert the tag to set1stat = tagdef.add()

See also MbeTagDef.add.

MbeTagDef.styleMbeTagDef.style

Descr. MbeTagDef.style is a read/write String property which sets or retrieves the style used to overwrite the text style while creating the tag.

✍ Currently MicroStation does not make use of this property.

Example Dim tagdef as new MbeTagDef'set tag definition propertiestagdef.setName = "set1"tagdef.name = "name"tagdef.style = “newStyle”

8-192 MicroStation BASIC Guide

Page 503: 48784209 Microstation Basic

MbeTagDef Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 193 Friday, October 15, 1999 1:27 PM

‘insert the tag to set1stat = tagdef.add()

See also MbeTagDef.add.

MbeTagDef.tagTypeMbeTagDef.tagType

Descr. MbeTagDef.tagType is a read/write Integer property which sets or retrieves the data type of the tag value. MbeTagDef.tagType can take any of the following values: MBE_TagString, MBE_TagInteger, MBE_TagLong, MBE_TagDouble or MBE_TagBinary.

Example Dim tagdef as new MbeTagDef'set tag definition propertiestagdef.name = “company”tagdef.tagType = MBE_TagStringtagdef.defaultValue = “Bentley Systems"‘insert the tag to set1stat = tagdef.add()

See also MbeTagDef.defaultValue.

MbeTagDef.defaultValueMbeTagDef.defaultValue

Descr. MbeTagDef.defaultValue is a read/write String property which sets or retrieves the default tag value. MbeTagDef.tagType should be set before setting the defaultValue.

Example Dim tagdef as new MbeTagDef'set tag definition propertiestagdef.setName = “empoyee”tagdef.name = “salary”tagdef.tagType = MBE_TagDoubletagdef.defaultValue = “3235.45"‘insert the tag to set1stat = tagdef.add()

See also MbeTagDef.tagType.

MicroStation BASIC Guide 8-193

Page 504: 48784209 Microstation Basic

MbeTagDef Object

600macro.bk : 608_EXT.FRA Page 194 Friday, October 15, 1999 1:27 PM

MbeTagDef.isHiddenMbeTagDef.isHidden

Descr. MbeTagDef.isHidden is a read/write Integer property which sets or retrieves the display mode for the tag. MbeTagDef.isHidden takes values either 1 (hidden) or 0 (display). Default value is 0.

Example Dim tagdef as new MbeTagDef'set tag definition propertiestagdef.setName = “empoyee”tagdef.name = “salary”‘hide the salary tagtagdef.isHidden = 1‘update salary tagstat = tagdef.update()

See also MbeElement.attachTag, MbeTagDef.update.

MbeTagDef.isConstantMbeTagDef.isConstant

Descr. MbeTagDef.isConstant is a read/write Integer property which sets or retrieves the constant mode for the tag. MbeTagDef.isConstant takes valueseither TRUE (1 -> constant) or FALSE (0->variable). Default is FALSE. If the tag is constant, every instance of the tag takes MbeTagDef.defaultValue as its value.

Example Dim tagdef as new MbeTagDef'set tag definition propertiestagdef.setName = “empoyee”tagdef.name = “sector”‘let every employee has the same sectortagdef.isConstant = TRUE tagdef.tagType = MBE_TagStringtagdef.defaultValue = “SECT01”‘update sector tagstat = tagdef.update()

See also MbeElement.attachTag, MbeTagDef.update.

MbeTagDef.tagIdMbeTagDef.tagId

Descr. MbeTagDef.tagId is a read only property of type Long which gets the unique ID associated with the tag definition. Most Macro users do not need this extension.

Example Dim tagdef as new MbeTagDef'set tag definition properties...

8-194 MicroStation BASIC Guide

Page 505: 48784209 Microstation Basic

MbeTagDef Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 195 Friday, October 15, 1999 1:27 PM

‘insert the tag to set1stat = tagdef.add()‘query the new tagprint tagdef.tagId

See also MbeTag.id, MbeTagDef.add.

MbeTagDef.addstat = MbeTagDef.add()

Descr. MbeTagDef.add adds a new tag definition to the tagset specified by MbeTagDef.setName.

MbeTagDef.add returns MBE_Success if the tag definition is added successfully, MBE_InvalidTagSet if the name or setName properties are not set and a different error code otherwise.

Example Dim tagdef as new MbeTagDeftagdef.setName = "set0001"tagdef.name = "elemnum"tagdef.tagType = MBE_TagLongstat = tagdef.add()

See also MbeTagDef.delete, MbeTagSet.add.

MbeTagDef.updatestat = MbeTagDef.update()stat = MbeTagDef.update(newName as string)

Descr. MbeTagDef.update updates the properties of an existing tag definition in the tagset specified by MbeTagDef.setName. If the optional argument newName is provided, MbeTagDef.update also renames the tag definition name with it.

MbeTagDef.update returns MBE_Success if the tag definition is updated successfully, MBE_InvalidTagSet if the name or setName properties are not set and a different error code otherwise.

Example Dim tagdef as new MbeTagDeftagdef.setName = "set0001"tagdef.name = "elemnum"‘hide elemnum tag now onwardstagdef.isHidden = 1‘also rename it to elnumberstat = tagdef.update(“elnumber”)

See also MbeTagDef.add, MbeTagSet.update.

MicroStation BASIC Guide 8-195

Page 506: 48784209 Microstation Basic

MbeTagDef Object

600macro.bk : 608_EXT.FRA Page 196 Friday, October 15, 1999 1:27 PM

MbeTagDef.deletestat = MbeTagDef.delete()

Descr. MbeTagDef.delete deletes an existing tag definition from the tagset pointed by MbeTagDef.setName. User should delete the tag instances if any using MbeTagSet.deleteInstances function before deleting its definition.

MbeTagDef.delete returns MBE_Success if the tag definition is deleted successfully, MBE_InvalidTagSet if the name or setName properties are not set and a different error code otherwise.

Example Dim tagdef as new MbeTagDefDim tagset as new MbeTagSettagset.name = "set1"tagdef.setName = “set1”tagdef.name = "elemnum"‘remove all its instancesstat = tagset.deleteInstances(“elemnum”)‘drop the tag from set1stat = tagdef.delete()

See also MbeTagDef.add, MbeTagSet.update.

8-196 MicroStation BASIC Guide

Page 507: 48784209 Microstation Basic

MbeTag Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 197 Friday, October 15, 1999 1:27 PM

MbeTag Object

MbeTag.setNameMbeTag.setName

Descr. MbeTag.setName is a read/write String property which sets or retrieves the name of tagset which contains the definition for the tag instance object MbeTag. MbeTag.setName should be set before calling most of MbeTag methods.

Example Dim tag as new MbeTag'set tag propertiestag.setName = “set1”tag.name = "tag1"

See also MbeTagDef.setName, MbeTagDef.name.

Properties and Methods Used to

MbeTag.setName (page 8-197) get or set the parent tagset name.

MbeTag.name (page 8-198) get or set tag name.

MbeTag.fileNum (page 8-198) get the file number from which the tag is read.

MbeTag.id (page 8-198) get the unique ID associated with the tag element.

MbeTag.targetId (page 8-199) get the association ID of the element the tag is attached to.

MbeTag.type (page 8-199) get the data type of tag value.

MbeTag.value (page 8-199) get or set the tag value.

MbeTag.size (page 8-200) get the size of character/binary tag value.

MbeTag.version (page 8-200) get the data type of tag value.

MbeTag.isHidden (page 8-200) get or set the display mode of the tag element.

MbeTag.setOffset (page 8-201) set the offset of the tag from the base element.

MbeTag.getOffset (page 8-201) get the offset of the tag from the base element.

MbeTag.getMbeElement (page 8-201)

get the underlying attribute element (type 37).

MbeTag.getTaggedElement (page 8-202)

get the element the tag is attached to.

MbeTag.getTextElement (page 8-202)

get a text element from tag.

MicroStation BASIC Guide 8-197

Page 508: 48784209 Microstation Basic

MbeTag Object

600macro.bk : 608_EXT.FRA Page 198 Friday, October 15, 1999 1:27 PM

MbeTag.nameMbeTag.name

Descr. MbeTag.name is a read/write String property which sets or retrieves the name of the tag definition from which tag instance object MbeTag is derived. MbeTag.name should be set before calling most of MbeTag methods.

Example Dim tag as new MbeTag'set tag propertiestag.setName = “set1”tag.name = "tag1"‘check the typeif tag.tagType = MBE_TagString()

‘attach tagend if

See also MbeTagDef.name, MbeTagDef.setName.

MbeTag.fileNumMbeTag.fileNum

Descr. MbeTag.fileNum is a read only Integer property specifying the file number from which the MbeTag object is originated.

Example ‘check the file numberif tag.fileNum = 0 then

‘attach tagend if

See also MbeElement.attachTag, MbeElement.getMbeTag.

MbeTag.idMbeTag.id

Descr. MbeTag.id is a read only property of type Long specifying the unique ID associated with the underlying tag (type 37) instance.

Example ‘check the validity of the tagif tag.id > 0 then

‘extract text elementend if

See also MbeElement.attachTag, MbeElement.getMbeTag.

8-198 MicroStation BASIC Guide

Page 509: 48784209 Microstation Basic

MbeTag Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 199 Friday, October 15, 1999 1:27 PM

MbeTag.targetIdMbeTag.targetId

Descr. MbeTag.targetId is a read only property of type Long specifying the unique association ID of the element the tag is attached to.

Example ‘check whether the tag is attachedif tag.targetId > 0 then

stat = tag.getTaggedElement(el)‘extract text element

end if

See also MbeElement.attachTag, MbeTag.getTaggedElement.

MbeTag.typeMbeTag.type

Descr. MbeTag.type is a read only Integer property which retrieves the data type of the tag value. MbeTag.type can take any of the following values: MBE_TagString, MBE_TagInteger, MBE_TagLong, MBE_TagDouble or MBE_TagBinary.

Example Dim tag as new MbeTagdim size as integerif tag.tagType = MBE_TagString then

size = tag.sizeend if

See also MbeTagDef.tagType, MbeTag.value.

MbeTag.valueMbeTag.value

Descr. MbeTag.value is a read/write String property which sets or retrieves the tag value.

Example Dim tag as new MbeTagtag.setName = "set0001"'tag element counttag.name = "elemnum"tag.value = Str$ (count)stat = inElem.attachTag(tag)

See also MbeTagDef.tagType.

MicroStation BASIC Guide 8-199

Page 510: 48784209 Microstation Basic

MbeTag Object

600macro.bk : 608_EXT.FRA Page 200 Friday, October 15, 1999 1:27 PM

MbeTag.sizeMbeTag.size

Descr. MbeTag.size is a read only Integer property which retrieves the size in bytes of tag value if it is of type MBE_TagString or MBE_TagBinary.

Example Dim tag as new MbeTagdim size as Integerif tag.tagSize = MBE_TagString then

size = tag.sizeend if

See also MbeTagDef.tagType, MbeTag.value.

MbeTag.versionMbeTag.version

Descr. MbeTag.version is a read only Integer property which retrieves the version number of the underlying tag element.

Example if tag.version > 5 then‘ do 95 special

end if

See also MbeElement.attachTag, MbeTag.value.

MbeTag.isHiddenMbeTag.isHidden

Descr. MbeTag.isHidden is a read/write Integer property which sets or retrieves the display mode for the tag. MbeTag.isHidden takes values either 1 (hidden) or 0 (display). Default value is the MbeTagDef.isHidden value for the parent tag definition.

Example Dim tag as new MbeTagDim inElem as MbeElement'tag element counttag.name = "elemnum"tag.value = Str$ (count)‘hide the tag elementtag.isHidden = 1stat = inElem.attachTag(tag)

See also MbeElement.attachTag, MbeTagDef.isHidden.

8-200 MicroStation BASIC Guide

Page 511: 48784209 Microstation Basic

MbeTag Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 201 Friday, October 15, 1999 1:27 PM

MbeTag.setOffsetstat = MbeTag.setOffset(offset as MbePointObj)

Descr. MbeTag.setOffset sets the offset for the underlying tag element from its attached element

MbeTag.setOffset returns MBE_Success if the offset is set successfully, MBE_InvalidTagSet if the name or setName properties are not.

Example Dim tag as new MbeTagDim offset as new MbePointObjoffset.x = 10.0offset.y = 10.0offset.x = 0stat = tag.setOffset(offset)stat = inElem.attachTag(tag)

See also MbeTag.getOffset.

MbeTag.getOffsetstat = MbeTag.getOffset(offset as MbePointObj)

Descr. MbeTag.getOffset gets the offset for the underlying tag element from its attached element

MbeTag.getOffset returns MBE_Success if the offset is retrieved successfully, MBE_InvalidTagSet if the name or setName properties are not.

Example Dim tag as new MbeTagDim offset as new MbePointObjstat = tag.getOffset(offset)

See also MbeTag.setOffset.

MbeTag.getMbeElementstat = MbeTag.getMbeElement(element as MbeElement)

Descr. MbeTag.getMbeElement retrieves the underlying MbeElement of type 37.

MbeTag.getMbeElement returns MBE_Success if the element is retrieved successfully, MBE_InvalidTagSet if the name or setName properties are not and a different error code otherwise.

Example Dim tag as new MbeTagDim tagElem as new MbeElement

MicroStation BASIC Guide 8-201

Page 512: 48784209 Microstation Basic

MbeTag Object

600macro.bk : 608_EXT.FRA Page 202 Friday, October 15, 1999 1:27 PM

...stat = tag.getMbeElement(tagElem)

See also MbeTag.getTaggedElement.

MbeTag.getTaggedElementstat = MbeTag.getTaggedElement(baseElem as MbeElement)

Descr. MbeTag.getTaggedElement retrieves the MbeElement baseElem to which the underlying tag is attached.

MbeTag.getTaggedElement returns MBE_Success if the tag is attached to an element and is retrieved successfully, MBE_InvalidTagSet if the name or setName properties are not and a different error code otherwise.

Example Dim tag as new MbeTagDim tagElem as new MbeElement...stat = tag.getTaggedElement(baseElem)

See also MbeElement.getMbeTag.

MbeTag.getTextElementstat = MbeTag.getTextElement(txtElem as MbeElement)

Descr. MbeTag.getTextElement function creates a Text element, txtElem (of type 17) from the underlying tag element. New Text element gets similar properties and symbologies of the tag element.

MbeTag.getTextElement returns MBE_Success if the Text element is created successfully, MBE_InvalidTagSet if the name or setName properties are not and a different error code otherwise.

Example Dim tag as new MbeTagDim txtElem as new MbeElement...stat = tag.getTextElement(txtElem)

See also MbeTag.getMbeElement, MbeElement.getMbeTag.

8-202 MicroStation BASIC Guide

Page 513: 48784209 Microstation Basic

MbeMacro Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 203 Friday, October 15, 1999 1:27 PM

MbeMacro ObjectThe MbeMacro object is used to control certain operational characteristics of the currently executing macro.

MbeMacro.suspendMbeMacro.suspend [duration As Long]

Descr. The MbeMacro.suspend method will suspend the macro for the stated number of milliseconds [ms]. The number of milliseconds is supplied in the optional duration parameter. If duration is not supplied, the default for the suspension is 250 ms (0.25 seconds). This BASIC extension is very similar to the Sleep command. The Sleep command also suspends the macro for a given duration, however, in that case, the MicroStation BASIC interpreter is not suspended therefore other parts of MicroStation are not allowed to "catch up" in their processing. With MbeMacro.suspend, the MicroStation BASIC interpreter is also suspended. This allows the rest of MicroStation to catch up on some of its processing, such as refreshing parts of views that were revealed by the closing of modal dialogs during the execution of the macro.

See also Sleep.

Properties and Methods Used to

MbeMacro.suspend suspend the macro (and the MicroStation BASIC interpreter) such that other parts of MicroStation can get processing time.

MicroStation BASIC Guide 8-203

Page 514: 48784209 Microstation Basic

Topology Objects

600macro.bk : 608_EXT.FRA Page 204 Friday, October 15, 1999 1:27 PM

Topology Objects

The following properties and methods refer to one of the GbeTLayerType objects.

Object Type Description

GbeTLayerPoint Point-type topology layer.

GbeTLayerLine Line-type topology layer.

GbeTLayerPolygon Polygon-type topology layer.

GbeTLayerMixed Mixed-type topology layer.

Properties and Methods Used to

GbeTLayerPoint.type, GbeTLayerLine.type, GbeTLayerPolygon.type, GbeTLayerMixed.type (page 8-205)

retrieve the type of the topology layer.

GbeTLayerPoint.sqlStatement, GbeTLayerLine.sqlStatement, GbeTLayerPolygon.sqlStatement, GbeTLayerMixed.sqlStatement (page 8-205)

get or set the topology layer SQL statement. This is not a member of the GbeTLayerMixed object.

GbeTLayerPoint.name, GbeTLayerLine.name, GbeTLayerPolygon.name, GbeTLayerMixed.name (page 8-205)

get or set the topology layer name.

GbeTLayerPoint.queryList, GbeTLayerLine.queryList, GbeTLayerPolygon.queryList, GbeTLayerMixed.queryList (page 8-206)

set whether or not to use query lists. This is not a member of the GbeTLayerMixed object.

GbeTLayerPoint.holes, GbeTLayerLine.holes, GbeTLayerPolygon.holes, GbeTLayerMixed.holes (page 8-206)

set whether or not to use holes. This is not a member of the GbeTLayerMixed object.

GbeTLayerPoint.shapesAsAreas, GbeTLayerLine.shapesAsAreas, GbeTLayerPolygon.shapesAsAreas, GbeTLayerMixed.shapesAsAreas (page 8-206)

set whether or not to shapes as areas. This is not a member of the GbeTLayerMixed object.

GbeTLayerPoint.load, GbeTLayerLine.load, GbeTLayerPolygon.load, GbeTLayerMixed.load (page 8-206)

load the topology layer. This is not a member of the GbeTLayerMixed object.

8-204 MicroStation BASIC Guide

Page 515: 48784209 Microstation Basic

Topology Objects

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 205 Friday, October 15, 1999 1:27 PM

GbeTLayerPoint.type, GbeTLayerLine.type, GbeTLayerPolygon.type, GbeTLayerMixed.type

GbeTLayerPoint.typeGbeTLayerLine.typeGbeTLayerPolygon.typeGbeTLayerMixed.type

Descr. The GbeTLayer_.type read-only Integer properties return the topology layer type.

GbeTLayerPoint.sqlStatement, GbeTLayerLine.sqlStatement, GbeTLayerPolygon.sqlStatement, GbeTLayerMixed.sqlStatement

GbeTLayerPoint.sqlStatementGbeTLayerLine.sqlStatementGbeTLayerPolygon.sqlStatementGbeTLayerMixed.sqlStatement

Descr. The GbeTLayer_.sqlStatement read/write String properties set or retrieve the topology layer SQL statement.

GbeTLayerPoint.name, GbeTLayerLine.name, GbeTLayerPolygon.name, GbeTLayerMixed.name

GbeTLayerPoint.nameGbeTLayerLine.nameGbeTLayerPolygon.nameGbeTLayerMixed.name

GbeTLayerPoint.display, GbeTLayerLine.display, GbeTLayerPolygon.display, GbeTLayerMixed.display (page 8-207)

display the topology layer.

GbeTLayerPoint.add, GbeTLayerLine.add, GbeTLayerPolygon.add, GbeTLayerMixed.add (page 8-207)

add the topology layer to the design file.

Type Mask Value

GBE_TypePolygon 1

GBE_TypeLine 2

GBE_TypePoint 3

GBE_TypeMixed 4

Properties and Methods Used to

MicroStation BASIC Guide 8-205

Page 516: 48784209 Microstation Basic

Topology Objects

600macro.bk : 608_EXT.FRA Page 206 Friday, October 15, 1999 1:27 PM

Descr. The GbeTLayer_.name read/write String properties set or retrieve the topology layer name.

GbeTLayerPoint.queryList, GbeTLayerLine.queryList, GbeTLayerPolygon.queryList, GbeTLayerMixed.queryList

GbeTLayerPoint.queryList [GBE_True, GBE_False]GbeTLayerLine.queryList [GBE_True, GBE_False]GbeTLayerPolygon.queryList [GBE_True, GBE_False]GbeTLayerMixed.queryList [GBE_True, GBE_False]

Descr. The GbeTLayer_.queryList object functions will set whether or not to use query lists.

GbeTLayerPoint.holes, GbeTLayerLine.holes, GbeTLayerPolygon.holes, GbeTLayerMixed.holes

GbeTLayerPoint.holes [GBE_True, GBE_False]GbeTLayerLine.holes [GBE_True, GBE_False]GbeTLayerPolygon.holes [GBE_True, GBE_False]GbeTLayerMixed.holes [GBE_True, GBE_False]

Descr. The GbeTLayer_.holes object functions will set whether or not to use holes.

GbeTLayerPoint.shapesAsAreas, GbeTLayerLine.shapesAsAreas, GbeTLayerPolygon.shapesAsAreas, GbeTLayerMixed.shapesAsAreas

GbeTLayerPoint.shapesAsAreas [GBE_True, GBE_False]GbeTLayerLine.shapesAsAreas [GBE_True, GBE_False]GbeTLayerPolygon.shapesAsAreas [GBE_True, GBE_False]GbeTLayerMixed.shapesAsAreas [GBE_True, GBE_False]

Descr. The GbeTLayer_.shapesAsAreas object functions will set whether or not to use shapes as areas.

GbeTLayerPoint.load, GbeTLayerLine.load, GbeTLayerPolygon.load, GbeTLayerMixed.load

stat = GbeTLayerPoint.load()stat = GbeTLayerLine.load()stat = GbeTLayerPolygon.load()stat = GbeTLayerMixed.load()

8-206 MicroStation BASIC Guide

Page 517: 48784209 Microstation Basic

Topology Objects

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 207 Friday, October 15, 1999 1:27 PM

Descr. The GbeTLayer_.load object functions create a topology layer based upon the specifications previously defined. Will return MBE_Success if the topology layer is loaded successfully.

GbeTLayerPoint.add, GbeTLayerLine.add, GbeTLayerPolygon.add, GbeTLayerMixed.add

stat = GbeTLayerPoint.add()stat = GbeTLayerLine.add()stat = GbeTLayerPolygon.add()stat = GbeTLayerMixed.add()

Descr. The GbeTLayer_.add object functions add the topology layer to the design file. Will return MBE_Success if the topology layer is added successfully.

GbeTLayerPoint.display, GbeTLayerLine.display, GbeTLayerPolygon.display, GbeTLayerMixed.display

stat = GbeTopoLayerPoint.display()stat = GbeTLayerLine.display()stat = GbeTLayerPolygon.display()stat = GbeTLayerMixed.display()

Descr. The GbeTLayer_.display object functions display the topology layer. The topology layer must have been previously loaded. MBE_Success will be returned if the layer can be displayed.

MicroStation BASIC Guide 8-207

Page 518: 48784209 Microstation Basic

GbeTLayerPoint Object

600macro.bk : 608_EXT.FRA Page 208 Friday, October 15, 1999 1:27 PM

GbeTLayerPoint Object

GbeTLayerPoint.colorGbeTLayerPoint.color

Descr. The GbeTLayerPoint.color read/write Integer property sets or retrieves the centroid color.

GbeTLayerPoint.levelGbeTLayerPoint.level

Descr. The GbeTLayerPoint.level read/write Integer property sets or retrieves the centroid level.

GbeTLayerPoint.weightGbeTLayerPoint.weight

Descr. The GbeTLayerPoint.weight read/write Integer property sets or retrieves the centroid weight.

GbeTLayerPoint.nodeTypeGbeTLayerPoint.nodeType

Properties and Methods Used to

GbeTLayerPoint.color (page 8-208) get or set the color.

GbeTLayerPoint.level (page 8-208) get or set the level.

GbeTLayerPoint.nodeType (page 8-208) get or set the node type.

GbeTLayerPoint.weight (page 8-208) get or set the weight.

GbeTLayerPoint.pointPolyOverlay (page 8-209)

generate a point overlay.

8-208 MicroStation BASIC Guide

Page 519: 48784209 Microstation Basic

GbeTLayerPoint Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 209 Friday, October 15, 1999 1:27 PM

Descr. The GbeTLayerPoint.nodeType read/write Integer property sets or retrieves the centroid node type.

GbeTLayerPoint.pointPolyOverlaystat = GbeTLayerPoint.pointPolyOverlay(pointTopo as GbeTLayerPoint, _polyTopo as GbeTLayerPolygon, linkage as [GBE_True, GBE_False],selection _as Integer)

Descr. The GbeTLayerPoint.pointPolyOverlay object function will generate a point overlay from a point topology object and a polygon topology object. The pointTopo and polyTopo objects must have been previously loaded. Set linkage to GBE_True to copy the feature linkages. The selection criteria should be based upon a bitwise OR combination of the following selection criteria.

Example status = GbeTLayerPoint.pointPolyOverlay(pointTopo, polyTopo, GBE_TRUE, _GBE_Inside OR GBE_Overlap)

Node Type Mask Value

GBE_Point 1

GBE_TextNode 2

Selection Mask Value

GBE_Inside 4

GBE_Outside 8

GBE_Overlap 16

MicroStation BASIC Guide 8-209

Page 520: 48784209 Microstation Basic

GbeTLayerLine Object

600macro.bk : 608_EXT.FRA Page 210 Friday, October 15, 1999 1:27 PM

GbeTLayerLine Object

GbeTLayerLine.colorGbeTLayerLine.color

Descr. The GbeTLayerLine.color read/write Integer property sets or retrieves the boundary color.

GbeTLayerLine.levelGbeTLayerLine.level

Descr. The GbeTLayerLine.level read/write Integer property sets or retrieves the boundary level.

GbeTLayerLine.styleGbeTLayerLine.style

Descr. The GbeTLayerLine.style read/write Integer property sets or retrieves the boundary style.

GbeTLayerLine.weightGbeTLayerLine.weight

Descr. The GbeTLayerLine.weight read/write Integer property sets or retrieves the boundary weight.

GbeTLayerLine.linePolyOverlaystat = GbeTLayerPolygon.linePolyOverlay (lineTopo as GbeTLayerLine, _polyTopo as GbeTLayerPolygon, linkage as [GBE_True, GBE_False],selection _as Integer)

Properties and Methods Used to

GbeTLayerLine.color (page 8-210) get or set the color.

GbeTLayerLine.level (page 8-210) get or set the level.

GbeTLayerLine.style (page 8-210) get or set the style.

GbeTLayerLine.weight (page 8-210) get or set the weight.

GbeTLayerLine.linePolyOverlay (page 8-210)

generate a line overlay.

8-210 MicroStation BASIC Guide

Page 521: 48784209 Microstation Basic

GbeTLayerLine Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 211 Friday, October 15, 1999 1:27 PM

Descr. The GbeTLayerLine.linePolyOverlay object function will generate a line overlay from a line topology object and a polygon topology object. The lineTopo and polyTopo objects must have been previously loaded. Set linkage to GBE_True to copy the feature linkages. The selection criteria should be based upon a bitwise OR combination of the following selection criteria.

Example status = GbeTLayerLine.linePolyOverlay(lineTopo, polyTopo, GBE_TRUE, _GBE_Inside OR GBE_Overlap)

Selection Mask Value

GBE_Inside 4

GBE_Outside 8

GBE_Overlap 16

MicroStation BASIC Guide 8-211

Page 522: 48784209 Microstation Basic

GbeTLayerPolygon Object

600macro.bk : 608_EXT.FRA Page 212 Friday, October 15, 1999 1:27 PM

GbeTLayerPolygon Object

GbeTLayerPolygon.colorGbeTLayerPolygon.color

Descr. The GbeTLayerPolygon.color read/write Integer property sets or retrieves the polygon color.

GbeTLayerPolygon.levelGbeTLayerPolygon.level

Descr. The GbeTLayerPolygon.level read/write Integer property sets or retrieves the polygon level.

GbeTLayerPolygon.styleGbeTLayerPolygon.style

Descr. The GbeTLayerPolygon.style read/write Integer property sets or retrieves the polygon style.

GbeTLayerPolygon.weightGbeTLayerPolygon.weight

Properties and Methods Used to

GbeTLayerPolygon.color (page 8-212) get or set the color.

GbeTLayerPolygon.level (page 8-212) get or set the level.

GbeTLayerPolygon.style (page 8-212) get or set the style.

GbeTLayerPolygon.weight (page 8-212) get or set the weight.

GbeTLayerPolygon.fillColor (page 8-213)

get or set the fill color.

GbeTLayerPolygon.doFill (page 8-213) set whether or not to fill the area.

GbeTLayerPolygon.polyPolyOverlay (page 8-213)

generate a polygon overlay from two polygon overlays.

GbeTLayerPolygon.pointPolyOverlay (page 8-213)

generate a polygon overlay from a point and a polygon overlay.

GbeTLayerPolygon.linePolyOverlay (page 8-214)

generate a line overlay from a line and a polygon overlay.

8-212 MicroStation BASIC Guide

Page 523: 48784209 Microstation Basic

GbeTLayerPolygon Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 213 Friday, October 15, 1999 1:27 PM

Descr. The GbeTLayerPolygon.weight read/write Integer property sets or retrieves the polygon weight.

GbeTLayerPolygon.fillColorGbeTLayerPolygon.fillColor

Descr. The GbeTLayerPolygon.fillColor read/write Integer property sets or retrieves the polygon fill color. GbeTLayerPolygon.doFill must be set to GBE_True for this property to have any affect.

GbeTLayerPolygon.doFillGbeTLayerPolygon.doFill [GBE_True, GBE_False]

Descr. The GbeTLayerPolygon.doFill write-only Integer property determines whether or not fill the polygon. If GBE_True is set, the polygon will be filled with the color specified by the fillColor property.

GbeTLayerPolygon.polyPolyOverlaystat = GbeTLayerPolygon.polyPolyOverlay(polyOne as GbeTLayerPolygon, _polyTwo as GbeTLayerPolygon, operator as [GBE_AND, GBE_OR, GBE_XOR, _GBE_DIFF], linkage as [GBE_True, GBE_False])

Descr. The GbeTLayerPolygon.polyPolyOverlay object function will generate a polygon overlay from two polygon topology objects. The polyOne and polyTwo objects must have been previously loaded. Set linkage to GBE_True to copy the feature linkages. Set operator to one of the following:

GbeTLayerPolygon.pointPolyOverlaystat = GbeTLayerPolygon.pointPolyOverlay(pointTopo as GbeTLayerPoint, _polyTopo as GbeTLayerPolygon, linkage as [GBE_True,GBE_False],selection _as Integer)

Descr. The GbeTLayerPolygon.pointPolyOverlay object function will generate a polygon overlay from a point topology and a polygon topology. The pointTopo and polyTopo objects must have been previously loaded. Set linkage to GBE_True to copy the feature

operator Mask Value

GBE_ADD 1

GBE_OR 2

GBE_XOR 3

GBE_DIFF 4

MicroStation BASIC Guide 8-213

Page 524: 48784209 Microstation Basic

GbeTLayerPolygon Object

600macro.bk : 608_EXT.FRA Page 214 Friday, October 15, 1999 1:27 PM

linkages. The selection criteria should be based upon a bitwise OR combination of the following selection criteria.

Example status = GbeTLayerPolygon.pointPolyOverlay(pointTopo,polyTopo,GBE_TRUE, _GBE_Inside OR GBE_Overlap)

GbeTLayerPolygon.linePolyOverlaystat = GbeTLayerPolygon.linePolyOverlay(lineTopo as GbeTLayerLine, _polyTopo as GbeTLayerPolygon, linkage as [GBE_True,GBE_False],selection _as Integer)

Descr. The GbeTLayerPolygon.linePolyOverlay object function will generate a polygon overlay from a line topology and a polygon topology. The lineTopo and polyTopo objects must have been previously loaded. Set linkage to GBE_True to copy the feature linkages. The selection criteria should be based upon a bitwise OR combination of the following selection criteria.

Example status = GbeTLayerPolygon.linePolyOverlay(lineTopo, polyTopo,GBE_TRUE, _GBE_Inside OR GBE_Overlap)

Selection Mask Value

GBE_Inside 4

GBE_Outside 8

GBE_Overlap 16

Selection Mask Value

GBE_Inside 4

GBE_Outside 8

GBE_Overlap 16

8-214 MicroStation BASIC Guide

Page 525: 48784209 Microstation Basic

GbeTLayerMixed Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 215 Friday, October 15, 1999 1:27 PM

GbeTLayerMixed Object

GbeTLayerMixed.pointPolyOverlaystat = GbeTLayerMixed.pointPolyOverlay (pointTopo as GbeTLayerPoint, poltTopo as GbeTLayerPolygon, linkage as [GBE_True, GBE_False], selection as Integer)

Descr. The GbeTLayerMixed.pointPolyOverlay object function will generate a mixed overlay from a point topology and a polygon topology. The pointTopo and polyTopo objects must have been previously loaded. Set linkage to GBE_True to copy the feature linkages. The selection criteria should be based upon a bitwise OR combination of the following selection criteria.

Example status = GbeTLayerMixed.pointPolyOverlay(pointTopo, polyTopo, GBE_TRUE, _ GBE_Inside OR GBE_Overlap)

GbeTLayerMixed.linePolyOverlaystat = GbeTLayerMixed.linePolyOverlay(lineTopo as GbeTLayerLine, polyTopo as GbeTLayerPolygon, linkage as [GBE_True, GBE_False], selection as Integer)

Descr. The GbeTLayerMixed.linePolyOverlay object function will generate a mixed overlay from a line topology and a polygon topology. The lineTopo and polyTopo objects must have been previously loaded. Set linkage to GBE_True to copy the feature linkages.

Properties and Methods Used to

GbeTLayerMixed.pointPolyOverlay (page 8-215)

generate a mixed overlay from point and polygon topologies.

GbeTLayerMixed.linePolyOverlay (page 8-215)

generate a mixed overlay from line and polygon topologies.

Selection Mask Value

GBE_Inside 4

GBE_Outside 8

GBE_Overlap 16

MicroStation BASIC Guide 8-215

Page 526: 48784209 Microstation Basic

GbeTLayerMixed Object

600macro.bk : 608_EXT.FRA Page 216 Friday, October 15, 1999 1:27 PM

The selection criteria should be based upon a bitwise OR combination of the following selection criteria.

Example status = GbeTLayerMixed.linePolyOverlay(lineTopo, polyTopo, GBE_TRUE, _GBE_Inside OR GBE_Overlap)

Topology Error Codes

Selection Mask Value

GBE_Inside 4

GBE_Outside 8

GBE_Overlap 16

Error Number

Error Message Built-in Constant Name

2520 Error when trying to initialize the topology layer.

GBE_TopologyInitFail

2521 The topology layer name has not been defined.

GBE_NoLayerName

2522 No fence has been placed previous to performing topology load.

GBE_NoFenceDefined

2523 Empty topology will not be created. GBE_EmptyTopology

2524 Attempt to produce an overlay layer in a previously populated topology layer.

GBE_LayerAlreadyPopulated

2525 Error when trying to generate an overlay. GBE_ErrorGeneratingOverlay

2526 The topology SQL statement has not been set. GBE_SqlNotSpecified

8-216 MicroStation BASIC Guide

Page 527: 48784209 Microstation Basic

Category Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 217 Friday, October 15, 1999 1:27 PM

Category Object

The properties and methods listed below in this table refer to a GbeCategory object and the category table slot to which it refers.

GbeCategories.maxCategoriesGbeCategories.maxCategories

Descr. The GbeCategories.maxCategories read-only property returns an Integer that is the maximum number of categories which are available to the currently open project.

GbeCategories.listByMslinkvalue = GbeCategories.listByMslink(array() as Long)

Properties and Methods Used to

GbeCategories.maxCategories (page 8-217)

determine the maximum number of categories that are available in the currently open project.

GbeCategories.listByMslink (page 8-217)

propagate a Long array with a list of category mslinks available in the currently open project.

GbeCategories(index) (page 8-218) return an individual GbeCategory object corresponding to the category identified by index.

GbeCategories.indexFromMslink (page 8-218)

return the index number of the GbeCategory object identified by mslink.

Properties and Methods Used to

GbeCategory.attachMaps (page 8-218) attach all maps associated with the category.

GbeCategory.cellLibrary (page 8-218) retrieve the cell library name of the category.

GbeCategory.detachMaps (page 8-218) detach all maps associated with the category.

GbeCategory.fileExt (page 8-219) retrieve the file extension of the category.

GbeCategory.listFeaturesByMslink (page 8-219)

propagate a Long array with the mslinks of all feature associated with the category.

GbeCategory.listMapsByMslink (page 8-219)

propagate a Long array with the mslinks of all maps currently available to the category.

GbeCategory.mslink (page 8-219) retrieve the mslink of the category.

GbeCategory.name (page 8-219) retrieve the name of the category.

MicroStation BASIC Guide 8-217

Page 528: 48784209 Microstation Basic

Category Object

600macro.bk : 608_EXT.FRA Page 218 Friday, October 15, 1999 1:27 PM

Descr. The GbeCategories.listByMslink command propagates array with Longs corresponding to the mslinks of all categories available in the currently open project. Returns the number of category mslinks added to array.

GbeCategories(index)GbeCategories(index)

Descr. GbeCategories(index) retrieves the GbeCategory object associated with the index. The properties of the GbeCategory object to be retrieved can be directly referenced, or a GbeCategory object can be declared and set to GbeCategory(index).

Example Dim iCat as IntegerFor iCat = 1 to GbeCategories.maxCategories

print "Category Names: " & GbeCateogies(iCat).nameNext iCat

GbeCategories.indexFromMslinkvalue = GbeCategories.indexFromMslink(mslink as Long)

Descr. GbeCategories.indexFromMslink returns an Integer representing the index of the GbeCategory matching mslink. Zero is returned if no GbeCategory is found.

GbeCategory.attachMapsstat = GbeCategory.attachMaps()

Descr. The GbeCategory.attachMaps command will attach all maps associated with the category being referenced. Returns the number of maps attached.

GbeCategory.cellLibraryGbeCategory.cellLibrary

Descr. The GbeCategory.cellLibrary read-only property returns a String that corresponds to the category cell library.

GbeCategory.detachMapsstat = GbeCategory.detachMaps()

8-218 MicroStation BASIC Guide

Page 529: 48784209 Microstation Basic

Category Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 219 Friday, October 15, 1999 1:27 PM

Descr. The GbeCategory.detachMaps command will detach all maps associated with the category being referenced. Returns the number of maps detached.

GbeCategory.fileExtGbeCategory.fileExt

Descr. The GbeCategory.fileExt read-only property returns a String that corresponds to the category file extension.

GbeCategory.listFeaturesByMslinkvalue = GbeCategory.listFeaturesByMslink(array() as Long)

Descr. The GbeCategory.listFeaturesByMslink command propagates array with Longs corresponding to the mslinks of all features associated to the category being referenced. Returns the number of features associated with the specified category.

GbeCategory.listMapsByMslinkvalue = GbeCategory.listMapsByMslink(array() as Long)

Descr. The GbeCategory.listMapsByMslink command propagates array with Longs corresponding to the mslinks of all maps available to the category being referenced. Returns the number of maps associated with the specified category.

GbeCategory.mslinkGbeCategory.mslink

Descr. The GbeCategory.mslink read-only property returns an Integer that corresponds to the category mslink.

GbeCategory.nameGbeCategory.name

Descr. The GbeCategory.name read-only property returns a String that corresponds to the category name.

Example Sub mainDim iMax as IntegerDim catList() as LongDim i as IntegerDim taxCategory as GbeCategory

iMax = GbeCategories.listByMslink(catList)

For i = 1 to iMax

MicroStation BASIC Guide 8-219

Page 530: 48784209 Microstation Basic

Category Object

600macro.bk : 608_EXT.FRA Page 220 Friday, October 15, 1999 1:27 PM

print "Category Name: " & GbeCategories(i).nameprint " Mslink : " & str$(catList(i-1))print " File Ext : " & GbeCategories(i).fileExtprint

Next i

numMaps = GbeCategories(2).attachMaps ()print "Number of maps attached: " & str$(numMaps)

Set taxCategory = GbeCategories (2)

print taxCategory.name & " category mslink is" & _str$(taxCategory.mslink)

End Sub

Category Error Codes

Error Number

Error Message Built-in Constant Name

2530 An invalid category index has been entered. The index specifying the category object has exceeded the maximum number of category indexes.

GBE_InvalidCategoryIndex

8-220 MicroStation BASIC Guide

Page 531: 48784209 Microstation Basic

Feature Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 221 Friday, October 15, 1999 1:27 PM

Feature Object

The properties and methods listed below in this table refer to a GbeFeature object and the feature table slot to which it refers.

GbeFeatures.maxFeaturesGbeFeatures.maxCategories

Descr. The GbeFeatures.maxCategories read-only property returns an Integer that is the maximum number of features which are available to the currently open project.

GbeFeatures.listByMslinkvalue = GbeFeatures.listByMslink(array() as Long)

Properties and Methods Used to

GbeFeatures.maxFeatures (page 8-221)

determine the maximum number of features that are available in the currently open project.

GbeFeatures.listByMslink (page 8-221)

propagate a Long array with a list of feature mslinks available in the currently open project.

GbeFeatures(index) (page 8-222) return an individual GbeFeature object corresponding to the feature identified by index.

GbeFeatures.indexFromMslink (page 8-222)

return the index number of the GbeFeature object identified by mslink.

Properties and Methods Used to

GbeFeature.categoryMslink (page 8-222)

retrieve the category mslink of the feature.

GbeFeature.color (page 8-222) retrieve the color of the feature.

GbeFeature.description (page 8-222)

retrieve the description of the feature.

GbeFeature.display (page 8-223)

turn on or off the display of the feature.

GbeFeature.level (page 8-223) retrieve the level of the feature.

GbeFeature.mslink (page 8-223) retrieve the mslink of the feature.

GbeCategory.name (page 8-219) retrieve the name of the feature.

GbeFeature.style (page 8-223) retrieve the style of the feature.

GbeFeature.type (page 8-223) retrieve the type of feature element.

GbeFeature.weight (page 8-224) retrieve the weight of the feature.

MicroStation BASIC Guide 8-221

Page 532: 48784209 Microstation Basic

Feature Object

600macro.bk : 608_EXT.FRA Page 222 Friday, October 15, 1999 1:27 PM

Descr. The GbeFeatures.listByMslink command propagates array with Longs corresponding to the mslinks of all features available in the currently open project. Returns the number of features added to array.

GbeFeatures(index)GbeFeatures(index)

Descr. GbeFeatures(index) retrieves the GbeFeature object associated with the index. The properties of the GbeFeature object so retrieved can be directly referenced, or a GbeFeature object can be declared and Set to GbeFeature(index).

Example Dim iFea as IntegerFor iFea = 1 to GbeFeature.maxFeatures

print "Feature Names: " & GbeFeatures(iFea).nameNext iFea

GbeFeatures.indexFromMslinkvalue = GbeFeatures.indexFromMslink(mslink as Long)

Descr. GbeFeatures.indexFromMslink returns an Integer representing the index of the GbeFeature matching mslink. Zero is returned if GbeFeature is found.

GbeFeature.categoryMslinkGbeFeature.categoryMslink

Descr. The GbeFeature.categoryMslink read-only property returns a Long that corresponds to the feature’s category mslink.

GbeFeature.colorGbeFeature.color

Descr. The GbeFeature.color read-only property returns an Integer that corresponds to the feature color.

GbeFeature.descriptionGbeFeature.description

8-222 MicroStation BASIC Guide

Page 533: 48784209 Microstation Basic

Feature Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 223 Friday, October 15, 1999 1:27 PM

Descr. The GbeFeature.description read-only property returns a String that corresponds to the feature description.

GbeFeature.displayGbeFeature.display(view as Integer, apply as [GBE_True,GBE_False],onOff _as [GBE_True, GBE_False])

Descr. The GbeFeature.display command will either turn on or off the display of the GbeFeature specified by view. Set apply to true if you wish to apply the changes to the specified view; otherwise, the changes to display will be updated. OnOff specifies whether or not to turn the feature on or off. Specify the view which the feature should be displayed [1 - 8].

GbeFeature.levelGbeFeature.level

Descr. The GbeFeature.level read-only property returns an Integer that corresponds to the feature level.

GbeFeature.mslinkGbeFeature.mslink

Descr. The GbeFeature.mslink read-only property returns an Integer that corresponds to the feature mslink.

GbeFeature.nameGbeFeature.name

Descr. The GbeFeature.name read-only property returns a String that corresponds to the feature name.

GbeFeature.styleGbeFeature.style

Descr. The GbeFeature.style read-only property returns an Integer that corresponds to the feature style.

GbeFeature.typeGbeFeature.type

MicroStation BASIC Guide 8-223

Page 534: 48784209 Microstation Basic

Feature Object

600macro.bk : 608_EXT.FRA Page 224 Friday, October 15, 1999 1:27 PM

Descr. The GbeFeature.type read-only property returns an Integer that corresponds to the feature type.

GbeFeature.weightGbeFeature.weight

Descr. The GbeFeature.weight read-only property returns an Integer that corresponds to the feature weight.

Feature Error Codes

Error Number

Error Message Built-in Constant Name

2540 An invalid feature index has been entered. The index specifying the feature object has exceeded the maximum number of feature indexes.

GBE_InvalidFeatureIndex

8-224 MicroStation BASIC Guide

Page 535: 48784209 Microstation Basic

Map Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 225 Friday, October 15, 1999 1:27 PM

Map Object

The properties and methods listed below in this table refer to a GbeMap object and the map table slot to which it refers.

GbeMaps.maxMapsGbeMaps.maxMaps

Descr. The GbeMaps.maxMaps read-only property returns an Integer that is the maximum number of maps which are available to the currently open project.

GbeMaps.listByMslinkvalue = GbeMaps.listByMslink(array() as Long)

Properties and Methods Used to

GbeMaps.maxMaps (page 8-225) determine the maximum number of maps that are available in the currently open project.

GbeMaps.listByMslink (page 8-225)

propagate a long array with a list of map mslinks available in the currently open project.

GbeMaps.attachByView (page 8-226)

attach all maps included in a specified view.

GbeMaps(index) (page 8-226) return an individual GbeMap object corresponding to the map identified by index.

GbeMaps.indexFromMslink (page 8-226)

return the index number of the GbeMap object identified by mslink.

Properties and Methods Used to

GbeMap.mslink (page 8-226) retrieve the mslink of the map.

GbeMap.name (page 8-226) retrieve the name of the map.

GbeMap.description (page 8-227)

retrieve the description of the map.

GbeMap.directory (page 8-227) retrieve the directory of the map if not in project/dgn.

GbeMap.attach (page 8-227) attach the map being referenced.

GbeMap.detach (page 8-227) detach the map being referenced.

GbeMap.isAttached (page 8-227) return whether or not the map being referenced is currently attached.

GbeMap.categoryMslink (page 8-227)

retrieve the category mslink of the map.

MicroStation BASIC Guide 8-225

Page 536: 48784209 Microstation Basic

Map Object

600macro.bk : 608_EXT.FRA Page 226 Friday, October 15, 1999 1:27 PM

Descr. The GbeMaps.listByMslink command propagates array with Longs corresponding to the mslinks of all maps available in the currently open project. The number of map mslinks added to array will be returned.

GbeMaps.attachByViewvalue = GbeMaps.attachByView(view as Integer)

Descr. The GbeMaps.attachByView command will attach all maps included in the view specified. Will return the number of maps attached as an Integer.

GbeMaps(index)GbeMaps(index)

Descr. GbeMaps(index) retrieves the GbeMap object associated with index. The properties of the GbeMap object so retrieved can be directly referenced, or an GbeMap object can be declared and set to GbeMap(index).

Example Dim iMap as IntegerFor iMap = 1 to GbeMaps.maxMaps

print "Map Names: " & GbeMaps(iMap).nameNext iMap

GbeMaps.indexFromMslinkvalue = GbeMaps.indexFromMslink (mslink as Long)

Descr. GbeMaps.indexFromMslink returns an Integer value representing the index of the GbeMap matching mslink. Zero is returned if no GbeMap is found.

GbeMap.mslinkGbeMap.mslink

Descr. The GbeMap.mslink read-only property returns an Integer that corresponds to the map mslink.

GbeMap.nameGbeMap.name

8-226 MicroStation BASIC Guide

Page 537: 48784209 Microstation Basic

Map Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 227 Friday, October 15, 1999 1:27 PM

Descr. The GbeMap.name read-only property returns a String that corresponds to the map name.

GbeMap.descriptionGbeMap.description

Descr. The GbeMap.description read-only property returns a String that corresponds to the map description.

GbeMap.directoryGbeMap.directory

Descr. The GbeMap.directory read-only property returns a String that corresponds to the map file directory if something other than project/dgn.

GbeMap.attachGbeMap.attach

Descr. The GbeMap.attach object command will attach the map currently being referenced.

GbeMap.detachGbeMap.detach

Descr. The GbeMap.detach object command will detach the map currently being referenced.

GbeMap.isAttachedstat = GbeMap.isAttached()

Descr. The GbeMap.isAttached object function returns an Integer that is nonzero if the map specified is attached.

GbeMap.categoryMslinkGbeMap.categoryMslink

Descr. The GbeMap.categoryMslink read-only property returns a Long that corresponds to the category mslink of the map being referenced.

Example Sub mainDim iMap as IntegerDim maps() as Long

iMap = GbeMaps.listByMslink (maps)

MicroStation BASIC Guide 8-227

Page 538: 48784209 Microstation Basic

Map Object

600macro.bk : 608_EXT.FRA Page 228 Friday, October 15, 1999 1:27 PM

For i = 1 to iMap print "Map Name:" & GbeMaps(i).nameprint " Mslink: " & str$(GbeMaps(i).mslink)print " Directory: " & GbeMaps(i).directoryprint " Description: " & GbeMaps(i).descriptionprint

next iGbeMaps.attachByView 8

End Sub

Map Error Codes

Error Number

Error Message Built-in Constant Name

2510 An invalid map index has been entered. The index specifying the map object has exceeded the maximum number of map indexes.

GBE_InvalidMapIndex

8-228 MicroStation BASIC Guide

Page 539: 48784209 Microstation Basic

Project Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 229 Friday, October 15, 1999 1:27 PM

Project Object

GbeProject.DBconnectGbeProject.DBconnect [GBE_True, GBE_False]

Descr. The GbeProject.DBconnect write-only property will set whether or not to create a connection to the relational database using the name provided with GbeProject.loginName.

GbeProject.DBloadGbeProject.DBload [GBE_True, GBE_False]

Descr. The GbeProject.DBload write-only property will set whether or not to load the project tables from the relational database. If GbeProject.DBconnect is being used but GbeProject.DBload is not, the project database information will be loaded from the export file name specified by GbeProject.exportFile.

GbeProject.directoryGbeProject.directory

Properties and Methods Used to

GbeProject.DBconnect (page 8-229)

Set whether or not to connect to the database.

GbeProject.DBload (page 8-229) Set whether or not to load the database.

GbeProject.directory (page 8-229)

Get or set the project directory.

GbeProject.exportFile (page 8-230)

Get or set the project export file.

GbeProject.keyMap (page 8-230) Set whether or not to load the Key Map.

GbeProject.loginName (page 8-230)

Get or set the project database login name.

GbeProject.mapManager (page 8-230)

Set whether or not to load the MAPS table.

GbeProject.workMap (page 8-230)

Set whether or not open a blank GeoGraphics Work Map.

GbeProject.open (page 8-230) Performs a project open.

GbeProject.close (page 8-231) Performs a project close.

MicroStation BASIC Guide 8-229

Page 540: 48784209 Microstation Basic

Project Object

600macro.bk : 608_EXT.FRA Page 230 Friday, October 15, 1999 1:27 PM

Descr. The GbeProject.directory write-only String property sets or retrieves the directory name of the project to be opened.

GbeProject.exportFileGbeProject.exportFile

Descr. The GbeProject.exportFile write-only String property sets or retrieves the export filename of the project to be opened.

GbeProject.keyMapGbeProject.keyMap [GBE_True, GBE_False]

Descr. The GbeProject.keyMap write-only property will set whether or not to load the Key Map into the Key View window display. The GbePorject.mapManager must be set to GBE_True for this option to take affect.

GbeProject.loginNameGbeProject.loginName

Descr. The GbeProject.loginName write-only String property sets or retrieves the login name of the project to be opened.

GbeProject.mapManagerGbeProject.mapManager [GBE_True, GBE_False]

Descr. The GbeProject.mapManager write-only property will set whether or not to load the MAPS table (to make available for attachment) when GeoGraphics is started.

GbeProject.workMapGbeProject.workMap [GBE_True, GBE_False]

Descr. The GbeProject.workMap write-only property will set whether or not to close the master design file and open a blank GeoGraphics Work map.

GbeProject.openGbeProject.open

8-230 MicroStation BASIC Guide

Page 541: 48784209 Microstation Basic

Project Object

Mic

roSt

atio

n Ex

tens

ions

to

BA

SIC

8

600macro.bk : 608_EXT.FRA Page 231 Friday, October 15, 1999 1:27 PM

Descr. The GbeProject.open command will attempt to open a project based upon the information setup previously. A runtime error will be generated if the project cannot be opened.

GbeProject.closeGbeProject.close

Descr. The GbeProject.close command will close the currently open project.

Example Sub mainDim status as Integer

GbeProject.loginName = "mytown"GbeProject.DBconnect = GBE_TrueGbeProject.DBload = GBE_FalseGbeProject.workMap = GBE_TrueGbeProject.exportFile = "c:\projects\mytown\mytown.exp"GbeProject.directory = "c:\projects\mytown\"GbeProject.open

...Perform project functionsGbeProject.close

End Sub

Project Error Codes

Error Number

Error Message Built-in Constant Name

2501 An invalid project directory name has been specified. Either the path is not valid or the appropriate project files/directories do not exist.

GBE_InvalidProjDir

2502 An invalid database login name has been specified.

GBE_InvalidDBLogin

2503 If DBLoad property has been set to GBE_False, the user must provide an export file name (absolute path) for table information. If the export file has not been specified or is an invalid file, this error will be returned.

GBE_InvalidExportFile

2504 If the user attempts to open a project while one is currently open, this error will be returned.

GBE_ProjectAlreadyOpen

MicroStation BASIC Guide 8-231

Page 542: 48784209 Microstation Basic

Project Object

600macro.bk : 608_EXT.FRA Page 232 Friday, October 15, 1999 1:27 PM

8-232 MicroStation BASIC Guide

Page 543: 48784209 Microstation Basic

600macro.bk : 609_ERRO.FRA Page 1 Friday, October 15, 1999 1:27 PM

9 Error Codes

“error.pdf”

When you encounter an error in your macro, use the tables in the following sections to determine the error that corresponds to the error number. The errors are divided into runtime errors (those encountered while the macro is executing), and compiler errors (those encountered when the macro begins executing).

Runtime Error MessagesThis section contains listings of all the runtime errors. It is divided into two sections, the first describing errors messages compatible with “standard” BASIC, as implemented by Microsoft Visual Basic, and the second describing error messages specific to MicroStation’s implementation of and extensions to the BASIC language.

MicroStation BASIC Guide 9-1

Page 544: 48784209 Microstation Basic

Runtime Error Messages

600macro.bk : 609_ERRO.FRA Page 2 Friday, October 15, 1999 1:27 PM

Visual Basic Compatible Error Messages

ErrorNumber

Error Message Built-in Constant Name

3 Return without gosub

5 Illegal function call MBE_IllegalFunctionCall

6 Overflow MBE_Overflow

7 Out of memory MBE_OutOfMemory

9 Subscript out of range MBE_IndexOutOfBounds

11 Divide by zero

13 Type mismatch MBE_TypeMismatch

14 Out of string space MBE_OutOfStringSpace

19 No Resume

20 Resume without error

28 Out of stack space

35 Sub or Function not defined MBE_SubFuncNotDefined

51 Internal error

52 Bad file name or number MBE_BadFileNumber

53 File not found MBE_FileNotFound

54 Bad file mode MBE_BadFileMode

55 File already open

57 Device I/O error

58 File already exists

59 Bad record length

61 Disk full MBE_DiskFull

62 Input past end of file

63 Bad record number MBE_BadRecordNumber

64 Bad file name

67 Too many files MBE_TooManyChannels

68 Device unavailable

70 Permission denied MBE_AccessDenied

71 Disk not ready

74 Can’t rename with different drive

75 Path/File access error MBE_FileAccessError

76 Path not found

91 Object variable not Set MBE_ObjectVariableNotSet

93 Invalid pattern string MBE_PatternInvalid

281 No more DDE channels(Windows platforms only)

9-2 MicroStation BASIC Guide

Page 545: 48784209 Microstation Basic

Runtime Error Messages

Erro

r C

odes

9

600macro.bk : 609_ERRO.FRA Page 3 Friday, October 15, 1999 1:27 PM

282 No foreign application responded to a DDE initiate(Windows platforms only)

283 Multiple applications responded to a DDE initiate(Windows platforms only)

285 Foreign application won’t perform DDE method or operation(Windows platforms only)

286 Timeout while waiting for DDE response(Windows platforms only)

287 User pressed escape key during DDE operation(Windows platforms only)

288 Destination is busy(Windows platforms only)

289 Data not provided in DDE operation(Windows platforms only)

290 Data in wrong format(Windows platforms only)

291 Foreign application quit(Windows platforms only)

292 DDE conversation closed or changed(Windows platforms only)

295 Message queue filled; DDE message lost(Windows platforms only)

298 DDE requires ddeml.dll(Windows platforms only)

MBE_NoDDEML

ErrorNumber

Error Message Built-in Constant Name

MicroStation BASIC Guide 9-3

Page 546: 48784209 Microstation Basic

Runtime Error Messages

600macro.bk : 609_ERRO.FRA Page 4 Friday, October 15, 1999 1:27 PM

MicroStation Error Messages

ErrorNumber

Error Message Built-in Constant Name

801 Too many dimensions MBE_WrongDimension

806 Invalid DDE Channel MBE_InvalidChannel

825 Can’t redimension a fixed array MBE_RedimFixedArray

826 Can’t load and initialize extension

827 Can’t find extension

1100 Can’t parse string MBE_CantParseString

1101 Wrong input type MBE_WrongInputType

1102 Command received MBE_ReceivedCommand

1201 Unable to read element MBE_CantReadElemDscr

1202 Invalid level MBE_InvalidLevel

1203 Invalid color MBE_InvalidColor

1204 Invalid weight MBE_InvalidWeight

1205 Invalid line style MBE_InvalidStyle

1206 Invalid element class MBE_InvalidClass

1207 Wrong element type MBE_WrongElemType

1208 Unable to rewrite element MBE_CantRewrite

1209 Font not found MBE_FontNotFound

1210 Component not found MBE_ComponentNotFound

1211 Element off design plane MBE_NotOnDesignPlane

1212 Not enough points MBE_NotEnoughPoints

1213 Too many points MBE_TooManyPoints

1214 Error in array processing MBE_ArrayError

1215 Component of a complex element MBE_ComplexComponent

1216 Writing to design file inhibited MBE_WriteInhibit

1217 No more component elements MBE_NoMoreElems

1218 Not component of a complex element MBE_NotComplex

1219 Bad element MBE_BadElement

1301 No selection set MBE_NoSelectionSet

1302 No fence MBE_NoFence

1303 Must get set from user MBE_MustGetFromUser

1304 No more elements in set MBE_NoMoreInSet

1401 String too long MBE_StringTooLong

1501 Invalid view number MBE_InvalidView

1601 Invalid reference file number MBE_InvalidRefFile

1602 Defer saving reference file information MBE_RefSaveDeferred

9-4 MicroStation BASIC Guide

Page 547: 48784209 Microstation Basic

Compiler Error Messages

Erro

r C

odes

9

600macro.bk : 609_ERRO.FRA Page 5 Friday, October 15, 1999 1:27 PM

Compiler Error MessagesThe following table contains a list of all the errors generated by the built-in BASIC compiler. With some errors, the compiler changes placeholders within the error to text from the script being compiled. These placeholders are represented in this table by two single quotes (' ').

1701 Data type not supported MBE_UnsupportedDataType

1702 Variable not found MBE_VariableNotFound

1703 Variable wrong type MBE_VariableWrongType

1801 Graphics subsystem not initialized MBE_NoGraphics

Error Number Error Message

1 Letter range must be in ascending order

2 Redefinition of default type

3 Out of memory, too many variables defined

4 Type character doesn’t match defined type

5 Expression too complex

6 Cannot assign whole array

7 Assignment variable and expression are different types

8 Identifier is not an array variable

9 Array type mismatch in parameter

10 Array type expected for parameter

11 Array type unexpected for parameter

12 Integer expression expected for an array index

13 Integer expression expected

14 String expression expected

15 Long expression expected

16 Invalid dialog element

17 Left of '.' must be an object or structure

18 Invalid string operator

19 Can’t apply operator to array type

20 Operator type mismatch

21 ' ' is not a variable

22 ' ' is not a array variable or a function

23 Unknown ' ' ' '

ErrorNumber

Error Message Built-in Constant Name

MicroStation BASIC Guide 9-5

Page 548: 48784209 Microstation Basic

Compiler Error Messages

600macro.bk : 609_ERRO.FRA Page 6 Friday, October 15, 1999 1:27 PM

24 Out of memory

25 ' ': Too many parameters encountered

26 ' ': Missing parameter(s)

27 ' ': Type mismatch in parameter ' '

28 Missing label ' '

29 Too many nested statements

30 Encountered newline in string

31 Overflow in decimal value

32 Overflow in hex value

33 Overflow in octal value

34 Expression is not constant

35 Function name not explicitly typed or missing type character

36 No type characters allowed on parameters with explicit type

37 Missing type for variable

38 Can’t pass an array by value

39 ' ' is already declared as a parameter

40 Variable name used as label name

41 Duplicate label

42 Not inside a function

43 Not inside a sub

44 Long expression expected

45 Can’t assign to function

46 Identifier is already a variable

47 Unknown type

48 Variable is not an array type

49 Can’t redimension an array to a different type

50 Identifier is not an string array variable

51 0 expected

52 Parameter 1: string expected

53 Parameter 2: string expected

54 Integer expression expected for file number

55 Unsubscripted array in expression

56 String variable expected for parameter 1

57 Expecting 0 or 1

58 Boolean expression expected.

59 Numeric expression expected

60 Numeric type FOR variable expected

61 For...Next variable mismatch

Error Number Error Message

9-6 MicroStation BASIC Guide

Page 549: 48784209 Microstation Basic

Compiler Error Messages

Erro

r C

odes

9

600macro.bk : 609_ERRO.FRA Page 7 Friday, October 15, 1999 1:27 PM

62 Out of string storage space

63 Out of identifier storage space

64 Internal error 1

65 Maximum line length exceeded

66 Internal error 3

67 Division by zero

68 Overflow in expression

69 Floating point expression expected

70 Floating point expression expected

71 Invalid floating point operator

72 Math error

73 Single character expected

74 Subroutine identifier can’t have a type declaration character

75 Script is too large to be compiled

76 Variable type expected

77 Types and dialog variables can’t be passed by value

78 Can’t assign to user type variable

79 Maximum string length exceeded

80 Identifier name already in use as another type

81 Left of '.' must be an object or structure

82 Operator result on variant type is ambiguous

83 Operator cannot be used on an object

84 ' ' is not a property or method of the object

85 Type character on label

86 Type character mismatch on routine ' '

87 Destination name is already a constant

88 Can’t assign to constant

89 Error in format of compiler extensions

90 Identifier too long

91 Expecting string or structure expression

92 Can’t assign to expression

93 Object types are not supported in this context

94 Array expression not supported as parameter

95 Objects and structures expressions are not supported as a parameter

96 Invalid numeric operator

97 Invalid structure element name following '.'

98 Access value can’t be used with specified mode

Error Number Error Message

MicroStation BASIC Guide 9-7

Page 550: 48784209 Microstation Basic

Run-time error codes

600macro.bk : 609_ERRO.FRA Page 8 Friday, October 15, 1999 1:27 PM

Run-time error codesThe following tables shows the defined run-time error codes:

Topology Error CodesThe following tables shows the topology error codes:

99 Use the SET statement to assign objects

100 Invalid operator for object

101 Can’t LSet a type with a variable length string

102 Syntax Error

103 ' ' is not a method of the object

104 No members defined

105 Duplicate type member

106 Set is for object assignments

107 Type character mismatch on variable

108 Identifier already defined as a different type

Error Number Error Message

1901 Invalid block name

1902 Invalid cell name

1903 Cannot open table file

1904 Invalid font filename

1905 Invalid font number

1906 Invalid settings value

ErrorNumber

Error Message Built-in Constant Name

2520 Error when trying to initialize the topology layer.

GBE_TopologyInitFail

2521 The topology layer name has not been defined.

GBE_NoLayerName

2522 No fence has been placed previous to performing topology load.

GBE_NoFenceDefined

Error Number Error Message

9-8 MicroStation BASIC Guide

Page 551: 48784209 Microstation Basic

Category Error Codes

Erro

r C

odes

9

600macro.bk : 609_ERRO.FRA Page 9 Friday, October 15, 1999 1:27 PM

Category Error CodesThe following tables shows the category error codes:

Feature Error CodesThe following tables shows the feature error codes:

2523 Empty topology will not be created.

GBE_EmptyTopology

2524 Attempt to produce an overlay layer in a previously populated topology layer.

GBE_LayerAlreadyPopulated

2525 Error when trying to generate an overlay.

GBE_ErrorGeneratingOverlay

2526 The topology SQL statement has not been set.

GBE_SqlNotSpecified

ErrorNumber

Error Message Built-in Constant Name

2530 An invalid category index has been entered. The index specifying the category object has exceeded the maximum number of category indexes.

GBE_InvalidCategoryIndex

ErrorNumber

Error Message Built-in Constant Name

2540 An invalid feature index has been entered. The index specifying the feature object has exceeded the maximum number of feature indexes.

GBE_InvalidFeatureIndex

ErrorNumber

Error Message Built-in Constant Name

MicroStation BASIC Guide 9-9

Page 552: 48784209 Microstation Basic

Map Error Codes

600macro.bk : 609_ERRO.FRA Page 10 Friday, October 15, 1999 1:27 PM

Map Error CodesThe following tables shows the map error codes:

Project Error CodesThe following tables shows the project error codes:

ErrorNumber

Error Message Built-in Constant Name

2510 An invalid map index has been entered. The index specifying the map object has exceeded the maximum number of map indexes.

GBE_InvalidMapIndex

ErrorNumber

Error Message Built-in Constant Name

2501 An invalid project directory name has been specified. Either the path is not valid or the appropriate project files/directories do not exist.

GBE_InvalidProjDir

2502 An invalid database login name has been specified.

GBE_InvalidDBLogin

2503 If DBLoad property has been set to GBE_False, the user must provide an export file name (absolute path) for table information. If the export file has not been specified or is an invalid file, this error will be returned.

GBE_InvalidExportFile

2504 If the user attempts to open a project while one is currently open, this error will be returned.

GBE_ProjectAlreadyOpen

9-10 MicroStation BASIC Guide

Page 553: 48784209 Microstation Basic

600macro.bk : 6A_OLE.FRA Page 1 Friday, October 15, 1999 1:27 PM

Appendix A: OLE Automation

OLE Automation is just one of many Windows OLE2 standards developed to help users make programs work together. The intent of OLE Automation is to define and standardize a way for applications to expose their functionality to the outside world.

Programs that expose their functionality are referred to as OLE Automation Servers. Programs that implement the protocol to access that functionality via the exposed interface are referred to as OLE Automation Controllers. Examples of OLE Automation Controllers include Microsoft Visual Basic and various implementations of Visual Basic for Applications embedded in applications such as Microsoft Excel. Since MicroStation is an OLE Automation Server, it is possible to use a number of these OLE Automation controllers to program MicroStation.

OLE Automation Servers expose their functionality through objects that encapsulate related properties or methods of an application, just as MicroStation BASIC exposes its programming interface through the object model. Thus it should come as no surprise that MicroStation exposes the same set of objects through OLE Automation that are available through MicroStation BASIC. To program MicroStation using OLE Automation, first familiarize yourself with the objects and techniques used in MicroStation BASIC. With very few exceptions, those concepts carry over directly to using OLE Automation. The intent of this section is to provide the information you need to program MicroStation using OLE Automation once you are familiar with MicroStation BASIC. The examples shown here are appropriate to Microsoft Visual Basic Version 4.0, but you can apply the same concepts to the OLE Automation Controller of your choice.

✍ In order to use MicroStation’s OLE Automation features, you must run either Windows 95 or Windows NT, since multithreading support is required. Furthermore, since many of MicroStation’s OLE Automation methods use read/write arguments, an OLE Automation Controller capable of passing arguments by reference is required. Since Visual Basic Version 3.0 does not provide this capability, Visual Basic Version 4.0 is required.

MicroStation BASIC Guide A-1

Page 554: 48784209 Microstation Basic

Differences Between MicroStation BASIC and OLE Automation

600macro.bk : 6A_OLE.FRA Page 2 Friday, October 15, 1999 1:27 PM

Differences Between MicroStation BASIC and OLE Automation

The Application objectOLE Automation Servers must supply an “Application” object. The Application object provides access to top-level functionality of the application—that is, functionality that is not related to a specific object within the application. Such functionality in MicroStation BASIC is provided through “standalone” extension functions. For example, an extension function called MbeGetConfigVar returns the expansion of a MicroStation configuration variable. In MicroStation’s OLE Automation implementation, standalone extension functions are not allowed, so all such functions and statements are instead methods of the Application object. Thus, whereas in MicroStation BASIC, the syntax for retrieving a configuration variable expansion is:

Sub MainDim expConfigVar As String...expConfigVar = MbeGetConfigVar("MS_DEF")...

End Sub

In Visual Basic the syntax is:

’ Note: The Application object declaration is usually in‘ the public declarations section ’ so it can be used anywhere in the programDim msApp As Object

Sub MainDim expConfigVar As StringSet msApp = CreateObject("MicroStation.Application")...expConfigVar = msApp.MbeGetConfigVar("MS_DEF")...

End Sub

The line creating the msApp object must be executed only once in the program. To convert a program from MicroStation BASIC to Visual Basic, find all the standalone extension functions and make them methods of the MicroStation Application Object.

A-2 MicroStation BASIC Guide

Page 555: 48784209 Microstation Basic

Differences Between MicroStation BASIC and OLE Automation

Ap

pen

dix

A: O

LE A

utom

atio

n

600macro.bk : 6A_OLE.FRA Page 3 Friday, October 15, 1999 1:27 PM

MicroStation-defined constants MicroStation BASIC defines a number of constants that are available for use by any MicroStation BASIC program. For example, element type numbers are defined so that a Basic programmer doesn’t need to know that element type 3 is a line—he uses the MBE_Line constant instead.

Constants cannot be defined in the same manner by an OLE Automation Controller, so MicroStation uses the same approach as for standalone functions—all defined constants are implemented as read-only properties of the Application object. To test whether an element object is a line, the following code is appropriate for MicroStation BASIC:

If element.type = MBE_Line Then...

End If

while the following code is appropriate for Visual Basic:

If element.type = msApp.MBE_Line Then...

End If

When converting a MicroStation BASIC program to run with Visual Basic, make sure to check the code carefully to ensure that this change is made. Any other error made in converting the code from MicroStation BASIC to Visual Basic is caught as either a compile time or runtime error. If the defined constant change is not made and the code is left in MicroStation BASIC form, Visual Basic assumes MBE_Line is an undeclared variable and initializes it to zero, so the test erroneously tests to see if element.type is zero, clearly not the desired result.

Dim statementsIn MicroStation BASIC, MicroStation objects and their methods are known to the compiler, and can be used directly in a Dim statement. The MicroStation BASIC compiler, which is executed transparently whenever the code is modified, is responsible for checking to ensure the validity of the method or property name, and that it has the correct number and type of arguments, etc. This compile-time checking is a form of what is called “early binding”.

In contrast, OLE Automation supports only late binding—an actual object is associated with a variable only at runtime. At the time the code is compiled, the methods and properties of the

MicroStation BASIC Guide A-3

Page 556: 48784209 Microstation Basic

Differences Between MicroStation BASIC and OLE Automation

600macro.bk : 6A_OLE.FRA Page 4 Friday, October 15, 1999 1:27 PM

object are not known, so anything is accepted. The checks to determine if the method/property is valid and whether the arguments are correct occur at runtime. Since the compiler doesn’t know what applications and objects are going to be in use at runtime, all objects are declared simply as “Object,” and the association between the declared object and an actual object happens at runtime by assigning the object variable to the return value of a function or property that returns an object. MicroStation’s Application object implements a read-only property that returns an object of the correct type for each MicroStation BASIC object type.

Thus, in MicroStation BASIC you use the following code to specify that the variable “element” represents an MbeElement object and reads the first element in a design file:

Dim element As New MbeElementDim filePos As LongfilePos = element.fromFile(0)...

While in Visual Basic you use the following:

Dim element As ObjectDim filePos As LongSet element = msApp.mbeElementfilePos = element.fromFile(0)

MicroStation-defined “User-Defined Types”Both MicroStation BASIC and Visual Basic Version 4.0 support a concept called “User-Defined Types” (UDTs), which allow a programmer to group related variables using the Type statement. (If you’re familiar with C programming, you will recognize that UDTs and C structures are essentially the same thing.) In MicroStation BASIC, there are a number of pre-defined UDTs that are used as arguments to some of the object methods. Unfortunately, OLE Automation does not allow use of UDTs as arguments to methods or functions. To overcome this limitation, MicroStation implements objects having read/write properties with the same names as the field names in our pre-defined UDTs.

For example, the MicroStation BASIC MbePoint UDT consists of three Double fields, (x, y, z) and is used to send points to and retrieve points from some object methods. For OLE Automation, MicroStation defines an object having Double read/write properties x, y, and z. The syntax for using an object property and a UDT field are identical in Basic—in either case, the field/

A-4 MicroStation BASIC Guide

Page 557: 48784209 Microstation Basic

Differences Between MicroStation BASIC and OLE Automation

Ap

pen

dix

A: O

LE A

utom

atio

n

600macro.bk : 6A_OLE.FRA Page 5 Friday, October 15, 1999 1:27 PM

property names are separated from the UDT/object by the period character, “.”.

In Visual Basic, a point object is obtained in a manner similar to that of obtaining an MbeElement object (that is, as a read-only property of the MicroStation Application object). Every object method that takes a pre-defined UDT as an argument in MicroStation BASIC is implemented in OLE Automation as taking the argument as an Object instead. Putting this together in an example, suppose you want to get the origin of an element. In MicroStation BASIC you use the following code:

Dim origin As MbePointDim element As New MbeElement... (get the element from the file)If element.getOrigin(origin) = MBE_Success Then distFromOrigin = Sqr(origin.x * origin.x +

origin.y * origin.y + origin.z * origin.z)End If

With Visual Basic, you use the following code instead:

Dim origin As ObjectDim element As ObjectSet element = msApp.mbeElementSet origin = msApp.mbePoint... (get the element from the file)If element.getOrigin(origin) = msApp.MBE_Success Then distFromOrigin = Sqr(origin.x * origin.x +

origin.y * origin.y + origin.z * origin.z)End If

✍ In MicroStation 95, MicroStation BASIC supports using objects in place of the predefined UDTs. Objects with the same properties as the equivalent UDTs are named by adding the suffix Obj. Thus, in MicroStation BASIC you have the choice of representing a point as either MbePoint or MbePointObj. The MicroStation BASIC code for using the object form of point is:

Dim origin as New MbePointObjDim element as New MbeElement... (get the element from the file)If element.getOrigin(origin) = MBE_Success Then

distFromOrigin = Sqr(origin.x * origin.x +origin.y * origin.y + origin.z * origin.z)

End If

The UDT form is slightly more efficient, and is compatible with both MicroStation 95 and MicroStation PowerDraft, so it is generally preferred.

MicroStation BASIC Guide A-5

Page 558: 48784209 Microstation Basic

MicroStation Application methods

600macro.bk : 6A_OLE.FRA Page 6 Friday, October 15, 1999 1:27 PM

Special considerations

Converting a program from MicroStation BASIC to a Visual Basic program is generally fairly easy, consisting mostly of making the conversions listed above. There are, however, a few functions and object methods available in MicroStation BASIC that cannot be implemented in OLE Automation or require special consideration for OLE Automation.

MicroStation Application methods• The form of MbeSendDataPoint that takes separate x, y and z

arguments is not supported. The form that takes a MbePoint object as the first argument is supported.

• The form of MbeSendTentPoint that takes separate x, y and z arguments is not supported. The form that takes a MbePoint object as the first argument is supported.

• The form of MbeSendDragPoints that takes separate x, y and z arguments is not supported. The form that takes two MbePoint objects as the first two argument is supported.

• MbeSetAppVariable works a little differently under OLE Automation:

To use the form that takes a string argument, use msApp.MbeSetAppVariable as you would expect.

To use the form that takes a double as the third argument, use msApp.MbeSetAppVariableReal.

To use the form that takes a long as the third argument, use msApp.MbeSetAppVariableInteger.

• None of the dialog box methods are available under OLE Automation (MbeFileOpen, MbeFileCreate, MbeOpenModalDialog, MbeMessageBox, MbeInputBox, MbeMessageBox, MbeSelectBox). Use the tools provided by the native programming environment instead.

MbeElement methods

Visual Basic reserves the “scale” method name, so to scale an element, use MbeElement.scaleElem rather than “MbeElement.scale.”

A-6 MicroStation BASIC Guide

Page 559: 48784209 Microstation Basic

MicroStation Application methods

Ap

pen

dix

A: O

LE A

utom

atio

n

600macro.bk : 6A_OLE.FRA Page 7 Friday, October 15, 1999 1:27 PM

MbeCurrentTransform methods

Visual Basic reserves the “scale” method name, so to scale the current transformation, use MbeCurrentTransform.scaleTrans rather than “MbeElement.scale.”

OLE Automation-specific methods and objectsThis section describes a number of extensions that are available through OLE Automation but not applicable to MicroStation BASIC.

MicroStation Application object

As mentioned above, all the standalone extension functions of MicroStation BASIC are implemented as methods of the MicroStation Application object. In addition, there are a number of properties and methods standard for Application objects, including the following:

• Application—returns the MicroStation Application object. This is not very useful for the Application object, since it returns itself, but it is standard for all objects to implement a read-only property that returns the application object.

• ActiveDocument—returns the Document object for the current design file (read-only property).

• Caption—returns or sets the caption for the MicroStation application window (read/write property).

• FullName—returns the full path to the MicroStation executable—for example, c:\win32app\ustation\ustation.exe (read-only property).

• Name—returns the name of the MicroStation executable without the path—for example, ustation.exe (read-only property).

• Left—returns or sets the location of the left side of the MicroStation application window (read/write property).

• Top—returns or sets the location of the top of the MicroStation application window (read/write property).

• Width—returns or sets the width of MicroStation application window (read/write property).

• Height—returns or sets the height of MicroStation application window (read/write property).

• Parent—returns the Parent object of the object. This is not very useful for the Application object, since the Application object’s

MicroStation BASIC Guide A-7

Page 560: 48784209 Microstation Basic

600macro.bk : 6A_OLE.FRA Page 8 Friday, October 15, 1999 1:27 PM

Parent is always itself, but it is standard for all objects to implement a read-only property that returns the Parent object.

• Path—returns the path where the MicroStation executable resides—for example, c:\win32app\ustation (read-only property).

• Visible—returns or sets whether the MicroStation application window is visible (read/write property).

• Quit—uses MicroStation to exit (method).

Document object

The Document object is obtained from the ActiveDocument property of the Application object. It is used to access information about the current design file with OLE Automation-standard properties and methods. It includes the following properties and methods:

• Application—returns the application object (read-only property).

• FullName—returns the full path to the active design file—for example, c:\dgn\myfile.dgn (read-only property).

• Name—returns the name of the active design file without the path—for example, myfile.dgn (read-only property).

• Parent—returns the parent object, which is always MicroStation's application object (read-only property).

• Path—returns the path where the active design file is located—for example, c:\dgn. (read-only property).

• Readonly—returns whether the active design file is opened for read-only access (read-only property).

• Saved—returns whether the active design file has been saved to disk or not. Return TRUE always if in “continuous save” mode (read-only property).

• Save—Saves the active design file (method).

• Close—Closes the active design file.

Other MicroStation objects

The other MicroStation objects support “Application” and “Parent” properties. The “Application” read-only property returns the MicroStation Application object. The “Parent” read-only property returns the parent of the object to which it is applied; in the case of MicroStation objects, this is always the MicroStation Application object.

A-8 MicroStation BASIC Guide

Page 561: 48784209 Microstation Basic

MicroStation Application methods

Ap

pen

dix

A: O

LE A

utom

atio

n

600macro.bk : 6A_OLE.FRA Page 9 Friday, October 15, 1999 1:27 PM

ExamplesThe Visual Basic Version 4.0 project file “autodemo.vbp” shows an example of how the elemshow, currtrans, scaletxt, cellmod, and locate examples are converted to Visual Basic.

MicroStation BASIC Guide A-9

Page 562: 48784209 Microstation Basic

MicroStation Application methods

600macro.bk : 6A_OLE.FRA Page 10 Friday, October 15, 1999 1:27 PM

A-10 MicroStation BASIC Guide

Page 563: 48784209 Microstation Basic

600macro.bk : 6B_CONST.FRA Page 1 Friday, October 15, 1999 1:27 PM

Appendix B: MicroStation BASIC Constants

MbeGetInput Types Value

MBE_CommandInput 1

MBE_DataPointInput 2

MBE_ResetInput 3

MBE_KeyinInput 4

Misc. Constants Value

MBE_Success 0

MBE_MaxViews 8

MBE_On 1

MBE_Off 0

MBE_None 0

MBE_Linestyle 1

MBE_Color 2

MBE_Width 1

Element Types Value

MBE_CellLibraryHdr 1

MBE_CellHeader 2

MBE_Line 3

MBE_LineString 4

MBE_Shape 6

MBE_TextNode 7

MBE_Curve 11

MicroStation BASIC Guide B-1

Page 564: 48784209 Microstation Basic

MicroStation BASIC Constants

600macro.bk : 6B_CONST.FRA Page 2 Friday, October 15, 1999 1:27 PM

MBE_ComplexString 12

MBE_Conic 13

MBE_ComplexShape 14

MBE_Ellipse 15

MBE_Arc 16

MBE_Text 17

MBE_Surface 18

MBE_Solid 19

MBE_BSplinePole 21

MBE_PointString 22

MBE_Cone 23

MBE_BSplineSurface 24

MBE_BSplineBoundary 25

MBE_BSplineKnot 26

MBE_MSplineCurve 27

MBE_BSplineWeight 28

MBE_Dimension 33

MBE_SharedCellDefinition 34

MBE_SharedCell 35

MBE_MultiLine 36

MBE_Tag 37

MBE_RasterHeader 87

MBE_RasterComponent 88

Draw Modes Value

MBE_NormalDraw 0

MBE_Erase 1

MBE_Hilite 2

Element Types Value

B-2 MicroStation BASIC Guide

Page 565: 48784209 Microstation Basic

MicroStation BASIC Constants

Mic

roSt

atio

n B

ASI

C C

onst

ants

B

600macro.bk : 6B_CONST.FRA Page 3 Friday, October 15, 1999 1:27 PM

Element Classes Value

MBE_PrimaryClass 0

MBE_PatternClass 1

MBE_ConstructionClass 2

MBE_DimensionClass 3

MBE_PrimaryRuleClass 4

MBE_PatternedLineClass 5

MBE_ConstRuleClass 6

Element Properties Value

MBE_LockedProp 1

MBE_NewProp 2

MBE_ModifiedProp 4

MBE_AttributesProp 8

MBE_ViewIndProp 16

MBE_PlanarProp 32

MBE_NoSnapProp 64

MBE_HoleProp 128

Text Justification Value

MBE_LeftTop 0

MBE_LeftCenter 1

MBE_LeftBottom 2

MBE_LeftMarginTop 3

MBE_LeftMarginCenter 4

MBE_LeftMarginBottom 5

MicroStation BASIC Guide B-3

Page 566: 48784209 Microstation Basic

MicroStation BASIC Constants

600macro.bk : 6B_CONST.FRA Page 4 Friday, October 15, 1999 1:27 PM

MBE_CenterTop 6

MBE_CenterCenter 7

MBE_CenterBottom 8

MBE_RightMarginTop 9

MBE_RightMarginCenter 10

MBE_RightMarginBottom 11

MBE_RightTop 12

MBE_RightCenter 13

MBE_RightBottom 14

Pen Table Constants Value

MBE_ElemNormal 0

MBE_ElemIgnore 1

MBE_ElemPrioritize 2

Message Box Ids Value

MBE_OKBox 1

MBE_OKCancelBox 3

MBE_YesNoBox 12

MBE_YesNoCancelBox 14

Message Box Icon Ids Value

MBE_CriticalIcon 256

MBE_QuestionIcon 512

MBE_InfoIcon 1024

MBE_WarningIcon 2048

Text Justification Value

B-4 MicroStation BASIC Guide

Page 567: 48784209 Microstation Basic

MicroStation BASIC Constants

Mic

roSt

atio

n B

ASI

C C

onst

ants

B

600macro.bk : 6B_CONST.FRA Page 5 Friday, October 15, 1999 1:27 PM

Button Values Value

MBE_BUTTON_APPLY 1

MBE_BUTTON_OK 3

MBE_BUTTON_CANCEL 4

MBE_BUTTON_DEFAULT 5

MBE_BUTTON_YES 6

MBE_BUTTON_NO 7

MBE_BUTTON_RETRY 8

MBE_BUTTON_STOP 9

Product Codes Value

MBE_MicroStation 10

MBE_MSReview 30

MBE_MSPowerDraft 50

Database Constants Value

MBE_QueryNotFinished 0

MBE_QueryFinished 1

MBE_DBChar 1

MBE_DBNumber 2

MBE_DBDate 3

MBE_DBInteger 4

MBE_DBRaw 5

MBE_DBBinary 6

MicroStation BASIC Guide B-5

Page 568: 48784209 Microstation Basic

MicroStation BASIC Constants

600macro.bk : 6B_CONST.FRA Page 6 Friday, October 15, 1999 1:27 PM

Input Result Codes Value

MBE_Success 0

MBE_ElementNotFound 21

MBE_AcceptQuery 68

MBE_UnknownCommand 16

MBE_3DOnly 39

MBE_RefFileNotFound 7

MBE_ViewNotFound 18

MBE_IllegalDefinition 23

MBE_SelectView 196

MBE_OffDesignPlane 22

MBE_NeedChars 27

MBE_CellLibNotFound 12

MBE_NoCellLibrary 54

MBE_NoOrigin 56

MBE_NoFenceActive 57

MBE_EmptyFence 27

MBE_BadCellName 47

MBE_CellExists 55

MBE_CellNotFound 44

MBE_NoActiveCell 19

MBE_3DLib2DFile 50

MBE_CellDeleted 59

MBE_CellNestError 43

MBE_FileReadOnly 287

MBE_InvalidRefOp 481

B-6 MicroStation BASIC Guide

Page 569: 48784209 Microstation Basic

MicroStation BASIC Constants

Mic

roSt

atio

n B

ASI

C C

onst

ants

B

600macro.bk : 6B_CONST.FRA Page 7 Friday, October 15, 1999 1:27 PM

Database Link Constants Value

MBE_ORACLE_Linkage 8

MBE_INFORMIX_Linkage 1

MBE_RIS_Linkage 16

MBE_DMRS_Linkage 2

MBE_ODBC_Linkage 128

MBE_XBASE_Linkage 4

MBE_DBASE_Linkage 4

MBE_SYBASE_Linkage 64

MBE_INGRES_Linkage 32

Topology Layer Type Mask Value

GBE_TypePolygon 1

GBE_TypeLine 2

GBE_TypePoint 3

GBE_TypeMixed 4

Centroid Node Type Mask Value

GBE_Point 1

GBE_TextNode 2

MicroStation BASIC Guide B-7

Page 570: 48784209 Microstation Basic

MicroStation BASIC Constants

600macro.bk : 6B_CONST.FRA Page 8 Friday, October 15, 1999 1:27 PM

Selection Criteria Mask Value

GBE_Inside 4

GBE_Outside 8

GBE_Overlap 16

operator Mask Value

GBE_ADD 1

GBE_OR 2

GBE_XOR 3

GBE_DIFF 4

B-8 MicroStation BASIC Guide

Page 571: 48784209 Microstation Basic

600macro.bk : 600MACRO.IX Page 1 Friday, October 15, 1999 1:27 PM

Index

- Operator 3-12, 7-1, 7-13

& Operator 7-1, 7-11

* Operator 3-12, 7-1, 7-12

+ Operator 3-12, 7-1, 7-12

.BA extension 5-3

.BAS extension 2-6

/ Operator 3-12, 7-1, 7-13

< Operator 3-13, 7-2, 7-13

<= Operator 3-13, 7-2, 7-14

<> Operator 3-13, 7-2, 7-14

= Operator 3-11, 3-13, 7-2, 7-15

> Operator 3-13, 7-2, 7-15

>= Operator 3-13, 7-2, 7-16

\ Operator 3-12, 7-2, 7-16

^ Operator 3-12, 7-2, 7-17

_ Operator 7-2, 7-17

’ Operator 3-1, 7-2, 7-12

AAbs 7-2, 7-18

Access Strings 5-8

Adding 1-8

Advanced Macro Programming 1-3

Alignment Editor 5-18

And 3-14, 7-2, 7-19

angle 4-13

angleLock 4-13

application software 6-1

arcs and ellipsesprimaryAxis 4-5secondaryAxis 4-5startAngle 4-5sweepAngle 4-5

areaMode 4-13

arguments see parameters

arithmetic operators see Expressions

arithmetic operators

ArrayDims 7-3, 7-19

arrays 3-5boundaries 3-5fixed-length 3-6multi-dimensional arrays 3-5variable-length 3-7

ArraySort 7-3, 7-20

As 3-26

Asc 7-6, 7-20

assignment operator see Expressionsassignment operator

associationLock 4-13

Atn 7-2, 7-21

axisAngle 4-13

axisLock 4-13

axisOrigin 4-13

BBaker’s Rounding Rules 3-12

BASICconstructs see BASIC Constructsextensions 1-3, 2-4language 1-1objects see BASIC Objects

BASIC Constructsselection sets 4-9

BASIC extensions see MicroStation-specificextensions

BASIC Function GroupsArray Handling 7-1Business Calculations 7-1Character Manipulation 7-1Constants & Special Keywords 7-1Date commands 7-1Dynamic Data Exchange 7-1File Handling 7-1Math commands 7-1Miscellaneous commands 7-1

MicroStation BASIC Guide i-1

Page 572: 48784209 Microstation Basic

Index: C

600macro.bk : 600MACRO.IX Page 2 Friday, October 15, 1999 1:27 PM

Numerical Operators Array commands 7-1Numerical OperatorsArray commands 7-1Operators 7-1Program Control 7-1String Manipulation 7-1System commands 7-1Time commands 7-1Variable Control 7-1

BASIC Objectsaccessing object methods in 3-36accessing object properties in 3-36constant 3-37creating an object instance in 3-35declaring variables in 3-32methods in 3-33properties in 3-34variable operations in 3-34

BASIC Programming Extensions 3-1, 4-1MicroStation PowerDraft conventions 4-1sequencing commands 4-1

BASIC see Macro Language

Basic.Capability 7-4

Basic.Capability% 7-21

Basic.Eoln$ 7-4, 7-22

Basic.FreeMemo 7-4

Basic.FreeMemory 7-22

Basic.HomeDir$ 7-22

Basic.OS 7-4, 7-22

Basic.PathSeparator$ 7-4, 7-23

Beep 7-4, 7-24

block to cell cross reference 4-28

Boolean Operators 3-13

boresiteLock 4-13

Browse 1-5button 1-5

built-in functions 6-1

ByVal 3-26

CC Expression Statements 8-120

MbeCExpressionDouble 8-120MbeCExpressionLong 8-120

MbeCExpressionString 8-120

C Programming Language 6-2

CAD engine 6-2

CAD Input Operations 8-123MbeAngleFromString 8-123MbeFindFile 8-124MbeGetConfigVar 8-124MbeGetInput 8-123MbeLocateElement 8-123MbePoint 8-123MbePointFromString 8-123MbeRelocate 8-123MbeScalarFromString 8-123MbeSendAppMessage 8-123MbeSendCommand 8-123MbeSendDataPoint 8-123MbeSendDragPoints 8-123MbeSendKeyin 8-123MbeSendReset 8-123MbeSendTentPoint 8-123MbeSetAppVariable 8-123MbeSetScaledAppVar 8-123MbeStartDefaultCommand 8-124MbeStartLocate 8-123MbeStringFromAngle 8-124MbeStringFromPoint 8-124MbeStringFromScalar 8-123MbeWriteCommand 8-123MbeWriteError 8-123MbeWriteMessage 8-123MbeWritePrompt 8-123MbeWriteStatus 8-123

Call 7-4, 7-24

Call Statement 3-27

calling functions 3-30

calling subroutines 3-27

capMode 4-13

Case 7-5

case statement see Select...Case

CDbl 7-2, 7-24

cell 4-13

cell to block cross reference 4-28

cellStretchLock 4-13

Change Variable Value dialog box 2-13

i-2 MicroStation BASIC Guide

Page 573: 48784209 Microstation Basic

Index: D

600macro.bk : 600MACRO.IX Page 3 Friday, October 15, 1999 1:27 PM

changeAll 4-8

Chr$ 7-6, 7-25

CInt 7-3, 7-25

class 4-8, 4-13

clear 4-9

CLng 7-3, 7-26

Close 7-7, 7-27

color 4-8, 4-13

colorName 4-13

Column Number Field 2-8

Command$ 1-4, 7-5, 7-27

Comment 3-1

complex graphics elements 4-3, 4-5concept 4-5firstElement 4-6nextComponent 4-6nextElement 4-6ProcessElement 4-8

complex variables see UDT variables

Const 7-5, 7-28

controlling execution 3-16Do...Loop 3-19For...Next 3-22GoSub 3-24Goto 3-24If...Then...Else 3-16Return 3-24Select...Case 3-18While...Wend 3-22

contructionPlaneLock 4-13

Coordinate SystemdistanceFromUors 4-3distanceToUors 4-3fromView 4-2masterUnits 4-2MbeCurrentTransform 4-2moveOrigin 4-3moveOriginWorld 4-3rotate 4-3scalarFromUors 4-3scalarToUors 4-3scale 4-3

Cos 7-3, 7-28

Create Macro dialog box 2-1

description of 2-1

CSng 7-3, 7-28

CStr 7-6, 7-29

Current Transformation Object 8-93MbeCurrentTransform.dgnUnits 8-93MbeCurrentTransform.fromView 8-93MbeCurrentTransform.masterUnits 8-93MbeCurrentTransform.moveOrigin 8-93MbeCurrentTransform.moveOriginWorld 8-

93MbeCurrentTransform.pointFromUors 8-93MbeCurrentTransform.pointToUors 8-93MbeCurrentTransform.rotate 8-93MbeCurrentTransform.scalarFromUors 8-93MbeCurrentTransform.scalarToUors 8-93MbeCurrentTransform.scale 8-93

currentGraphicGroup 4-13

customizing MicroStation 6-1

Ddatabase 4-15

MbeDatabase 4-17MbeDatabaseLink 4-17MbeSqlda 4-15MbeTable 4-16

Date$ 7-8, 7-29

DateAdd 7-8, 7-30

DateDiff 7-8, 7-31

DatePart 7-8, 7-33

DateSerial 7-8, 7-34

DateValue 7-9, 7-34

Day 7-9, 7-34

DDB 7-9, 7-35, 7-36, 7-37, 7-38, 7-39, 7-40

DDEExecute 7-10, 7-36

DDEInitiate 7-10, 7-36

DDEPoke 7-10, 7-37

DDERequest 7-10, 7-38

DDESend 7-10, 7-38

DDETerminate 7-10, 7-39

DDETerminateAll 7-10, 7-39

DDETimeOut 7-40

MicroStation BASIC Guide i-3

Page 574: 48784209 Microstation Basic

Index: E

600macro.bk : 600MACRO.IX Page 4 Friday, October 15, 1999 1:27 PM

DDETimout 7-10

Declare 7-4, 7-40

Declare statement 3-32

declaring variables 3-3arrays 3-5double 3-5integers 3-4long 3-4single 3-5string 3-4user-defined types 3-8

DEF… 7-5, 7-41

depthLock 4-13

Design File Information Objects 8-87MbeDgnInfo.cell3D 8-87MbeDgnInfo.cellFileName 8-87MbeDgnInfo.cellFileReadOnly 8-87MbeDgnInfo.dgn3D 8-87MbeDgnInfo.dgnFileName 8-87MbeDgnInfo.dgnFileReadOnly 8-87MbeDgnInfo.endOfFile 8-87MbeDgnInfo.getGlobalOrigin 8-87MbeDgnInfo.graphicGroup 8-87MbeDgnInfo.masterUnitName 8-87MbeDgnInfo.nextGraphicGroup 8-87MbeDgnInfo.subPerMaster 8-87MbeDgnInfo.subUnitName 8-87MbeDgnInfo.uorPerSub 8-87

Dialog Boxattributes 5-8builder 5-3color picker 5-14control see Dialog Box Controlcustom 5-2group box editor 5-17item editor 5-10item see Dialog Box Controllabel editor 5-11level map editor 5-15option button editor 5-12push button editor 5-13radio button editor 5-17save before editing 5-20scale editor 5-15standard 5-1text editor 5-11

toggle button editor 5-12

Dialog Box Control 5-9, 5-19editing 5-8hooks 5-8

Dialog Box Statements 8-145MbeFileCreate 5-1, 8-145MbeFileOpen 5-1, 8-145MbeInputBox 8-145MbeMessageBox 8-145MbeOpenModalDialog 8-145MbeSelectBox 8-145

Dialog BoxesChange Variable Value dialog box 2-13Create Macro dialog box 1-6, 2-1Customize dialog box 1-6Macros settings box 1-5Select Macro dialog box 1-5Start Macro dialog box 1-5

Dialogscustom 1-3standard 1-3utility 1-3

Dim 3-4, 7-5, 7-42

Dir$ 7-7, 7-44

distanceFromUors 4-3

distanceToUors 4-3

Do 7-4

Do...Loop 7-4, 7-45

Doubles see Macro Data Types

DWG export settings 4-26

DWG import settings 4-26

EebArchive 7-7, 7-47

ebDirectory 7-7, 7-47

ebHidden 7-7, 7-47

ebNone 7-7, 7-48

ebNormal 7-7, 7-48

ebReadOnly 7-7, 7-49

ebSystem 7-7, 7-49

ebVolume 7-7, 7-49

Edit Menu 5-6

i-4 MicroStation BASIC Guide

Page 575: 48784209 Microstation Basic

Index: E

600macro.bk : 600MACRO.IX Page 5 Friday, October 15, 1999 1:27 PM

Editing macros see Macroeditor

editing macros see Macroeditor

efficient program structure 3-25function procedures 3-25recursion 3-25subroutine procedures 3-25

Element Objects 8-15MbeElement.addToFile 8-15MbeElement.area 8-15MbeElement.bottomRadius 8-17MbeElement.cellName 8-15MbeElement.changeAll 8-15MbeElement.charHeight 8-15MbeElement.charWidth 8-15MbeElement.class 8-15MbeElement.color 8-15MbeElement.componentFilePos 8-15MbeElement.display 8-15MbeElement.fileNum 8-15MbeElement.filePos 8-15MbeElement.fileSize 8-15MbeElement.firstElement 8-15MbeElement.font 8-15MbeElement.fontName 8-15MbeElement.fromFile 8-15MbeElement.fromLocate 8-15MbeElement.getCellBox 8-16MbeElement.getCellLevels 8-16MbeElement.getCentroid 8-16MbeElement.getEndPoints 8-16MbeElement.getOrigin 8-16MbeElement.getPoints 8-16MbeElement.getRange 8-16MbeElement.getRotation 8-16MbeElement.getString 8-16MbeElement.getTopOrigin 8-16MbeElement.group 8-16MbeElement.headerElement 8-16MbeElement.internalSize 8-16MbeElement.isComponent 8-16MbeElement.isGraphics 8-16MbeElement.isHeader 8-16MbeElement.justification 8-16MbeElement.level 8-16MbeElement.lineSpacing 8-16

MbeElement.move 8-16MbeElement.nextComponent 8-16MbeElement.nextElement 8-16MbeElement.perimeter 8-17MbeElement.primaryAxis 8-17MbeElement.properties 8-17MbeElement.publish 8-17MbeElement.rewrite 8-17MbeElement.rotate 8-17MbeElement.scale 8-17MbeElement.secondaryAxis 8-17MbeElement.setPoints 8-17MbeElement.setString 8-17MbeElement.startAngle 8-17MbeElement.style 8-17MbeElement.sweepAngle 8-17MbeElement.thisComponent 8-17MbeElement.topRadius 8-17MbeElement.type 8-17MbeElement.volume 8-17MbeElement.weight 8-17

Element Set Objects 8-62MbeElementSet.clear 8-62MbeElementSet.fromFence 8-62MbeElementSet.fromSelection 8-62MbeElementSet.getFirst 8-62MbeElementSet.getNext 8-62

Else 7-5

End 7-5, 7-50

Environ$ 7-5, 7-50

Eof 7-7, 7-50

Eqv 3-14, 7-2, 7-51

Erase 7-3, 7-52

Erl 7-4, 7-53

Err (function) 7-4, 7-53

Err (statement) 7-4, 7-54

Error 7-54

Error (statement) 7-4

Error handling 3-38

Error Messages 9-1Compiler 9-5MicroStation 9-4Runtime 9-1Visual Basic 9-2

Error$ 7-55

MicroStation BASIC Guide i-5

Page 576: 48784209 Microstation Basic

Index: F

600macro.bk : 600MACRO.IX Page 6 Friday, October 15, 1999 1:27 PM

Error$ (function) 7-4

execution flow 3-16

Exit Do 7-5, 7-56

Exit For 7-5, 7-56

Exit Function 7-5, 7-57

Exit Sub 7-5, 7-57

Exp 7-3, 7-58

exponent 3-3

Expressions 3-11arithmetic operators 3-12assignment operator 3-11assignment operators 3-11defined 3-11logical operators 3-14operator precedence 3-15operator precedence in 3-15relational operators 3-13string concatenation operators 3-13string concatentation operators 3-13

Extensions see MicroStation-specific extensions

extensions see MicroStation-specific extensions

FFalse 7-2, 7-58

fenceClip 4-13

fenceOverlap 4-13

Fences see Selection Sets

fenceVoid 4-13

FileAttr 7-7, 7-58

FileCopy 7-7, 7-59

FileDateTime 7-7, 7-60

FileDirs 7-7, 7-61

FileExists 7-7, 7-61

FileLen 7-7, 7-62

FileList 7-7, 7-62

FileParse$ 7-7, 7-64

fillColor 4-13

fillMode 4-13

firstElement 4-6

Fix 7-3, 7-65

flat subroutines 2-4

font 4-13

fontName 4-13

fonts cross reference 4-27

For 7-5

For...Next 7-5, 7-65

Format$ 7-6, 7-66

FreeFile 7-8, 7-73

fromFence 4-9

fromFile 4-4

fromLocate 4-4

fromSelectionSet 4-9

fromView 4-2

function procedures 3-25

Function...End Function 7-5, 7-73

Fv 7-9, 7-75

GGbeCategories(index) 8-218

GbeCategories.indexFromMslink 8-218

GbeCategories.listByMslink 8-217

GbeCategories.maxCategories 8-217

GbeCategory.attachMaps 8-218

GbeCategory.cellLibrary 8-218

GbeCategory.detachMaps 8-218

GbeCategory.fileExt 8-219

GbeCategory.listFeaturesByMslink 8-219

GbeCategory.listMapsByMslink 8-219

GbeCategory.mslink 8-219

GbeCategory.name 8-219

GbeFeature.categoryMslink 8-222

GbeFeature.color 8-222

GbeFeature.description 8-222

GbeFeature.display 8-223

GbeFeature.level 8-223

GbeFeature.mslink 8-223

GbeFeature.name 8-223

GbeFeature.style 8-223

i-6 MicroStation BASIC Guide

Page 577: 48784209 Microstation Basic

Index: G

600macro.bk : 600MACRO.IX Page 7 Friday, October 15, 1999 1:27 PM

GbeFeature.type 8-223

GbeFeature.weight 8-224

GbeFeatures(index) 8-222

GbeFeatures.indexFromMslink 8-222

GbeFeatures.listByMslink 8-221

GbeFeatures.maxFeatures 8-221

GbeMap.attach 8-227

GbeMap.categoryMslink 8-227

GbeMap.description 8-227

GbeMap.detach 8-227

GbeMap.directory 8-227

GbeMap.isAttached 8-227

GbeMap.mslink 8-226

GbeMap.name 8-226

GbeMaps(index) 8-226

GbeMaps.attachByView 8-226

GbeMaps.indexFromMslink 8-226

GbeMaps.listByMslink 8-225

GbeMaps.maxMaps 8-225

GbeProject.close 8-231

GbeProject.DBconnect 8-229

GbeProject.DBload 8-229

GbeProject.directory 8-229

GbeProject.exportFile 8-230

GbeProject.keyMap 8-230

GbeProject.loginName 8-230

GbeProject.mapManager 8-230

GbeProject.open 8-230

GbeProject.workMap 8-230

GbeTLayerLine.color 8-210

GbeTLayerLine.level 8-210

GbeTLayerLine.linePolyOverlay 8-210

GbeTLayerLine.style 8-210

GbeTLayerLine.weight 8-210

GbeTLayerMixed.linePolyOverlay 8-215

GbeTLayerMixed.pointPolyOverlay 8-215

GbeTLayerPoint.color 8-208

GbeTLayerPoint.level 8-208

GbeTLayerPoint.nodeType 8-208

GbeTLayerPoint.pointPolyOverlay 8-209

GbeTLayerPoint.weight 8-208

GbeTLayerPolygon.color 8-212

GbeTLayerPolygon.doFill 8-213

GbeTLayerPolygon.fillColor 8-213

GbeTLayerPolygon.level 8-212

GbeTLayerPolygon.linePolyOverlay 8-214

GbeTLayerPolygon.pointPolyOverlay 8-213

GbeTLayerPolygon.polyPolyOverlay 8-213

GbeTLayerPolygon.style 8-212

GbeTLayerPolygon.weight 8-212

GbeTLayerType.add 8-207

GbeTLayerType.display 8-207

GbeTLayerType.holes 8-206

GbeTLayerType.load 8-206

GbeTLayerType.name 8-205

GbeTLayerType.queryList 8-206

GbeTLayerType.shapesAsAreas 8-206

GbeTLayerType.sqlStatement 8-205

GbeTLayerType.type 8-205

Get 7-8, 7-76

GetAttr 7-8, 7-78

getFirst 4-9

getNext 4-9

getPatternDelta 4-13

getScale 4-13

Global 7-5, 7-79

GoSub 7-5, 7-79

Goto 7-5, 7-80

graphGroupLock 4-13

Graphics Elementscomplex 4-5determining type 4-5isHeader 4-5location 4-11modifying 4-8simple 4-5type 4-5

gridLock 4-13

gridReference 4-13

MicroStation BASIC Guide i-7

Page 578: 48784209 Microstation Basic

Index: H

600macro.bk : 600MACRO.IX Page 8 Friday, October 15, 1999 1:27 PM

gridUnits 4-13

group 4-8

HHex$ 7-6, 7-80

Hour 7-9, 7-81

IIEEE 3-3

If 7-5

If...Then...Else 3-16, 7-5, 7-81

Imp 3-14, 7-2, 7-83

initialization of variables 3-11

Input # 7-8, 7-84

Input$ 7-8, 7-85

InStr 7-6, 7-85

Int 7-3, 7-86

Integers see Macro Data Types

intrinsic procedures see efficient programstructureintrinsic procedures

IPmt 7-9, 7-87

IRR 7-9, 7-88

Is 7-2, 7-90

isHeader 4-5

isometricLock 4-13

Item$ 7-6, 7-90

ItemCount 7-6, 7-91

KKill 7-8, 7-91

LLBound 7-3, 7-92

LCase$ 7-6, 7-93

Left$ 7-6, 7-93

Len 7-6, 7-94

Let 7-6, 7-95

level 4-8, 4-13

levelLock 4-13

Like 7-2, 7-95

line continuation 3-15

Line Input # 7-8, 7-96

Line Number Field 2-8

Line$ 7-6, 7-97

LineCount 7-6, 7-98

lineStyle 4-13

lineStyleName 4-13

lineTerminator 4-13

Loc 7-8, 7-98

local variables 2-12, 3-10

Local Variables see Data Type Variables

Lock 7-8, 7-99

Lof 7-8, 7-101

Log 7-3, 7-101

logical operators see Expressionslogical operators

Long Integers see Macro Data Types

Loop 7-4

LSet 7-6, 7-102

LTrim$ 7-6, 7-102

MMacro

adding BASIC language constructs 1-2comments in 3-1creating 1-1, 1-6data type variables see Macro Data Type

Variablesdata types in see Macro Data Typesdebugger see Macro Debuggerdebugging 2-11defined 1-1editing existing 2-6editor 1-7, 2-6error handling in 3-38examples 1-1interactions with user 5-1

i-8 MicroStation BASIC Guide

Page 579: 48784209 Microstation Basic

Index: M

600macro.bk : 600MACRO.IX Page 9 Friday, October 15, 1999 1:27 PM

language see Macro Languageload 1-5making the program more interactive 1-2naming rules in 3-1overview 1-1procedures see Macro Proceduresprototyping 1-1, 1-2prototyping see Macro Prototypingrecording 4-2run 1-5running the generator 1-2use of BASIC 1-1using constructs to control the execution of

3-16

Macro Data Type Variablesarrays of 3-5creating user-defined 3-8declaring double 3-5declaring integer 3-3declaring long 3-4declaring single 3-5declaring string 3-4fixed-length arrays 3-6initial value 3-11local 3-10private 3-10public 3-10variable-length arrays 3-7working with user-defined 3-9

Macro Data Typesdoubles 3-3integers 3-2long integers 3-2singles 3-3strings 3-2

Macro Debuggerbuttons 2-11

Macro Generatoruses of 1-2

Macro Language 3-1overview 3-1

Macro Language Extensions 2-4design file information object 1-3design view information object 1-4element location 1-3element object 1-3element set object 1-3

reference file object 1-4settings object 1-3state object 1-3

Macro Manager 1-7

Macro Procedures 3-25declaring 3-32function 3-28passing arguments to 3-30subroutine 3-26

Macro Prototyping 2-1example of 2-3

Macro RecordingEnd 1-7Pause 1-6play 1-6

Macroscoordinate system 4-2graphics elements with 4-3

Main 7-5, 7-103

Manipulating Graphics Elements see Macros

mantissa 3-3

master units 4-2

masterUnits 4-2

Mbe prefix 1-1

MBE_ 4-1

Mbe_ 4-1

MBE_AccessDenied 9-2

MBE_ArrayError 9-4

MBE_BadElement 9-4

MBE_BadFileMode 9-2

MBE_BadFileNumber 9-2

MBE_BadRecordNumber 9-2

MBE_CantParseString 9-4

MBE_CantReadElemDscr 9-4

MBE_CantRewrite 9-4

MBE_CommandInput 8-124

MBE_ComplexComponent 9-4

MBE_ComponentNotFound 9-4

MBE_DataPointInput 8-124

MBE_DiskFull 9-2

MBE_FileAccessError 9-2

MicroStation BASIC Guide i-9

Page 580: 48784209 Microstation Basic

Index: M

600macro.bk : 600MACRO.IX Page 10 Friday, October 15, 1999 1:27 PM

MBE_FileNotFound 9-2

MBE_FontNotFound 9-4

MBE_IllegalFunctionCal 9-2

MBE_IndexOutOfBounds 9-2

MBE_InvalidChannel 9-4

MBE_InvalidClass 9-4

MBE_InvalidColor 9-4

MBE_InvalidLevel 9-4

MBE_InvalidRefFile 9-4

MBE_InvalidStyle 9-4

MBE_InvalidView 9-4

MBE_InvalidWeight 9-4

MBE_KeyinInput 8-124

MBE_MustGetFromUser 9-4

MBE_NoDDEML 9-3

MBE_NoFence 9-4

MBE_NoGraphics 9-5

MBE_NoMoreElems 9-4

MBE_NoMoreInSet 9-4

MBE_NoSelectionSet 9-4

MBE_NotComplex 9-4

MBE_NotEnoughPoints 9-4

MBE_NotOnDesignPlane 9-4

MBE_ObjectVariableNotSet 9-2

MBE_OutOfMemory 9-2

MBE_OutOfSTringSpace 9-2

MBE_Overflow 9-2

MBE_PatternInvalid 9-2

MBE_ReceivedCommand 9-4

MBE_RedimFixedArray 9-4

MBE_RefSaveDeferred 9-4

MBE_ResetInput 8-124

MBE_StringTooLong 9-4

MBE_SubFuncNotDefined 9-2

MBE_Success 4-1

MBE_TooManyChannels 9-2

MBE_TooManyPoints 9-4

MBE_TypeMismatch 9-2

MBE_UnsupportedDataType 9-5

MBE_VariableNotFound 9-5

MBE_VariableWrongType 9-5

MBE_WriteInhibit 9-4

MBE_WrongDimension 9-4

MBE_WrongElemType 9-4

MBE_WrongInputType 9-4

MbeAngleFromString 8-141

MbeBlockNameTable object 4-28

MbeCExpressionDouble 8-120

MbeCExpressionLong 8-120

MbeCExpressionString 8-121

MbeCurrentTransform 4-2

MbeCurrentTransform.dgnUnits 8-95

MbeCurrentTransform.fromView 8-97

MbeCurrentTransform.masterUnits 8-93

MbeCurrentTransform.moveOrigin 8-96

MbeCurrentTransform.moveOriginWorld 8-96

MbeCurrentTransform.pointFromUors 8-98

MbeCurrentTransform.pointToUors 8-98

MbeCurrentTransform.rotate 8-96

MbeCurrentTransform.scalarFromUors 8-98

MbeCurrentTransform.scalarToUors 8-97

MbeCurrentTransform.scale 8-97

MbeDatabase 8-161MbeDatabase.activeEntity 8-161MbeDatabase.connect 8-161MbeDatabase.dAType 8-161MbeDatabase.defineActiveEntity 8-161MbeDatabase.describe 8-161MbeDatabase.disconnect 8-161MbeDatabase.editActiveEntity 8-161MbeDatabase.errorText 8-161MbeDatabase.modeCommit 8-161MbeDatabase.modeConfirm 8-161MbeDatabase.modeDelete 8-161MbeDatabase.modeForms 8-161MbeDatabase.modeLinkages 8-161MbeDatabase.mslink 8-161MbeDatabase.name 8-161MbeDatabase.reportClose 8-161MbeDatabase.reportOpen 8-161MbeDatabase.showActiveEntity 8-161

MbeDatabase. errorText 8-162

i-10 MicroStation BASIC Guide

Page 581: 48784209 Microstation Basic

Index: M

600macro.bk : 600MACRO.IX Page 11 Friday, October 15, 1999 1:27 PM

MbeDatabase.activeEntity 8-162

MbeDatabase.connect 8-163

MbeDatabase.dAType 8-167

MbeDatabase.defineActiveEntity 8-164

MbeDatabase.describe 8-163

MbeDatabase.disconnect 8-163

MbeDatabase.editActiveEntity 8-164

MbeDatabase.modeCommit 8-165

MbeDatabase.modeConfirm 8-165

MbeDatabase.modeDelete 8-165

MbeDatabase.modeForms 8-166

MbeDatabase.modeLinkage 8-166

MbeDatabase.mslink 8-162

MbeDatabase.name 8-161

MbeDatabase.reportClose 8-167

MbeDatabase.reportOpen 8-167

MbeDatabase.showActiveEntity 8-164

MbeDatabaseLink 8-168

MbeDatabaseLink Object 8-168

MbeDatabaseLink.dAType 8-168, 8-169

MbeDatabaseLink.entityNumber 8-168, 8-169

MbeDatabaseLink.isInformation 8-168, 8-169

MbeDatabaseLink.isModified 8-169

MbeDatabaseLink.isRemote 8-169

MbeDatabaseLink.isUserLink 8-169

MbeDatabaseLink.linkClass 8-168, 8-170

MbeDatabaseLink.linkSize 8-168, 8-170

MbeDatabaseLink.linkType 8-168, 8-170

MbeDatabaseLink.mslink 8-168, 8-171

MbeDatabaseLink.tableName 8-168, 8-171

MbeDgnInfocell3d 4-12cellFileName 4-12cellFileReadOnly 4-12dgn3d 4-12dgnFileName 4-12dgnFileReadOnly 4-12endOfFile 4-12graphicGroup 4-12masterUnitName 4-12nextGraphicGroup 4-12

subPerMaster 4-12subUnitName 4-12uorPerSub 4-12

MbeDgnInfo.cell3D 8-91

MbeDgnInfo.cellFileName 8-91

MbeDgnInfo.cellFileReadOnly 8-92

MbeDgnInfo.dgn3D 8-88

MbeDgnInfo.dgnFileName 8-87

MbeDgnInfo.dgnFileReadOnly 8-88

MbeDgnInfo.endOfFile 8-88

MbeDgnInfo.getGlobalOrigin 8-90

MbeDgnInfo.graphicGroup 8-90

MbeDgnInfo.masterUnitName 8-88

MbeDgnInfo.nextGraphicGroup 8-91

MbeDgnInfo.subPerMaster 8-90

MbeDgnInfo.subUnitName 8-89

MbeDgnInfo.uorPerSub 8-89

MbeDgnLevels Object 8-172

MbeDgnLevels.freeAll 8-174

MbeDgnLevels.freeGroups 8-173

MbeDgnLevels.freeLevels 8-174

MbeDgnLevels.getGroup 8-173

MbeDgnLevels.getLevel 8-173

MbeDgnLevels.loadAllFromFile 8-175

MbeDgnLevels.loadGroupsFromFile 8-174

MbeDgnLevels.loadLevelsFromFile 8-174

MbeDgnLevels.numGroups 8-172

MbeDgnLevels.numNamedLevels 8-173

MbeDgnLevels.rootGroup 8-172

MbeDgnLevels.saveAllToFile 8-176

MbeDgnLevels.saveGroupsToFile 8-175

MbeDgnLevels.saveLevelsToFile 8-175

MbeDWGExportSettings 4-26

MbeDWGImportSettings 4-26

MbeElement 4-3, 4-6

MbeElement.addToFile 8-45

MbeElement.appendDBLinkage 8-15, 8-21

MbeElement.appendLinkage 8-60

MbeElement.area 8-46

MbeElement.attachActiveEntity 8-15, 8-18

MicroStation BASIC Guide i-11

Page 582: 48784209 Microstation Basic

Index: M

600macro.bk : 600MACRO.IX Page 12 Friday, October 15, 1999 1:27 PM

MbeElement.attachTag 8-59

MbeElement.bottomRadius 8-55

MbeElement.cellName 8-47

MbeElement.changeAll 8-34

MbeElement.charHeight 8-50

MbeElement.charWidth 8-50

MbeElement.clas 8-36

MbeElement.color 8-35

MbeElement.componentFilePos 8-33

MbeElement.deleteDBLinkage 8-21

MbeElement.deleteDBLinkages 8-15

MbeElement.deleteLinkage 8-61

MbeElement.display 8-45

MbeElement.extractDBLinkages 8-15, 8-20

MbeElement.extractLinkage 8-59

MbeElement.extractTags 8-58

MbeElement.fileNum 8-33

MbeElement.filePos 8-33

MbeElement.fileSize 8-30

MbeElement.firstElement 8-22

MbeElement.font 8-49

MbeElement.fontName 8-49

MbeElement.foundDBLinkages 8-15, 8-19

MbeElement.fromFile 8-31

MbeElement.fromLocate 4-12, 8-32

MbeElement.getCellBox 8-48

MbeElement.getCellLevels 8-48

MbeElement.getCentroid 8-47

MbeElement.getEndPoints 8-41

MbeElement.getMbeTag 8-58

MbeElement.getNumLinkages 8-59

MbeElement.getOrigin 8-38

MbeElement.getPoints 8-39

MbeElement.getRange 8-41

MbeElement.getRotation 8-49

MbeElement.getString 8-52

MbeElement.getTopOrigin 8-55

MbeElement.group 8-57

MbeElement.headerElement 8-26

MbeElement.internalSize 8-30

MbeElement.isComponent 8-29

MbeElement.isGraphics 8-29

MbeElement.isHeader 8-28

MbeElement.isTagged 8-57

MbeElement.justification 8-51

MbeElement.level 8-34

MbeElement.lineSpacing 8-51

MbeElement.loadDAttributes 8-16, 8-19

MbeElement.move 8-42

MbeElement.nextComponent 8-24

MbeElement.nextElement 8-22

MbeElement.numTags 8-58

MbeElement.perimeter 8-46

MbeElement.primaryAxis 8-53

MbeElement.properties 8-37

MbeElement.publish 8-56

MbeElement.reportDBLinkages 8-19

MbeElement.reportLinkages 8-17

MbeElement.reviewDBAttributes 8-17, 8-18

MbeElement.rewrite 8-44

MbeElement.rotate 8-42

MbeElement.scale 8-43

MbeElement.secondaryAxis 8-54

MbeElement.setPoints 8-40

MbeElement.setString 8-53

MbeElement.startAngle 8-54

MbeElement.style 8-35

MbeElement.sweepAngle 8-55

MbeElement.tagId 8-57

MbeElement.thisComponent 8-27

MbeElement.topRadius 8-55

MbeElement.type 8-29

MbeElement.volume 8-47

MbeElement.weight 8-36

MbeElementSet.clear 8-65

MbeElementSet.fromFence 8-63

MbeElementSet.fromSelectionSet 8-62

MbeElementSet.getFirst 8-64

i-12 MicroStation BASIC Guide

Page 583: 48784209 Microstation Basic

Index: M

600macro.bk : 600MACRO.IX Page 13 Friday, October 15, 1999 1:27 PM

MbeElementSet.getNext 8-64

MbeFileCreate 5-1, 8-145

MbeFileOpen 5-1, 8-145

MbeFindFile 8-143

MbeFontNameTable object 4-27

MbeGetConfigVar 8-143

MbeGetInput 4-2, 8-124

MbeGetTagSetNames 8-184

MbeInputBox 5-1, 8-147

MbeLevelGroup Object 8-177

MbeLevelGroup.addGroup 8-180

MbeLevelGroup.addLevel 8-180

MbeLevelGroup.deleteGroup 8-180

MbeLevelGroup.getDescendentGroups 8-178

MbeLevelGroup.getDescendentLevels 8-178

MbeLevelGroup.getLevelMask 8-179

MbeLevelGroup.getLevels 8-177

MbeLevelGroup.getParentGroup 8-179

MbeLevelGroup.groupName 8-177

MbeLocateElement 8-139

MbeMacro Object 8-203MbeMacro.suspend 8-203

MbeMacro.suspend 8-203

MbeMessageBox 5-1, 8-146

MbeNamedLevel Object 8-181

MbeNamedLevel.deleteLevel 8-183

MbeNamedLevel.getLevelMask 8-182

MbeNamedLevel.getParentGroup 8-182

MbeNamedLevel.levelComment 8-182

MbeNamedLevel.levelName 8-181

MbeNamedLevel.levelNumber 8-181

MbeNumberOfTagSets 8-184

MbeOpenModalDialog 5-2, 8-148

MbePoint 4-2, 8-125

MbePointFromString 8-141

MbeRefFile.active 8-109

MbeRefFile.attachName 8-112

MbeRefFile.description 8-113

MbeRefFile.display 8-110

MbeRefFile.fileName 8-112

MbeRefFile.getLevels 8-114

MbeRefFile.levelsOff 8-114

MbeRefFile.levelsOn 8-114

MbeRefFile.locate 8-110

MbeRefFile.logical 8-113

MbeRefFile.notFound 8-110

MbeRefFile.plot 8-111

MbeRefFile.saveSettings 8-115

MbeRefFile.scale 8-113

MbeRefFile.scaleLineStyle 8-111

MbeRefFile.snap 8-111

MbeRefFiles(index) 8-109

MbeRefFiles.maxRefFiles 8-109

MbeRelocate 4-12, 8-131

MbeScalarFromString 8-141

MbeSelectBox 5-2, 8-147

MbeSendAppMessage 8-125

MbeSendCommand 4-1, 4-12, 8-127

MbeSendDataPoint 4-2, 8-127

MbeSendDragPoints 8-128

MbeSendKeyin 4-1, 8-129

MbeSendReset 4-2, 8-129

MbeSendTentPoint 4-2, 8-129

MbeSession.canSwapScreen 8-119

MbeSession.elapsedTime 8-119

MbeSession.language 8-118

MbeSession.msPlatform 8-117

MbeSession.msProduct 8-116

MbeSession.msVersion 8-117

MbeSession.numScreens 8-118

MbeSetAppVariable 8-125

MbeSetMember 4-9

MbeSetScaledAppVar 8-126

MbeSettings 8-66

MbeSettings.angle 8-67

MbeSettings.areaMode 8-68

MbeSettings.associationLock 8-81

MbeSettings.axisAngle 8-68

MicroStation BASIC Guide i-13

Page 584: 48784209 Microstation Basic

Index: M

600macro.bk : 600MACRO.IX Page 14 Friday, October 15, 1999 1:27 PM

MbeSettings.axisLock 8-82

MbeSettings.axisOrigin 8-68

MbeSettings.boresiteLock 8-82

MbeSettings.capMode 8-69

MbeSettings.cell 8-69

MbeSettings.cellStretchLock 8-82

MbeSettings.class 8-69

MbeSettings.color 8-70

MbeSettings.colorName 8-70

MbeSettings.constructionPlaneLock 8-83

MbeSettings.currentGraphicGroup 8-71

MbeSettings.depthLock 8-83

MbeSettings.fenceClip 8-84

MbeSettings.fenceOverlap 8-84

MbeSettings.fenceVoid 8-85

MbeSettings.fillColor 8-71

MbeSettings.fillMode 8-71

MbeSettings.font 8-72

MbeSettings.fontName 8-72

MbeSettings.getPatternDelta 8-77

MbeSettings.getScale 8-78

MbeSettings.graphGroupLock 8-83

MbeSettings.gridLock 8-84

MbeSettings.gridReferences 8-72

MbeSettings.gridUnits 8-73

MbeSettings.level 8-73

MbeSettings.levelLock 8-85

MbeSettings.lineStyle 8-74

MbeSettings.lineStyleName 8-74

MbeSettings.lineTerminator 8-74

MbeSettings.nodeJustification 8-75

MbeSettings.patternAngle1 8-75

MbeSettings.patternAngle2 8-75

MbeSettings.patternCell 8-76

MbeSettings.patternScale 8-77

MbeSettings.point 8-77

MbeSettings.selectionSetLock 8-85

MbeSettings.setPatternDelta 8-76

MbeSettings.setScale 8-78

MbeSettings.settingErr 8-86

MbeSettings.snapLock 8-86

MbeSettings.tagIncremen 8-78

MbeSettings.terminatorScale 8-79

MbeSettings.textHeight 8-79

MbeSettings.textJustification 8-80

MbeSettings.textLineLength 8-80

MbeSettings.textLineSpacing 8-80

MbeSettings.textNodeLock 8-86

MbeSettings.textWidth 8-79

MbeSettings.weight 8-81

MbeSqlda 4-15, 8-150MbeSqlda.column 8-150MbeSqlda.getIndex 8-150MbeSqlda.isNull 8-150MbeSqlda.length 8-150MbeSqlda.numColumns 8-150MbeSqlda.precision 8-150MbeSqlda.scale 8-150MbeSqlda.type 8-150MbeSqlda.value 8-150

MbeSqlda.column 8-150

MbeSqlda.getIndex 8-152

MbeSqlda.isNull 8-151

MbeSqlda.length 8-151

MbeSqlda.numColumns 8-150

MbeSqlda.precision 8-152

MbeSqlda.scale 8-152

MbeSqlda.type 8-151

MbeSqlda.value 8-150

MbeStartDefaultCommand 8-144

MbeStartLocate 4-11, 8-132

MbeState 4-2

MbeState.cmdResult 8-5

MbeState.errorMessages 8-6

MbeState.getInputCommand 8-3

MbeState.getInputDataPoint 8-4

MbeState.getInputKeyin 8-4

MbeState.getLocateFileMask 8-10

MbeState.getLocateTypeMask 8-11

MbeState.inputType 8-3

i-14 MicroStation BASIC Guide

Page 585: 48784209 Microstation Basic

Index: M

600macro.bk : 600MACRO.IX Page 15 Friday, October 15, 1999 1:27 PM

MbeState.locateClassMask 8-14

MbeState.locateComponentFilePos 8-10

MbeState.locateFileNum 8-9

MbeState.locateHeaderFilePos 8-10

MbeState.locatePropMask 8-13

MbeState.locatePropVal 8-13

MbeState.locateTolerance 8-8

MbeState.measureResult1 8-7

MbeState.measureResult2 8-7

MbeState.messages 8-2, 8-6

MbeState.noElementDisplay 8-6

MbeState.parseAll 8-7

MbeState.setLocateFileMask 8-10

MbeState.setLocateTypeMask 8-11

MbeStringFromAngle 8-143

MbeStringFromPoint 8-142

MbeStringFromScalar 8-142

MbeTable 8-153MbeTable.activeReview 8-153MbeTable.copy 8-153MbeTable.create 8-153MbeTable.criteria 8-153MbeTable.describe 8-153MbeTable.drop 8-153MbeTable.entityNumber 8-153MbeTable.largestMslink 8-153MbeTable.name 8-153MbeTable.recordDelete 8-153MbeTable.recordFirst 8-153MbeTable.recordInsert 8-153MbeTable.recordLast 8-153MbeTable.recordNext 8-153MbeTable.recordUpdate 8-153MbeTable.reportTable 8-153

MbeTable.activeReview 8-154

MbeTable.copy 8-159

MbeTable.create 8-159

MbeTable.criteria 8-153

MbeTable.describe 8-156

MbeTable.drop 8-160

MbeTable.entityNumber 8-154

MbeTable.fenceFilter 8-155

MbeTable.largestMslink 8-154

MbeTable.name 8-153

MbeTable.recordDelete 8-159

MbeTable.recordFirst 8-156

MbeTable.recordInsert 8-158

MbeTable.recordLast 8-157

MbeTable.recordNext 8-157

MbeTable.recordUpdate 8-158

MbeTable.reportTable 8-155

MbeTag Object 8-197MbeTag.fileNum 8-197MbeTag.getMbeElement 8-197MbeTag.getOffset 8-197MbeTag.getTaggedElement 8-197MbeTag.getTextElement 8-197MbeTag.id 8-197MbeTag.isHidden 8-197MbeTag.name 8-197MbeTag.setName 8-197MbeTag.setOffset 8-197MbeTag.size 8-197MbeTag.targetId 8-197MbeTag.type 8-197MbeTag.value 8-197MbeTag.version 8-197

MbeTag.fileNum 8-198

MbeTag.getMbeElement 8-201

MbeTag.getOffset 8-201

MbeTag.getTaggedElement 8-202

MbeTag.getTextElement 8-202

MbeTag.id 8-198

MbeTag.isHidden 8-200

MbeTag.name 8-198

MbeTag.setName 8-197

MbeTag.setOffset 8-201

MbeTag.size 8-200

MbeTag.targetId 8-199

MbeTag.type 8-199

MbeTag.value 8-199

MbeTag.version 8-200

MbeTagDef Object 8-191MbeTagDef.add 8-191

MicroStation BASIC Guide i-15

Page 586: 48784209 Microstation Basic

Index: M

600macro.bk : 600MACRO.IX Page 16 Friday, October 15, 1999 1:27 PM

MbeTagDef.defaultValue 8-191MbeTagDef.delete 8-191MbeTagDef.isConstant 8-191MbeTagDef.isHidden 8-191MbeTagDef.name 8-191MbeTagDef.prompt 8-191MbeTagDef.setName 8-191MbeTagDef.style 8-191MbeTagDef.tagId 8-191MbeTagDef.tagType 8-191MbeTagDef.update 8-191

MbeTagDef.add 8-195

MbeTagDef.defaultValue 8-193

MbeTagDef.delete 8-196

MbeTagDef.isConstant 8-194

MbeTagDef.isHidden 8-194

MbeTagDef.name 8-191

MbeTagDef.prompt 8-192

MbeTagDef.setName 8-192

MbeTagDef.style 8-192

MbeTagDef.tagId 8-194

MbeTagDef.tagType 8-193

MbeTagDef.update 8-195

MbeTagSet Object 8-186MbeTagSet.add 8-186MbeTagSet.delete 8-186MbeTagSet.deleteInstances 8-186MbeTagSet.fileNum 8-186MbeTagSet.generateReport 8-186MbeTagSet.getTagDef 8-186MbeTagSet.getTagDefNames 8-186MbeTagSet.name 8-186MbeTagSet.numTagDefs 8-186MbeTagSet.reportName 8-186MbeTagSet.update 8-186

MbeTagSet.add 8-188

MbeTagSet.delete 8-188

MbeTagSet.deleteInstances 8-190

MbeTagSet.fileNum 8-187

MbeTagSet.generateReport 8-189

MbeTagSet.getTagDef 8-189

MbeTagSet.getTagDefNames 8-187

MbeTagSet.name 8-186

MbeTagSet.numTagDefs 8-187

MbeTagSet.reportName 8-186

MbeTagSet.update 8-188

MbeView.active 8-100

MbeView.areaFill 8-105

MbeView.construction 8-104

MbeView.deferApply 8-105

MbeView.dimension 8-104

MbeView.enterDataField 8-103

MbeView.fastCurve 8-101

MbeView.fastRefClip 8-105

MbeView.getLevels 8-106

MbeView.grid 8-103

MbeView.levelsOff 8-107

MbeView.levelsOn 8-107

MbeView.levelSymbology 8-103

MbeView.lineWeight 8-102

MbeView.noText 8-101

MbeView.pattern 8-102

MbeView.refBoundary 8-105

MbeView.screenNum 8-101

MbeView.slowFont 8-102

MbeView.textNode 8-103

MbeView.update 8-106

MbeViews(index) 8-99

MbeWriteCommand 4-2, 8-130

MbeWriteError 4-2, 8-130

MbeWriteMessage 4-2, 8-131

MbeWritePrompt 4-2, 8-131

MbeWriteStatus 4-2, 8-131

MDE 6-1

MDL 6-2advantages over BASIC 6-3Built-in Functions 6-2

MicroCSL 6-3

MicroStationaccessing database features 4-15accessing design file view information 4-14accessing reference file information 4-14accessing session information 4-15

i-16 MicroStation BASIC Guide

Page 587: 48784209 Microstation Basic

Index: N

600macro.bk : 600MACRO.IX Page 17 Friday, October 15, 1999 1:27 PM

accessing settings 4-13accessing state information 4-13

MicroStation Development Environment 6-1tools provided 6-1

MicroStation Development Language 6-2

MicroStation Error MessageMBE_ArrayError 9-4MBE_BadElement 9-4MBE_CantParseString 9-4MBE_CantReadElemDscr 9-4MBE_CantRewrite 9-4MBE_ComplexComponent 9-4MBE_ComponentNotFound 9-4MBE_FontNotFound 9-4MBE_InvalidChannel 9-4MBE_InvalidClass 9-4MBE_InvalidLevel 9-4MBE_InvalidRefFile 9-4MBE_InvalidStyle 9-4MBE_InvalidView 9-4MBE_InvalidWeight 9-4MBE_MustGetFromUser 9-4MBE_NoFence 9-4MBE_NoGraphics 9-5MBE_NoMoreElems 9-4MBE_NoMoreInSet 9-4MBE_NoSelectionSet 9-4MBE_NotComplex 9-4MBE_NotEnoughPoints 9-4MBE_NotOnDesignPlane 9-4MBE_ReceivedCommand 9-4MBE_RedimFixedArray 9-4MBE_RefSaveDeferred 9-4MBE_StringTooLong 9-4MBE_TooManyPoints 9-4MBE_UnsupportedDataType 9-5MBE_VariableNotFound 9-5MBE_VariableWrongType 9-5MBE_WriteInhibit 9-4MBE_WrongDimension 9-4MBE_WrongElemType 9-4MBE_WrongInputType 9-4

MicroStation Error Messages 9-4

MicroStation Settings 4-13

MicroStation-specific extensionreasons for 2-4

MicroStation-specific extensions 4-1collections 4-1data types 4-1differences from other BASIC features 4-1functions 4-1objects 4-1overloading 2-4predefined constants 4-1prefixes 4-1

Mid$ 7-6, 7-103

Minute 7-9, 7-104

MIRR 7-9, 7-104

MkDir 7-8, 7-105

Mod 7-2, 7-106

Mod Operator 3-12

Month 7-9, 7-106

moveOriginWorld 4-3

multi-dimensional arrays see arraysmulti-dimensional arrays

NName 7-8, 7-107

Next 7-5

nextComponent 4-6

nextElement 4-6

nodeJustification 4-13

Not 3-14, 7-2, 7-107

Now 7-9, 7-108

NPer 7-9, 7-108

Npv 7-9, 7-110

Null 7-6, 7-111

Oobject

collections 3-37declaring 3-33methods 3-33properties 3-33

Object ExtensionsDesign File Information 1-3Design View Information 1-4

MicroStation BASIC Guide i-17

Page 588: 48784209 Microstation Basic

Index: P

600macro.bk : 600MACRO.IX Page 18 Friday, October 15, 1999 1:27 PM

MbeDgnInfo 1-3MbeRefFile 1-4MbeSettings 1-3MbeState 1-3MbeView 1-4Reference File 1-4Settings 1-3State 1-3

object methods 4-13

Objects in BASIC 3-32defined 3-32methods 3-32, 3-36properties 3-32, 3-36

Oct$ 7-6, 7-111

On Error 7-5, 7-112

Open 7-8, 7-114

operator precedence 3-15

Option Base 7-3, 7-116

Option Compare 7-6, 7-116

Option Menu 5-8

Or 3-14, 7-2, 7-117

overloaded extensions 2-4

Pparameters 3-30

ByVal 3-26

parenthesis 3-15

patternAngle1 4-13

patternAngle2 4-13

patternCell 4-13

patternScale 4-13

pen tableentry points 4-22

pen tables 4-18creating 4-19

PI 7-2, 7-118

Pmt 7-9, 7-118

point 4-13

PPmt 7-9, 7-119

precedence 3-15

Print 7-121

Print # 7-8, 7-122

Print (statement) 7-4

Private 7-6, 7-123

private variables 2-12, 3-10

Private Variables see Macro Data Type Variables

procedures 3-25

ProcessElement 4-8

program entry pointsPen Table Plot Element Hook 4-24Plot Finished Hook 4-25Post-Plot Hook 4-24Pre-Plot Hook 4-24

program structure see efficient program structure

propertiesclass 4-5color 4-5getEndPoints 4-5getOrigin 4-5getPoints 4-5getRange 4-5level 4-5style 4-5weight 4-5

prototyping see Macro Prototyping

Public 7-6, 7-124

public variables 2-12, 3-10

Put 7-8, 7-125

Pv 7-9, 7-127

QQuerying Graphics Elements see Macros

RRandom 7-3, 7-128

Randomize 7-3, 7-128

Rate 7-9, 7-129

recursion see efficient program structurerecursion

ReDim 7-3, 7-130

Reference File Objects 8-108MbeRefFile.active 8-108

i-18 MicroStation BASIC Guide

Page 589: 48784209 Microstation Basic

Index: S

600macro.bk : 600MACRO.IX Page 19 Friday, October 15, 1999 1:27 PM

MbeRefFile.attachName 8-108MbeRefFile.description 8-108MbeRefFile.display 8-108MbeRefFile.fileName 8-108MbeRefFile.getLevels 8-108MbeRefFile.levelsOff 8-108MbeRefFile.levelsOn 8-108MbeRefFile.locate 8-108MbeRefFile.logical 8-108MbeRefFile.notFound 8-108MbeRefFile.plot 8-108MbeRefFile.saveSettings 8-108MbeRefFile.scale 8-108MbeRefFile.scaleLineStyle 8-108MbeRefFile.snap 8-108MbeRefFiles(index) 8-108MbeRefFiles.maxRefFiles 8-108

relational operators see Expressionsrelational operators

REM 3-1, 7-2, 7-131

Reset 7-8, 7-131

Resource Files 5-4

Resume 7-5, 7-131

Return 7-5, 7-133

return values 4-1

Right$ 7-6, 7-133

RmDir 7-8, 7-133

Rnd 7-3, 7-134

rotate 4-3

Rounding 3-12

RSet 7-6, 7-134

RTrim$ 7-7, 7-135

run-time error codes 4-30

Runtime Error Messagesbad filename 9-2bad record length 9-2can’t rename with different drive 9-2data in wrong format 9-3data not provided in DDE operation 9-3DDE conversation closed or changed 9-3DDE requires ddeml.dll 9-3destination is busy 9-3device I/O error 9-2device unavailable 9-2

disk not ready 9-2division by zero 9-2file already exists 9-2file already open 9-2foreign app won’t perform DDE method 9-3foreign application quit 9-3input past end of file 9-2internal errors 9-2message queue filled, DDE msg lost 9-3multiple apps responded to DDE initiate 9-3no foreign app responded to DDE initiate 9-3no more DDE channels 9-2no resumes 9-2out of stack space 9-2path not found 9-2resume without error 9-2timeout waiting for DDE response 9-3user pressed ESC during DDE operation 9-3

SscalarFromUors 4-3

scalarToUors 4-3

scale 4-3

scaleLock 4-13

scope 3-9

Second 7-9, 7-135

Seek (function) 7-8, 7-135

Seek (statement) 7-8, 7-136

Select 7-5

Select...Case 3-18, 7-5, 7-137

Selection Sets 4-9clear 4-9fromFence 4-9fromSelectionSet 4-9getFirst 4-9getNext 4-9MbeElementSet 4-9MbeSetMember 4-9

selectionSetLock 4-13

Session Object 8-116MbeSession.canSwapScreen 8-116MbeSession.elapsedTime 8-116MbeSession.language 8-116MbeSession.msPlatform 8-116

MicroStation BASIC Guide i-19

Page 590: 48784209 Microstation Basic

Index: S

600macro.bk : 600MACRO.IX Page 20 Friday, October 15, 1999 1:27 PM

MbeSession.msProduct 8-116MbeSession.msVersion 8-116MbeSession.numScreens 8-116

Set 7-6, 7-139

SetAttr 7-8, 7-140

setPatternDelta 4-13

setScale 4-13

Settings Object 8-66MbeSettings.angle 8-66MbeSettings.associationLock 8-67MbeSettings.axisAngle 8-66MbeSettings.axisLock 8-67MbeSettings.axisOrigin 8-66MbeSettings.boresiteLock 8-67MbeSettings.capMode 8-66MbeSettings.cell 8-66MbeSettings.cellStretchLock 8-67MbeSettings.class 8-66MbeSettings.color 8-66MbeSettings.colorName 8-66MbeSettings.constructionPlaneLock 8-67MbeSettings.currentGraphicGroup 8-66MbeSettings.depthLock 8-67MbeSettings.fenceClip 8-67MbeSettings.fenceOverlap 8-67MbeSettings.fenceVoid 8-67MbeSettings.fillColor 8-66MbeSettings.fillMode 8-66MbeSettings.font 8-66MbeSettings.fontName 8-66MbeSettings.getPatternDelta 8-66MbeSettings.getScale 8-66MbeSettings.graphGroupLock 8-67MbeSettings.gridLock 8-67MbeSettings.gridReferences 8-66MbeSettings.gridUnits 8-66MbeSettings.level 8-66MbeSettings.levelLock 8-67MbeSettings.lineStyle 8-66MbeSettings.lineStyleName 8-66MbeSettings.lineTerminator 8-66MbeSettings.nodeJustification 8-66MbeSettings.patternAngle1 8-66MbeSettings.patternAngle2 8-66MbeSettings.patternCell 8-66MbeSettings.patternScale 8-66MbeSettings.point 8-66

MbeSettings.selectionSetLock 8-67MbeSettings.setPatternDelta 8-66MbeSettings.setScale 8-66MbeSettings.settingErr 8-67MbeSettings.snapLock 8-67MbeSettings.tagIncrement 8-66MbeSettings.terminatorScale 8-66MbeSettings.textHeight 8-67MbeSettings.textJustification 8-67MbeSettings.textLineLength 8-67MbeSettings.textLineSpacing 8-67MbeSettings.textNodeLock 8-67MbeSettings.textWidth 8-67MbeSettings.weight 8-67

Sgn 7-3, 7-141

simple graphics elements 4-3attributes 4-5properties 4-5

Sin 7-3, 7-141

Singles see Macro Data Types

Sleep 7-4, 7-141

Sln 7-9, 7-142

snapLock 4-13

Space$ 7-7, 7-142

Spc 7-4, 7-143

Sqr 7-3, 7-143

State informationcmdResult 4-13errorMessages 4-14locateClassMask 4-14locateComponentFilePos 4-13locateFileNum 4-13locateHeaderFilePos 4-13locatePropMask 4-14locatePropVal 4-14locateTolerance 4-14measureResult1 4-14measureResult2 4-14messages 4-14noElementDisplay 4-14setLocateFileMask 4-14setLocateTypeMask 4-14

State Object 8-2MbeState.cmdResult 8-2MbeState.errorMessages 8-2

i-20 MicroStation BASIC Guide

Page 591: 48784209 Microstation Basic

Index: T

600macro.bk : 600MACRO.IX Page 21 Friday, October 15, 1999 1:27 PM

MbeState.getInputCommand 8-2MbeState.getInputDataPoint 8-2MbeState.getInputKeyin 8-2MbeState.getLocateFileMask 8-2MbeState.getLocateTypeMask 8-2MbeState.inputType 8-2MbeState.locateClassMask 8-3MbeState.locateComponentFilePos 8-2MbeState.locateFileNum 8-2MbeState.locateHeaderFilePos 8-2MbeState.locatePropMask 8-3MbeState.locatePropVal 8-3MbeState.locateTolerance 8-2MbeState.measureResult1 8-2MbeState.measureResult2 8-2MbeState.noElementDisplay 8-2MbeState.parseAll 8-2MbeState.setLocateFileMask 8-2MbeState.setLocateTypeMask 8-2

Status Message Field 2-8

Stop 7-5, 7-144

Str$ 7-7, 7-144

StrComp 7-7, 7-145

string concatenation operators see Expressionsstring concatenation operators

String$ 7-7, 7-146

Strings see Macro Data Types

style 4-8

Sub...End Sub 7-5, 7-146

Subroutine procedures 3-25

SYD 7-9, 7-147

Symbolic Constants 3-11

TTab 7-4, 7-148

Tag BASIC Extensions 8-184MbeGetTagSetNames 8-184MbeNumberOfTagSets 8-184

tagIncrement 4-13

Tan 7-3, 7-148

terminatorScale 4-13

text attributescharHeight 4-5

charWidth 4-5font 4-5getString 4-5justification 4-5

textHeight 4-13

textJustification 4-13

textLineLength 4-13

textLineSpacing 4-13

textNodeLock 4-13

textWidth 4-13

Then 7-5

Time$ 7-9, 7-149

Timer 7-9, 7-149

TimeSerial 7-9, 7-150

TimeValue 7-9, 7-150

Topology Objects 8-204GbeTLayerLine 8-204GbeTLayerMixed 8-204GbeTLayerPoint 8-204GbeTLayerPolygon 8-204

translation settings 4-26

Trim$ 7-7, 7-151

True 7-2, 7-151

truncation 3-12

Type 7-6, 7-151

type 4-5, 4-8

UUBound 7-3, 7-152

UCase$ 7-7, 7-153

UDT (User Defined Type) variables 2-13creating 3-8

UnLock 7-8, 7-153

User inputMbeGetInput 4-2MbeSendCommand 4-1MbeSendDataPoint 4-2MbeSendKeyin 4-1MbeSendReset 4-2MbeSendTentPoint 4-2MbeState 4-2

MicroStation BASIC Guide i-21

Page 592: 48784209 Microstation Basic

Index: V

600macro.bk : 600MACRO.IX Page 22 Friday, October 15, 1999 1:27 PM

MbeWriteCommand 4-2MbeWriteError 4-2MbeWriteMessage 4-2MbeWritePrompt 4-2MbeWriteStatus 4-2

Utilities MenuCreate Macro… 1-6, 2-1End Macro 1-7, 2-2Macros 1-5

VVal 7-7, 7-154

variable scope 3-9

Variable see Macro Data Type Variables

variables 1-2, 2-12changing values 2-12Variables dialog box 2-12viewing values 2-12

View Objects 8-99MbeView.active 8-99MbeView.areaFill 8-99MbeView.construction 8-99MbeView.deferApply 8-99MbeView.dimension 8-99MbeView.enterDataField 8-99MbeView.fastCurve 8-99MbeView.fastRefClip 8-99MbeView.getLevels 8-99MbeView.grid 8-99MbeView.levelsOff 8-99MbeView.levelsOn 8-99MbeView.levelSymbology 8-99MbeView.lineWeight 8-99MbeView.noText 8-99MbeView.pattern 8-99MbeView.refBoundary 8-99MbeView.screenNum 8-99MbeView.slowFont 8-99MbeView.textNode 8-99MbeView.update 8-99

Visual Basic 9-2

WWeekday 7-9, 7-155

weight 4-8, 4-13

Wend 7-5

While 7-5, 7-156

While...Wend 7-5, 7-156

Width# 7-8, 7-156

Word$ 7-7, 7-157

WordCount 7-7, 7-157

Write # 7-8, 7-158

XXor 3-14, 7-2, 7-158

YYear 7-9, 7-159

i-22 MicroStation BASIC Guide