More than 15 years ago, Visual Basic (VB) was the first modern programming language I learned. This knowledge was critical to taking my custom programs to a whole new level. VB allows you to develop stand-alone applications that can communicate with other programs using Microsoft's Object Linking and Embedding (OLE) and ActiveX technologies. Autodesk® AutoCAD® supports a variant of VB known as Visual Basic for Applications (VBA) that requires a host application to execute the programs you write; it can't be used to develop stand-alone executable files.
I found VB easier to learn than AutoLISP® for a couple of reasons. First, there are, in general, many more books and online resources dedicated to VB. Second, VB syntax feels more natural. By natural, I mean that VB syntax reads as if you are explaining a process to someone in your own words, and it doesn't contain lots of special characters and formatting like many other programming languages.
As with learning anything new, there will be a bit of hesitation on your part as you approach your first projects. This chapter eases you into the AutoCAD VBA environment and the VB programming language.
Custom programs developed with VBA implemented in the AutoCAD program are stored in a project that has a .dvb
file extension. VBA projects contain various objects that define a custom program. These objects include the following:
UserForms
that define the dialog boxes to be displayed by a custom programThe AutoCAD VBA Editor is an integrated development environment (IDE) that allows for the creation and execution of macros stored in a project file. A macro is a named block of code that can be executed from the AutoCAD user interface or privately used within a project. You can also enter and execute a single VBA statement at the AutoCAD Command prompt using the vbastmt
command.
The most recent generation of VB is known as VB.NET. Although VB and VB.NET have similar syntax, they are not the same. VBA, whether in AutoCAD or other programs such as Microsoft Word, is based on VB6 and not VB.NET. If you are looking for general information on VBA, search the Internet using the keywords VBA and VB6.
To complete the exercises in this chapter and create and edit VBA project files, you must have the following:
Beginning with AutoCAD 2010, the AutoCAD VBA Enabler is an additional component that must be downloaded and installed to enable VBA support in the AutoCAD drawing environment. (For AutoCAD 2000 through AutoCAD 2009, VBA capabilities were part of a standard install.)
Without the VBA Enabler, you won't have access to the VBA Editor and can't create or execute VBA code contained in a DVB file with AutoCAD 2010 and later releases. All of the VBA commands were available without an additional download and install. Changes in the later AutoCAD releases were made due to Microsoft's planned deprecation of the VBA technology and editor, only to eventually extend its life cycle because of its continued importance to Microsoft Office. Microsoft planned to move to Visual Studio Tools for Applications (VSTA) as the replacement for VBA, but the company backed off because there was no easy migration from VBA to VSTA.
Prior to working with the AutoCAD VBA Editor, you must ensure that the VBA environment is installed on your workstation. The following steps explain how to determine whether VBA is installed and, if necessary, how to download the AutoCAD VBA environment for installation. These steps are important if you are using AutoCAD 2010 or later.
vbaide
and press Enter.http://www.autodesk.com/vba-download
link to open your system's default web browser to the download website.After downloading the AutoCAD 2015 VBA Enabler using the steps explained in the previous section, follow these steps to install it:
vbaide
and press Enter.
The VBA Editor is displayed, indicating that the AutoCAD VBA environment has been installed.
The VBA Editor (see Figure 1.1) is the authoring environment used to create custom programs that are stored in a VBA project. The following tasks can be performed from the VBA Editor:
Any of the following methods can be used to display the VBA Editor:
vbaide
and press Enter.VBA supports four types of components to define the functionality of a custom program. Each component can be used to store code, but the code in each component serves a distinct purpose within a VBA project. Before you begin learning the basic features of the VBA Editor, you should have a basic understanding of the component types in a VBA project.
The following provides an overview of the component types:
Code modules, also referred to as standard code modules, are used to store procedures and define any global variables for use in the module or globally across the VBA project. I recommend using code modules to store procedures that can be executed from the AutoCAD user interface or used across multiple projects.
When you add a new code module to a VBA project, you should give the module a meaningful name and not keep the default name of Module1
, Module2
, and so on. Standard industry naming practice is to add the prefix of bas
to the name of the module. For example, you might name a module that contains utility procedures as basUtilities
. I explain how to define procedures and variables in the “Learning the Fundamentals of the VBA Language” section in Chapter 2, “Understanding Visual Basic for Applications.”
Class modules are used to define a custom class—or object. Custom classes aren't as common as code modules in a VBA project, but they can be helpful in organizing and simplifying code. The variables and procedures defined in a class module are hidden from all other components in a VBA project, unless an instance of the class is created as part of a procedure in another component.
When you add a new class module to a VBA project, you should give the module a meaningful name and not keep the default name of Class1
, Class2
, and so on. Standard industry naming practice is to add the prefix of cls
to the name of the module. For example, you might name a module that contains a custom class named employee as clsEmployee
. I explain how to define procedures and variables and work with objects in the “Learning the Fundamentals of the VBA Language” section in Chapter 2.
ThisDrawing is a specially named object that represents the current drawing and is contained in each VBA project. The ThisDrawing component can be used to define events that execute code based on an action performed by the user or the AutoCAD program. Variables and procedures can be defined in the ThisDrawing component, but I recommend storing only the variables and procedures related to the current drawing in the ThisDrawing component. All other code should be stored in a code module. I explain how to work with the current drawing and events in Chapter 3, “Interacting with the Application and Documents Objects,” and Chapter 10, “Modifying the Application and Working with Events.”
UserForm
UserForms
are used to define custom dialog boxes for use in a VBA program. A UserForm
can contain controls that present messages to the user and allow the user to provide input. When you add a new UserForm
to a VBA project, you should give the UserForm
a meaningful name and not keep the default name of UserForm1
, UserForm2
, and so on. Standard industry naming practice is to add the prefix of frm
to the name of the UserForm
. For example, you might name a UserForm
that contains a dialog box that draws a bolt as frmDrawBolt
. I explain how to create and display a UserForm
in Chapter 11, “Creating and Displaying User Forms.”
The following explains how to add a new component to a VBA project and change its name:
The VBA Editor interface contains a variety of tools and windows that are used to manage and edit the components and code stored in a VBA project. While all of the tools and windows in the VBA Editor will be important over time, there are four windows that you should have a basic understanding of when first getting started:
The Project Explorer window (see Figure 1.2) lists all of the VBA projects that are currently loaded into the AutoCAD drawing environment and the components of each loaded project. By default, the Project Explorer should be displayed in the VBA Editor, but if it isn't you can display it by clicking View Project Explorer or pressing Ctrl+R.
When the Project Explorer is displayed, you can
UserForm
in an editor window.The Properties window (see Figure 1.3) allows you to change the name of a component in a loaded VBA project or modify the properties of a control or UserForm
. Select a component or UserForm
from the Project Explorer, or a control to display its properties in the Properties window. Click in a property field, and enter or select a new value to change the current value of the property. The Properties window is displayed by default in the VBA Editor, but if it isn't you can display it by clicking View Properties Window or pressing F4.
A code editor window (see Figure 1.4) is where you will write, edit, and debug code statements that are used to make up a custom program. You display a code editor window by doing one of the following in the Project Explorer:
UserForm
and then clicking View CodeThe code editor window supports many common editing tools: copy and paste, find and replace, and many others. In addition to common editing tools, it supports tools that are designed specifically for working with VBA code statements, and some of these tools allow you to accomplish the following:
The text area is the largest area of the code editor window and where you will spend most of your time. The Object drop-down list typically is set to (General), which indicates you want to work with the General Declaration area of the code window. When working in the code editor window of a UserForm
, you can select a control or the UserForm
to work with from the Object drop-down list. The Object drop-down list is also used when working with events.
Once an object is selected, a list of available events or procedures for the selected object is displayed in the Procedure drop-down list. Select a procedure from the drop-down list to insert the basic structure of that procedure. Enter the code statements to execute when the procedure is executed. I explain how to work with events in Chapter 10 and UserForms
in Chapter 11.
The margin indicator bar of the code editor window helps you know where a bookmark or breakpoint is inserted by displaying an oval for a bookmark or a circle for a breakpoint. I discuss more about breakpoints in Chapter 13, “Handling Errors and Deploying VBA Projects.”
The Object Browser (see Figure 1.5) allows you to view the classes and enumerated constants defined in a referenced programming library. Each AutoCAD VBA project contains a reference to the VBA and AutoCAD Object libraries. I discuss referencing other libraries in Chapter 12, “Communicating with Other Applications.” You can display the Object Browser by clicking View Object Browser or pressing F2.
A class is used to create an instance of an object, which I discuss in the “Working with Objects” section in Chapter 2. An enumerated constant is a set of integer values with unique names that can be used in a code statement. Using a constant name makes the integer value easier to understand, and also protects your code when values change. For example, the constant name of acBlue
is equal to an integer value of 5. If the meaning of 5 were changed to mean a different color than blue, the constant of acBlue
would be updated with the new integer and no changes to your code would need to be made if you used the constant.
When the Object Browser is displayed, you can select a class or enumerated constant from the Classes list. The Classes list contains all the classes and enumerated constants of the referenced libraries in the VBA project. You can filter the list by selecting a referenced library from the Libraries drop-down list located at the top of the Object Browser. Select a class or enumerated constant from the Classes list to see its members, which are methods, properties, events, or constant values. Select a member to learn more about it and press F1 to display its associated help topic. I explain how to access the AutoCAD VBA documentation in the “Accessing the AutoCAD VBA Documentation” section later in this chapter.
The four windows that I described in the previous sections are the main windows of the VBA Editor; they are used the most frequently. You will use some additional windows on occasion. These are primarily used for creating UserForms
and debugging VBA statements. (I discuss creating UserForms
in Chapter 11 and debugging in Chapter 13.)
Here are the windows you will use when creating UserForms
and debugging:
Print
method of the Debug
object. I discuss more about the Debug
object and Immediate window in Chapter 13.UserForm
Editor Window The UserForm
editor window allows you to add controls and organize controls on a UserForm
to create a custom dialog box that can be displayed from your VBA project. You add controls to a UserForm
from the Toolbox window. While the UserForm
editor window is current, the Format menu on the menu bar contains tools to lay out and align the controls on a UserForm
. I explain how to create and work with UserForms
in Chapter 11.UserForm
when displayed in the UserForm
editor window. Click a tool and then drag it into the UserForm
editor window to place an instance of the control. Right-click over one of the tools on the window and click Additional Controls to display the Additional Controls dialog box. Click any of the available controls to make it available for use in a UserForm
. I explain how to add controls to a UserForm
in Chapter 11.There are several settings that affect the behavior of the AutoCAD VBA environment and not just the currently loaded VBA projects. These settings can be changed in the Option dialog box of the VBA environment (see Figure 1.6), which can be displayed using one of the following methods:
vbarun
command, click Options.vbapref
and press Enter.Here is an explanation of the settings in the Options dialog box:
VBA programs developed in the AutoCAD VBA environment can be stored in a project file or embedded in a drawing file. VBA projects can also be embedded in a drawing template (DWT) or drawing standards (DWS) file. By default, VBA programs developed in the AutoCAD VBA environment are stored in a project file with a .dvb
file extension and then are loaded into the AutoCAD drawing environment as needed.
DVB files can be managed externally from Windows Explorer or File Explorer, or from within AutoCAD whenever the file is loaded into the AutoCAD drawing environment. General file-management tasks on a DVB file can be performed using Windows Explorer or File Explorer. Once the DVB file is loaded into the AutoCAD drawing environment, you can manage it using the VBA Manager (see Figure 1.7). The VBA Manager allows you to do the following:
There are two ways to display the VBA Manager in AutoCAD:
vbaman
and press Enter.A new VBA project can be created automatically by the AutoCAD program or manually as needed. When the VBA environment is initialized the first time during an AutoCAD session, a new VBA project is created automatically unless a VBA project has already been loaded into memory. If you want to create a new project after the VBA environment has been initialized, do one of the following:
vbanew
and press Enter.Each new VBA project is assigned two default names: a project name and a location name. The project name is an internal name used by the AutoCAD program to differentiate the procedures and components in each loaded VBA project. The default project name for a new VBA project is ACADProject
; I recommend assigning a descriptive project name for each VBA project you create. A project name can contain alphanumeric characters and underscores, but can't start with a number or underscore character.
The location name of a VBA project is the same as a filename and is used to specify where the DVB
file is stored. Since a new VBA project exists only in memory, it is assigned the default location name of Global1
. The location name is incremented by one for each new VBA project created during an AutoCAD session; thus the second and third VBA projects have location names of Global2
and Global3
, respectively. When you save VBA projects, they are stored in DVB
files locally or on a network. To ensure that AutoCAD knows where the DVB
files are located, you add the locations of your DVB
files to the AutoCAD support file search and trusted paths. I discuss how to add a folder to the AutoCAD support file search and trusted paths in Chapter 13.
New VBA projects can be saved to disc using the Save As option in the VBA Manager or Save in the VBA Editor. When an existing project is loaded in memory, the Save As option can be used to create a copy of the project on disc or to overwrite an existing VBA project file. Typically, changes made to an existing project file that already has been loaded in the VBA environment are saved to the project file using the Save option in the VBA Editor. I discussed the VBA Editor earlier in the “Getting Started with the VBA Editor” section.
The following explains how to save a VBA project:
Before a VBA project can be edited and before the code stored in the project can be executed, the project must be loaded into the AutoCAD VBA environment. The process for loading a project into the AutoCAD VBA environment is similar to opening a drawing file.
A VBA project can be manually loaded using the VBA Manager or the vbaload
command. The following explains how to manually load a VBA project:
vbaload
and press Enter.)ch01_hexbolt.dvb
.As an alternative, DVB and other types of custom program files can be dragged and dropped onto an open drawing window in the AutoCAD drawing environment. When you drop a DVB file onto an open drawing window, AutoCAD prompts you to load the file and/or to enable the macros contained in the VBA project file.
The Load Project button in the VBA Manager and the vbaload
command require input from the user to load a VBA project, which isn't ideal when you want to integrate your VBA projects as seamlessly as possible into the AutoCAD drawing environment. A script, custom AutoLISP program, or command macro from the AutoCAD user interface can all be used to load a VBA project without user input. The following outlines some of the methods that can be used to load a VBA project without user input:
-vbaload
command. The -vbaload
command is the command-line version of the vbaload
command. When the -vbaload
command is started, the Open VBA Project:
prompt is displayed. Provide the name of the DVB file as part of the macro or script file.vl-vbaload
function. The AutoLISP vl-vbaload
function can be used to load a DVB file from a custom AutoLISP program. If the DVB file that is passed to the vl-vbaload
function isn't found, an error is returned that should be captured with the AutoLISP vl-catch-all-apply
function.acad.dvb
and place it in one of the AutoCAD support file search paths. AutoCAD looks for a file named acad.dvb
during startup and if the file is found, that file is loaded automatically.appload
command). When a DVB file is added to the Startup Suite, the file is loaded when the first drawing of a session is opened. Removing a file from the Startup Suite causes the file not to be loaded in any future drawings that are opened or in AutoCAD sessions. If you want to use the Startup Suite to load DVB files, you must add the files to the Startup Suite on each workstation and AutoCAD user profile.I discuss each of these methods in greater detail in Chapter 13.
When a VBA project is no longer needed, it can be unloaded from memory to release system resources. A VBA project can be manually unloaded from memory using the VBA Manager or the vbaunload
command. The following explains how to unload the ch01_hexbolt.dvb
file with the VBA Manager:
vbaman
and press Enter.)If you want to unload a DVB file as part of a script, custom AutoLISP program, or command macro from the AutoCAD user interface, you will need to use the vbaunload
command. When the vbaunload
command starts, the Unload VBA Project:
prompt is displayed. Provide the filename and full path of the DVB file you want to unload; the path you specify must exactly match the path for the DVB file that was loaded into the AutoCAD drawing environment. If it doesn't, the unload fails and an error message will be displayed. A failed execution of the vbaunload
command doesn't cause the program calling the command to fail.
A VBA project can be embedded in a drawing file to make the components and code in the project available when the drawing file is opened in the AutoCAD drawing environment. Only one VBA project can be embedded in a drawing file at a time. Embedding a VBA project in a file can be helpful to make specific tools available to anyone who opens the file, but there are potential problems using this approach. Here are the main two problems with embedding a VBA project file into a drawing:
So, while you can embed a VBA project, I don't recommend doing it.
The following explains how to embed a VBA project in a current drawing file:
Extracting a VBA project reverses the embedding process. After a project is selected for extraction, you can either export the project to a DVB file or discard the project. The following explains how to extract a VBA project from a current drawing file:
VBA projects contain components that organize code and define user forms and custom classes. A component can contain one or more procedures that are used to perform a task on the objects in a drawing or request input from an end user. Most procedures are defined so they are executed from other procedures in a VBA project and not from the AutoCAD user interface. A procedure that can be executed from the AutoCAD user interface is known as a macro. I explain how to define a procedure in Chapter 2.
A macro can be executed using the Macros dialog box (see Figure 1.8). In addition to executing a macro, the Macros dialog box can also be used to do the following:
The following methods can be used to display the Macros dialog box:
vbarun
and press Enter.The Macros dialog box requires input from the user to execute a macro in a loaded VBA project. If you want to execute a macro as part of a script, custom AutoLISP program, or command macro from the AutoCAD user interface you can use one of the following methods:
-vbarun
command is the command-line version of the vbarun
command. When the -vbarun
command is started, the Macro name:
prompt is displayed.vl-vbarun
function can be used to execute a macro in a loaded DVB file from a custom AutoLISP program. If the macro isn't found, an error message is displayed but the error doesn't cause the program to terminate.The name of the macro to execute with the -vbarun
command or vl-vbarun
function must be in the following format:
DVBFilename.ProjectName!MacroName
For example, you would use the string value firstproject.dvb!ThisDrawing.CCircles
to execute the CCircle
macro in the ThisDrawing
component of the firstproject.dvb
file.
These steps explain how to execute the macro named hexbolt
:
vbarun
and press Enter).ch01_hexbolt.dvb
.
Figure 1.9 shows the macro that is stored in and can be executed from the ch01_hexbolt.dvb
file with the Macros dialog box.
The Draw Hex Bolt View dialog box, shown in Figure 1.10, is displayed.
Specify center of bolt head:
prompt, specify a point in the drawing area to draw the top view of the hex bolt.Specify middle of bolt head:
prompt, specify a point in the drawing area to draw the side view of the hex bolt.Figure 1.11 shows the top and side views of the hex bolt that were drawn with the macro.
The AutoCAD VBA documentation is available from the AutoCAD product Help landing page and the VBA Editor. The documentation is composed of two documentation sets: the AutoCAD Object Library Reference and the ActiveX Developer's Guide. Although this book is designed to make it easy to learn how to use the AutoCAD Object library and the VBA programming language, you will want to refer to the documentation that is provided with the AutoCAD product too, as it just isn't possible to cover every function and technique here.
The topics of the AutoCAD Object Library Reference explain the classes, methods, properties, and constants that make up the AutoCAD Object library. The ActiveX Developer's Guide topics can be used to explore advanced techniques and features that aren't covered in this book.
You can see the AutoCAD VBA and ActiveX documentation written for AutoCAD 2015 here:
http://help.autodesk.com/view/ACD/2015/ENU/
On the Autodesk AutoCAD 2015 Help landing page, click the Developer Home Page link. On the AutoCAD Developer Help Home Page, use the AutoCAD Object Library Reference and Developer's Guide links under the ActiveX/VBA section to access the AutoCAD VBA and ActiveX documentation.
When working in the VBA Editor, you can access the AutoCAD Object Library Reference and Microsoft Visual Basic for Applications Help by doing the following:
Help can also be accessed from the Object Browser. In the Object Browser, select a class, method, property, or constant and then press F1 to open the associated help topic. I discussed the Object Browser earlier, in the “Exploring Loaded Libraries with the Object Browser” section.
3.143.239.44