To load a VBA project and run a macro within it:

The square brackets must surround the name of the project to be loaded.

What's inside a VBA project?

A VBA project is normally a collection of several VBA items related to a specific task or operation. There are three types of items within a project:

Forms

Forms are definitions for GUI components such as dialog boxes or settings windows (also referred to as UserForms).

Modules

Modules are programming code organized as functions and subroutines. Macro names are identified from specific subroutine names. Modules also are referred to as Code Modules.

Note: A “macro” in MicroStation VBA is a sub procedure that takes no arguments, and is defined in a code module.

Class Modules

A class module is a container in which you can create a definition of your own object type. Usually a class module has data and methods for working with that data. This sounds a lot like a code module doesn't it? The primary difference between a code module and a class module is that there is never more than one copy of anything inside a code module, but you can create multiple copies of a class by creating objects from the class.

MicroStation V8 Objects

MicroStation Object Model Hierarchy

The classes* in the MicroStation Automation Object Model are shown below:

*The classes that represent the graphic elements are not shown in this chart with the exception of the general Element class.

Application object structure

The structure of the application object is shown below:

Application Object

ModelReference object structure

The structure of the ModelReference object is shown below:

ModelReference Object

Attachment object structure

The structure of the Attachment object is shown below:

Attachment Object

ActiveSettings object structure

The structure of the ActiveSettings object is shown below:

ActiveSettings Object

What is not in the Automation Object Model?

The Automation Object Model in MicroStation does not include the following capabilities and features:

Drawing design elements into an ActiveX control

Displaying a MicroStation view as an ActiveX control

Plotting, other than Windows printing

Creating MicroStation menu entries

Understanding Objects, Properties and Methods in MicroStation VBA

Collectively, the objects and methods that are specific to MicroStation are known as the “MicroStation Automation Object Model”.

Nearly every instruction that you add to VBA code in MicroStation will somehow reference an object, property or method, so it is important to understand these terms and the features they represent.

MicroStation's Objects

Each drawing element in a MicroStation DGN file can be represented by an object in Visual Basic. Objects are also used to represent MicroStation's features such as views and view groups, cell libraries, the fence, fonts and many other features. There is also an object that represents the MicroStation application itself. In short, objects are a fundamental necessity for working with VBA in MicroStation.

Object Properties

Most objects, especially objects that represent drawing elements, have properties. A property is an attribute of an object, such as color, line weight or style. Properties can also affect the behavior of the object. For example the IsLocked property can be used to set an element's locked status.

To set the value of a property, use the name of the object followed by a period and the name of the property, an equal sign, and the new value for the property. For example, to change the color of a line element object named “element1” to red, you would use the following line:

element1.Color = 3

Some object properties cannot be changed, for example the IsPlanar property is used to test whether an element lies completely in one plane. Since this is a test of whether the object meets the specific condition, it is useful for taking action based on that condition. To continue with the same example, the following line sets the color of line element “element1” to blue if it is planar:

If element1.isPlanar = True Then element1.Color = 1

When object properties can only be “read” in this fashion and are not changeable, they are said to be “Read-only” properties. The Help topic for each property indicates whether it is “Read/Write” or “Read-only”.

Object Methods

A “method” is an action that an object can perform. For example, the ShapeElement object has an Area method. To calculate the area enclosed by the ShapeElement object “shape1”, you would use the following line:

Double dArea = shape1.area()

Methods often require arguments that determine specifically how the action is performed, or with what information it is performed. For instance, the View object has a Zoom method for zooming in. The Zoom method requires a value for setting the zoom factor. Using the zoom method to increase magnification by a factor of 3.0 in the view “view1” looks like this:

view1.Zoom 3.0

Calling sub and function procedures

The most common types of methods in VBA are sub procedures and functions. The primary difference between them is that a function returns a value to the statement where it was called, and a sub procedure does not. When you call a sub procedure, you can either use the Call statement, like this:

Call OpenDesignFile ("d:\myDesign.dgn")

or, just use the name of the sub procedure followed by any arguments it requires, like this:

OpenDesignFile "d:\myDesign.dgn"

Note: when you use the Call statement, you must put parentheses around the arguments for the procedure. When you use just the name of the sub procedure, the parentheses should not be used.

Calling a function is similar to calling a sub procedure. If you are not using the return value of the function you may choose to use the Call statement or not, following the guidelines above. If you use the return value from a function, you must surround the arguments to the function with parentheses.

MicroStation VBA Overview FAQ

Do I have to use the MicroStation VBA editor for my VBA applications to run in MicroStation V8? Answer

Are there any configuration variables in MicroStation V8 that must be set before I can use MicroStation VBA? Answer

What key-ins are used with MicroStation VBA and what do they do? Answer

Answers to MicroStation VBA Overview Questions

(What is MicroStation VBA?)MicroStation V8 includes and supports Visual Basic for Applications, one of today's most popular languages. MicroStation VBA is a complete Application Programming Interface that allows you to write custom applications that interface with MicroStation V8.

(What can I do with MicroStation VBA?)The goal of MicroStation VBA is to allow you to develop your own custom applications to automate many activities in MicroStation. Using VBA, you can develop standard desktop applications that can interact with MicroStation, increasing user productivity. VBA includes a wide array of tools that provide users with more and easier customization that ever before.

(What Bentley products support MicroStation VBA?)Currently, Bentley MicroStation, MicroStation PowerDraft, Bentley Navigator, and Bentley Redline support creating, recording and running MicroStation VBA macros. Support for MicroStation VBA is limited in Bentley Redline to the abilities of that product. Other Bentley software products provide APIs that are accessible from VBA. More information is available on the Bentley web site.

(Do I have to use the MicroStation VBA editor for my VBA applications to run in MicroStation V8?)No, you can write VBA code in whatever text editor you choose; however, to compile the code to work in MicroStation V8 you must paste it into a code window in the VBA editor in MicroStation V8.

(Are there any configuration variables in MicroStation V8 that must be set before I can use MicroStation VBA?)No. There are configuration variables that modify the behavior of MicroStation VBA, but they do not have to be adjusted before using VBA in MicroStation. See MicroStation VBA Environment Variables.

(What key-ins are used with MicroStation VBA and what do they do?)A list of the key-in commands that can be used with various parts of MicroStation VBA can be found in this help file. See MicroStation VBA Key-ins.

MicroStation VBA Programming FAQ

Typically, what skills are needed to start programming with VBA in MicroStation V8? Answer

Can I protect my MicroStation VBA project so that others cannot see the source code in it, but can still run it? Answer

How can I get the contents of the current selection set in MicroStation VBA? Answer

How can I pass arguments to a VBA macro that is activated with a key-in command? Answer

Answers to MicroStation VBA Programming Questions

(Typically, what skills are needed to start programming with VBA in MicroStation V8?)The MicroStation VBA language is most consistent with the Visual Basic for Applications programming language standards and styles. Programming skills acquired in learning the Visual Basic for Applications language with the Microsoft Office suite of applications will provide a good background for programming with VBA in MicroStation V8.

(Can I add non-modal dialog boxes to my MicroStation VBA macro?)Yes. To make a user form non-modal, set the ShowModal property of the form to False. This can be done in the Properties window for the user form. Additionally, a dialog can be displayed in a non-modal form using the optional boolean parameter to the Show method that sets the ShowModal property. To display a form named UserForm1 as non-modal, the Show method would be written:

UserForm1.Show vbModeless

(How do I compile a MicroStation VBA macro?)In the VBA editor window, select the Run menu, then choose Run Sub/User Form. The macro is compiled immediately before it is executed. A shortcut to this menu item is to press the <F5> function key, which has the same effect.

(Can I protect my MicroStation VBA project so that others cannot see the source code in it, but can still run it?)Yes. In the Visual Basic editor window select the Tools menu, then select the menu item that shows [project name] Properties, where [project name] is the name of the current project. In this dialog, select the Protection tab. Here, a password can be added so that editing or viewing the source code in the project requires the user to enter the password.

(How can I get the contents of the current selection set in MicroStation VBA?)First dimension a variable of type ElementEnumerator, then set this variable to the return value of GetSelectedElements from the ActiveModelReference, like this:

(How can I pass arguments to a VBA macro that is activated with a key-in command?)Microsoft's VBA implementation does not support passing command line arguments to a basic macro. However, Bentley has added a means to accomplish this through the use of a global variable named KeyinArguments. This string variable will contain any additional arguments that were provided to the vba run <macro>keyin. For example, this sub-procedure:

To open the Project Manager dialog box:

The Project Manager Tool bar

The Project Manager dialog box does not have pull-down menus like most other dialog boxes in MicroStation that manage files or settings. Instead, it has a tool bar at the top of the dialog that gives access to most of the commands necessary to manage Visual Basic projects and macros. Each of the tools that appears in the Project Manager tool bar is described below.

New Project

The New Project icon is used to create a new VBA project. When you click the New Project icon, the Create VBA Project dialog appears, allowing you to enter the name and location of the file that will be created to contain the new project. Initially, the root file name is also used to name the project module in the Project Manager dialog. It is not necessary for the project module to remain the same as the file that contains it.

Load Project

The Load Project icon is used to load an existing VBA project into the Project Manager. When you click the Load Project icon, the Load Project dialog appears, allowing you to select the .mvba file to load. After choosing a file, clicking the OK button loads the contents of the chosen file into Project Manager.

Like many other dialogs that load various files in MicroStation, a configuration variable can be selected to set the path to choose a project file, or the Current Working directory can also be selected from the Directory menu in this dialog box.

Unload Project

The Unload Project icon is used to unload a Visual Basic project that is currently loaded in memory. The Unload Project icon is dimmed and unselectable until a project is selected in the Project Manager window. Clicking the Unload Project icon immediately unloads the selected project. If a macro in the selected project is currently running when the Unload Project icon is selected, it is halted before the project unloads.

Save As

The Save As icon is used to duplicate the selected project to another project file, but it does not rename the project module itself. For example, if a project module named “macros2” is currently loaded in Project Manager and is selected, and the Save As icon is chosen, another file can be created which will then also contain a project named “macros2” even though the file name will be different from the file that contained the original project.

Visual Basic Editor

The Visual Basic Editor icon is used to display the editor window and its contents. All currently loaded projects are accessible from the editor window, so it is not necessary to select a project from the Project Manager before clicking the Visual Basic Editor window. Since it is not possible to create a Visual Basic project in the editor window, any necessary project should be created or loaded before opening the editor.

Macros

The Macros icon is used to display the Macros dialog box, showing a list of all available macros in all loaded projects. See the Macros dialog box for more information.

Start Record

The Start Record icon is used to begin the process of recording actions in MicroStation to a Visual Basic macro. The Start Record icon is dimmed and not selectable unless a project is currently highlighted in the Project Manager list of projects.

Stop Record

The Stop Record icon is used to stop the process of recording actions in MicroStation to a Visual Basic macro. The Stop Record icon is dimmed and not selectable until the recording process has been initiated. Once the Stop Record icon is clicked, the macro can only be changed or appended by using the Visual Basic editor.

Pause Record

The Pause Record icon is used to temporarily stop the macro recording process so that some action or command that should not be recorded can take place. The Pause Record icon is dimmed and not selectable until the recording process is initiated. Once the recording process has been paused, any actions in MicroStation are not recorded to the macro. To resume recording, click the Pause Record icon a second time.

Other functions of the Project Manager

The Project Manager dialog box also provides features for renaming projects, for adding and editing macro descriptions, and for setting a project to autoload. These functions are described below.

In addition, the Project Manager has a pop-up menu that appears when a right-click takes place in the project list area of the dialog. The items in this menu parallel the functions of the tool bar icons, or the functions described below.

Renaming a project

The Name field in the VBA Project Manager dialog is an editable field. This means the name of the currently highlighted project can be edited by clicking directly on the name, or by right-clicking, and selecting Rename from the pop-up menu.

Adding or editing a project description

The Description field in the VBA Project Manager dialog box is also an editable field. This means the description of the currently highlighted project can be edited by clicking directly on the description. While there is no practical limit to the length of a project description, it is only displayed in the Project Manager dialog, which has limited room for description display, and in a flyover tag that appears when the pointer is moved over the description field.

Autoloading a project

A project can be selected to “autoload” when MicroStation is opened. This makes the macros within that project available immediately upon startup. To set a project to autoload, load the project into Project Manager, then click the Autoload field for that project in the Project Manager dialog box. A check mark in this field indicates the project will “autoload” the next time MicroStation is started.

Note: A project is not automatically loaded at startup unless the file that contains it is in a directory that is specified in the MicroStation configuration variable MS_VBASEARCHDIRECTORIES. See VBA Configuration Variables for more information.

The Macros dialog box

The Macros dialog box provides a list of available macros within a selected VBA project, or within all currently loaded projects. Its functions are described below.

Viewing the contents of a project

The Macros dialog box displays either the list of macros available from all currently loaded projects, or from one selected project, depending on the method by which the Macros dialog was initiated.

If the spin-box item labeled Macros In: shows “<All Standard Projects>”, then the contents of the macro list include macros from all currently loaded project files. The spin-box can then be used to limit the list to just the macros in one project.

If the spin-box item labeled Macros In: shows “<All Standard Modules>”, then the contents of the macro list is limited to the macros in the project shown in the dialog title bar. The spin-box can then be used to further limit the list to just the macros in one module within the selected project.

Running a macro

Once a macro is selected from the list in the Macros dialog box, running it can be initiated by clicking the Run button in the Macros dialog.

Debugging a macro

A macro selected from the list in the Macros dialog box can be started in the debugging mode by clicking the Step Into button in the Macros dialog.

Editing a macro

The macro selected from the list in the Macros dialog box can be opened in the Visual Basic Editor by clicking the Edit button in the Macros dialog.

Deleting a macro

The macro selected from the list in the Macros dialog box can be deleted from the project in which it resides by clicking the Delete button in Macros dialog.

MicroStation VBA Environment Variables

There are several environment variables that are specific to the Visual Basic implementation in MicroStation. These primarily control the location for new Visual Basic project files, and the search path for existing Visual Basic project files. There are additional considerations though, when setting these variables.

To quickly find the variables related to Visual Basic, open the Configuration dialog box (Workspace >Configuration from the main menu) then scroll through the list on the left side of the dialog to the bottom, and select the Visual Basic for Applications category.

Location of new VBA projects

The MicroStation configuration variable MS_VBANEWPROJECTDIRECTORY determines the default location for new Visual Basic project files. By default, this variable is set to \Bentley\Workspace\standards\vba\ which is also the location of the SampleProject.mvba file, one of the delivered Visual Basic projects.

The MS_VBANEWPROJECTDIRECTORY can contain more than one directory, although only the first directory is used, all others are ignored.

Search path for VBA projects

The MicroStation configuration variable MS_VBASEARCHDIRECTORIES determines the directories in which MicroStation will search for projects when they are loaded by name. This variable also sets the location from which VBA projects can be autoloaded at startup time. See Autoloading a project for more information on choosing a project to load automatically.

Names of standard projects

The MicroStation configuration variables MS_VBAAUTOLOADPROJECTS and MS_VBAREQUIREDPROJECTS determine which projects are automatically loaded at startup time. MicroStation loads the projects listed in MS_VBAREQUIREDPROJECTS prior to loading the projects listed in MS_VBAAUTOLOADPROJECTS.

MS_VBAAUTOLOADPROJECTS is not usually set in the Configuration dialog box, but it contains a list of the project names that are chosen in the Project Manager dialog. See Autoloading a project for more information on choosing a project to load automatically.

One benefit of adding a project to the MS_VBAAUTOLOADPROJECTS variable through the Configuration dialog box, is that a project outside of the paths specified by MS_VBASEARCHDIRECTORIES can be set to autoload by entering the full file path specification including drive and directory paths.

The MicroStation configuration variable MS_VBAREQUIREDPROJECTS also names projects that are autoloaded. The VBA Project Manager nevers adds projects to or removes projects from the list that MS_VBAREQUIREDPROJECTS specifies.

The VBA Project Manager displays a check in the Auto-Load column for every project listed by MS_VBAAUTOLOADPROJECTS or MS_VBAREQUIREDPROJECTS. However, the user cannot turn off Auto-Load for projects listed by MS_VBAREQUIREDPROJECTS.

MicroStation has some configuration variables that let a user specify a list of applications to be loaded in response to some event. When MicroStation processes one of these lists, it checks each entry to see if it ends with ".MVBA". If the entry does end with ".MVBA", then MicroStation interprets it as the name of a VBA application. Otherwise, MicroStation interprets it as the name of an MDL application. As an example, the Standards Checker's initialization logic asks MicroStation to load all of the applications that the configurarion variable MS_STANDARDSCHECKER_APPS specifies. Therefore, setting MS_STANDARDSCHECKER_APPS to "SCByLevel.mvba;SCCompleteRefCheck.mvba;SCSimpleRefCheck.mvba" causes the StandardsChecker's initialization logic to load these VBA projects.

Automatically saving projects

The MicroStation configuration variable MS_VBASAVEONRUN determines whether modified VBA projects are automatically saved when a VBA program is executed. The default value for this variable is 1, indicating projects will automatically be saved. To prevent MicroStation from saving modified projects automatically, set this variable to 0. If this variable is 0, MicroStation does not automatically save the project. When unloading a project MicroStation tests to see if a project has changes that have not been saved. If it does and this variable is 1 then MicroStation saves the project. If it has unsaved changes and this variable is 0, then MicroStation asks the user if he wants to save the changes. This logic applies when the user makes an explicit request to unload a project. It also applies at shutdown, since MicroStation unloads every project at shutdown.

Opening project from memory or disk

The MicroStation configuration variable MS_VBA_OPEN_IN_MEMORY controls whether MicroStation keeps a project's data available by keeping the project's disk file open, or by copying the project into memory. If a lot of users are accessing they same project, they may encounter an error that happens because there is a limit on the number of processes that can simultaneously have a file open. To avoid this restriction, set MS_VBA_OPEN_IN_MEMORY to tell MicroStation to open the project from an in-memory image instead of keeping the project file open.

The allowable values for MS_VBA_OPEN_IN_MEMORY are "all", "readonly", and "none". If the value is "readonly", then MicroStation tests to see if the project file is read-only. If it is, then MicroStation copies the image into memory and opens it from the in-memory image. Otherwise, it opens the project from the file and keeps the file open. If the value is "all", then everytime MicroStation opens a project it copies that project into memory and opens it from the in-memory image. A value of "all" also forces MicroStation to make all projects read-only. If the value of MS_VBA_OPEN_IN_MEMORY is "none" or if MS_VBA_OPEN_IN_MEMORY is not defined, then MicroStation opens all projects from disk.

To be able to save the changes to a project, it is necessary to have MicroStation load it from disk. A user who edits projects should not have MS_VBA_OPEN_IN_MEMORY defined, or should have it defined as "none" or "readonly".

To be able to have a lot of users open a project at once, it is necessary to have MicroStation copy it into memory so MicroStation does not need to keep the project file open. The users who open this project should have MS_VBA_OPEN_IN_MEMORY set to "readonly" if they edit some projects and open some shared, readonly projects; or they should have MS_VBA_OPEN_IN_MEMORY set to "all" if they open projects shared by a lot of users but never edit projects.

The value of "a lot of users" is determined by the number of processes that can have a file open at once. The limit comes from the Windows enviroment. 20 is a common limit.

MS_VBA_OPEN_IN_MEMORY normally is not defined because the default behavior is acceptable for most users.

Automatically referencing projects at project creation

A MicroStation project can contain references to other VBA projects and to type libraries. A user can set these refererences manually in the VBA Editor by selecting the project, selecting References from the Tools pulldown menu, and then selecting the library or VBA project. A user can use the MS_VBAGUIDREFERENCES and the MS_VBANAMEDREFERENCES enviroment variables to force MicroStation to assign project references when it creates a new project. For a example, a user could add the following lines to msfiles.cfg:

# The following causes MicroStation to add a reference# to Microsoft Visual Basic for Applications Extensibility 5.3# (VBE6EXT.OLB) when it creates a new VBA projectMS_VBAGUIDREFERENCES > {0002E157-0000-0000-C000-000000000046},5,3# The following causes causes MicroStation to add a reference# to the Microsoft Scripting Runtime (scrrun.dll) when it creates# a new VBA projectMS_VBAGUIDREFERENCES > {420B2830-E718-11CF-893D-00A0C9054228}# The following causes causes MicroStation to add a reference# to Microsoft VBScript Regular Expressions (vbscript.dll) when it# creates a new VBA project# MS_VBAGUIDREFERENCES > {3F4DACA7-160D-11D2-A8E9-00104B365C9F}# The following causes causes MicroStation to references to the # VBA project NativeCodeUtilities, VBE_Tools, and MSElementWrapper when # it creates a new VBA project.MS_VBANAMEDREFERENCES=NativeCodeUtilities;VBE_Tools;MSElementWrapper

MicroStation VBA Key-ins

Key-ins can also be used to activate and control Visual Basic projects and macros within MicroStation.

Controlling VBA projects with keyins

Most functions relating to projects that can be accomplished in the Project Manager can also be controlled using key-in commands. The most common keyins related to projects are described below.

To create a Visual Basic project:

Use the following key-in:

VBA CREATE <projectname>

This key-in creates a new VBA project and loads it into the project list in the Project Manager. If a file path is not specified, the project is created in the \Bentley\Program\MicroStation\ directory, unless the MS_VBANEWPROJECTDIRECTORY configuration variable has been set. If the path has been set, the location specified by this variable is the location for the new project. See Location of new VBA projects.

To load an existing Visual Basic project:

Use the following key-in:

VBA LOAD <projectname>

If the file path to the .mvba file is not specified, then MicroStation searches in the directories specified by MS_VBASEARCHDIRECTORIES. If a .mvba file is found with a root name that matches the specified project name, it is loaded. See Search path for VBA projects.

To open the Visual Basic editor:

Use the following key-in:

VBA EDIT <projectname>

The Microsoft Visual Basic window opens showing the specified project. If the named project is not currently loaded but can be found in the path(s) set by MS_VBASEARCHDIRECTORIES, it will be loaded automatically. The Visual Basic editor window can also be invoked with the following key-in:

VBA SHOW EDITOR

To run a VBA macro from a currently loaded project:

Use the following key-in:

VBA RUN <macroname>

The macro begins running immediately.

To load a project and run a macro with one key-in:

Use the following key-in:

VBA RUN [projectname]<macroname>

Be sure to include the square brackets around the project name, so that MicroStation knows which .mvba file to search for.

Note: The square brackets are also needed if two loaded projects have macros with the same name.

To execute a VBA statement with a key-in:

Use the following key-in:

VBA EXECUTE [projectname] <statement>

The statement is executed in the context of the named project. If no project name is specified, MicroStation chooses a project to use as the context. There is no need to specify a context if the statement uses only the MicroStationDGN object model.

The VBA statement is not case-sensitive. For example, the key-in:

VBA EXECUTE if ActiveModelReference.Is3D then MsgBox "Three D"

is the equivalent of:

VBA EXECUTE if activemodelreference.is3d then msgbox "Three D"

To save all currently loaded projects:

Use the following key-in:

VBA SAVEALL

Any project that is currently loaded and has been modified is saved to its .mvba disk file.

To unload a currently loaded project:

Use the following key-in:

VBA UNLOAD <projectname>

The specified project is immediately unloaded.

To hide the Visual Basic editor:

Use the following key-in:

VBA HIDE

The Visual Basic editor window is closed, even if it is in the background (not visible) when the key-in is entered. This key-in does not disable any VBA functionality, it merely hides the development environment.

To start recording macro:

Use the following key-in:

VBA START RECORDING [project]<macroname>

The recording process starts.

Note: There are a couple of variations to this key-in.

vba start recording [myProject]myMacroThis will create a macro named “myMacro” in the first module in the project named “myProject”. Be sure to include the square brackets around the project name.

vba start recording myModule.mymacroThis will create a macro named “myMacro” in the first module named “myModule”. The module must already exist before the macro can be recorded.

Using the key-in: vba start recording myMacro will result in an error message because not enough information has been supplied.

To stop recording a macro:

Use the following key-in:

VBA STOP RECORDING

The recording process stops immediately.

To pause recording a macro:

Use the following key-in:

VBA PAUSE RECORDING

No actions will be recorded after this key-in until the recording process is resumed.

To stop recording a macro:

Use the following key-in:

VBA STOP RECORDING

The recording process is stopped immediately.

Using the MicroStation VBA Editor

The MicroStation VBA editor window provides standard features found in all implementations of Visual Basic for Applications whether in Microsoft Word, Microsoft Excel, MicroStation V8 or any other program that includes VBA.

About the VBA Editor

Visual Basic and VBA present a user-friendly yet complete program development environment for both the casual programmer and the professional application developer alike. Once opened (from MicroStation's main menu, Utilities > Macro > Visual Basic Editor), the Visual Basic editor provides a rich set of tools and functions. If you are starting a new VBA project, you must first create then load the project using the VBA Project Manager (select the New Project icon located on the Project Manager toolbar). This is also required before you can use the Record macro function.

Project files loaded from the Project Manager or the command line will appear in the Project window. From here, you begin the program creation process by inserting one or more of the VB items (Forms, Modules or Class Modules). Probably the fastest way to get some code into your project is to insert a code module (from the Visual Basic Editor's main menu, Insert > Module). The VB Editor inserts an empty module named Module1 in your project file (the Modules category automatically appears when you create your first module). Module1 is also opened for editing in its own code window. You can rename the module using the Properties window for the module.

The Properties window is another important feature you will want to watch in the VB Editor. This window displays the properties of whatever item you currently have selected. You can set or change a variety of settings for the active item, depending on the nature of the item.

The Object Browser

One of the most useful features in the VBA Editor environment is the Object Browser window. To display the object browser, select View >Object Browser, or press the <F2> key after the VBA Editor environment is opened.

The Object Browser provides a point-and-click interface to all objects currently available for use in your program. This is a good place to start exploring the actions you can perform using VBA in MicroStation. Selecting “MicroStationDGN” from the Libraries selection menu shows only those objects, methods, properties and events associated with the MicroStation DGN Object Library. Clicking on an individual class item in the left column displays the members of the class in the right column. If you then click on the Help icon (the question mark), the entry on that particular member is displayed in the Help window.

Debugging a macro

Once a macro has executable code in it, you can step through the code in the debugger. This process allows you to watch the execution of the code line by line to help you identify problem areas of the macro.

To debug a macro in the VBA Editor environment:

Make sure the input focus is in the code window in the macro to be run in debugging mode.

From the Visual Basic Editor main menu select Debug >Step Into.The debugging process begins. The first line becomes highlighted and an arrow on the left side of the code shows the current line of execution.

Pressing the <F8> key advances the execution to the next line in the macro that contains an executable instruction.Note: Dimension statements are not considered executable statements in a macro and are skipped over in the debugger.

To stop the debugging process:

Advance the debugger to the last instruction in the macro by repeatedly pressing the <F8> key. The debugger stops after last instruction is executed.

Alternative method to stop the debugging process:

From the main menu in the VBA Editor environment, select Run >Reset.If the debugging process is running, it stops immediately.

Recording and Revising a VBA macro

The “record” feature that is provided with VBA in MicroStation V8 is intended to be an aid in writing VBA macros more quickly and easily. The code that it records is frequently not suitable for playing back immediately after it is recorded. It is always a good idea to edit the recorded macro and revise its contents at least to make it more user friendly.

Recording a VBA macro in MicroStation

To record a set of actions as a VBA macro

From the Utilities menu, choose Macro > Project Manager.

In the Project Manager dialog, create a new project to contain the recorded macro or load an existing project to contain the macro.

When you have performed all of the actions to be recorded, click the Stop Recording button in the Project Manager to stop recording actions to the macro.

Editing a recorded VBA macro

When a macro is recorded in VBA in MicroStation, the first data point entered is in absolute coordinates, and all following data points are relative to this location. A recorded macro that places a few line segments using the Place SmartLine tool might look like this:

Sub Macro1() Dim startPoint As Point3d Dim point As Point3d, point2 As Point3d

When this macro is played back it will redraw the same elements in exactly the same location every time. This macro would be much more useful if the location were determined by user input rather than hard coded with specific coordinates. To do this, the macro must be edited slightly to get the first location from the first data point entered by the user. The changes to make this happen are shown in bold type in the code below.

Running this modified code will draw the same elements as the recorded macro, only it will wait for a data point from the user, and the elements are drawn at that location. Other attributes of the elements could also be specified within the macro, such as color, level, line weight, and line style.

Playing back a VBA macro

Once a macro has been recorded, it can be “played back” to duplicate the actions it recorded. This is the same as running a VBA macro that was written using the editor. From within the editor, select the Run menu, then choose Run Sub/User Form. The <F5> function key is a keyboard shortcut to this menu item. The recorded macro can also be played back from the Macros dialog box .

Automating MicroStation Tasks with VBA

One of the purposes of Visual Basic for Applications is to assist in automating repetitive tasks in MicroStation. To this end, VBA has a “record” feature that will watch your actions in MicroStation and write them to a VBA macro that you can edit later. While the results of recording a set of actions this way can be played back as is, the macro is nearly always more useful if you edit the code to be more flexible.

Automating key-in command sequences

One way that you can begin to write your own VBA macros, even without recording a sequence of actions, is to use the MicroStation key-in commands as “instructions”. For example, if you use the same sequence of actions to reset your MicroStation environment every time you begin a new file, you can automate this process using the necessary key-in commands and simply run the macro each time you need it.

To use a MicroStation key-in as a macro instruction

From the Utilities menu, choose Macro > Project Manager.

In the Project Manager dialog, create a new project, or load an existing project to contain the macro.

Add a code module to the project by selecting the Insert menu, then choosing Module.

In the Properties window for the Module, change the Name to myKeyinMacro.The title of the editor window also changes to show the new macro name.

In the blank code module window type these two lines:Option ExplicitSub myStartUpCommand()then, press the <Enter> key on the keyboard. The Visual Basic Editor will add a line for you to complete the subroutine.

As you might have guessed, the instruction to get VBA to send a key-in command to MicroStation is a method called SendKeyin. This method belongs to the CadInputQueue object though, so we have to address that object first. We could have written each line as:CadInputQueue.SendKeyin "active color green"but, it was easier to use the With statement to tell the Visual Basic compiler that each of the statements beginning with a period is addressing the same object, the CadInputQueue. The With statement saved a considerable amount of typing, and reduced the chances of a typing error.

Prompting the user

When a macro is played back, the user might not recognize exactly what is happening, so it's always a good idea to add a prompt message at the beginning of a macro. We could have the prompt appear in any of several places, but let's keep it simple.

Add the following lines before the With statement in this macro:ShowCommand "myKeyinMacro"ShowPrompt "Running custom setup macro"

Let's also add a prompt to tell the user when it's safe to start doing things. Add the following line after the End With statement:ShowPrompt "Setup complete. Ready for user input."

The complete key-in macro example

This example macro can now be saved and played back. The complete macro looks like this:

Of course, you can add other key-in commands to this macro, and customize it with other features that you use when you set up your DGN file. Similar macros might be used at other times as well, perhaps before plotting you would run a similar macro to turn off construction elements, and hide certain levels.

Running a VBA macro

Once a macro has been written, it can be run to execute the instructions it contains. This is the same as “playing back” a VBA macro that was recorded using the record feature. From within the editor, select the Run menu, then choose Run Sub/User Form. The <F5> function key is a keyboard shortcut to this menu item. The macro can also be run from the Macros dialog box , or by using a key-in command (see MicroStation VBA key-ins).

The key-in command for running a specific macro can also be assigned to a function key, so that a VBA macro can be launched with a single keystroke.

Working with MicroStation objects

Visual Basic is an “object oriented” language. A full explanation of object-oriented programming is beyond the scope of this documentation. There are many good books available on the subject, and many are written expressly for Visual Basic programmers. It is necessary though, to understand the role that “objects” play in Visual Basic in MicroStation.

Where are the objects?

Nearly every instruction you write in a Visual Basic macro deals with some object, whether it is implied that the object is MicroStation itself, or Visual Basic, or whether the object is explicitly referenced. Many statements will refer to more than one object, but the point is that objects are everywhere.

Global methods and properties

In the Visual Basic Editor, you can view the set of object classes, methods, and properties through the Object Browser. This is an excellent place to start learning about MicroStation's objects that are available to Visual Basic programs. Select the Object Browser from the View menu.

The Object Browser displays available features by library. The MicroStationDGN library contains the objects specific to MicroStation, so change the combo-box in the Object Browser from <All Libraries> to MicroStationDGN.

In the list on the left, select <globals> from the list of Classes. The list on the right shows the members of the MicroStationDGN.Application object. This is the “default” object that is implied when one of the methods or properties in the list on the right is used in a Visual Basic instruction. For example to change the active color to yellow, we can use the instruction:

ActiveSettings.Color = 4

The ActiveSettings property belongs to the MicroStationDGN.Application object, but we don't need to specify this object because it is implied. This instruction actually uses another object as well, that is a Settings object. The ActiveSettings property gives us access to the Settings object that holds the active settings in MicroStation. The Color property belongs to the Settings object.

Elements as objects

An element in a DGN file can be manipulated and modified in VBA by using an object of the appropriate type. The MicroStationDGN library contains an Element class for generic handling of elements where the type may not be known or may not be particularly important, and specific classes for each element type such as ArcElement and LineElement.

Other objects in MicroStation

There are several other objects besides design elements and the Application object that are important to know about. They allow your VBA programs to access specific features of MicroStation. One of these objects is the CadInputQueue.

The CadInputQueue object

The methods of the CadInputQueue object allow your VBA programs to send input to MicroStation, and to collect input from the user. Using the CadInputQueue object, your program can respond to key-ins, data points, and resets. Your program can also send these messages to MicroStation, and it can send messages to an MDL application that is running at the same time.

The ActiveWorkspace object

The ActiveWorkspace object is an instance of the Workspace class. This class has methods for reading, creating and deleting MicroStation's configuration variables. To see an example of how the ActiveWorkspace object can be used, see the Configuration Variable Example.

More objects and documentation

There are many more classes listed in the Object Browser, each is documented in the Reference part of the MicroStation VBA documentation. To find the documentation for a specific class, property or method, select the item in the Object Browser window, then press the <F1> key.

Working with MicroStation events

The application object contains two events, OnDesignFileOpened and OnDesignFileClosed. These events are intended to allow a VBA program to respond to the action of opening or closing a DGN file in MicroStation.

Using the OnDesignFileClosed event

The OnDesignFileClosed event is intended to let a MicroStation VBA program cleanup and save any data before the design file is actually exited. The OnDesignFileClosed event passes the path and name of the design file as an argument to the method receiving this event.

The code for a class that uses this event to respond to the closing of a design file would look like this:

This code is for a class named openClose, so it can only be written in a class module. To run it, we create a sub procedure in a code module that creates an object of this class. To make it easy to see the action of the OnDesignFileClosed event, a command is issued to create and open a new design file. This command causes the OnDesignFileClosed event to occur. This sub procedure is written like this:

Running the makeNewFile sub procedure would cause a dialog box to appear that tells the user the design file is closing. The same approach would be used to respond to the OnDesignFileOpened event.

WithEvents

The mechanism that allows the class to respond to the two events is the WithEvents declaration. When the Dim statement is used to create the hooks variable as type Application, the WithEvents keyword signifies that hooks will respond to some event. This means that MicroStation will send event messages to the hooks object, but it does not mean that hooks must respond to every event. The hooks object can only respond to the event that we wrote the code for, the OnDesignFileClosed event.

To make the hooks object respond to the OnDesignFileOpened event we would add another sub procedure in the openClose class that looks like this:

Other ways to respond to events

The Application object does not provide many events to respond to using the WithEvents keyword. There are other events that your program can make use of, but your program must implement an interface to receive these events. For more information, see Interface Oriented Programming.

Customizing MicroStation with Visual Basic

While Visual Basic does not have access to the graphical components of MicroStation (menus, windows, etc.), you can still easily customize MicroStation to use VBA programs for your own purposes.

Function keys

MicroStation provides a utility to customize the commands that are issued by pressing function keys on the keyboard. You can use this feature to execute a VBA program by setting a function key to issue the key-in command to load and run your VBA macro. See MicroStation VBA Key-ins for the key-in command to use.

Custom tools

Another place that a VBA macro can be executed from is a custom tool icon. Using the Customize utility in MicroStation's Workspace menu you can create a custom tool box and tool icon. The tool icon passes a key-in command to MicroStation, so it can easily be set to load and execute your VBA program. See MicroStation VBA Key-ins for the key-in command to use.

Configuration Variables

One area of MicroStation that can be accessed by a VBA macro is configuration variables and their settings. By using the Workspace object you can read configuration variable values for the current workspace, and create new configuration variables as well as delete them.

Reading a value from a configuration variable

Reading a configuration variable from a VBA program is reasonably easy if you know ahead of time which variable you need to get the value of. The value of a configuration variable is returned as a String, so it can be retrieved with the following lines:

Note: Configuration variable values can contain other configuration variables. It is generally a good idea to “expand” a configuration variable value if you need to use it to find a file. Expanding means to substitute the values for any other configuration variables in the value you just read. The ConfigurationVariableValue method will do this for you.

Creating a new configuration variable

A new configuration variable is defined and set using the AddConfigurationVariable method of the ActiveWorkspace object. To create a new configuration variable named “AddedByVba” use the following lines:

Before creating the variable, this example checks to see if it already exists, and if not it creates the configuration variable at the User level. All VBA changes to configuration variables are at the User level.

Deleting a configuration variable

A configuration variable can be deleted by using the RemoveConfigurationVariable method of the ActiveWorkspace object. Here again, it is a good idea to check to see if the configuration variable is defined before trying to delete it. To remove the configuration variable added by the example above, use the following lines:

If IsConfigurationVariableDefined "AddedByVba" Then ActiveWorkspace.RemoveConfigurationVariable "AddedByVba"End If

Converting macros from MicroStation BASIC to VBA

MicroStation BASIC macros are not automatically converted to Visual Basic macros in MicroStation V8. To convert macros from MicroStation BASIC to Visual Basic requires an in-depth knowledge of MicroStation, and an understanding of programming in both MicroStation BASIC and Visual Basic. This documentation does not attempt to cover this process in complete detail, instead it gives a broad overview of the process and different areas of concentration that will assist the programmer who undertakes this task.

Different object models

The object model used by Visual Basic macros in MicroStation V8 is very different from the one used by MicroStation BASIC. This is the primary reason that macros cannot be automatically converted. The different Mbe objects and extensions in MicroStation BASIC may not have exact equivalents in the VBA Automation Object model in MicroStation V8.

MbeSettings to ActiveSettings

Perhaps the most commonly accessed Mbe object in MicroStation BASIC macros is the MbeSettings object. This object allowed access to the current settings of MicroStation, including various locks, grid settings, and text settings. Many of these same settings are accessible in VBA through the ActiveSettings object, but some are not. Text settings are now part of the TextStyle object, and the name of the current font can only be accessed through the font object itself.

MbeElement to Element class and others

If you've ever had to manipulate drawing elements in a MicroStation BASIC macro, then you know about MbeElement. This object is used to handle nearly all of the possible design elements, but it can't be used to create a new design element. In VBA, the rough equivalent to MbeElement is the Element class. This class can handle many different kinds of design elements, but there are now separate classes for each design element type. These can also be used to create design elements instead of sending commands to MicroStation to add elements to the drawing.

Other Mbe objects

All Mbe objects in a MicroStation BASIC macro must be changed to use an equivalent Visual Basic object or class to accomplish the same result. Because of many changes to MicroStation, such as the addition of models and other new features, there is not an easy one to one mapping from MicroStation BASIC to Visual Basic.

Dialog Box Resources

Dialog boxes in MicroStation BASIC macros were always modal, and were stored within the compiled .ba file for the macro. There is no way to extract the information from a .ba file and recreate a dialog box for Visual Basic from it. Many dialog box features that could work in MicroStation BASIC macros cannot be duplicated in Visual Basic dialogs. Items such as the Color Picker, or Level Picker have no direct equivalent in Visual Basic.

MicroStation BASIC code

For the most part, the syntax of MicroStation BASIC is the same as Visual Basic. Operators, and the core language keywords are all the same, so transporting code from MicroStation BASIC to Visual Basic is really a matter of cut and paste.

Macro entry points

MicroStation BASIC macros always began with a sub procedure called Main, and this was the entry point for every macro. Visual Basic does not require a sub procedure called Main, but it will use it if it is there.

MicroStation BASIC supported Pen Tables for plotting by allowing the programmer to create functions that could be called at certain times during the plotting process. These plot hook functions are still supported in MicroStation BASIC, but are not supported in VBA in MicroStation.

Translation Macros

Previous versions of MicroStation used Basic macros to assist in data translation from other CAD software file formats to MicroStation's data format. Since MicroStation V8 reads the DWG data format directly, it does not need to execute Basic macros to assist in translation. The translation macros from earlier versions of MicroStation will not work in MicroStation V8 nor are they needed.

MicroStation's New Display Engine

MicroStation's new display engine affects VBA programs in the following ways:

There is no need to call Redraw outside of a dynamics-method because MicroStation keeps the views up-to-date. In fact, calling Redraw outside of dynamics has no effect.

Dynamics methods are only called once to draw. They are not called to erase.

There is no way to draw a temporary representation of an element that is not in the design file.

Change History

To get a list of new methods, properties, and types select the search pane of MicroStation V8 Visual Basic for Applications Help and search for 08.09* or 08.09.02 or 08.09.03.

The documentation for each method, property, and type contains a Version section that identifies when that method, property, and type was added to the object model.

The version numbers that appear in the documentation are: 08.00.00, 08.00.01, 08.00.02, 08.00.04, 08.01.00, 08.01.01, 08.01.02, 08.01.03, 08.05.00, 08.05.01, 08.05.02, 08.09.02, and 08.09.03. You can search for any of these numbers to find what was added in that version.