You are currently reviewing an older revision of this page.
Before you can run a Visual Basic macro in MicroStation (VBA programs are often called macros) you must first load the VBA project within which the macro resides.
A project is usually a complete collection of the VBA components for a particular macro or set of macros. A project file has the file extension .mvba.
Before running a macro, first make sure the project that contains it is loaded.
With one command, a project can be loaded and a macro within the project initiated, but only from the Keyin window in MicroStation.
VBA RUN [Default]CopyElement
The square brackets must surround the name of the project to be loaded.
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 are definitions for GUI components such as dialog boxes or settings windows (also referred to as UserForms).
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.
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.
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.
The structure of the application object is shown below:
The structure of the ModelReference object is shown below:
The structure of the Attachment object is shown below:
The structure of the ActiveSettings object is shown below:
The Automation Object Model in MicroStation does not include the following capabilities and features:
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.
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.
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”.
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
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.
If DistanceXY(point1, point2) > 10 Then userChoice = MsgBox ("Distance is too great.", vbOKCancel)End If
This example shows two function calls, the first to DistanceXY() and the second to MsgBox. In both cases, the return value is used in the calling statement, so the parentheses are required.
Below are several lists of questions with links to answers listed further down in the document. The lists are divided into the following categories:
UserForm1.Show vbModeless
Dim oEnumerator as ElementEnumeratorSet oEnumerator = ActiveModelReference.GetSelectedElements
See the Selection Set example.
vba run <macro>
Public Sub getArgs() MsgBox KeyinArgumentsEnd Sub
called with this key-in string:
VBA RUN getArgs VBA is fun!
will display a dialog box with the string “VBA is fun!”.
The Project Manager dialog box provides easy access to all functions related to loading, running, and managing Visual Basic macros in MicroStation.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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 provides a list of available macros within a selected VBA project, or within all currently loaded projects. Its functions are described below.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
Key-ins can also be used to activate and control Visual Basic projects and macros within MicroStation.
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.
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.
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.
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
VBA RUN <macroname>
The macro begins running immediately.
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.
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"
VBA SAVEALL
Any project that is currently loaded and has been modified is saved to its .mvba disk file.
VBA UNLOAD <projectname>
The specified project is immediately unloaded.
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.
VBA START RECORDING [project]<macroname>
The recording process starts.
Note: There are a couple of variations to this key-in.
vba start recording [myProject]myMacro
vba start recording myModule.mymacro
Using the key-in: vba start recording myMacro will result in an error message because not enough information has been supplied.
vba start recording myMacro
VBA STOP RECORDING
The recording process stops immediately.
VBA PAUSE RECORDING
No actions will be recorded after this key-in until the recording process is resumed.
The recording process is stopped immediately.
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.
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.
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.
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.
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.
To record a set of actions as a 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 'Start a command CadInputQueue.SendCommand "PLACE SMARTLINE " 'Coordinates are in master units startPoint.X = 7.316122 startPoint.Y = -4.865692 startPoint.Z = 0# 'Send a data point to the current command point.X = startPoint.X point.Y = startPoint.Y point.Z = startPoint.Z CadInputQueue.SendDataPoint point, 1 'Send a data point to the current command point.X = startPoint.X + 2.48087 point.Y = startPoint.Y + 3.0765 point.Z = startPoint.Z CadInputQueue.SendDataPoint point, 1 'Send a data point to the current command point.X = startPoint.X + 7.6503 point.Y = startPoint.Y + 1.9341 point.Z = startPoint.Z CadInputQueue.SendDataPoint point, 1 'Send a reset to the current command CadInputQueue.SendReset CommandState.StartDefaultCommandEnd Sub
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.
Sub Macro1() Dim startPoint As Point3d Dim point As Point3d, point2 As Point3d Dim userPnt As CadInputMessage 'Start a command CadInputQueue.SendCommand "PLACE SMARTLINE " Set userPnt = CadInputQueue.GetInput(msdCadInputTypeDataPoint) 'Coordinates are in master units startPoint.X = userPnt.point.X startPoint.Y = userPnt.point.Y startPoint.Z = userPnt.point.Z 'Send a data point to the current command point.X = startPoint.X point.Y = startPoint.Y point.Z = startPoint.Z CadInputQueue.SendDataPoint point, 1 'Send a data point to the current command point.X = startPoint.X + 2.48087 point.Y = startPoint.Y + 3.0765 point.Z = startPoint.Z CadInputQueue.SendDataPoint point, 1 'Send a data point to the current command point.X = startPoint.X + 7.6503 point.Y = startPoint.Y + 1.9341 point.Z = startPoint.Z CadInputQueue.SendDataPoint point, 1 'Send a reset to the current command CadInputQueue.SendReset CommandState.StartDefaultCommandEnd Sub
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.
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 .
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.
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
Option ExplicitSub myStartUpCommand()
With CadInputQueue .SendKeyin "active color green" .SendKeyin "active level 10" .SendKeyin "history initialize" .SendKeyin "popset on" .SendKeyin "accudraw shortcuts default"End With
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.
CadInputQueue.SendKeyin "active color green"
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"
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."
ShowPrompt "Setup complete. Ready for user input."
This example macro can now be saved and played back. The complete macro looks like this:
Option ExplicitSub myStartUpCommand() ShowCommand "myKeyinMacro" ShowPrompt "Running custom setup macro" With CadInputQueue .SendKeyin "active color green" .SendKeyin "active level 10" .SendKeyin "history initialize" .SendKeyin "popset on" .SendKeyin "accudraw shortcuts default" End WithShowPrompt "Setup complete. Ready for user input."End Sub
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.
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.
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.
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.
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.
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.
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 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 CommandState object is used to implement and initiate VBA programs that operate like standard MicroStation element-creation and element-modification commands. These programs must create an object that implements the IPrimitiveCommandEvents interface, or the ILocateCommandEvents interface. Either the CommandState object's StartPrimitive method or StartLocate method is then called to activate the object. For code examples of these, see the Element Creation Command Example and the Analyze Arc Example.
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.
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.
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.
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:
Dim WithEvents hooks As ApplicationPrivate Sub Class_Initialize() Set hooks = ApplicationEnd SubPrivate Sub hooks_OnDesignFileClosed (ByVal dgnFileName As String) MsgBox "Closing DGN file " + dgnFileNameEnd Sub
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:
Public Sub makeNewFile() Dim eventMsg as openClose Set eventMsg = New openClose CreateNewDesignFile DesignFileName, "newdgnfile.dgn", TrueEnd Sub
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.
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:
Private Sub hooks_OnDesignFileOpened (ByVal dgnFileName As String) MsgBox "Opening DGN file " + dgnFileNameEnd Sub
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.
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.
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.
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.
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 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:
Dim configVarValue As StringconfigVarValue = ActiveWorkspace.ConfigurationVariableValue ("MS_DEF")
Usually, it is a good idea to check whether the configuration variable you want to read is defined. To check this, the example above would look like this:
Dim configVarValue As StringIf IsConfigurationVariableDefined ("MS_DEF") Then configVarValue = ActiveWorkspace.ConfigurationVariableValue ("MS_DEF")End If
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.
For additional information, see the Configuration Variable Example.
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:
If (IsConfigurationVariableDefined "AddedByVba" = False) Then ActiveWorkspace.AddConfigurationVariable "AddedByVba", "VBA DEFINITION"End If
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.
See the Configuration Variable Example.
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
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.
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.
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.
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.
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 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.
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.
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.
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 affects VBA programs in the following ways:
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.