Documente Academic
Documente Profesional
Documente Cultură
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.
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
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.
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.
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
(princ) )
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
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
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
AutoCAD Programming
Applications Programmer
ObjectArx
Visual Basic
Visual Basic Application Programmer Visual LISP AutoLISP User DIESEL Menu Customization
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.
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.
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
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.
(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