941
Learning Microstation VBA Jerry Winters

Learning MicroStation VBA

  • Upload
    bill

  • View
    1.820

  • Download
    472

Embed Size (px)

DESCRIPTION

Learning with MicroStation VBA provides full coverage of the VBA subject, taking you through the basics like the editing environments, modules, visual interface and MicroStation object model through advanced topics like Windows API, interacting with other applications and Visual Basic. The book starts by supplying the foundation for understanding VBA basics and then shows how to apply the fundamentals to real-world situations.

Citation preview

  • Learning Microstation VBA

    Jerry Winters

  • LEARNING MICROSTATION VBA First Edition

    Copyright 0 2006 Bentley Systems, Incorporated. All Rights Reserved.

    Bentley, B Bentley logo, Bentley Institute Press, and Microstation are either registered or unregistered trademarks or servicemarks of Bentley Systems, Incorporated or one of its direct or indirect wholly-owned subsidiaries. Other brands and product names are trademarks of their respective owners.

    Publisher does not warrant or guarantee any of the products described herein or perform any independent analysis in connection with any of the product information contained herein. Publisher does not assume, and expressly disclaims, any obligation to obtain and include information other than that provided to it by the manufacturer.

    The reader is expressly warned to consider and adopt all safety precautions that might be indicated by the activities herein and to avoid all potential hazards. By following the instructions contained herein, the reader willingly assumes all risks in connection with such instructions.

    The publisher makes no representation or warranties of any kind, including but not limited to, the warranties of fitness for particular purpose of merchantability, nor are any such representations implied with respect to the material set forth herein, and the publisher takes no responsibility with respect to such material. The publisher shall not be liable for any special, consequential, or exemplary damages resulting, in whole or part, from the readers use of, or reliance upon, this material.

    ISBN Number: 0-9714141-8-1 Library of Congress Control Number: 2006903498

    Published by: Bentley Institute Press Bentley Systems, Incorporated 685 Stockton Drive Exton, PA 19341 yww.bentlev.com

    Printed in the U.S.A.

  • Introduction

    Learning Microstation VBA provides an in-depth tour of one of Microstations most powerful customization abilities. The book starts by supplying the foundation for understanding VBA basics and then shows how to apply the fundamentals to real-world situations.

    Learning Microstation VBA provides full coverage of the VBA subject - taking you through the basics like the editing environment, modules, visual interface, and Microstation object model through advanced topics like the Windows API, interacting with other applications, and Visual Basic, among many other things.

    Whether you are a Microstation user who simply wants to make your job easier or an experienced programmer who wants to master the nuances of Microstation VBA, this book is an invaluable resource for learning Microstation VBA.

    The following type styles are used in this book to distinguish various text:

    Filename or URL Menu and menu items

    Func t ion

    F u n c t i onIndex

    Keyboard key

    Object Variable

    xvi i

  • xviii I Introduction I

    ACCOMPANYING CD-ROM The accompanying CD includes all source code referenced in each chapter of the book. The CD also includes procedures, and addenda to the book as well as a comprehensive Object Model listing and other example files such as V8 DGN files, Microsoft Excel spreadsheets, Microsoft Access databases, and more.

    MYSELECT CD Bentley SELECT Subscribers can order the supporting files through the MySELECT CD program. MySELECT CD allows you to select the Bentley software or documents you need and have a CD delivered to your door.

    To become a Bentley SELECT Subscriber, go to http://1Yww.selectservices. bentley.com. Bentley SELECT is a subscription program that features product upgrades and updates.

    ABOUT THE AUTHOR Jerry Winters began his CAD career as many have, at the bottom of the totem pole, drafting eight hours a day. It didn't take long for him to discover that in many situations, the computer could complete repetitive tasks much faster than he could. So, he began writing programs that not only simplified the drawing creation process but significantly decreased the amount of time needed to create drawings. Rather than wasting the time saved by his programming efforts, Jerry used the new found time to write more programs until he stopped 'using' CAD software and began 'customizing' CAD software on a full-time basis. So, for the past 15 years, Jerry Winters has been customizing CAD software and teaching others to do the same.

    Whether it's on stage or in the written word, Jerry brings occasionally complex programming topics down to the level of the average CAD user (in part because he considers himself an average CAD user). His extensive knowledge of Visual Basic programming is complimented with Active Server Page development, database programming expertise, and the occasional creation of Java applets for graphically-rich web- based development.

  • I Acknowledgments I xix

    This is his first book on customizing Microstation with VBA and he experienced one difficulty throughout the entire book. There is just so much that can be done in Microstations VBA environment, it is difficult to know what to include and what to shelf for a later date.

    Jerry and his wife Candice are the parents of six children. They live in Lake Point, Utah, where they raise their children and their children raise chickens.

    ACKNOWLEDGMENTS I would like to thank the Technical Review Committee of Mark Anderson, Phil Chouinard and Robert Hook, as well as the Bentley Institute Press Team of Gilda Cellini, Frank Conforti, Lissa Jennings, Drew b o x , Maureen Rhoads, and Christopher Rogers, without whom this book would have never gotten off the ground.

    Furthermore, I would like to thank the Bentley Institute for affording me the opportunity to write about Microstations implementation of VBA. I hope the lessons learned in this book will be as rewarding to the reader as they have been for me.

  • Contents

    Introducing VBA ........................................ 1.1 Why Learn VBA? .............................................. 1-2 What is VBA? ................................................. 1-1

    When Should You Use VBA? .................................... 1-2 How Do We Use VBA? ......................................... 1-2 What does VBA look like? ....................................... 1-6 Review ........................................................ 1-7

    The VBA Project Manager ............................... 2.9 Macros Dialog Box ............................................ 2.12 VBA Project Manager Functionality ............................. 2.10

    Review ....................................................... 2-13

    The VBA IDE .......................................... 3-15 Menus ....................................................... 3-16

    File Menu ................................................ 3.16 Edit Menu ............................................... 3.17 ViewMenu ............................................... 3-18 InsertMenu .............................................. 3-19 FormatMenu ............................................. 3-19

    RunMenu ............................................... 3-20 Tools Menu .............................................. 3.20 Add-Ins Menu ............................................ 3.20 Window Menu ........................................... 3.21

    Debug Menu ............................................. 3.19

    iii

  • iv I Contents I

    Help Menu ............................................... 3.21 Toolbars ..................................................... 3.22

    Standard toolbar .......................................... 3-22 Edit toolbar .............................................. 3.22

    UserForm toolbar ......................................... 3.23 Windows .................................................... 3.23

    Debug toolbar ............................................ 3.22

    Project Explorer .......................................... 3.23 Object Browser ........................................... 3.24 Properties Window ........................................ 3-25 Watch Window ........................................... 3.25 Locals Window ........................................... 3.26 Immediate Window ....................................... 3.26 Call Stack Window ........................................ 3-27 Toolbox Window ......................................... 3.27 Other Windows ........................................... 3.28

    Review ...................................................... 3-30

    Finding Help ......................................... 4.31 Terminology ................................................. 4.32 Help Files .................................................... 4.34

    Contents tab .............................................. 4.35 Index tab ................................................. 4.36 Search tab ................................................ 4.37 Favorites tab .............................................. 4.37 Microstation VBA Help File ................................ 4.39

    The Net ...................................................... 4.40

    Review ...................................................... 4-44 The Object Browser ........................................... 4.42

    Modules. Forms. and Class Modules .................... 5.45 Modules ..................................................... 5.45 Forms ....................................................... 5-49 Classes ...................................................... 5.52 Procedures and Functions ...................................... 5.55

    Returning an Array ........................................ 5.60 Returning 'Types' ......................................... 5.62 Returning Objects ......................................... 5.63 ByVal and ByRef .......................................... 5.64 Declaring Variables ....................................... 5-66 Option Explicit ........................................... 5.67

    Review ...................................................... 5-67

  • V

    Variables ............................................ 6-69 Standard VBA Variable Types .................................. 6.70

    Integer ................................................... 6-70 Long .................................................... 6-70 Double .................................................. 6.71 Boolean .................................................. 6.72 Date ..................................................... 6-72 String .................................................... 6.72 Object ................................................... 6.72

    Application .............................................. 6.73 DesignFile ................................................ 6.74

    Variant .................................................. 6-73 Microstation-Specific Variable Types ............................ 6.73

    ModelReference .......................................... 6.74 Level .................................................... 6.74 LineElement .............................................. 6.75

    ArcElement .............................................. 6.75 TextElement .............................................. 6.76

    Assigning Values and Setting Objects ............................ 6.76

    Constants .................................................... 6-78 Variable Names ............................................... 6.78

    EllipseElement ............................................ 6.75

    Arrays ....................................................... 6.77

    Case Sensitivity ........................................... 6.80 Option Explicit ............................................... 6.80 Using Variables ............................................... 6.81 Review ....................................................... 6.82

    Working With Text ................................... 7-83 VBA String Functions ......................................... 7.84

    UCase ................................................... 7.84 LCase .................................................... 7.84 StrConv .................................................. 7.85 WeekDayName, WeekDayNumber .......................... 7.85 MonthName ............................................. 7.86 LTrim, RTrim, Trim ....................................... 7.86 StrComp ................................................. 7.87 Len ...................................................... 7.90 Left ..................................................... 7.90 Right .................................................... 7.90 Mid ..................................................... 7.91 Replace .................................................. 7.92 InStr .................................................... 7.92 InStrRev ................................................. 7-94

  • vi I Contents I

    Split and Join ............................................. 7.95 Asc and Chr .............................................. 7.96 FormatCurrency .......................................... 7.98 FormatNumber ........................................... 7.98 FormatDateTime .......................................... 7.99 Format ................................................. 7.100

    vbCr .................................................... 7.100 vbTab .................................................. 7.101

    Review ...................................................... 7-101

    & ...................................................... 7.100

    Working With Numbers .............................. 8-103 Numeric Functions ........................................... 8.103

    Addition ................................................ 8.104 ........................................................ 8-105 Subtraction .............................................. 8.105 Multiplication ........................................... 8.105 Division ................................................ 8-106 Squares and Exponents ................................... 8.106 SquareRoot ............................................. 8-107 Sine, Cosine, Tangent ..................................... 8.107 Arc Tangent ............................................. 8.110 Absolute Value .......................................... 8.110 Convert to Integer, to Long, to Double, and Value . . . . . . . . . . . . 8.111 CLng ................................................... 8.111 Fix ..................................................... 8.112 CDbl ................................................... 8.112 Val ..................................................... 8.113 IsNumeric .............................................. 8. 113 Round .................................................. 8.114 Mod . Find the Remainder ................................ 8.114 Sgn . Show me a sign ..................................... 8.115 Rnd and Randomize ...................................... 8. 115 Order of Operations ...................................... 8.116

    Review ...................................................... 8.116

    Standard VBA Calls .................................. 9-1 17 MessageBoxes ............................................... 9-117 InputBox ................................................... 9-120

    DateAdd ................................................ 9.122 DateDiff ................................................ 9.123 Timer .................................................. 9.124 FileDateTime ............................................ 9.124

    NOW! ................................................... 9.122

  • I Contents I vii

    FileLen ................................................. 9.124 MkDir .................................................. 9.124 RmDir .................................................. 9-125 Dir ..................................................... 9-125 Kill ..................................................... 9.127 Beep .................................................... 9-128 Savesetting .............................................. 9-128 Getsetting ............................................... 9-128 Deletesetting ............................................ 9.129 GetAllSettings ........................................... 9.129

    Reading and Writing to ASCII Files ............................ 9.130 FreeFile ................................................. 9.131 Reading from ASCII Files ................................. 9.134

    Controlling Code Execution ................................... 9.135 For ... Next .............................................. 9-136 While . . .Wend .......................................... 9.137

    For Each . . . Next ........................................ 9.141 If . . .Then .............................................. 9.141 Select Case .............................................. 9.142 Error Handling .......................................... 9.143

    Review ...................................................... 9-149

    DO . . . LOOP ............................................. 9-138

    Visual Interface .................................... 10-1 51 Properties. Methods. and Events ............................. . 1 0.152

    Properties .............................................. 10-152 Control Events ......................................... . 1 0.154

    Common Control Properties ................................. 10.155 Name .................................................. 10-156 Left.Top .............................................. . 1 0.156 Width. Height ......................................... . l 0.157 Visible ................................................. 10.157 Enabled ................................................ 10.157 TabStop ............................................... 10.157 TabIndex .............................................. 10-157 Tag ................................................... . l 0-158 ControlTipText ......................................... 10-158 Label ................................................. . l 0.158 TextBox ............................................... 10.158 Properties .............................................. 10-159 Events ................................................. 10.160

    ComboBox ................................................. 10-160 Properties .............................................. 10-160 Methods ............................................... 10.161

  • viii I Contents I

    Events ................................................. 10-161 ListBox .................................................... 10-161

    Properties .............................................. 10- 161 Methods ............................................... 10-161 Events ................................................. 10-162

    CheckBox .................................................. 10-162 Properties .............................................. 10-162 Events ................................................. 10-162

    OptionButton .............................................. 10.162 Properties .............................................. 10-163 Events ................................................. 10-163

    Toggle Button .............................................. 10-163 Properties .............................................. 10-163 Events ................................................. 10-163

    Frame .................................................... . l 0.164 Properties .............................................. 10-164

    CommandButton ........................................... 10-164 Properties .............................................. 10-164 Events ................................................. 10-164

    Tab Strip ................................................... 10-164 Properties .............................................. 10-165 Methods ............................................... 10-165 Events ................................................. 10-165

    MultiPage .................................................. 10.165 Properties .............................................. 10-165 Methods ............................................... 10-165 Events ................................................. 10-166

    ScrollBar ................................................... 10-166 Properties .............................................. 10-166 Events ................................................. 10-166

    SpinButton ................................................. 10.166 Properties .............................................. 10-167 Events ................................................. 10-167

    Image ..................................................... 10-167 Properties .............................................. 10-167

    User Interface Exercises ...................................... 10-167 Point List Reader ............................................ 10-174 Write Out File .............................................. 10.177 Zoom And Pan ............................................. 10-182 Review .................................................... 10-185

    The Microstation Object Model . Objects ............. . l l-187 The Object Browser ........................................ . ll-188 Auto List Members ......................................... . 1 1.190

  • I Contents I ix

    Microstation VBA Help File .................................. 11-190 Adding Watches ........................................... . 1 1.192 The Microstation Object Model .............................. . 1 1.192

    Application Object ..................................... . 1 1.193 Review .................................................... 11-241

    The Microstation Object Model . Enums ............. .I 2.243 MsdDesignFileFormat ....................................... 12.243 The Enumeration List ....................................... 12-245 Review .................................................... 12-277

    The Microstation Object Model . Types .............. .I 3.279 Review .................................................... 13-283

    The Microstation Object Model . Events ............. .I 4.285 OnDesignFileOpened and OnDesignFileClosed . . . . . . . . . . . . . . . . . 14.286 Review .................................................... 14-288

    Adding To Documents .............................. .I 5.289 Graphical Elements ......................................... 15-289

    Lines .................................................. 15-289 Creating Shapes ........................................ . 1 5.295 Creating Circles ......................................... 15-297 Creating Ellipses ....................................... . 1 5.300 Creating Arcs ........................................... 15-301 Creating Text .......................................... . 1 5.303 Creating Cells .......................................... 15-304

    Creating New Documents .................................... 15-307 Security Issues with Creating Data ............................ . 1 5.309 Review .................................................... 15-309

    Searching In Files .................................. .I 6.311 The Basics of Searching Files ................................. 16-31 1 Using Scancriteria .......................................... 16-316 Multiple Combinations of Criteria ............................. 16-321 Reviewing Three Collection methods ......................... . 1 6.324 Scan Criteria Methods ...................................... . 1 6.325 Review .................................................... 16-327

    Interactive Modification ............................ .I 7.329 Giving Users Feedback and Information ....................... 17.329 Working With Selection Sets ................................. 17-332

  • X I Contents I

    Getting User Input .......................................... 17.334 Some Real-World Applications .............................. . 1 7.338 Using Sendcommand ...................................... . 1 7.348 Modeless Dialog Boxes ...................................... . 1 7.353

    frmMatchProperties.frm ................................. 17.353 Providing User Feedback and Information ..................... 17.359

    UserForm Initialize ...................................... 17.360 frmAlignText.frm ....................................... 17.362 frmExportElements.frm. ................................. 17.377 frmDFAV.frm .......................................... 17.381

    Interacting with MDL Applications ........................... . 1 7.387 Review ..................................................... 17-390

    Interface Essentials ................................. 18-391 Interface Basics ............................................. 18.392 Class Module Review ........................................ 18.393 Class Module Lifecycle ....................................... 18.395

    ILocateCommandEvents ................................. 18.396 LocateFilter Event ....................................... 18.398 Accept Event ........................................... 18.399 LocateResetEvent ....................................... 18-399 LocateFailed Event ...................................... 18.399 StartEvent ............................................. 18-399 Cleanup Event ......................................... . 1 8.399 DynamicsEvent ........................................ 18-399

    Optimizing The Dynamics Event ......................... . 1 8.426

    Locatecriteria .......................................... 18.404 IPrimitiveCommandEvents ............................... 18.406

    Review ..................................................... 18-430

    Using MicroStation's Built-In User Forms ............. 19-431 Declaring Microstation User Form Functions . . . . . . . . . . . . . . . . . . . 19.431

    The mdlDialogfileOpen Function ........................ 19.432 The mdlDialogfileCr eate Function ....................... 19 -439 The mdlDialogfileCreateFromSeed Function . . . . . . . . . . . . . . 19.441 The mdlDialogopenAlert Function ....................... 19.443 The mdlDialogopenInfoBox Function .................... 19.443

    Review ..................................................... 19-444

    Class Modules ..................................... . 2 0.445 Encapsulating Similar Functionality .......................... . 2 0.446 Creating Objects with Properties. Methods. and Events . . . . . . . . . . . 2 0.462 Using Class Modules with Collections ........................ . 2 0.470

    Accessing Objects in a Collection ......................... . 2 0.471

  • I Contents I xi

    Removing Objects from a Collection ...................... .2 0.474 Using Custom Class Modules ............................ . 2 0.474

    Review ..................................................... 20-478

    VBA for CAD Managers ............................. . 2 1.479 Using VBA for Maintaining Standards ........................ . 2 1.479 Cross-Company Standards .................................. . 2 1.485 Tracking Time .............................................. 2 1-490

    Drafters ............................................... . 2 1.490 Managers .............................................. 21-490 Accountants ........................................... . 2 1.490

    Auto-Load and Auto-Run ................................... . 2 1.494

    Protecting Projects ......................................... . 2 1.498 Distributing VBA Projects ................................... . 2 1.501 Working in High Security Mode ............................. . 2 1.502 Review ..................................................... 21-503

    MS-VBA-OPEN-IN-MEMORY ......................... 2 1-495

    Microstation File-Based Events ...................... 22-505 OnDesignFileOpened ....................................... . 2 2.506 OnDesignFileClosed ........................................ . 2 2.507 ISaveAsEvents Interface ..................................... . 2 2.510 Review ..................................................... 22-517

    Responding to Microstation Attachment Events ..... . 2 3.519 The IAttachmentEvents Interface ............................ . 2 3.520 AfterAttach ............................................... . 2 3.520 After Detach ............................................... . 2 3.524 AttachmentModified Event .................................. . 2 3.525 BeforeAttach Event ......................................... . 2 3.525 BeforeDetach Event ........................................ . 2 3.526 Review ..................................................... 23-526

    Model Events ...................................... 24-527 Review ..................................................... 24-530

    Level Events ...................................... . 2 5.531 The Active Event ........................................... . 2 5.535 The Aftercreate Event ...................................... . 2 5.535 The AfterDelete Event ...................................... . 2 5.535 The BeforeChangeActive Event .............................. . 2 5.536 The BeforeDelete Event ..................................... . 2 5.536

  • xi i I Contents I

    The ChangeAttribute Event ................................. .2 5.536 Review .................................................... 25-536

    Change Track Events ............................... .2 6.537

    Example 1 ............................................. . 2 6.542 Example 2 ............................................. . 2 6.543 Example 3 ............................................. . 2 6.547 Example 4 ............................................. . 2 6.548

    BeginUndoRedo Event ...................................... . 2 6.537 Element Changed Event .................................... . 2 6.539

    Activating the ChangeTrackEvents Interface . . . . . . . . . . . . . . . . . . . .2 6.549 Review .................................................... 26-550

    Non-Graphical Info . Databases ..................... .2 7.551 Creating a Database from Scratch ............................ . 2 7.554 Making Use of UDL Files ................................... . 2 7.563

    How Microstation 'link elements to Databases . . . . . . . . . . . . . . . . . . 2 7.552

    Linking Microstation Elements to Database Records . . . . . . . . . . . . . 2 7.564 Creating Database Records using SQL ........................ . 2 7.565 Creating a User Interface to view Database Information . . . . . . . . . . 2 7.566 Review .................................................... 27-569

    Tags .............................................. .2 8.571 Getting Information from Tags based on a Selection . . . . . . . . . . . . . 2 8.572 Getting All Tags in a File .................................... . 2 8.574 Working with Tagsets ...................................... . 2 8.575 Getting All Tags of All Files in a Folder ....................... . 2 8.576

    Changing multiple Tags in Multiple Files ...................... . 2 8.579

    Review .................................................... 28-584

    Changing a Tag's Value ..................................... . 2 8.578

    Exporting Tag Information to a File .......................... . 2 8.580

    XML .............................................. .2 9.585

    Reading XML Files ......................................... . 2 9.587

    What is XML? ............................................. . 2 9.585 XML File Structure ......................................... . 2 9.586

    Review .................................................... 29-597

    Batch Processing .................................. .3 0.599 Processing All Files in a Folder ............................... . 3 0.603 Processing Files Listed in an ASCII File ....................... . 3 0.599

    Processing All Files in a Folder and SubFolders . . . . . . . . . . . . . . . . . 3 0.606

  • I Contents I xiii

    Creating a User Interface for File Selection .................... . 3 0.608 Logging File Batch Processing ............................... . 3 0.613

    Using a Log File ........................................ . 3 0.613 Tracking Activities with a Database ....................... . 3 0.615 Storing Information in the Registry ....................... . 3 0.615 Logging Activities over the Internet ....................... . 3 0.616 E-mailing Transaction Logs ............................. . 3 0.619

    Review ..................................................... 30-621

    The Standards Checker ............................ . 3 1.623 Basics of Implementing the Standards Checker . . . . . . . . . . . . . . . . . . 3 1-624

    Standards Check A ..................................... . 3 1.626 Standards Checker Settings .................................. . 3 1.631 Checking for Standards ..................................... . 3 1.634

    Where we are at this point ............................... . 3 1.634 Standards Checker Reporting ................................ . 3 1.639 Automatically Loading Custom Standards Checker Add-Ins . . . . . . 3 1.647 Review ..................................................... 31-648

    Using the Windows API ............................ . 3 2.649 Declaring API Calls ........................................ . 3 2.649 Declaring Types ........................................... . 3 2.650 Utilizing API Calls ......................................... . 3 2.651

    GetLogicalDrives ....................................... . 3 2.652 GetDriveType .......................................... 32-652 GetComputerName .................................... . 3 2.654 GetVersionEx ......................................... . 3 2.654 Sleep ................................................. . 3 2.656 FindExecutable ........................................ . 3 2.656 GetDiskFreeSpace ...................................... . 3 2.657 GetSystemMetrics ...................................... . 3 2.658

    GetWindowsDirectory .................................. . 3 2.660

    MessageBeep .......................................... . 3 2.662 Playsound ............................................ . 3 2.663

    GetTickCount ......................................... . 3 2.659 GetUserName ......................................... . 3 2.660

    Logonuser ............................................. 32-661

    ShellExecute ........................................... . 3 2.664 SHGetFileInfo ......................................... . 3 2.665

    Review ..................................................... 32-666

  • xiv I Contents I

    Using Third Party ActiveX Controls and DLLs ......... .3 3.667 Using ActiveX Controls ..................................... . 3 3.667 Using Existing DLLs ........................................ . 3 3.670

    Microsoft Scripting Runtime ............................ . 3 3.674 Microsoft Speech Object Library ......................... . 3 3.679 Microsoft CDO for Windows 2000 Library . . . . . . . . . . . . . . . . . 3 3.680 DSO OLE Document Properties Reader 2.0. . . . . . . . . . . . . . . . . 3 3.681

    Review ................................................... . 3 3.688

    Working With Excel ................................ .3 4.689 Connecting to Excel ........................................ . 3 4.689

    Getobject ............................................. . 3 4.689 Createobject .......................................... . 3 4.691 New .................................................. . 3 4.692

    Workbooks, Worksheets, Ranges, and Cells . . . . . . . . . . . . . . . . . . . . 3 4.692 Cell and Range Addresses ............................... . 3 4.697 Working with Worksheets .............................. . 3 4.702

    Tag Extraction ............................................. . 3 4.707 Review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.712

    Working With Databases (ActiveX Data Objects) ...... .3 5.713 Primer on ActiveX Data Objects ............................. . 3 5.714 UDL File Basics ............................................ . 3 5.716 Connections. Recordsets. and More .......................... . 3 5.719

    Recordsets ............................................ . 3 5.724 The Find Method ...................................... . 3 5.727 The GetString Method .................................. . 3 5.728 AddNew and Update ................................... . 3 5.729

    SQL Essentials ............................................. . 3 5.730 Select Statement ....................................... . 3 5.731 Where ................................................ . 3 5.732 Order By .............................................. . 3 5.732

    Extending ActiveX Data Objects ............................. . 3 5.740 Examining Database Schema ................................ . 3 5.745 Excel Files as Databases ..................................... . 3 5.749 Review ................................................... . 3 5.754

  • I Contents I xv

    Microstation Leveraging Mathcad via VBA .......... . 3 6.755 A Brief Introduction to Mathcad ............................. . 3 6.756 Adding a Reference and using the Object Browser . . . . . . . . . . . . . . . 3 6.756 Basic Macros that Communicate With Mathcad ................ .3 6.763 Region Objects . The Basis for All Calculations . . . . . . . . . . . . . . . . . . 3 6.766 The Mathcad Object Model .................................. . 3 6.769

    Application ........................................... . 3 6.769 IMathcadApplication2 .................................. . 3 6.770

    Driving Microstation Geometry from Mathcad . . . . . . . . . . . . . . . . . 3 6.771 Review ..................................................... 36-782

    Accessing Data from External Applications .......... . 3 7.783 ActiveX I COM Basics ...................................... . 3 7.784 References. Early Binding. and Late Binding . . . . . . . . . . . . . . . . . . . . 3 7.785 Getobject. Setobject. and New .............................. . 3 7.788

    When to use Getobject. Createobject. and New . . . . . . . . . . . . . 3 7.790 What does 'WithEvents' do for us? ............................ . 3 7.792 Run Macros from Excel or Microstation? ...................... . 3 7.793

    Running Excel Macros .................................. . 3 7.797 Review ..................................................... 37-805

    Controlling Microstation from within Excel . . . . . . . . . . . . . . . . . . . . 3 7.794

    Writing VB6 Applications ........................... 38-807 VB6 Project Structure ....................................... . 3 8.809 Controlling Microstation with VB6 ........................... . 3 8.816

    Creating an ActiveX Control in VB6 ...................... . 3 8.822 Debugging ActiveX Control Projects ...................... . 3 8.827 Compiling our ActiveX Control .......................... . 3 8.830 Creating ActiveX DLLs ................................. . 3 8.832

    Compiling and Distributing Applications ..................... . 3 8.837 Compiling Applications ................................. . 3 8.838 Distributing VB6 Applications ........................... . 3 8.839

    Differences between VBA and VB6 ........................... . 3 8.807

    Review ..................................................... 38-847

    Using VB.NET ..................................... . 3 9.849 VB.NET Introduction ...................................... . 3 9.850 You can do this in VB.NET! ................................. . 3 9.856 A DGN Browser Application ................................ . 3 9.862 VBA to VB.NET Reference .................................. . 3 9.866

    Everything is an Object ................................. . 3 9.866 Overloaded ............................................ . 3 9.867 Procedures and Functions ............................... . 3 9.868

  • xvi I Contents I

    Accessing ASCII Files ................................... . 3 9.868 Traversing a Folder and its Subfolders .................... . 3 9.870 Getting All Files in a path ............................... . 3 9.871 Returning Function Values .............................. . 3 9.872 Windows API Calls ..................................... . 3 9.872

    Distributing VB.NET Applications ........................... . 3 9.877 Review .................................................... 39-880

    Additional Sources ..................................... 881 Index ................................................. 883

  • Introducing VBA

    "LET'S START AT THE VERY BEGINNING. IT'S A VERY GOOD PLACE TO START."

    El WhatisVBA?

    El Why should we learn it?

    El When should we use it?

    El How do we use it?

    El What does it look like?

    These are five very good questions and they deserve answers.

    WHAT IS VBA? VBA is an abbreviation for Visual Basic for Applications. Microsoft licenses VBA to companies such as Bentley Systems, Inc., so users can customize the company's software. Then, companies that develop world-class software, such as Microstation, can give their customers the best set of tools available. These companies know that one way to accomplish this goal is to empower customers to modify and personalize their software to meet individual needs.

    1

  • 2 I Chapter 1 : Introducing VBA I

    WHY LEARN VBA? Learn VBA to rapidly develop programs that meet your individual needs. Much of what you learn in MicroStations VBA environment can be used in other VBA environments. The first two-thirds of the VBA abbreviation is VB. Visual Basic includes both the Visual Basic programming language and its programming environment. A finishes up the final third of VBA. The X is the Application-specific Objects and Application Programming Interfaces ( APIs).

    If we think of VBA as being two-thirds Visual Basic and one third Application, we could state that two-thirds of everything you learn in this book is directly applicable to other VBA environments. For example, if you learn Microstation VBA, you would be 2/3 of the way to knowing Microsoft Excel VBA. And this is not far off. So, in addition to being able to customize Microstation to meet your needs, learning VBA allows you to leverage other VBA-enabled applications.

    WHEN SHOULD You USE VBA? Only under the direct supervision of an adult?

    Between the hours of 8 AM and 5 PM?

    Holidays? Weekends?

    The real question you should be asking yourself is, Can the program I need to write be written in VBA? If the answer to this question is YES, then it should probably be written in VBA. And as you learn more about VBA, more and more often the answer to this question will be YES!

    How Do WE USE VBA? Microstation VBA programming is stored in files with an .mvba extension. To run any of the code in one of these Microstation VBA files you must first load the file. Before we go any further, lets create a new

  • I How Do We Use VBA? I 3

    drawing file named Introductiondgn. Go to the Microstation menu Utility > Macros > Project Manager to open the Project Manager.

    w

    We use the Project Manager to begin new VBA projects and open existing VBA projects.

    In this dialog box, click the Load Project button. Now, browse to the CD included with this book for a folder named MVBA Files. In this folder

  • 4 I Chapter 1 : Introducing VBA I

    you will find a file named Introductionmvba. Select this file and click the OK button.

    This loads the .mvba file into Microstation and displays it in the VBA Project Manager.

    1

    Opening an MVBA file does not close the Project Manager. The Project Manager remains open until you click the Close button in the upper right-hand corner of the dialog box.

    Now that we have loaded an .mvba file, we can run some code. How do we do it? There are a few ways. Lets begin by running code from within the VBA Project Manager. If the VBA Project Manager (VBAPM) is closed, follow the instructions above to re-open it. Make sure to load the 1ntroduction.rnvba file. In the VBAPM, select the VBA Project 1ntroduction.rnvba. Now look at the top of the VBAPM for a triangle that looks like the play button on a VCR. This is the Run Macro button.

  • I How Do We Use VBA? I 5

    When you click it, the Macros dialog box opens, which allows you to select which macro (procedure or function) you want to run.

    Select P r o c e d u r e A from the list of macros and click the Run button. The macros dialog box closes and a diagonal line is drawn in the active model. P r o c e d u r e A draws a line from (0, 0,O) to (10, 10,O) in the active file. If the macro is run and the line is not visible, use the Fit View button to zoom the active view to display all of the contents of the file.

    Remember, the steps to running an MVBA macro are:

    1

    2

    3

    Load the MVBA file using the VBAPM (VBA Project Manager).

    Select the project in the list of projects.

    Click the Run Macro button in the VBAPM, or click the Microstation menu Utilities > Macro > Macros, or hold down the key on your keyboard and press key.

    Its a three-step process. Of course, if the .mvba file is already loaded, You do not need to load it each time you run the macro. You can run a specific macro by using one of three methods described above in Step 3.

    You have just run a macro using the VBAPM. Now run one by using the keyboard shortcut. Hold down the key and then press the key to display the Macros dialog box. Select P r o c e d u r e C from the list and click the Run button. P r o c e d u r e C draws a square using

  • 6 I Chapter 1 : Introducing VBA I

    lines from (0, 0,O) to (10,0,0) to (10,10,0) to (0,10,0) and finally back to (0, 0,O).

    That's all there is to running a Microstation VBA macro. Load it and run it.

    WHAT DOES VBA LOOK LIKE? Here is the VBA code behind that macro:

    Sub P rocedureAo I ******** ' * T h i s P r o c e d u r e d raws a l i n e f r o m (10, 1 0 , 0) t o ( 3 0 , 1 0 , 0)

    D i m S t a r t p o i n t As P o i n t 3 d D i m E n d p o i n t As P o i n t 3 d D i m M y L i n e As L i n e E l e m e n t S t a r t P 0 i n t . X = 0 S t a r t P 0 i n t . Y = 0 : S t a r t P 0 i n t . Z = 0 E n d P 0 i n t . X = 10: E n d P 0 i n t . Y = 10: E n d P 0 i n t . Z = 0 S e t M y L i n e = CreateLineElementZ(Nothing, ~

    A c t i v e M o d e l R e f e r e n c e . A d d E 1 emen t M y L i n e

    I ********

    S t a r t p o i n t , E n d p o i n t )

    End Sub

    VBA Projects are broken up into blocks of code called procedures, functions, and events. Each block of code has a name. The procedure shown above is named ProcedureA. Comments in the code begin with an apostrophe. Everything after the apostrophe is part of the comment. Variables are declared with 'Dim' statements and are then assigned values or set to objects. Code in procedures, functions, and events runs from top to bottom. Together we will write a large number of functions and procedures as we study Microstation VBA.

    Back to the code in ProcedureA. It does not have a graphical user interface - it is just code. Writing code is one part of VBA development.

  • I Review I 7

    The other part of VBA development is the graphical user interface (GUI), such as buttons, text boxes, and labels.

    Some of the applications we write will have no GUI, but we will also explore the visual side of Visual Basic.

    VBA projects are contained in .mvba files. Each file contains code and can also contain graphical user interfaces. Load and unload VBA projects using the VBA Project Manager. After the code is written, You run VBA projects and the code they contain by using the Microstation menu Utilities > Macro > Macros ... or by pressing on the keyboard.

    Learning VBA is very much like learning a new language. It requires patience and time. Keep this in mind as we continue to study together.

  • The VBA Project Manager

    You have already seen how to display the VBA Project Manager. Remember, go to the Microstation menu Utilities > Macro > Project Manager. We used the Project Manager to load a VBA project and run a couple of macros contained in that project. Lets take a more comprehensive look at what the Project Manager can do for us.

    The Project Manager gives us the ability to load existing VBA projects.

    The Project Manager allows us to run the procedures and functions of projects that have already been loaded.

    Start new VBA projects using the Project Manager.

    Unload VBA Projects that are already loaded.

    Save loaded VBA Projects to a new location and/or a different

    Enter the Visual Basic Editor from the Project Manager.

    Record macros from the Project Manager.

    Auto-Load VBA Projects so projects are loaded each time

    file name.

    Microstation is started.

    9

  • 10 I Chapter 2: The VBA Project Manager I

    We can use the Microstation menu to display the VBA Project Manager or we can hold down the key and press the key to display the macros that are loaded and are ready to be run.

    We need to be careful when discussing the VBA Project Manager. The term Project Manager is so generic it could be confused with other products or functionality. For brevity we will refer to the VBA Project Manager as the VBAPM from time to time throughout this book.

    Now that we have identified the VBAPMs functionality in general it is time to examine it in greater detail.

    VBA PROJECT MANAGER FUNCTIONALITY The following graphic shows the VBAPM with its elements identified with leader lines. We will refer to the image during the remainder of this chapter.

    You are prompted for the location of the new .MVBA file and for its name.

    This button is enabled only when a n existing project is

  • I VBA Project Manager Functionality I 11

    Click this button to display the Run Macro dialog box

    activated, activities in Microstation are recorded to a

    Macro Recorder automatically names the macros. You can rename recorded macros in the VBA Editor.

    column, a checkmark indicates the file is set to Auto-

    We have just identified ten things that you can do directly from within the VBA Project Manager. One of these is Run Macro which, rather than actually running a macro, displays the Macros dialog box.

  • 12 I Chapter 2: The VBA Project Manager I

    MACROS DIALOG Box We use the Macros dialog box to select a macro to run but we can do far more in this dialog box than just running a macro. We can Step Into it.

    Step Into executes the macro in debug mode stepping through the code one line at a time so we can see how the code is executing, what values are stored in variables, etc. It is one of the best features of VBA, whether you are a novice programmer or a seasoned developer.

    The Edit button takes us into the VBA Editor window with the cursor on the top line of the selected Macro.

    The Delete button deletes the selected Macro from the VBA Project. This is a very dangerous button. After all, there is no Undo button displayed in this dialog box. Is there? Use with care.

    Macros in: lists VBA projects. If you select , the Macro list displays all executable macros from all loaded VBA Projects. Selecting a project filters the Macros list to display only those in the selected project.

    The Description area allows us to type in a description for a selected macro. This is a nice feature because we are given the ability to provide more information than by using the macro name only. For example, we do not need to name a macro,

  • I Review I 13

    Draw-A-Li n e ~ F r o r n ~ O ~ O ~ O ~ t o ~ l 0 ~ 0 ~ 0 . We can name it P r o c e d u r e A and enter a description in the Macros dialog box.

    We have covered every button in the Macros dialog box except for one, the button that is grayed out in the image above. You use the Create button to create new Macros. Its simple. Heres how it works:

    As you select macros in the Macros list, a TextBox just above the list box displays the macro selected name. If you change the text in the TextBox to a macro name (Procedure name) not already shown in the Macros list box, the Create button is enabled to begin a new macro with the name specified. So, if you type P r o c e d u r e A - 1 into the TextBox and click the Create button, a new Procedure named P r o c e d u r e A - 1 is created. Of course, no code is entered into the procedure after it is created. That is our job. We can now select P r o c e d u r e A - 1 from the ListBox, click the Edit button, and go into the new procedure in the VBA Editor to begin writing code.

    The VBA Project Manager is useful for performing a number of tasks. Among them are:

    To load and unload VBA projects (MVBA files).

    To save existing VBA projects to new files and locations.

    To begin new VBA projects.

    To record macros into existing VBA projects.

    To use Auto-Load to automatically load VBA projects within

    To enter the VBA Editor from within the VBAPM.

    the VBAPM.

  • The VBA IDE

    Open the VBA IDE PDQ!!! Yes, the IDE is WYSIWYG. GM?

    Translation: Open the Visual Basic for Applications Integrated Development Environment Pretty Darn Quick!!! Yes, the Integrated Development Environment is What You See Is What You Get: Got Milk?

    The VBA IDE is where we do our VBA programming work. As with most Windows programs, the VBA IDE is composed of three elements:

    Menus

    Toolbars

    El Windows

    15

  • 16 I Chapter 3: The VBA IDE I

    Nearly all Microsoft Windows applications utilize Menus to issue commands. Many menu items have shortcuts. For example, holding down the key and pressing the key does the same thing as selecting File > Print from the menu. Whether you click your mouse or use the associated shortcuts, it is helpful to know what a menu item does. Lets look at the menu items that are available in VBA.

    File Menu Import File imports existing

    form (.frm), module (.bas), and class (.cls) files into our project.

    Export File exports forms, modules, and classes from our project to their own .frm, .bas,

    and .cls files. After these files have been exported, they can be imported into another project.

    Remove removes forms, modules, and classes from our project. When we attempt to remove an element from our project we are asked if we want to export it (save it) first.

    Ctrl+M

  • I Menus I 17

    Print allows us to print code and/or forms.

    Close and Return to Microstation hides the VBA environment and gives Microstation focus.

    Edit Menu Undo and Redo are standard Windows menu items.

    Cut, Copy, and Paste perform standard Windows Clipboard operations.

    objects.

    Select All selects all text when in a Code window or all controls when in a User Form.

    Clear deletes selected text or

    The Find, Find Next, and Replace menu items perform standard Find and Replace functions.

    Indent indents the selected code by one tab to the right. Outdent (is Outdent a real word?) shifts the selected code by one tab to the left.

    *

    List Properties/Methods displays the Properties/Methods list.

    List Constants works with an API call that utilizes constants. A list of the applicable constants is shown.

    objects property or method and then click Quick Info to display the type of object or variable on which the cursor was placed.

    To use Quick Info, set the cursor on a variable, an object, or an

    Parameter Info displays information about the Method the

    Complete Word shows the list of Constants and Methods in

    cursor is over.

    VBA so we can select something from the list.

    moves from bookmark to bookmark. A bookmark is a flag that Bookmarks sets and removes bookmarks in our code and

  • 18 I Chapter 3: The VBA IDE I

    lets you quickly jump to a line of code. Bookmarks are not saved with .mvba projects.

    View Menu El When looking at a user form,

    click Code to jump to the code behind the form.

    El Object displays the form associated with the code we are looking at.

    El Click on Definition when the cursor is over the item you want to look at to quickly display where the variable is declared or the method is defined.

    ElLast Position moves the cursor to the previous line of code the cursor was in.

    El Object Browser, Immediate Window, Locals Window, Watch Window, Call Stack, Project Explorer, Properties Window, and Toolbox display a window with the same name.

    can see the order in which controls receive focus when the user hits the Tab button in the form.

    Tab Order displays the Tab Order properties of controls so we

    Toolbars toggles the display of the Debug, Edit, Standard, and

    El Click on Microstation to bring the Microstation window to the

    User Form toolbars.

    forefront.

  • I Menus I 19

    Insert Menu Procedure displays the Add Procedure dialog box to begin new procedures. This dialog box is most useful for creating new Properties for Class Modules.

    inserts these new objects into our project.

    One way to speed up our development is to reuse code that has already been written. If we place code in ASCII Text Files, insert snippets into our project by clicking File and then selecting the file to insert.

    UserForm, Module, and Class Module

    Format Menu

    Use the Format menu to perform standard formatting when editing a User Form.

    Debug Menu The Debug menu allows us to perform debugging operations on our code. We will cover this functionality in Chapter 9 "Standard VBA Calls".

  • 20 I Chapter 3: The VBA IDE I

    Run Menu Run Macro, Break into, and Reset

    code execution by using these menu items in the Run menu.

    Design Mode is a standard VBA *

    button that does nothing substantive in the Microstation implementation of VBA.

    Tools Menu References allows us to add a reference to existing DLLs and type libraries. For example, if we want to work with Microsoft Excel, we can add a reference to the Microsoft Excel Object Library. Doing so makes working with Excel in VBA very easy.

    forms. We can add more controls by selecting the Additional Controls menu item.

    Macros displays the Macros dialog box where we can create,

    Change preferences such as font size, tab width, and grid

    By default, 14 controls display in the toolbox for use in our

    edit, run, delete, and debug macros in our project.

    settings by clicking on Options.

    1

    The Properties menu item displays the properties for the active VBA project. In the image shown above, the project is named Default.

    Digital Signature allows us to sign our VBA projects. This assures end users that the code they are going to run is created by a specific company.

    Add-Ins Menu Third party developers can create add-Ins for VBA. Add-In Manager displays the Add-In dialog box where we can set properties for available add-ins.

  • I Menus I 21

    Since we will not be discussing Add-Ins anywhere else in this book, here is a snapshot of the manager with an add-in that has been loaded. Add- ins can be loaded based on the Load Behavior settings.

    Window Menu

    These are the standard menu items available in nearly every Microsoft Windows program.

    L

    Help Menu We will cover Help issues in the next chapter. One way to get there is by clicking the Microsoft Visual Basic Help menu item.

    About Microsoft Visual Basic displays the About dialog box.

  • 22 I Chapter 3: The VBA IDE I

    TOOLBARS Toolbars offer a very quick way to issue a command. One click is usually all it takes to get things started. Compare this with at least two clicks to issue the same command using a menu and we can instantly double our CIP (Command Issuing Performance). As a general rule, all commands issued by clicking on a toolbar icon can be issued from the menus.

    It can take a little while to become familiar with toolbar icons. Until you learn what each icon does, hold your cursor over an icon to see what the icon does.

    Standard toolbar

    The Standard toolbar is very, very important. Why? Because the only way to save the changes we are making in our VBA project from within VBA is to click the Save button. We cannot Save changes by using the menu. We must use the Save icon in the Standard toolbar. And please, please, please, my friend, save your project often. There are few things worse than spending a couple of hours working on a project only to have something silly like a power outage or a fatal error cause you to lose all of that work.

    Notice how holding your cursor over an icon displays the icons tool tip.

    We could show each and every button on every toolbar but that would be a bit of a waste because you can move your cursor over the icons to see what they do.

    View MivoStatmn

    Edit toolbar The Edit toolbar displays functionality found in the . Edit menu.

    Debug tool bar

    The Debug toolbar displays the functionality found in the Debug menu.

  • I Windows I

    UserForm tool bar

    23

    The UserForm toolbar exposes functionality found in the Format menu.

    WINDOWS Use the toolbars and menu items to display and hide VBA windows. Lets take a look at the VBA windows we will be working with on a regular basis.

    Project Explorer The Project Explorer displays the top-level objects in the loaded projects.

    In this project we have a form named UserForm 1, a module named Module1 and a class module named Class1 . The view shown uses folders to group the common types of objects.

    Click on the Folder icon in the top of the Project Explorer to turn off Folders and display the objects in alphabetical order.

  • 24 I Chapter 3: The VBA IDE I

    Object Browser

    L

    The Object Browser gives us a way to explore the objects (classes) loaded into the current VBA project. In addition to the objects themselves, we see a list of properties, methods, and events associated with each object under the Members list. The gray area at the bottom of the window gives us the declaration of the selected method, property, or event. We can display All Libraries or select a specific library. We also have the ability to search the loaded libraries.

    We will cover the Object Browser in more detail in the next chapter.

  • I Windows I

    Properties Window

    25

    Objects in VBA have names. For example, this user form has the name UserForml. We can use the Properties window to change this forms name, color, and other properties. The Properties window is used extensively when working with forms and controls on forms.

    Watch Window

    The Watch window is a favorite among VBA developers. It allows us to watch the value of a variable, object, or property. As we can see above, I added a watch to a variable named MyApp. This variable points to the Microstation Application. Take a look at all of the properties with which we can work.

  • 26 I Chapter 3: The VBA IDE I

    Locals Window

    The Locals window looks a lot like the Watch window. There is one primary difference however. To look at items in the Watch window, you must add a watch to the item. The Locals window automatically displays the variables declared in the active procedure or function along with each variables type and value.

    Immediate Window

    The Immediate window does a couple of things for us. First, it allows us to display text as our code executes. When we use the following code

    D i m MyApp As A p p l i c a t i o n Se t MyApp = A p p l i c a t i o n

    D e b u g . P r i n t MyApp.Capt ion

    the caption of the Microstation application is printed to the Immediate window. For this reason, it is also called the Debug window.

    The other thing the Immediate window does is it allows us to execute code immediately. For example, we can type MsgBox L e a r n i n g M i c r o s t a t i o n V B A

  • I Windows I 27

    in the Immediate window and press the key. When we do so, a MessageBox displays.

    Call Stack Window

    As we step through our code line-by-line or break into our code as it is executing, the Call Stack window shows us where we are (the top line), where we started (the bottom line), and how we got there (all of the lines in between). There are times when one procedure calls another procedure which calls a function which calls a procedure. Knowing how we arrived inside a procedure or function can help us debug it.

    Toolbox Window The Toolbox window displays the standard controls that can be placed on our user forms. It only displays when a user form is the active window in VBA. If we are working with a user form and the toolbox is not visible, click on the Toolbox icon in the Standard toolbar or go to the View > Toolbox menu to display it.

    All of the windows discussed so far are dockable except for the Toolbox. This means they can be snapped to the bottom, top, right, or left window of the VBA IDE. These windows dockable property is set in the

  • 28 I Chapter 3: The VBA IDE I

    Docking tab of the Options dialog box. To view this, go to the Tools menu in VBA and select Options.

    OK

    If an attempt to dock a window fails, look at the Docking property of the window in the Options dialog box and turn on Docking for the specific window you want to dock. As with many applications, these windows are docked by dragging the window to the edge where you want the window docked. They are un-docked by dragging the window away from the edge where the window is currently docked.

    Other Windows There are a couple of additional windows in VBA we should discuss. As we have already discovered, VBA projects are composed of forms, modules, and classes. Each of these elements has its own windows.

    Here is a Form.

  • I Windows I 29

    A single CommandButton has been added to this form. This form window allows us to place controls on it. Remember, the controls are placed from the toolbox to the form.

    What happens when we are running this form and the user clicks the button? Code is executed. Double-clicking the button takes us to Code window behind the form. Another way to see the code is to right-click on the button and select View Code.

    This is the C l i c k E v e n t of CommandButtonl. View Code takes us to the default event of the control we right-click over. So, here we can see the C1 i c k Event . Are there other events we can work with? How do we see them and write code in them?

    Private Sub Comman Dim MyApp As A Set MyApp = Ap Debug.Print My DrawL ine

    End Sub

    Sub DrawLine ( )

    End Sub MsgBox "XI is

    Private Sub CommandButtonl-Click() Dim MyApp As Application Set MyApp = Application Debug.Print MyApp.Caption DrawL ine

    End Sub

    Sub DrawLine ( )

    Take a look at the top of the Code window. There are two ComboBoxes. The left one contains the controls and objects available in this Code window. The right one contains the events we can work with. Selecting an event

  • 30 I Chapter 3: The VBA IDE I

    from the right ComboBox takes us into the code for that event.

    Open Module (Code Module) and Class Module windows by double- clicking on their icons in the Project Explorer or by right-clicking on the icons and selecting View Code. They look exactly like the Code window shown above.

    We have spent a few pages discussing the VBA IDE. As we continue learning Microstation VBA, we will discover other facets of the IDE and get into more detail.

    The VBA IDE (Visual Basic for Applications Integrated Development Environment) is where we do our programming, i.e. writing code and creating user interfaces. As you become more familiar with this environment, you will be able to develop your programs much more quickly.

  • Finding Help

    Finding help can be one of the most difficult aspects of learning a new programming language. Why? If you have a question for someone, you can converse with them until the question is clear. Thats easy. When learning VBA, however, you dont always know what to ask. For example you might ask, How do I put something on a form that forces a user to enter a numeric value? If you could ask a VBA guru this question, you will get a straightforward answer. Working through a Help file for the answer is different. For starters, even if you know what to ask but you dont know the correct terminology, you wont find the answer.

    Distressing? Yes. Frustrating? Definitely. The end of civilization as we know it? No.

    This book is targeted toward helping you learn Microstation VBA. It is filled with code samples and explanations but it does not contain every answer to every possible question. Here a few things that will provide help when you need it.

    In this Chapter: Terminology

    Help Files

    TheNet

    The Object Browser

    31

  • 32 I Chapter 4: Finding Help I

    TERMINOLOGY Thingy. Dilly Whopper. Whatchamacallit. Gizmo. Whether we are asking a person or a computer, these words will get us nowhere. How can we get a little closer to the right keyword?

    Lets begin by looking in VBA.

    Holding your cursor over a variety of objects displays a Tool Tip. There is a ComboBox

    we ask about a ComboBox we are

    more likely to find answers than if we ask about a DropDown. Both combinations of words may make sense to us, but using the correct name for the control gets us closer to finding answers to our questions than using terminology that, although descriptive, is not correct.

    Since the terminology used in VBA may be foreign to you when getting started, it is a good idea to make notes or highlight areas of this book and other resources when you come across a word or phrase you want to remember or that you may want to be able to find quickly at a later date.

    For example, if you are asked to provide a string, you may produce a piece of flexible material useful for restricting blood circulation in ones index finger with the intent of reminding you of something. As for me, Im just as likely to forget the string is tied around my finger as I am to forget why the string is there in the first place. What does this mean? Before long we are collectively fingerless. Or is it finger-free? Digitless?

    m icon in the Toolbox. If

  • I Terminology I 33

    What is a string when it comes to VBA? It is a type of variable that can hold text, numbers, and other characters. This is a test is an example of a string. Since the word string is very different when dealing with VBA when compared to Benjamin Franklins experiments with electricity, highlighting the definition of a string type variable in a book may be helpful.

    In addition to highlighting existing text, get out a pen or pencil and write in the margins of this book.

    Chicken Soup for the VBA Programmer. The VBA Word of the Day. The VBA Programmers Daily Calendar. These products may not exist but they could be very helpful. Why? Frequent and regular exposure reinforces retention.

    If your goal were to obtain a dark tan, you would want regular exposure to the sun. If your goal were to bake bread, it would be out of reach if you rarely stepped inside a kitchen. Practice makes Perfect, No Pain, No Gain, and If at first you dont succeed, try, try again. We have heard these statements over and over again. Each of them reminds us that frequent and prolonged exposure and practice is usually necessary for success in any endeavor. While you dont need to write a thousand lines of code every day to learn VBA terminology, 20 lines of code every day will do more than 100 lines of code only on Monday mornings.

    If you expose yourself to VBA frequently, the terminology becomes familiar and you will be in a better position to find the help you need.

  • 34 I Chapter 4: Finding Help I

    HELP FILES One way to display the VBA Help File is to go to the Help menu in VBA and select Microsoft Visual Basic Help.

    Visual Basic See i\k Spea!!c>

    Welcome to the Visual Basic documentation.

    Visual Basic includes many documentation tools, each designed to help you learn and use a particular aspect of the product. The documentation provided with Visual Basic includes the following:

    Visual Basic User Interface Help

    Look here for Help on interface elements of the Visual Basic Editor, such as commands, dialog boxes, windows, and toolbars.

    Visual Basic Conceptual Topics

    The Conceptual Help topics include information to help you understand Visual Basic programming.

    Visual Basic HOW-TO Topics

    Look in the How To section of Help to find useful common procedures, for example, how to use the Object Browser or how to set Visual Basic Environment options.

    Visual Basic Language Reference

    The Language Reference is the place to find Help on Visual Basic the language: all its methods, properties, statements, functions, operators, and objects.

    It is filled with a large amount of information but also gives us the ability to organize our own unique help file by using of the Favorites tab.

    So, you want a little help with a ComboBox? Lets begin in the Contents tab and drill down to the ComboBox starting with the Microsoft Forms Reference.

  • I Help Files I

    Contents tab

    ComboBox Control See Also Example Properties Methods

    Combines the features of a ListBon and a TextBox. The user can en ter a new value, as with a TentBon, o r the user can select an existing value as with a ListBon.

    Remarks

    If a ComboBox is bound t o a data source, then the ComboBon inserts the value the user enters o r selects into t h a t data source, If a mult icolumn combo box is bound, then the BoundColumn property determines which value is stored in the bound data source,

    The list in a ComboBon consists of rows of data. Each row can have one o r more columns, which can appear with o r without headings. Some applications do not support column headings, others provide only l imi ted s u p p o r t

    Events 4pf t i imsr

    35

    It may take a little digging to find what you are looking for using the Contents tab but knowing the correct terminology is a big help. At the top of many help topics, are links for See Also, Example, Properties, Methods, Events, and Specifics: If you are looking for more explanations, See Also is very helpful. If you are looking for code to copy and paste, Example is the link you want. For information about specific Properties, Methods, and Events, click the appropriate link.

    The body of help topics often contain hyperlinks to other topics and pop-ups to explain the highlighted text in greater detail.

    You can print help Help topics by clicking the Print icon at the top of the file.

  • I Chapter 4: Finding Help I

    Index tab

    CompareMode property Filter function InStrRev function Replace function Split function wildcard s

    string conversion String data type String function String keyword String$ function strings

    aligning character comparing concatenating converting data types fixed-length formats justifying leftmost characters length manipulating matching middle characters removing spaces repeating replacing returning from functions reversing rightmost characters searching spaces substrings variable-length

    clearing color comparing converting cutting and pasting entering from numbers importing I o o p in g searchinglieplacing String data type

    text files inserting

    TextStream oblect The binary compatibility DLL or E) The binary compatibility DLL or E) Then keyword This [Me keyword] Tile Horizontally command Tile Vertically command Time function time intervals

    adding difference

    Time keyword time stamp Time statement Time$ function Timer function timers times

    adding converting creating Date data type determining

    The Index tab displays a different way to organize help topics. It works much like the index of a book. This is another area where using correct terminology is very helpful. If you enter string in the keyword textbox, you get a large number of linked topics. Enter text and you get a number of unrelated topics (if we are looking for information on the String variable type) but also a link to the String data type. So even if you dont have the exact terminology, getting close to the correct word may link you to the correct topic.

  • I Help Files I

    Search tab

    37

    Use the Search tab to enter a word or series of words to search for in the help topics. It returns a list of all help topics containing the word(s) entered. For example, if you enter combobox, you are returned a listing of 67 topics. Some topics are properties such as List Property. Other topics are instructional, such as Ways to put data in a ListBox or ComboBox. Keep in mind that most help topics are linked to related topics. So, we could begin with a search for combobox and read far more than 67 topics by jumping to other help topics.

    Toolbox Visual Basic ... 2 Unable to unload withi ... Visual Basic ... 3 Understanding Object ... Visual Basic ... 4 MatchFound, MatchR ... Microsoft Fo ... 5 Layout Event, OldLeft ... Microsoft Fo ... 6 Style Property Microsoft Fo ... 7 DblClick Event, CanP ... Microsoft Fo ... 8 ComboBox Control, A,.. Microsoft Fo ... 9 Ways to put data in a ... Microsoft Fo ... 10 List Property Microsoft Fo ... 11 Thingsyou can do wit ... Microsoft Fo ... 12 Style Property Example Microsoft Fo ... 13 MatchEntry Property, ... Microsoft Fo ... 14 AutoTab Property Microsoft Fo ... 15 BoundColumn Property Microsoft Fo ... 16 Text Property Microsoft Fo ... 17 CurX Property Microsoft Fo ... 18 TextColumn Property Microsoft Fo ... 19 Value Property Microsoft Fo ... 20 Locked, DropButtonS ... Microsoft Fo ... 21 DropDown Method Ex ... Microsoft Fo ... 22 DragBehavior Property Microsoft Fo ... 23 Listwidth Property Ex ... Microsoft Fo ... 24 ListRows Property Ex ... Microsoft Fo ... 25 Linecount Property Microsoft Fo ... 26 Add items to a list usin ... Microsoft Fo ... 27 Listlndex Property Microsoft Fo ... 28 Liststyle Property Microsoft Fo ... 29

    Favorites tab

    t data in a Listsox or

    See Also C-:oe:,i.c~

    In a ListBox or the AddItem rn technique for adding an indiv In a rnulticolurnn ListBo. or the List and Column properties offer another technique; you can load the list from a two- dimensional =.

    with a single column, er an effective

    o the list. ,however,

    If you find a particularly helpful help topic or one that was difficult to find, add it to your Favorites. The Current topic text box displays the

  • 38 I Chapter 4: Finding Help I

    default topic title. Fortunately, you can change this description to whatever you want it to say. For example, you could change it to ComboBox - Adding To the List. Then click the Add button.

    Favorites is one of the best ways to personalize the standard Visual Basic Help file. Sure, you can print out page after page after page, use a highlighter and make a binder. That is a fine way to catalog what you have learned and create additional reference material. But Favorites is a quick way to find bookmarked topics and jumps to linked topics. It also keeps the Copy and Paste functionality available.

    To sum up, VBA stands for Visual Basic for Applications. Thus far in this chapter, we have been discussing how to find help for the VB portion of VBA. What about the Y? The Application? Good question.

    Learning everything about the VBA programming language will give us some good background but will not get us very far when attempting to interact with Microstation.

  • I Help Files I

    Microstation VBA Help File

    p Loading and running a VBA macro Frequently asked MicroStation VBA Questions

    Recording and Revising Macros Automating common MicroStation tasks Working with MicroStation Objects Working with MicroStation Events Customizing MicroStation withvisual Basic Converting from MicroStation Basic toVBA

    Changes for MicroStationVBXM Edition

    39

    Microstation V8 Visual Basic for Applications Visual Basic and VBA are thoroughly modern object- oriented programming environments used by both professional application developers and casual programmers. Visual Basic is the primary development platform for a large number of commercial products, some of which you may use on a daily basis. Visual Basic for Applications shares most of Visual

    Microstation has its own VBA Help file. It contains MicroStation- specific help for VBA. Searching for the file microstationvba.chm on your computer should show us where it is and let you open it.

    m Adding the Contents of a Fence to a Named Group AnalyzeArc

    H Application Element Evample p A m By Length H Area Booleans

    Attaching and Searching a Cell Libraiy B spline Curve Point Extraction B spline Surface From Gridded Point Interpolation

    p B spline Surface From Poles p B spline Surface From Scattered Point Appioximation H Centering theview at the Curroi p Changing a Relerence File Path from Absolute to Logical

    Changing an Attachment to Releience the Oelault Model p Changing Coordinate Readout in a S a v d s Event p Changing the Update Order ol Attachments

    Vertex List Example This example illustrates some of the methods of the VelteXL1St interface. The example 15 a simple primitive command that implements event handlers for start, data point, and reset. Because the other event handlers of IP,imitiveCommandEvents do nothing in this example, they have been omitted.

    Mort of the logic for this example IS in the data point event handler. It tests to determine if it has a raved reference to an element. If not, it tries to locate an element using LocateElement. I f it successfully finds an element that rupportr the VertexLirt interface, it retriever the list of verticer using GetVerticer. It prints the vertex list, and i a v e s the reference t o the object. On rubsequent data points, it detects that it already har an element. It user GetClorertSesment to get the index of the first vertex of the segment closest to the data point. k i n g that information, it prints the range of the closest segment.

    The reset event handler in this example just restarts the command. It invoker CommandState.StartPrImltlve. StartPrimitiue f irst resets MicroStationr command

    One of the most helpful sections in the Microstation VBA help file is the Examples folder, which contains excellent explanations as well as the code to perform specific tasks.

  • 40 I Chapter 4: Finding Help I

    Another excellent way to open the Microstation VBA Help file is to select a Microstation-specific API call in the Object Browser or in our code and hit the key on the keyboard.

    THE NET Got Net? http://msdn.microsoft.com/isv/technology/vba/default.aspx gets us to Microsofts VBA web site. If this URL is difficult to remember, you can also use http://msdn.microsoft.com/vba, which contains links to white papers, Knowledge Base articles, and other reference materials that comprise a wealth of information on VBA programming and its associated topics. Although you are not likely to find much about Microstations VBA-specific implementation here, you will find many other examples on how to accomplish specific tasks in the VBA environment.

  • I The Net I 41

    Google, Yahoo, and other search engines can unlock the rest of the Internets VBA knowledge for us. Remember, there are a lot of programming languages out there. A search for Message Box returns us a large number of web pages to check out, but in addition to VBA results, we will get pages for C#, C++, Java, JavaScript, Fortran, Pascal, and other languages.

    A quick trip to the Bentley web site and a search for vba nets some good information as well. Why not go directly to the source?

    ~ ~ L ~ C 7 s ~ r ~ i ~ ~ ~ I 8279 - UP^^ W8A tine^ The follo:+irig GEOPAK \iBk rwt ines are provided t r ee far voiir use. We at Bentley I?OUI: that you red? prududivir), bsriclits from atitomaliny GEOFCK Civi! Engineering Su!te with VBA.

    ________________ ~ ~ L ~ C ~ ~ ~ r u i ~ e s Laz;?s _________ - C ~ n ~ i ~ ~ r ~ t i ~ ~ W ~ r i ~ b l ~ ~ in M i ~ ~ . u ~ t ~ ~ ~ ~ R V 8 Th!s technical Dociiment provides s description #f the variables in MicroStation V8 !Ziiii? Editiun, V8 0 and di3.t)

    ..............................................................

    .............................................................

    Among the Bentley Discussion Groups we find Bent/ey.microstution.v8.vba. This is a good place to ask questions. And who knows? As you become a VBA guru in your own right, you may be

  • 42 I Chapter 4: Finding Help I

    able to help others by answering their questions in this Discussion Group.

    You can access any of these groups via must papular discussion gruup neimre f rom a Web browser-, visit ht ip: i /discus5ion,ien:lry , c o n .

    g a n t t o past a test article from a newsreader? Ga to Bm:leg.tcstpcsts.

    M ~ c ~ ~ S t a ~ ~ ~ n R e ntl e f ~ n? i cm stati o n v 8 . >. n e a rl Y a cce s s I n e A 2

    THE OBJECT BROWSER We talk to Microstation through its Object Model. The top level of the Microstations Object Model is the Application Object. Using the Object Browser in VBA is a great help when you are trying to discover something about an Object Model. As shown, you can restrict browsing to the Microstation DGN library so all Microstation Classes show up in the ListBox on the left. Selecting Application in the left ListBox

  • I The Object Browser I 43

    displays its properties, methods, and events in the listbox on the right side of the window.

    For example, if you have selected Application in the ListBox on the left and want to do something with the active design file in Microstation, click on ActiveDesignFile in the right-hand ListBox. The description at the bottom of the Object Browser tells us the ActiveDesignFile property of the Application Object returns a DesignFile object. We can now select DesignFile in the Classes list (the listbox on the left) to see the Design Files properties, methods, and events in the Members list on the right.

  • 44 I Chapter 4: Finding Help I

    Selecting AddNewLevel in the Members list shows that we need to supply a LevelName when using AddNewLevel. It also shows that AddNewLevel returns a Level Object.

    One reason the Object Browser is helpful is because you can start at a very general level (Application) and work down through the object model to the object, property, method, or event for which you are looking. We can literally browse through the available objects and APIs using the Object Browser.

    Other ways to find/get help? Take a Bentley-approved VBA training class or attend the annual Bentley Developer Conference.

    Finding help is not always easy. Knowing where to look is the first step. Next, using correct terminology moves us along the path to finding the answers to our questions. Learning to use tools, such as the Object Browser, provides more answers.

    Keep in mind that the most simple subjects still require effort to learn and retain. VBA is no different. If you allow yourself to become frustrated, the chances of success are diminished. You can learn Microstation VBA. You really can.