Excel and AutoCAD® – A match made in heaven (again!)

by Will on December 8, 2010

Many people are oblivious to the wondrous things that can be achieved with programming. If you cringe at the prospect of writing code, I’ll put this to you now – I cringe at the thought of having to do things manually. Often (and yes, I mean often), I’ll write a little 6 line bit of code that saves me hours of work. Yes, HOURS – perhaps even days. Why people avoid learning this stuff is beyond me, because it really isn’t as hard as it looks.

Today I’m going to explain how you can write code in Microsoft Excel VBA that controls AutoCAD®. Firstly, let’s get VBA open in Microsoft Excel. With Excel open, press Alt+F11, which should open the VBA IDE (integrated development environment). If this doesn’t work, you can open this by going Tools>Macro>Visual Basic Editor. If you’re using Excel 2007+, you might struggle to find the option. You have to firstly go into Excel Options and check the box to show the Developer Tab on the ribbon interface.

So we’re now in a position to write a bit of code. On the left (or perhaps on your right depending on your PC), there should be a section called the Project Explorer. In here you should have a few things called Sheet1, Sheet2, Sheet3 and one called ThisWorkbook. Right click in this area and select Add Module. This will create an area for us to write our code, and if you’re feeling adventurous you can rename the module to whatever you like. Double click the module to edit it.

Now let’s see if we can get AutoCAD® to do something.

If you’ve done any programming before, you will know that you can have variables, and variables can have different types. These types can be simple, or can be more complex things known as objects. AutoCAD® has its own type library containing all the object types that we are likely to need. This is very useful to load into our application. To do this, go to Tools>References in the VBA window, and look for an option called AutoCAD® 2010 Type Library, or whatever version of AutoCAD® you are using. This has now made available some extra types that weren’t available before.

Now for some basic code! Put this code into the module, and press the run button at the top of the VBA editor. The subroutine name “Main” is unimportant – we could call this anything we like.

Sub Main()
    Dim ACAD As AcadApplication 'Create ACAD variable of type AcadApplication
    Set ACAD = New AcadApplication 'Set the ACAD variable to equal a new instance of AutoCAD®
    ACAD.Visible = True 'Once loaded, set AutoCAD® to be visible
    ACAD.ActiveDocument.Utility.Prompt "Hello from Excel!" 'Print a message to the AutoCAD® command line
End Sub


Here we’ve created a new instance of AutoCAD®, and stored a handle to the AutoCAD® object (application) in the ACAD variable, then just printed a line to the AutoCAD® command line. Easy right? Ok, but we’re not going to want to open a new instance of AutoCAD® every time we want to run some code… So instead, we could use this, which links to an already open instance of AutoCAD®:

Sub Main()
    Dim ACAD As AcadApplication 'Create ACAD variable of type AcadApplication
    Set ACAD = GetObject(, "AutoCAD®.Application") 'Get a running instance of the class AutoCAD®.Application
    ACAD.ActiveDocument.Utility.Prompt "Hello from Excel!" 'Print a message to the AutoCAD® command line
End Sub


Great – now we can link to a running instance of AutoCAD®. There is one last thing we need to do with this. If we run this code and AutoCAD® is not running, we will get an error message. Really, we ought to trap this exception – here’s one way this could be dealt with:

Sub Main()
    Dim ACAD As AcadApplication 'Create ACAD variable of type AcadApplication
    On Error Resume Next 'This tells VBA to ignore errors
    Set ACAD = GetObject(, "AutoCAD®.Application") 'Get a running instance of the class AutoCAD®.Application
    On Error GoTo 0 'This tells VBA to go back to NOT ignoring errors
    If ACAD Is Nothing Then 'Check to see if the above worked
        Set ACAD = New AcadApplication 'Set the ACAD variable to equal a new instance of AutoCAD®
        ACAD.Visible = True 'Once loaded, set AutoCAD® to be visible
    End If
    ACAD.ActiveDocument.Utility.Prompt "Hello from Excel!" 'Print a message to the AutoCAD® command line
End Sub


This code firstly tries to link to an existing instance of AutoCAD®. We use the On Error Resume Next statement to skim over any errors that might occur when we try to link to an existing instance of AutoCAD®. It is very important that we also add the statement On Error Goto 0 after we’re done ignoring errors. At first glance you might think that it’s a good idea to skim over all errors by adding On Error Resume Next to the beginning of all our code, but this makes it much more difficult for us as developers to debug our application. Use of On Error Resume Next in excess is generally considered bad programming practice, but under controlled circumstances its use is no problem, and it helps trap our error in the example above.

After our call to the GetObject function, the ACAD variable either contains a link to our AutoCAD® object, or it contains “Nothing” as it was unable to locate one. In the latter case, we are going to create a new instance using the method explained in the first example.

Now we’re getting there.

Let’s actually do something useful now. Go to Excel – Sheet1, and fill columns A and B with some coordinates, X being in column A, and Y being in column B. Here is some data you can copy/paste if you like, though you may need to copy and paste the columns seperately:

3
7
5
2
3
4
5
6
7
8
8
8
5
3
1.6
1
1
1
1.6
3

 

In Excel we can access the data in a worksheet by using Sheet1.Cells(Row, Column). We can loop through Sheet1.Cells and take action in AutoCAD® based on the content of the cells. Below is a quick example of how this can be achieved. The loop that is used is known as a For-Next loop, which increments the value of n in this example from 1 to 10. Then we’re just taking the data from the cells at row n, and using the data to insert a point into AutoCAD®. If you used the data above you’ll end up with a nice smiley face drawn in points!

Sub Main()
    Dim ACAD As AcadApplication 'Create ACAD variable of type AcadApplication
    On Error Resume Next 'This tells VBA to ignore errors
    Set ACAD = GetObject(, "AutoCAD®.Application") 'Get a running instance of the class AutoCAD®.Application
    On Error GoTo 0 'This tells VBA to go back to NOT ignoring errors
    If ACAD Is Nothing Then 'Check to see if the above worked
        Set ACAD = New AcadApplication 'Set the ACAD variable to equal a new instance of AutoCAD®
        ACAD.Visible = True 'Once loaded, set AutoCAD® to be visible
    End If
    ACAD.ActiveDocument.Utility.Prompt "Hello from Excel!" 'Print a message to the AutoCAD® command line
    Dim Coords(2) As Double 'This is an array of double precision floating point numbers
    ' The array goes from 0 - 2, which will contain our coordinates X, Y and Z
    Dim n As Integer 'Create the variable n as the type Integer
    For n = 1 To 10 'Loop this code, incrementing the value of n from 1 to 10
        Coords(0) = Sheet1.Cells(n, 1) 'Put the Column 1 value into the Coords array
        Coords(1) = Sheet1.Cells(n, 2) 'Put the Column 2 value into the Coords array
        ACAD.ActiveDocument.ModelSpace.AddPoint Coords 'Add a point in AutoCAD® at this location
    Next
End Sub


So there we have it – an introduction to using VBA in Excel to control AutoCAD®. Obviously what we have done here only scratches the surface of the capabilities, but I’ll leave you to get creative with the that… for now at least.

As with all my posts I’d finally like to encourage you to subscribe to my blog. I’m always going to be adding new content on here, and I’ll always try to explain everything the best I can. Also, I’ll always be willing to help you with any specific problems that you have, so please do sign up and get involved on my site.

Will

Enter Your Mail Address

Be Sociable, Share!