Sunteți pe pagina 1din 15

Introduction to VBA

By John Gibb Lets face it, most people looking at programming AutoCAD in VBA have some experience using either AutoLISP or Visual LISP. When asked to tackle an Introduction to VBA I had to decide where I wanted to start (starting from no programming experience at all would be too much ground to cover in 90 minutes). I figured that I could introduce you to the VBA environment by comparing it to a language and environment that many of you are already familiar with. The transition from a programming language like one of the LISP languages to the object modeled VBA would be a natural (despite their differences). This session is not so much about coding in the programming environment of VBA (although we will look at several examples) as it is about creating good coding habits or changing your existing habits and understanding what the languages have to offer. How you approach programming using the VBA language and what steps you need to complete the move into VBA and VB from the LISP languages or from no language experience at all is important. We will also discuss the transition step of learning Visual LISP on your way to using VBA and VB.

First the History Lesson


After R14 hit the streets the rumors were rampant about the end of AutoLISP. This was despite the fact that Autodesk kept saying AutoLISP is NOT going away. Even today, over four years later people are still asking the question Does VBA replace AutoLISP?. Put your mind to rest that AutoLISP is not disappearing (its already gone), it has evolved into Visual LISP. Autodesk still refers to AutoLISP with the Visual LISP engine inside the core of Release 2000 but that engine is actually the extension of AutoLISP into the object world with more functionality than ever. For the purposes of this session I will use AutoLISP to represent the old AutoLISP coding we are familiar with and Visual LISP to refer to the new extended AutoLISP object oriented coding complete with IDE and reactors. Together well explore the differences between these two languages and give you a good feeling for what the VBA language is to AutoCAD.

Now the Comparison


VBA inside AutoCAD does raise some interesting questions though. Should you move to VBA or VB as your programming platform? When should you use AutoLISP, Visual LISP, VBA, or VB on a project? Where should you start to make the transition? How should you start the transition? When should you start the transition? To answer these questions in short: Not for all projects should shift the programming platform. Use the language that best fits the situation for your project. Start in small or pilot projects. Start the transition at the beginning. Start it NOW! Short answers are not what you came here for. So lets examine the languages and the situations. AutoLISP and Visual LISP will continue to work well for internal processing but now you also have VBA for internal processing. Autodesk has shown that they are willing to extend AutoLISP into Visual LISP but some things are just beyond the technology or direction Autodesk is taking both LISP languages. This means that some new objects and tables probably will not be accessible through Visual
Page: 1

LISP but they will have hooks in VBA (when Autodesk wants them to) and VB. Both languages are interactive but VBA is supposed to be faster in some situations.

AutoLISP through VBA


VBA was not designed to replace AutoLISP or Visual LISP but to fill the gap between them and fullblown object oriented ObjectArx. VBA has now been fully implemented in Release 2000 and I will say that the on line documentation is better for VBA than what we got for AutoLISP over the years (though it is getting better for the Visual LISP material). Table 1 illustrates the features of interest about the four languages: The User base Memory usage by the language Development interface The languages orientation The languages ease of interface creation The languages method of evaluating Visual LISP VBA
Large user base Runs inside AutoCAD memory pool Has IDE and debugging environment Is Object Oriented Easy GUI creation Event driven

AutoLISP

VB
Large user base Runs outside AutoCAD memory pool Has IDE and debugging environment Is Object Oriented Easy GUI creation Event driven

Large AutoCAD Growing AutoCAD concentric user base concentric user base Runs inside AutoCAD Runs inside AutoCAD memory pool memory pool Lack of IDE and Has IDE and debugging debugging environment environment Not Object Oriented Limited Object Oriented Difficult GUI creation Difficult GUI creation Procedural Procedural with reactors Table 1. The four languages features of interest

Lets break the features down into their basic elements and compare each.

The User base


Table 1 illustrates the growing user base for each language. AutoLISP is the oldest language related to AutoCAD and currently has the largest group of programmers using it to customize AutoCAD. Visual LISP is a new comer language to the customization of AutoCAD and is growing based upon its relationship to AutoLISP. Visual LISP is similar to AutoLISP, AutoLISP code runs along side it without any changes, and Visual LISP has object oriented functions that AutoLISP doesnt have. VBA is about the same age as Visual LISP when it comes to AutoCAD implementations but it has a larger nonAutoCAD concentric programmer population from which to pull as does VB. Since both are object oriented languages, the programmer who already knows the language must only learn the object model of the software they are programming for.

Memory usage by the language


Programs that run inside AutoCADs memory pool will run faster (in most cases) that ones that run outside the memory pool. This is because AutoCAD can handle all of the resources for the program and does not have to translate anything into its memory registers. The exception to this rule is heavy database
Page: 2

connectivity where the application is off in a database doing queries and database manipulation instead of dealing with AutoCAD objects. Table 1 illustrates how the four languages use the AutoCAD memory pool. Notice that VB runs outside AutoCAD and that is usually where the heavy database applications are developed. This is also due in part to the limitation of the other languages with database connectivity.

Development interface
The Interactive Developer Environment (IDE) is a tool that all of the languages have except AutoLISP and it can be argued that AutoLISP has it to since you can develop AutoLISP code inside the Visual LISP IDE. The IDE in all of the languages work similar to each other and is easy to learn. Features such as interactive debugging and easy form development (but not in the Visual LISP IDE) make the IDE a great environment to develop in.

The languages orientation


This is how a programming language accesses data from AutoCAD. AutoLISP must use the list-based interface and access entity definitions that way. The language has a robust set of functions for manipulating AutoCAD through the command line interface. Visual LISP encompasses AutoLISP methods and extends them by granting limited access to the AutoCAD object model through ActiveX technology. VBA and VB expose the full object model that Autodesk has given us to date. This is not as comprehensive as ObjectArx but it is very powerful in its own right.

The languages ease of interface creation


Creating a dialog box in either AutoLISP or Visual LISP is not easy when compared to the way VBA and VB allow you to create a form (read that dialog box). This is because Autodesk still uses the old Prometheus dialog box language as the means for creating them in both AutoLISP and Visual LISP while VBA and VB have the standard Microsoft forms controls in them.

The languages method of evaluating


AutoLISP is procedural in nature when evaluating code. That means that it goes through the code one line at a time in a top down sequence branching off to procedures and coming back the original procedure when it is done to finish the top down run. Visual LISP works the same way for much of the code except that is has reactor objects; which are created and run in the background. These objects then wait for something to trigger them and then they run the code in a top down fashion. This is similar to event driven code that VBA and VB use. Event driven code responds to registered events that an object has programmed into it. This is best shown on forms. When you select a button on a form, the click event code is ran.

Now VBA
With all that said lets look at some VBA code.

Page: 3

Coding examples
Lets look at some sample code fragments showing AutoLISP, Visual LISP, VBA, and VB in a side by side comparison. The first is a simple routine for getting two points from the user and then placing a line in the drawing.

Page: 4

(defun drawline (/ pt1 pt2) (setq pt1 (getpoint "\nEnter the lines start point: ") pt2 (getpoint pt1 "\nEnter the lines end point: ") ) ;; check to see that the two points exist (if (and pt1 pt2) (command "_.line" pt1 pt2 "") (princ "\nInvalid or missing points!") ) ;; suppress any return value from the function - exit 'quietly' (princ) )

(defun drawline (/ acadApp acadDoc mSpace pt1 pt2 obj) (Setq acadApp (vlax-get-acad-object) acadDoc (vla-get-ActiveDocument acadApp) mSpace (vla-get-ModelSpace acadDoc) pt1 (getpoint "\nEnter the lines start point: ") pt2 (getpoint pt1 \nEnter the lines end point: ")) ;; check to see that the two points exist (if (and pt1 pt2) (progn (setq pt1 (vlax-3d-point pt1) pt2 (vlax-3d-point pt2) obj (vla-Addline mSpace pt1 pt2)) (vla-Update obj) );end progn (princ "\nInvalid or missing points!") );end if

AutoLISP line code

(princ) )

Visual LISP line code


Public Sub DrawLine() Dim objLine As AcadLine Dim pt1 As Variant, pt2 As Variant Public Sub DrawLine() AttachToAutoCAD Dim objLine As AcadLine Dim pt1 As Variant, pt2 As Variant pt1 = ThisDrawing.Utility.GetPoint _ (, "Enter the lines start point: ") pt2 = ThisDrawing.Utility.GetPoint _ (pt1, "Enter the line's end point: ") pt1 = ThisDrawing.Utility.GetPoint _ (, "Enter the line's start point: ") pt2 = ThisDrawing.Utility.GetPoint _ (pt1, "Enter the line's end point: ") Set objLine = ThisDrawing.ModelSpace.AddLine(pt1, pt2) objLine.Update End Sub Set objLine = ThisDrawing.ModelSpace.AddLine(pt1, pt2) objLine.Update End Sub ' attach to AutoCAD

VBA line code VB line code What the VB code example does not show is the subroutine that attaches to AutoCAD. This is only a few lines of code and the reference to the AutoCAD object model. The code is shown below.
Page: 5

Public Sub AttachToAutoCAD() On Error Resume Next Dim Application As AcadApplication Set Application = GetObject(, "AutoCAD.application") If Err.Number <> 0 Then Err.Clear Set Application = CreateObject("AutoCAD.application") ' create a running AutoCAD End If Set ThisDrawing = Application.ActiveDocument ' set the active document ' declare the application object ' Try to get a running AutoCAD

Was AutoCAD not running?

ThisDrawing.Application.WindowState = acMax ThisDrawing.Application.Visible = True End Sub

' window to maximum ' window visible

AutoCAD attachment subroutine in VB.

VBA Features and Limitations


All languages have limitations and strengths. Remember that VBA is a subset of VB. It does not have all of the abilities of VB. Here are some of the features and limitations of the languages. By default, dialog boxes in VBA are modal, whereas the default is modeless in standalone Visual Basic. This means that a dialog box will not remain interactive with AutoCAD during the execution of a VBA program. The dialog must be dismissed before AutoCAD can respond. This limitation is imposed by VBA and will require you to rethink user interface interactions when designing programs to run in both environments. VBA is an "in process" controller, translating to better application performance and throughput for AutoCAD. AutoCAD VBA shares AutoCADs memory and process space significantly improving performance. VBA uses the same memory pool as AutoLISP, Visual LISP, and the command line. You can not run a command line process while VBA is still active. VBA does not have DDE capabilities so you can not hook into other programs through DDE from a VBA application. When AutoCAD is being controlled by an external VBA hosted application (such as Microsoft Excel) or Visual Basic program, performance is compromised. The external application must communicate to AutoCAD through the Windows message loop using remote procedure calls (RPC). Using VBA as an ActiveX automation controller delivers performance levels bested only by native ObjectARX compiled executables. Multiple projects are now supported in Release 2000 as is multiple document interface (MDI).

VB Features and Limitations


Page: 6

Visual Basic packages contain various features (at an escalating cost) that better enable you to create complex programs. VB is an external process from AutoCAD. This slows the program when manipulating AutoCAD objects but makes for better performance when dealing with heavy database integration issues. VB supports DDE operations while VBA doesnt. This allows you to hook into another DDE server application while working with AutoCAD objects. Cycos workflow is an example of a DDE server application that you can manipulate from a VB application working with AutoCAD objects.

These two features are strengths that VBA does not have. When you are looking at designing an application that must work with one of these processes, your only option is VB. Table 3 shows those packages and their features.

Page: 7

Visual Basic Edition


Feature Enterprise Professional Learning Application Control Creation Scripting

IntelliSense File I/O, OS Access Project Templates Add-in Support Multiple Projects Visual Inheritance ActiveX Creation Standard Controls Application Creation Learning Tools DataBase Access Native Compiler Active Document Creation ActiveX Server Components Transaction Server Remote Data Objects SQL Debugger SQL Server, Visual SourceSafe Application Performance Explorer (APE) Microsoft Repository Microsoft Visual Database Tools
Table 3. VB package features.

Page: 8

Which language for which situation?


Comparisons are nice but what does it really mean? It all comes down to when should you use a given language for a particular job. Since Visual LISP is widely used, it will probably remain the most commonly used language for a long time to come. As AutoCAD grows and leaves AutoLISP behind Visual LISP will become the language of choice for the user who wants to do low to mid level customization. It will be more important for even the casual programmer to know VB and VBA to be able to do the mid to high level programming customization. Getting a jump on this trend will enable you to be ready to seamlessly make the switch. The question will be to use VB or VBA. I think VB will remain the language of choice for database integration because VBA currently does not fully support the necessary database controls and will probably be limited even in the future. VBA will be a strong contender for those jobs that are dialogue box driven and need lots of speed. VB will be the language that hovers on the edge of full-blown application development (where ObjectArx takes over). Its relative ease (compared to the C++ language) of use will allow the casual programmer to still develop very complex products without the need to learn the more complex C++ language. You are now given a wide choice of languages to manipulate AutoCAD. Figure 1 shows the languages and their relative position on the complexity chart.

AutoCAD Programming
Applications Programmer

ObjectArx

Visual Basic

Visual Basic Application Programmer Visual LISP AutoLISP User DIESEL Menu Customization

Figure 1. Language complexity chart.

Unfortunately, there is no clear cut division between the lower and middle level languages except maybe their database connectivity. You could even argue that AutoLISP and Visual LISP have simple database connectivity with ASE and ASI. The short term answer is to continue to use AutoLISP (assuming you
Page: 9

already know it) and pickup Visual LISP as you develop your VBA skills by doing simple short projects. Use Visual LISP where you have limited time (and it is appropriate) to get the job done and VBA where you have the time to experiment. Be comfortable with VB and VBA and start using it in bigger and more complex projects.

Where to start.
You actually have two avenues you can follow to pick up VB or VBA. The first is to purchase VB 6.0 (there are many levels of packaging for the product) or use the native VBA environment within Release 2000. VB can be expensive and you probably do not need the higher end packing (the database integration packaging) to start with and VB costs extra where VBA is free with AutoCAD (at least for now). The VBA sample code shipped starting with Release 14 and the on-line help provide a very good starting point for learning VBA. Actual training classes on VBA are getting easier to find and when you do find one, it is another source for learning the program. Looking at sample code can be a little confusing at first until you get used to the VB and VBA event-driven, modular design. Good AutoLISP and Visual LISP programming uses modules so you should not be thrown too much by this part of VBA. Event driven only takes a little getting used to and once you do get used to it, you wont want to look back. Some people are intimidated by object oriented programming. Just remember that each control object in VBA (and VB) has properties (properties control how the object looks and behaves) and some have methods (these are things that the object can do). You only have to click on a control and select the type of event you wish to place your code in. Then the program runs your code whenever the event that you placed it in is triggered.

Building your VBA toolbox


Many of you have spent countless hours creating your own toolbox routines or borrowing them from outside sources and then altering them to your needs. Some have even gone so far as to purchase my toolbox book (free plug here). No one wants to go through all of that effort again for a new language. The good news is that the same routines can be used in both VB and VBA. The bad news is that, while some are inherent in VBA, most routines will have to be translated to the new language from AutoLISP and Visual LISP. This is not as hard as it sounds. I have been translating code as I need the routines. Figure 2 shows a simple pause routine in VBA and AutoLISP.

Figure 2. Code comparison.

This approach is easier than trying to rebuild the whole toolbox at one time. My toolbox has over one hundred routines and I have another couple hundred utilities that I frequently use as the framework for new programs. Trying to translate these all into VB at one time would not allow me any time to do my
Page: 10

normal work. As you can see from the example in Figure 2, there are some differences but the basic structure remains the same.

Tricks, Tips, and Limitations


For help, you must go to the on-line help contents tab and select the Visual Basic Reference help. This is a surprisingly good source for sample code and information. Part of the help object model is shown in Figure 3.

Figure 3. On-line help for VBA.

You only have to click on an information box to get help on the subject. This tree structure gives you a good idea of how the object hierarchy works in AutoCAD. Many of the information boxes have example code attached. You can cut and paste this code into your applications. Another good source for understanding how VBA interacts with AutoCAD is the sample code shipped with AutoCAD. I found that one program had a reference library from Microsoft 97 (I just let it be ignored) and a control was being used that I did not have (the program deletes it for you) but the rest loaded and ran fine. Even the one that had these minor problems loaded and ran once I bypassed the problems. The best one to give you many different feature examples is ACAD_CG.DVB in the support/vba folder of the AutoCAD directory. This programs dialogue has buttons that allow you to link to an AutoCAD drawing, access data in the drawing, create objects in the drawing, modify objects in the drawing, select objects in the drawing, prompt for input from a user, work with selection sets, access the preferences, set variables, create table entries (layers), access Xdata, and plot a drawing. Reviewing the code behind each button gives you insight on how the program works and you can copy and paste the modules into your own programs. Much of the example code reviewed later in this session comes from these sources. Figures 4 and 5 show the dialogue box tabs used by the acad_cg example program.

Page: 11

Figure 4. Tab 1 of the ACAD_CG sample dialogue box.

Figure 5. Tab 2 of the ACAD_CG sample dialogue box.

Some of the code behind these buttons will be examined at the end of this session. VBA is not viewed as a replacement for Visual LISP and many functions in Visual LISP provide equivalent functionality. There are data acquisition routines in VBA that allow prompt arguments. You can find most, if not all of them by searching the AutoCAD type library using the Object Browser in the VBA IDE. Some OS dependencies for VBA are: Windows NT3.51 Service Pack 5 is required in order to run AutoCAD VBA. Windows NT4.0 It is highly recommended that Service Pack 2 for Windows NT 4.0 be installed to run AutoCAD Release VBA Edition. Or AutoCAD Release 2000 Windows 95 No requirements from Microsoft.

One limitation to VBA is the database connectivity. The data control is not present for record sets although two other database controls are present. Autodesk has indicated that what you see is pretty much what you get (a MicroSoft imposed limitation). Another limitation is that VBA does not support creation of executables, it does offer password protection for the visibility of the project forms, classes, and modules on a project basis. You can find this Project Protection facility in the VBA IDE menu. Choose Tools > Project Properties > {TAB}Protection.

Automatically run a VBA app on startup.


We have gotten used to such nice features in AutoCAD as automatically running our code as a drawing loads. Autodesk has continued this tradition by supplying several different ways to autoload (and run) features for VBA. You can run a project by calling it with the command line version of VBARUN from an AutoCAD startup facility like acad.lsp. First, you need to prepare the acad.dvb file for autoloading. As an example, take the VBA sample that was provided with the AutoCAD VBA called drawline.dvb and use the VBALOAD command to bring it up in the VBA IDE. Then use the VBA IDE Save menu pick and save the project with the name acad.dvb. Next, invoke notepad.exe and create (or append to) acaddoc.lsp the following lines:
Page: 12

(defun S::STARTUP() (command _-vbarun drawline) ) Start the VBA IDE (use the VBAIDE AutoCAD command or choose VBA > Show VBAIDE from the AutoCAD menu). From the IDE, hit the F2 function key to bring up the Object Browser or select the Object Browser item in the View menu. In the Object Browser window use the library scope drop down list to change from the default <All Libraries> to AutoCAD. The edit list box just below the library list, is used for searches. Enter GET in that edit list box and hit return. A list of AutoCAD classes and members that include get in the name will appear in the scroll list. Some of the IAcadUtility class member functions can prompt the user at the command line. You can find others by looking through the list. Installing VBA VBA is automatically installed during a full install of R2000. You must specify that you want VBA during a R14 installation.

Invoking a program
There are three actions that will invoke a VBA project: 1. The first uses the VBAIDE command. Enter this command at the AutoCAD command line or use the menu pick to access the VBA development environment. In the IDE, you can enter code, debug, design and run a Visual Basic application interactively while AutoCAD is running. This is typically used to start new projects or edit existing ones. 2. The second action allows you to explicitly load a project into an AutoCAD session using the VBALOAD command. This command accesses a standard Open File dialog box that filters for .DVB project files in the AutoCAD search path. 3. The third action occurs at AutoCAD start-up if a VBA project has the magic file name acad.dvb. Note that you can also load this special VBA project with the VBALOAD command and subsequently save it. This file is automatically loaded only at AutoCAD start-up. Accessing AutoCAD VBA To access and write code for these events in AutoCAD VBA, you must perform the following tasks: 1. 2. 3. 4. From the VBA IDE menu, choose View > Project Explorer. From the Project Explorer window, double-click AutoCAD Objects. Double-click This Drawing. From the VBA IDE Code window, click on the drop-down list (General is usually displayed) and choose IAcadDocument. 5. The Subroutine menu will now show these VBA AutoCAD events (this is a small part of the overall list): BeginSave EndSave BeginOpen EndOpen BeginQuit 6. Clicking on the desired event notification adds a subroutine for which you write an event handler.
Page: 13

7. The following code example notifies you with a Message dialog box that AutoCAD is about to open an existing drawing: Private Sub IAcadDocument_BeginOpen(bstrFileName As String) Msgbox About to open existing AutoCAD drawing + bstrFilename End Sub Note: This example includes a message box that echos the text and prints the file name selected.

Code Samples
The rest of this session is an examination, in detail, of some of the sample code provided by Autodesk and a sample routine I wrote for this conference. The sample routines dialogue box is shown in Figure 6.

Figure 6. Sample dialogue box. This program features, on the basic tab, the ability to set system variables, access tables, and allow you to select objects from in the drawing. The advanced tab shows you how to fill a list with information from a table and access the operating systems registry (something AutoLISP can not do). We will review the code to do each of these features and compare this to what AutoLISP, Visual LISP, VBA, and VB can do. Given the time, we will also examine some of the Autodesk sample code.

In Conclusion
A simple route to migrating to VBA is to leverage your AutoLISP skills through Visual LISP and then VBA. I would approach the migration in these steps. 1. 2. 3. 4. Select a small simple project as a test. Determine if Visual LISP or VBA would be a better choice in language. Code and test. Implement the program.

Page: 14

The goal of this session was not to confuse you with all of the programming choices but to give you a better understanding of what they are now that VBA is now a part of AutoCAD. It is clear that Autodesk views the future mid to low-high end programming language for AutoCAD as VBA. It is now our challenge to accept their view of the future and start to provide the programmers and programs of the future.

Page: 15

S-ar putea să vă placă și