Excel and AutoCAD® – A match made in heaven (again!)
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:
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.
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.
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
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 ....
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 ….
Glad to help. If you need anything else, please don't hesitate to ask.
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?
Check out the original Excel and AutoCAD® post - that should help you :-)
hello will i have a few questions:
- how i add lines from a specific range
- after the lines are created in autocad, i want to inset in excel as a dwg object
- when the coordonates are changed, i want to regen automaticaly the dwg object
this is possible?
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
I believe you can drag and drop a DWG file into Excel to embed the file in the drawing - would this be suitable?
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).
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
Point 1 seems pretty good - though I don't think you need:
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.
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
charbel abou samra
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
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.
At first take my salute,
sir, i am very eager to learn VBA (excel to CAD) and i have some IDEA, Sir can i learn this.
Sir Please advised me
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)
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!)
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.
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!
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?
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
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!
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
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.
I decided to create a new post for you - it's here
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.
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.
I have the same problem. I need to automate hundreds of drawings using information from excel. The numbers (and words) need to be placed at various places (attributes ) on a template. I think it would be very similar to the wiring diagrams.
Could you please post the solution you had to the wiring diagram problem??
Please help me!!!!!!!!! I am a beginner at autoCAD and VBA!.
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
Yes, it is possible. Please see the email replied to you for more info.
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...
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
Are you putting the code in the VBA editor of Excel ? If you're putting it in the AutoCAD® one, Sheet1 doesn't exist!
Hey Will, first i wanna thank you for providing the code including comments, which are very useful especially for "vba-newbies". Unfortunately, the same error pops up if i am copying your code into my Excel VBA.(nº 424 and it needs and object. The line that appears in yellow is :”Coords(0) = Sheet1.Cells(n, 1) ‘Put the Column 1 value into the Coords array”) I would really appreciate if you could help me detecting my mistake! Many thanks in advance Flo
I am unable to control length of arc in my code. Please can you suggest me how to control it.
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
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.
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
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.
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?
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
It is only a flow diagram after all so no complex shapes to redraw :)
I would like to change the line type in Autocad from continuous to dashed from Excel. Your help is appreciated.
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 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!
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.
L ENTER -5,2 -4,2.5 -3,3 . . . . . YOU CAN DO IT SIMPLY BY USING EXCEL
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?
Try a "For" loop
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?
Not presently I'm afraid, but I will endeavor to cover that soon!
HOW CAN I IMPORT TEXT FROM EXCEL TO AUTOCAD AT SPECIFIED CO-ORDINATES..? ANY ONE PLS HELP ME..
You could try just copying and pasting the cells - there are various options for "pasting special" from the Edit menu.
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.
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.
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
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.
That is just brilliant! Thanks a ton for this Will. I have one requirement. I have around 150 tables in AutoCAD®. How do i scale all of them using Excel VBA. I just need to scale them by a factor of 1.5 so that the prints will be bigger. Also, can i record macros in autocad and tailor them for vba? I'd really appreciate your reply. Thanks
Hi Will, I am into Quantity Surveying (Civil, Architectiral, Electro-Mechanical). I've been trying to conceptualize an interface between AutoCAD® and MSExcel but its really a pain because I can't concentrate on doing some VBA codes while doing my Job at the same time. I am hopeful you could give me some codes and tricks which I can work on.
Minimum feature of the interface would be:
-After the length, area, pieces or anything is measured, its value will be copied (through an inerface button) to a current spreadsheet (just to minimize the time consumed in switching between AutoCAD® and Excel as well as the time consumed in manually typing or copying it.
Hi! I just saw this post. Very helpfull! I would like to know how would the code look like if it would be backwards. Export a polygons coordinates and and point ID to an excel file?
Hi Will I am working on sending data from an excel sheet into cad that will also bring extended data in text form. Basically what we need is a sphere or block in AutoCAD® with attributes, it needs to read the XYZ coordinates from a file and input the XYZ of that sphere in the drawing. It then also needs to be able to attach attributes which will mainly be TEXT to that sphere. We need code that will read the XYZ co-ordinates, input as a sphere and then also read associated data attached to each sphere so that when we click on them in cad all the data will appear for each sphere, I cant find anybody that can solve the problem,
Thanks for your help and great site
Hi Will, I'm using AutoCAD® 2013 and I'm new to all of this type of stuff in AutoCAD®. Hopefully you can help guide me. I have a scenario similar to a previous persons. I have a floor plan for a 16 room building in AutoCAD®. I have already individually hatched each room. How can I link the hatch to a specific room such as Living Room, Kitchen, ect.? This seems like the easiest way to do it since the hatch location won't be moving. I know you said something about setting this in the Xdata for the hatch? Not sure what that is or how you do it. Secondly I would like to make a simple Excel spreadsheet that would be used to change the color of the hatch. For example the A column might be room name like Living Room, Kitchen then B column would be a number like 10, 20, ect. to represent the percent completion of the room. I don't know how to get the hatch for the Kitchen to turn say blue when the B column is 10 then change to red when it is 20? If you know of a simpler way of going about what I'm trying to achieve I'm eager to learn. I feel by learning this it can help me a lot on future projects.
3d architectural visualization
Hmm is anyone else experiencing problems with the images on this blog loading? I'm trying to find out if its a problem on my end or if it's the blog.
Any feedback would be greatly appreciated.
Hi Will !
Firstly, let me Honor VBA codes you have shared on various subjects This is simply superb & phenomenal ! I run short of words while appreciating you. reference :- excel-and-autocad-–-a-match-made-in-heaven-again
But, sir, I have one query that, if text in a cell is to be transferred to AutoCAD®, and if that needs to be rotated by an angle; let us say by 90 degrees, how I can do it by writing a code in Excel VBA? (i.e. Macro)
Can I Request for your help, to resolve this problem?
Thanks in advance.
plz sir i want a vba code for drawing cross section and long section in auto cad from the availabe data in excel spreed sheet...........plz help i really need it
hi will one big doubt i want to set a variable named b a value 5 how can i set it thru excel vba in the autocad i mean lik wen i enter !A in the auto cad command prompt it must give me answer 5
i mean like this can be done in autocad directly by entering ( setq a 5 ) in autocad command prompt how can i do it thru excell vba
and i have a lisp file named test.lsp i want to load it in autocad and i have a command named test which will run the test.lsp but this is not the autocad default command , so how can i call a non autocad command thru excell vba ... plse help for ppl like my queries are peice of cake and thank you in advance for your reply and for creating this website
Pls I need an easy material to start learning VBA for AutoCAD®, pls can you recommend any, or better still can you share a link with me?? I have know in VB.Net and AutoCAD®, but I want to take it further to oftware customization and process automation.
Please I need your help! Cheers!!!
Sir I have drawn many objects in AutoCAD® using VBA Excel. But i dont know how to mark the dimensions of those objects using VBA. Could you please help me?.
I have one query "How to make Number of drawing (.dwg) files using one Auto cad Template in that Template i am going to insert some tags from Excel sheet.
Above Query explained in steps.
- First I am making auto cad template
- Then Making IO List in Excel sheet
- In Template i am defining Excel sheet Column HEADING so this heading work as source and taking tags from that column.
- for Each signal we get separate .dwg file.
Kindly guide me for the same. i have template and excel sheet kindly give me your mail ID. so we communicate.
Hello, I will like to know how to extract information of a dinamic block of Autocad and exported to excel. For example: If I have a rectangle that can change his length and width, I am wondering if I can get both values. Normally I have a diferent set of blocks in a drawing. So I finally will like to getting the number of blocks, block's names, the lenght and width. Not sure if you still post any comments in here, Please email me if is possible. thanks!
I have tried using your code form Excel, but I get an "ActiveX component cannot create object" at the line " Set Acad = GetObject(, "AutoCAD®®.Application") 'Get a running instance of the class AutoCAD®®.Application"
I have the reference "Acad 2014 Type Library" in the reference.
What in the world could be the problem? Below is the small bit of code, which is basically your code, that I am using.
Sub ACAD_Test() ' Dim cTest As CAcadObject ' '' Dim Test As AcadObject ' ' cTest = cTest.GetClass ' cTest.ConnectToACAD Dim Acad As AcadApplication 'Create ACAD variable of type AcadApplication Dim bConnected As Boolean Dim nLineNum As Integer On Error GoTo ErrHandler 'This tells VBA where to go Err.Clear 'Ensure the error object is clear nLineNum = 1 'Assume success bConnected = True nLineNum = 2 Set Acad = GetObject(, "AutoCAD®®.Application") 'Get a running instance of the class AutoCAD®®.Application nLineNum = 3 'If we need to launch this then do so nLineNum = 4 ' If (bLaunchIfNotRunning = True) Then ' nLineNum = 5 ' If Acad Is Nothing Then 'Check to see if the above worked ' nLineNum = 6 ' Set Acad = New AcadApplication 'Set the ACAD variable to equal a new instance of AutoCAD®® ' nLineNum = 7 ' Acad.Visible = True 'Once loaded, set AutoCAD®® to be visible ' End If ' Else ' nLineNum = 8 ' bConnected = False ' End If nLineNum = 9 If (Acad Is Nothing) Then 'Do some notification here ' VBA.Err.Raise 15 'Fill our error object ' LocalErr.Description ' LocalErr.Number Else 'This is to just ensure communication has occured 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 If GoTo ExitThis ErrHandler: 'Since the Err Object can be modified with another error, copy the current error for reporting Call U_ErrorHandler.ErrorHandler(nLineNum, "ACAD:ConnectToACAD", Err.Number, Err.Description, Err.Source) 'Report our error Resume Next ExitThis: nLineNum = 11 ' ConnectToACAD = bConnected ' Set ' ConnectToACAD End Sub
Upon further playing.....
If I add:
Dim Acad As AcadApplication 'Create ACAD variable of type AcadApplication --- Set Acad = New AcadApplication ---
I link to the current open autocad program. I can see 2 documents open in the debug window, which is what I have.
So now my question is why?
Are you missing a step, or am I missing something?
I ran down to your GetObject, just to see if it would cause an error and it did. So which is the correct way, and why does my modification work? As I understand it, I have NOT "connected" to this instance of acad so I should not be able to see what it has.
hey will your website is one of the most useful sites I've ever visited. I'm completely unaccustomed with visual basic and I want to load an excel file with includes some data and make the vba to read it as a matrix. Is it possible? if yes, how? thankfully
how to link excel cell with dimension ?? if object dimension change so excel cell value should change.. its possible ??
I do agree to the fact that writing a small 6 line code to save 20 man hours is a wise choice but my logic's are not in place and hence I am writing to you. One of my colleague use Autocad 2010 and wishes to map the man hours that he or she has put into one project in Excel. Is there anyway to compute this with the help of a script?
HI, how to handle acad dimension change event in VBA, if any object dimension changed in AutoCad i want to handle that event in excel VBA. please tell me how to do that?
I am trying to get excel to on activating a cell (A1) to make AutoCAD® the active program with ("DI" then enter key) into the command line allowing me to click two spots on my drawing and getting the dimension and putting that into the excel cell (A1) and then making excel the active program again. for example:
cell A1 is blank I click into cell A1 so it is active at which point AutoCAD® (already running in background) pops up and excel goes to background in AutoCAD®'s command line the command "DIST" (distance) is typed and enter is hit automatically. I then click two points on drawing AutoCAD® command line gives the distance between those points excel pops back up making AutoCAD® return to the background cell A1 now has the dimension from AutoCAD® in it allowing me to run calculations off that dim
Is there a way for excel to place a block in autocad?
or make excel insert an autocad drawing inside another autocad drawing.
read this this thread on your page thinking it would lead to creating keynotes in excel to then import into cad. Do you have a faster, more effective manner of achieving this task?
thank you very much!
good day sir,
i have query and I consider it as a challenge for me, its been long time searching thru internet a concrete solution and answer but till date i dint fine it, i hope you able to help me sir or anyone who's reading this, here my question: what is the VB code how to link excel cell to Cad text (normal Autocad), if the value of excel cell will change the Cad text (normal Autocad) will automatically update. i already solve it but Architectural/MEP/Map Autocad using the AEC Database Field and its very slow due to issue of .dsn connection.