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!

{ 54 comments… read them below or add one }

Aprinto December 9, 2010 at 5:38 pm

Thanks Will,
I very appreciated with your solutions.

I post my current code here for this topic, similar with your post.

Option Explicit
Sub ReadCell()
Dim rgKoordinat As Range
Set rgKoordinat = ActiveSheet.UsedRange
rgKoordinat.Select

Dim respon As Long
If MsgBox(“Correct Selection?”, vbYesNo) = vbNo Then Exit Sub

Dim c As Range, i As Integer, j As Integer
Dim lstKoord() As Double, lstDes() As String

‘list from excel
‘Shape Col2 Col3 Col4 Value, Color
‘Poly1 ?? ?? ?? value, conditional format for value
‘…
‘Poly-n ?? ?? ?? value, conditional format for value

i = -1: j = -1
For Each c In rgKoordinat.Columns(2).Cells
If Application.IsNumber(c) Then
i = i + 3
j = j + 1
ReDim Preserve lstKoord(i)
lstKoord(i – 2) = c
lstKoord(i – 1) = c.Offset(, 1)
lstKoord(i) = c.Offset(, 2)

ReDim Preserve lstDes(j)
lstDes(j) = c.Offset(, -1) ‘ Shape
End If
Next

‘Connect to autocad (ruuning)
Dim appCAD As AcadApplication
On Error Resume Next
Set appCAD = GetObject(, “AutoCAD.Application”)
If Err.Number Then Exit Sub

Dim Koordinat(0 To 2) As Double
Const FontHeight = 0.05
j = -1
For i = LBound(lstKoord) To UBound(lstKoord) Step 3
j = j + 1
Koordinat(0) = lstKoord(i)
Koordinat(1) = lstKoord(i + 1)
Koordinat(2) = lstKoord(i + 2)
With appCAD.ActiveDocument.ModelSpace
‘plot koordinat
‘.AddText Koordinat(0), Koordinat, FontHeight ‘ col 2
‘.AddText Koordinat(1), Koordinat, FontHeight ‘ col 3
‘.AddText Koordinat(2), Koordinat, FontHeight ‘ col 4
.AddText lstDes(j), Koordinat, FontHeight ‘ col 1 = Shape


‘ If hatch position is same with Koordinat then change color relevant to its value.
‘ But how? I still don’t know how to find hatch position.

End With
Next i

appCAD.ZoomExtents
AppActivate appCAD.Caption
Set appCAD = Nothing
End Sub

And I still need some solutions to answer my problem above.

Reply

Will December 9, 2010 at 8:12 pm

Hi,

Now I understand what you are trying to achieve. You want to identify hatches in autocad at a certain position, and change the colour of the hatch at that position. There are a few problems that we need to overcome. Firstly, hatches do not have an “insert point” as such, so we need to create our own way of getting this value. I’ve used the getboundbox method to get the upper and lower limits, then taken an average to get the midpoint. Secondly, if we want to check against this value, we have another potential problem. Floating point number variable types such as doubles can be a pain to deal with. Making a direct comparison such as if num1 = num2 will return false if there is any minute margin of error, which can sometimes be present in our AutoCAD drawings. Incidentally this is sometimes the reason detecting a hatch boundary, or joining polylines can behave unexpectedly. For this reason I’ve included a tolerance for checking the positions.

Here is the code I produced. In Excel, Column A is X, Column B is Y, and Column C is the colour index for the target hatch.

Let me know how you get on:

Sub Main()
Dim Acad As AcadApplication
Set Acad = GetObject(, “AutoCAD.Application”)

Dim TargetPoint(2) As Double
Dim FoundHatch As AcadHatch

Dim n As Long
n = 1
Do
If Cells(n, 1) <> “” Then
TargetPoint(0) = Cells(n, 1)
TargetPoint(1) = Cells(n, 2)
Set FoundHatch = FindHatchAtLocation(Acad.ActiveDocument, TargetPoint, 0.1)
If Not FoundHatch Is Nothing Then
FoundHatch.Color = Cells(n, 3)
End If
Else
Exit Do
End If
n = n + 1
Loop

End Sub

Private Function FindHatchAtLocation(Doc As AcadDocument, TargetPoint As Variant, Tolerance As Double) As AcadHatch
‘Set default return value:
Set FindHatchAtLocation = Nothing

Dim ent As AcadEntity
Dim h As AcadHatch
Dim hatchPnt As Variant
For Each ent In Doc.ModelSpace
If TypeOf ent Is AcadHatch Then
Set h = ent
hatchPnt = GetHatchGripPosition(h)
If Tolerance > DistanceBetweenPoints(hatchPnt, TargetPoint) Then
Set FindHatchAtLocation = h
End If
End If
Next
End Function

Private Function DistanceBetweenPoints(Pnt1 As Variant, Pnt2 As Variant) As Double
Dim OffsetX As Double
Dim OffsetY As Double
OffsetX = Pnt1(0) – Pnt2(0)
OffsetY = Pnt1(1) – Pnt2(1)
DistanceBetweenPoints = (OffsetX ^ 2 + OffsetY ^ 2) ^ 0.5
End Function

Private Function GetHatchGripPosition(h As AcadHatch) As Variant
Dim pnt(2) As Double
Dim minPnt As Variant
Dim maxPnt As Variant
h.GetBoundingBox minPnt, maxPnt
pnt(0) = (minPnt(0) + maxPnt(0)) / 2
pnt(1) = (minPnt(1) + maxPnt(1)) / 2
GetHatchGripPosition = pnt
End Function

Reply

Aprinto December 11, 2010 at 2:39 pm

Great … very great …. very thanks to you.
You are a rock Will ….

It work, but it need strong computer to proceed this.
To proceed 1 row in Excel (change color of hatch), P4 dual core HT need 1 minute and P4 quad core need 5 seconds.

One more question, how to use Function FindHatchAtLocation, so I can save lists of hatch coordinates into a file, CSV or TXT or XLS?
This is to ensure the exact coordinates between Excel and AutoaCAD, prevent from moving hatch “accident”.

THANKS AGAIN ….

Reply

Aprinto December 12, 2010 at 5:51 pm

Sorry, Will
My problem solved….
Based on your GetHatchGripPosition function, I try to adopt to write function finding to a txt file.

Sub FindHatch()
Dim Acad As AcadApplication
Set Acad = GetObject(, “AutoCAD.Application”)
Dim ent As AcadEntity
Dim h As AcadHatch
Dim pnt(2) As Double
Dim minPnt As Variant
Dim maxPnt As Variant

Open “d:\Hatch2.txt” For Append Access Write As #10
Write #10, “Hatch Coordinates”
For Each ent In Acad.ActiveDocument.ModelSpace
If TypeOf ent Is AcadHatch Then
Set h = ent
h.GetBoundingBox minPnt, maxPnt
pnt(0) = (minPnt(0) + maxPnt(0)) / 2
pnt(1) = (minPnt(1) + maxPnt(1)) / 2
Write #10, pnt(0) & “;” & pnt(1)
End If
Next
Close #10
MsgBox “Finish menulis koordinat”, vbOKOnly
End Sub

THANKS AGAIN ….

Reply

Will December 13, 2010 at 8:09 am

Glad to help. If you need anything else, please don’t hesitate to ask.

Will

Reply

Jimab June 13, 2012 at 9:22 am

Hi Will,
Please, i want to plot some coordinates listed in excel column A and B in autocad using excel VBA, how is that possible?

Reply

Will August 8, 2012 at 6:43 pm

Check out the original Excel and AutoCAD post – that should help you :-)

Reply

ion March 2, 2011 at 8:30 am

hello will
i have a few questions:
1. how i add lines from a specific range
2. after the lines are created in autocad, i want to inset in excel as a dwg object
3. when the coordonates are changed, i want to regen automaticaly the dwg object

this is possible?

thank you

ion

Reply

Will March 3, 2011 at 8:43 am

Hello ion,

1. I’m not sure I understand exactly what you mean – but I will try to assist still! Adding lines from Excel should follow the same rules as adding points in the original article. The only difference would be instead of using the AddPoint method of the Modelspace object, you would use AddLine. For this you would need to have a coordinate for the start and end points of the line, e.g., Addline(Coords, Coords2). Then it would just be a case of looping through the range of interest to you. If you want to loop through every cell in a range you could use:

Dim r As Range
Dim c As Range
Set r = Range(“A1:d2″)
For Each c In r
‘c loops through the cells in the range
MsgBox c.Value
Next

2. I believe you can drag and drop a DWG file into Excel to embed the file in the drawing – would this be suitable?

3. The last one is pretty complicated I’m afraid, off the top of my head one solution could be to insert the objects (programmatically) into a block. Then, when something is changed you could retrieve the block and delete its contents, and then reinsert all the lines again (programmatically of course).

Will

Reply

ion March 3, 2011 at 10:14 am

Hello will,
please help me with improuve thise codes, witch i found and i trying unsuccesfull modified

Point 1: Add lines
Sub Deseneaza_Click()
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
Dim adoc As AcadDocument
Set adoc = ACAD.ActiveDocument
Dim aspace As AcadBlock
Dim oLine As AcadLine
Set aspace = adoc.ActiveLayout.Block
Dim startPt(0 To 2) As Double
Dim endPt(0 To 2) As Double
startPt(0) = Range(“A1″): startPt(1) = Range(“B1″): startPt(2) = 0#
endPt(0) = Range(“C1″): endPt(1) = Range(“D1″): endPt(2) = 0#
Set oLine = aspace.AddLine(startPt, endPt)
startPt(0) = Range(“A2″): startPt(1) = Range(“B2″): startPt(2) = 0#
endPt(0) = Range(“C2″): endPt(1) = Range(“D2″): endPt(2) = 0#
Set oLine = aspace.AddLine(startPt, endPt)
startPt(0) = Range(“A3″): startPt(1) = Range(“B3″): startPt(2) = 0#
endPt(0) = Range(“C3″): endPt(1) = Range(“D3″): endPt(2) = 0#
Set oLine = aspace.AddLine(startPt, endPt)
startPt(0) = Range(“A4″): startPt(1) = Range(“B4″): startPt(2) = 0#
endPt(0) = Range(“C4″): endPt(1) = Range(“D4″): endPt(2) = 0#
Set oLine = aspace.AddLine(startPt, endPt)
ACAD.ApplicationExit filesave:=True ‘this i d’ont know – i want to beak the conection beetwin vba and autocad
Set AcadApplication = Nothing
End Sub

Point 2:Insert in excel dwg object
Sub Insert_Desen_Ca_Fisier_Click()
Dim objNewDWG As Object
Dim DWGToOpen As String
On Error Resume Next
DWGToOpen = Application.GetOpenFilename(“All Files,*.dwg”, Title:=”Insert Fisier”)
If DWGToOpen False Then
ActiveSheet.OLEObjects.Add Filename:=DWGToOpen, Link:=True
‘ Setting The Opened Picture Into A Cell Range
Set objNewDWG = InsertDWGInRange(DWGToOpen, Range(“i20:l26″))
End If
End Sub
Function InsertDWGInRange(DWGFileName As String, TargetCells As Range) As Object
‘ inserts a picture and resizes it to fit the TargetCells range
Dim p As Object, t As Double, l As Double, w As Double, h As Double
If TypeName(ActiveSheet) “Worksheet” Then Exit Function
If Dir(DWGFileName) = “” Then Exit Function
‘ import DWG
Set p = ActiveSheet.OLEObjects
‘ determine positions
With TargetCells
t = .Top
l = .Left
w = .Offset(0, .Columns.Count).Left – .Left
h = .Offset(.Rows.Count, 0).Top – .Top
End With
‘ position picture
With p
.Top = t
.Left = l
.Width = w
.Height = h
End With
Set InsertDWGInRange = p
Set p = Nothing
End Function

Point 3: i delete the object and i repeate point 2

ion

Reply

Will March 3, 2011 at 12:59 pm

Point 1 seems pretty good – though I don’t think you need:

ACAD.ApplicationExit filesave:=True

There is no real “link” to AutoCAD as such, all you’ve done is created a reference to the AutoCAD object in the variable ACAD. Set ACAD = Nothing will remove the reference.

For points 2 & 3, can you tell me how you would achieve this manually? I’m not sure I understand the aim.

Will

Reply

ion March 3, 2011 at 2:09 pm

point 1 “produce” a dwg.file, point 2 insert this file in to excel in a specific place with a specific size,
and now comes the problem – when i modify the coordonates for the 1-st point and “produce”
another dwg.file i delete the old dwg.file and i save and exit excel. then i reopen excel and i insert the new dwg.
i wonder if is posible to make the changes automaticaly and not to make these operations.
thank you for your answers and your promtitude.
ion

Reply

charbel abou samra March 8, 2011 at 1:06 pm

Dear will,
I very appreciate your solutions, i’m a beginner and i know how to import points from excel to Autocad but i would like further to know how to attach text lines to these points.
regards

Reply

Will March 22, 2011 at 1:03 pm

Have you looked at my tutorial on importing points from Excel to AutoCAD? I have two versions, one for utilising VB to achieve this task, and one with a simple copy and paste method. Take a look at the copy and paste method which should be easy to tweak for lines.

Regards,
Will

Reply

Nils Fuessle March 23, 2011 at 1:04 pm

Hey, I greatly appreciate your website. This is about the only place online that I could find that didn’t get too complicated too fast. I have now successfully been drawing 3D models in AutoCAD through Excel’s VBA. Question – I am trying to insert text into different planes (XY,XZ, and YZ). My workaround has been to have the user manually switch plane views and then run separate macros for each plane. How can I either A) insert text into different planes or B) write code to switch plane views. See below for the code that I have been using to insert text. Thanks alot!

Dim oAcadMText As AcadMText
Dim InsertionPoint(0 To 2) As Double
Dim Width As Double
Dim Text As String

InsertionPoint(0) = Sheets(“Structural Model Input”).Range(“AB5″)
InsertionPoint(1) = Sheets(“Structural Model Input”).Range(“AC5″)
InsertionPoint(2) = Sheets(“Structural Model Input”).Range(“AD5″)

Text = Sheets(“Data”).Cells(irow, 29) & ” Connection #” & Sheets(“Data”).Cells(irow, 1)
Set oAcadMText = aspace.AddMText(InsertionPoint, Width, Text)

Reply

Will March 31, 2011 at 11:09 am

To be perfectly honest with you, I’m not sure off the top of my head – I will look it up asap. However, another approach could be to rotate the text after you’ve created it (programmatically of course!)

Reply

RochaPinto April 4, 2011 at 10:36 am

Hello everyone,

I’m having a problem writing information on an excel file. I already know how to read/write the information i want from/to the cells i want. I just can’t open/save the file in the adress i want. For instance, the folowing code creates the file (with the name and adress) i want but doesn’t write the information in it. It also creates another file called Book1, which i have to save manually, where it writes the information.

Option Explicit

Dim comp As Double
Dim largura As Double
Dim area As Double
Dim referencia As String

Private Sub CommandButton1_Click()

‘textbox 1 and 2 recieve values for algebric operations
comp = TextBox1.Value
largura = TextBox2.Value
area = comp * largura
‘textbox3 recieves a string with the name of the file where i want the information to be stored
referencia = TextBox3.Value

Dim oExcel As Excel.Application
Dim wrkb As Excel.Workbooks
Dim wrks1 As Excel.Worksheet
Set oExcel = New Excel.Application
On Error Resume Next

‘Check if Excel is open and if not open it.
Set oExcel = GetObject(, “c:\EN12354CAD\” & referencia & “.xlsx”)
If Err.Number > 0 Then
Set oExcel = CreateObject(“c:\EN12354CAD\” & referencia & “.xlsx”)
End If

Set wrkb = oExcel.Workbooks.Add(“c:\EN12354CAD\” & referencia & “.xlsx”)
Set wrkb = oExcel.Workbooks.Open(“c:\EN12354CAD\” & referencia & “.xlsx”, True, False)

oExcel.Visible = False
Set wrkb = oExcel.Workbooks.Add
Set wrks1 = oExcel.ActiveSheet
Set wrks1 = oExcel.ActiveWorkbook.Sheets(“wrks1″)

‘Code below adds column names
wrks1.Range(“A1″) = “COMPRIMENTO”
wrks1.Range(“B1″) = “LARGURA”
wrks1.Range(“C1″) = “AREA”

‘Fill the columns with block data from modelspace
wrks1.Range(“A” & 2) = comp
wrks1.Range(“B” & 2) = largura
wrks1.Range(“C” & 2) = area

oExcel.SaveWorkspace “c:\EN12354CAD\” & referencia & “.xlsx”

Unload GravarExcel1

End Sub

My project is completly stopped due to this problem… Can anyone please help me?
by the way, i’m using AutoCad 2009.

Thank you

Reply

Will April 4, 2011 at 12:13 pm

Hi there,

At a glance, I’m not sure you’re creating a link to Excel correctly using GetObject and CreateObject. I think you need something like:

‘Check if Excel is open and if not open it.
Set oExcel = GetObject(, “Excel.Application”)
If Err.Number > 0 Then
Set oExcel = CreateObject(“Excel.Application”)
End If

Try going through step by step – get the code to open Excel first, then add the data, then save and close Excel.

Hope this helps – let me know how you get on!

Will

Reply

RochaPinto April 5, 2011 at 11:15 am

Thanks Will.

I tried your sugestion, but i managed no results. The problem persists. It creates a file with the name i want in the adress i want, but when i try to open it it shows a message box:

“Excel cannot open the file ‘yuyu.xlsx’ because the file format or the file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file.”

It still asks me to save “Book1″ mannually (with the information it was suposed to save in the ‘yuyu.xlsx’)

Any idea? Don’t you have a piece of code that can actually create, open and save an excel file?

Another dumb question: How can i run it step by step?

Antonio

Reply

RANJAN April 25, 2011 at 10:32 am

hi Will,
i hope u r the rigth person to solve one of my query,
recently i did a excel program for trajectory calculation. can you provid me a code to draw the trajectory in autocad using the points obtained from the excel sheet calculations.
plz reply me

Reply

Will April 26, 2011 at 1:21 pm

The code in this article should help you get there – you’ll need to apply your own logic to ensure that you account for your own formatting etc. To be able to help with a specific example I’ll need you to send me an example for me to work with – feel free to do so!

Reply

Stuart May 2, 2011 at 10:37 pm

Hi will,
I have used autocad for 10 years designing bespoke boats with no reference to rules or standards (printed direct from model space, no templates and just modified my previous drawings, creating a catalogue of blocks) however a new career in bespoke window manufacture has got me interested in automation via excel. I have an IT guy who is seriously on the ball and a director keen to embrace change. We currently use pen and paper to make notes and the surveyors data input to excel back in the office onto our server database. manual calculations are them made and new data entered to an excel sheet( the sheets auto calculate a number of items but need manual adjustments as they are out-dated. I am writing an excel based ‘idiotproof’ form that will consist of dropdown fields alowing only verified data to be entered in the required cells, by the surveyors. IT guy has said he can put this form onto android pc/phones and the surveyors can input and upload info to the database from site. I would like to take this height and width info and either draw a number of rectangles that all have a defined height and width, are spaced appropriately in the x plane and are positioned in the y plane based on excel data ( rectangle lower start point, y reference = column value), or (in a perfect world!) use them to stretch the overall width and height of a pre existing block consisting of my window made of standard sections (in 2 or 3d). Saving it in a file name specified from an excel sheet field. in the future I also hope to add material weight and cost analysis but im not sure wheter to do this in excel alone or in conjunction with autocad. I have no programming experience but can follow instructions and was impressed when i ran the program above and got a smiley face. I put my first excel sheet into cad the other day, but this is something else! any advice much appreciated, many thanks,
Stuart

Reply

Will May 3, 2011 at 8:20 am

That sounds like a great opportunity to get some automation in there! And it certainly does sound doable.

However often the stumbling blocks come in when we start using phrases like “spaced appropriately” – this needs to be explicitly defined really, for example, spaced with 1m gaps.

Assuming you have all the information required, it can be automated. I’ll quickly write an example of drawing some rectangles for you, and hopefully it will point you in the right direction.

Reply

Will May 3, 2011 at 9:37 am

I decided to create a new post for you – it’s here

Reply

faiz May 30, 2011 at 5:23 pm

Hey ,

I am working on a similar problem . We use AutoCad for engineering drawings and follow a defined standard and attributes to make the template.

I have around 100 wiring diagrams which are in Excel . My task is to copy the indvidual text values and paste them in a template in AutoCad.I wanted to reference indvidual Autocad blocks to excel cells expecting Autocad to pick values automatically. Once I import the data – I need to remove any link between excel and Autocad so they are not dynamic.

Please suggest what approach should I use in order to automate this process. Can I use scripting in Autocad or I could achieve the same task in VBA Excel ?

Thank You for your time . Look forward for your detailed response.

Regards,

Faiz

Reply

Will June 21, 2011 at 9:05 am

This sounds like an interesting problem – in order to really come up with a detailed solution I’d need to see an example of an actual file you’re working with, and what you want to end up with. Feel free to forward this on and I’ll see how I can help you.

Reply

loganath September 23, 2011 at 10:09 am

HI Will,

We too spend lot of time in developing CAD drawings from information available in EXCEL. Could you please let me know from the attachment sent to your mail whether it is possible to develop in VBA excel to develop ACAD drawings similar to the attachment.

Thanks & Regards

Loganath

Reply

Will September 25, 2011 at 7:45 am

Yes, it is possible. Please see the email replied to you for more info.

Will

Reply

Layzie July 25, 2011 at 6:30 am

Hello Will,
I am very much impress with you….
I am new to vba and autocad..I have an excel file which contain formula that display diagram of different shapes…I want to display the diagram to autocad through vba….Can you plzz help me worked it out…

Reply

Deibitx October 3, 2011 at 8:39 pm

Hello everybody,
For me it doesn’t work. A message appears telling about the error nº 424 and it needs and object. The line tha appears in yellow is :”Coords(0) = Sheet1.Cells(n, 1) ‘Put the Column 1 value into the Coords array”
How can i solve it?
I am learning about this and i know near to nothing
Thanks

Reply

Will October 5, 2011 at 9:27 am

Are you putting the code in the VBA editor of Excel ? If you’re putting it in the AutoCAD one, Sheet1 doesn’t exist!

Reply

amit November 2, 2011 at 11:26 am

Dear Will,

I am unable to control length of arc in my code. Please can you suggest me how to control it.

Reply

Will November 8, 2011 at 2:12 pm

As you probably know, arcs are created by specifying a centre point, a radius, and a start and end angle.

I’m afraid working out the length is going to involve some maths, but don’t worry it’s not too hard.

The formula for working out the circumference of a circle is PI * Radius * 2. But to get the length of an arc, we only need a portion of the circumference, namely:

(endAngle – startAngle) / 360

That’s how much of the circumference you need. So that creates the final calculation:

lengthOfArc = (PI * Radius * 2) * (endAngle – startAngle) / 360

Using this we can rearrange the calculation to find out the end angle for a given start angle, radius and length.

endAngle = startAngle + 360 * lengthOfArc / (PI * Radius * 2)

Hope this helps!
Will

Reply

amit November 11, 2011 at 10:06 am

Thanks Will,

I also wanted to know how dimension the entities which have been drawn by input from excel and how to change their color, line type and all.

Reply

Will November 14, 2011 at 8:28 am

I’ll start by answering the second part of your question. To change the properties of entities you’ve added, you will need to do something like this:

Dim myPoint
myPoint = ACAD.ActiveDocument.ModelSpace.AddPoint Coords
myPoint.Color = 10

The AddPoint method does something called returning a value from the method. This return value is actually a reference to the entity we just created, which is precisely what you need.

As for the first, you’ll have to use:

ThisDrawing.ModelSpace.AddDimAligned ExtLine1Point, ExtLine2Point, TextPosition

Hope this helps,
Will

Reply

Bill Turner November 10, 2011 at 9:20 am

I stumbled across this site by accident but now I’ve read it I think it could point me in the right direction of curing one of my problems.
I am an AutoCAD user (not brilliant but basic) and I am a VBA fettler (again not the world’s best) but never connected the two so thanks for showing me the light there.

Further I’m wondering if you may have some suggestion on how to tackle my problem.
I have various flow charts done in AutoCAD that I want to automate i.e. turn the boxes a different colour if the condition is true. I haven’t got AutoCAD on all machines but I have Excel. Is there a way I could convert an AutoCAD flow diagram to an Excel diagram made of shapes? That way I can easily change the back ground colour of a shape depending on a variable. Thanks for your obvious years of fiddling Will and thanks for any assistance you may be able to give.

Reply

Will November 14, 2011 at 8:19 am

Hi Bill,

Unfortunately I don’t think this will be easy. But, the way I’d start is by finding a way to identify what a “shape” is in AutoCAD. If it’s a polyline or something, and you’re only selecting 1 polyline per shape, then that makes it easier. Once you’ve identified your individual shapes, you need to move them across to Excel as shapes. This will involve some conversion between the coordinate system of AutoCAD and Excel – I’m not sure what that would be, but you’d need to convert polyline.coordinates to whatever the shape equivalent is in Excel. There may even be some scaling involved to get stuff to show up right etc.. sounds like a lot of hassle really if I’m honest.

I’d try to avoid conversion if possible – unless you actually want the end result to be in Excel. If not, it will be far easier to do what you need doing natively in AutoCAD. So when you get to the point of having identified your shapes, you can then manipulate them as you see fit.

Does that make sense?

Will

Reply

Bill Turner November 25, 2011 at 1:36 pm

Hello Will, yes it makes sense and I’ve sort of fettled it now. I can export AutoCAD in DXF and I now decode DXF in excel and redraw the shapes. It is work in progress but appears to work ok. Only slight niggle is I get the vertices from the DXF I redraw the shape (say a square) and group it and call it ASquare but I can only change the line colour of the new square I can’t use the fill option. I have a plant information system and excel on all machines and not only would it be tricky to get the plant info in to AutoCAD we only have one PC with AutoCAD on so I’m pretty stuck with my options.
Thanks for your comments

Reply

Bill Turner November 25, 2011 at 1:37 pm

It is only a flow diagram after all so no complex shapes to redraw :)

Reply

Paul Mayer December 16, 2011 at 7:12 pm

I would like to change the line type in Autocad from continuous to dashed from Excel. Your help is appreciated.

Thanks.

Reply

Paul Mayer December 16, 2011 at 11:12 pm

I think I figured it out. I needed to load the line types from acad.lin first for it to recognize the DASHED line type.

Thanks.

Reply

Melb March 10, 2012 at 4:34 am

Thanks for the article.The First code run without any problem. but when I run second,third and fourth subs, it do nothing.! It was working yesterday but today, I am not able to get response. I have included refrences as you advised. Please help!

Reply

sanjeewa March 29, 2012 at 11:31 am

hi will,
i’m trying to make a drawing with the help of excel. but i’m not getting it right,
as a ex: x axis -5 ,-4,-3 ,-2 ,-1 ,0 ,1 ,2 ,3 ,4 ,5
y axis 2 ,2.5 ,3 ,2 ,1.8 ,3 ,2.2 ,2 ,1.8 ,2
need to connect all the points by a line,
thanks.

Reply

SAWAD August 1, 2012 at 7:48 am

L ENTER
-5,2
-4,2.5
-3,3
.
.
.
.
.
YOU CAN DO IT SIMPLY BY USING EXCEL

Reply

BAM April 25, 2012 at 8:44 pm

I have found all this very useful and am trying something very similar. I have a block and am inserting it into Autocad using VBA. Now I would like to have the same code read an excel sheet of X & Y ‘s for the insertion location on the drawing. It is the same block just in many very different locations that a simple spaced array won’t work. Here is the code I found on the web that works for inserting the block:

Sub test()
‘Sub to test the function
Insertblock “C:\block.dwg”
End Sub
Function Insertblock(ByVal blockname As String)
Dim pnt, pnt2 As Variant
prompt1 = vbCrLf & “Enter block insert point: ”
‘Get the first point without entering a base point
pnt = ThisDrawing.Utility.GetPoint(, prompt1)
‘Insert the block
Set blockRefObj = ThisDrawing.ModelSpace.Insertblock(pnt, blockname, 1#, 1#, 1#, 0)
On Error Resume Next
‘Specify rotation angle on screen
blockRefObj.Rotate pnt, ThisDrawing.Utility.GetAngle(pnt, “Select Rotation Angle:”)
End Function
Private Sub AcadDocument_BeginSave(ByVal FileName As String)
End Sub

Can anyone help get the data from an excel sheet to the X, Y, rotation attributes in a loop?

Reply

Will May 25, 2012 at 10:43 am

Try a “For” loop

Reply

Chris May 21, 2012 at 6:45 pm

Will,
I’m looking for a way to have a master excel sheet that my drawings reference to for a variety of data within an attribute (without using Sheet Set Manager). Something you’re familiar with or know how to do?

Reply

Will August 8, 2012 at 6:45 pm

Not presently I’m afraid, but I will endeavor to cover that soon!

Reply

SAWAD August 1, 2012 at 7:43 am

HOW CAN I IMPORT TEXT FROM EXCEL TO AUTOCAD AT SPECIFIED CO-ORDINATES..? ANY ONE PLS HELP ME..

Reply

Will August 8, 2012 at 6:33 pm

You could try just copying and pasting the cells – there are various options for “pasting special” from the Edit menu.

Reply

Lyle August 18, 2012 at 9:37 am

Will,

I have a problem that is not unique, but I’ve struggled to find a solution. I work on drawings that have parts lists and technical data associated with them. For example, There is a master parts list which I keep in Excel and it needs to make it’s way into AutoCAD. Right now, this is all done by hand. Not a really big deal if the parts list is small (like less than 50 items), but when the list is hundreds of items long, then it’s way too time consuming to cut and paste all the textual data over by hand. I’ve looked at the OLE, data linking, and past special options and they all basically have the same problem, the table that gets imported isn’t the right size, and I haven’t found a way to edit it without completely destroying the formatting. It’s not like the AutoCAD drawing has beautiful formatting or anything, it’s just a certain size.

I already have the technical data summary drawing with the right amount of columns/rows and the parts list drawing as well. I would just like to find a way to import the data from a particular row/column in Excel and populate it in AutoCAD. The drawing file right now doesn’t have a table er se, but a manually drawn table using individual lines and a ton of text boxes.

I can send you an e-mail with the drawing, spreadsheet, and my unsuccessful attempts thus far. I’m hoping that there’s a way to do this with code. I’m not much of a programmer, but your site came up while I was searching for solutions. I was able to get the “Hello from Excel!” to display on my command line in AutoCAD.

Thanks for your site and in advance for any suggestions you can come up with.

Reply

Will October 2, 2012 at 11:43 am

Sorry for the delay in getting back to you – please do feel free to send me an email and I’ll see what I can do.

Reply

Kingoro January 23, 2013 at 5:54 pm

Hi Will.
I have used your Sub Main() function as a template and adapted to draw “n” points from excel to AutoCAD. The routine does work, but seems to be taking too long. Is there a way to optimize the speed? I have hundreds of points and I would like to be able to plot them into AautoCAD very fast.

Please find a extract of the code below:

For i = 1 to n
Coords(0) = Sheet1.Cells(i + 1, 1)
Coords(1) = Sheet1.Cells(i + 1, 2)
Coords(2) = 0
ACAD.ActiveDocument.SetVariable “PDMODE”, 34
ACAD.ActiveDocument.SetVariable “PDSIZE”, 2
Set PointObject = ACAD.ActiveDocument.ModelSpace.AddPoint(Coords)
PointObject.Color = acRed
PointObject.Update
Next

Thank you.

Reply

Will March 18, 2013 at 12:51 pm

One of the ways to make this faster would be to firstly read the Cells into an array first, preferably using some method to copy the Sheet1.Range(“????”) directly to array without reading it cell by cell. Then it’s all in memory and should be much faster.

Reply

Leave a Comment

{ 1 trackback }

Previous post:

Next post: