You are on page 1of 20

3/4/12 Excel and AutoCAD How to link Excel with AutoCAD using VBA

HowToAutoCAD.com

Home
Forum
Subscribe
Shop
About
Contact Me
Links
Privacy Policy
Subscribe

Ma h P ac ice - Age 5-15 www.IXL.com/Math F ee P og amming Co e code.he.net


A math website kids LOVE Win awards, Get started in minutes! Become a Software
certificates, have fun! Engineer

Cla 1 o Cla 12 www.MeritNation.com F ee 3D CAD fo A chi ec myArchicad.com/freeDownload


Free NCERT Solutions, Test Papers, Lessons, ArchiCAD 15 3D modeling tool for architects &
Animations, Videos, Puzzle interior designers!

E cel Vie e Componen www.anydraw.com Po e Ba ic Vi alBa ic www.powerbasic.com


Host excel, xlsx, xls in a web page or form. support Faster. No Run-Times. No Bloat! CGI, Macros, ASM,
automation, upload Reg Expressions

Do nload Pa o d Manage www.RoboForm.com/PasswordManagement


Lea n E cel Ba ic Online www.WallStreetPrep.com
Never Forget Your Passwords Again. Over 50 Step-by-Step Self Study Program $39 Intuitive, Drill
Million Downloads To Date! Based Crash Course

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.
howtoautocad.com/excel-and-autocad- -a-match-made-in-heaven-again/ 1/20
3/4/12 Excel and AutoCAD How to link Excel with AutoCAD using VBA
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.

S M ()
D ACAD A A A 'C ACAD A A
S ACAD = N A A 'S ACAD A CAD
ACAD.V =T 'O , A CAD
ACAD.A D .U .P "H E !" 'P A CAD
E S

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:

S M ()
D ACAD A A A 'C ACAD A A
S ACAD = G O (, "A CAD.A ") 'G A CAD.A
ACAD.A D .U .P "H E !" 'P A CAD
E S

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:

S M ()
D ACAD A A A 'C ACAD A A
O E R N 'T VBA
S ACAD = G O (, "A CAD.A ") 'G A CAD.A
O E G T 0 'T VBA NOT
I ACAD I N T 'C
S ACAD = N A A 'S ACAD A CAD
ACAD.V =T 'O , A CAD
E I
ACAD.A D .U .P "H E !" 'P A CAD
E S

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 8
7 8
5 5
2 3
3 1.6
4 1
5 1
6 1
7 1.6

howtoautocad.com/excel-and-autocad- -a-match-made-in-heaven-again/ 2/20


3/4/12 Excel and AutoCAD How to link Excel with AutoCAD using VBA
8 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!

S M ()
D ACAD A A A 'C ACAD A A
O E R N 'T VBA
S ACAD = G O (, "A CAD.A ") 'G A CAD.A
O E G T 0 'T VBA NOT
I ACAD I N T 'C
S ACAD = N A A 'S ACAD A CAD
ACAD.V =T 'O , A CAD
E I
ACAD.A D .U .P "H E !" 'P A CAD
D C (2) A D 'T
'T 0 - 2, X, Y Z
D A I 'C I
F = 1 T 10 'L , 1 10
C (0) = S 1.C ( , 1) 'P C 1 C
C (1) = S 1.C ( , 2) 'P C 2 C
ACAD.A D .M S .A P C 'A A CAD
N
E S

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

En e Yo Mail Add e

Be Sociable, Share!

Li e 0

{ 39 comments… read them below or add one }

Aprinto December 9, 2010 at 5:38 pm

Thanks Will,

howtoautocad.com/excel-and-autocad- -a-match-made-in-heaven-again/ 3/20


3/4/12 Excel and AutoCAD How to link Excel with AutoCAD using VBA
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

howtoautocad.com/excel-and-autocad- -a-match-made-in-heaven-again/ 4/20


3/4/12 Excel and AutoCAD How to link Excel with AutoCAD using VBA

‘ 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

howtoautocad.com/excel-and-autocad- -a-match-made-in-heaven-again/ 5/20


3/4/12 Excel and AutoCAD How to link Excel with AutoCAD using VBA
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

howtoautocad.com/excel-and-autocad- -a-match-made-in-heaven-again/ 6/20


3/4/12 Excel and AutoCAD How to link Excel with AutoCAD using VBA

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

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
howtoautocad.com/excel-and-autocad- -a-match-made-in-heaven-again/ 7/20
3/4/12 Excel and AutoCAD How to link Excel with AutoCAD using VBA
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#

howtoautocad.com/excel-and-autocad- -a-match-made-in-heaven-again/ 8/20


3/4/12 Excel and AutoCAD How to link Excel with AutoCAD using VBA
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

howtoautocad.com/excel-and-autocad- -a-match-made-in-heaven-again/ 9/20


3/4/12 Excel and AutoCAD How to link Excel with AutoCAD using VBA
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 )


howtoautocad.com/excel-and-autocad- -a-match-made-in-heaven-again/ 10/20
3/4/12 Excel and AutoCAD How to link Excel with AutoCAD using VBA
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

howtoautocad.com/excel-and-autocad- -a-match-made-in-heaven-again/ 11/20


3/4/12 Excel and AutoCAD How to link Excel with AutoCAD using VBA
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.”

howtoautocad.com/excel-and-autocad- -a-match-made-in-heaven-again/ 12/20


3/4/12 Excel and AutoCAD How to link Excel with AutoCAD using VBA
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.

howtoautocad.com/excel-and-autocad- -a-match-made-in-heaven-again/ 13/20


3/4/12 Excel and AutoCAD How to link Excel with AutoCAD using VBA
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

howtoautocad.com/excel-and-autocad- -a-match-made-in-heaven-again/ 14/20


3/4/12 Excel and AutoCAD How to link Excel with AutoCAD using VBA
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:
howtoautocad.com/excel-and-autocad- -a-match-made-in-heaven-again/ 15/20
3/4/12 Excel and AutoCAD How to link Excel with AutoCAD using VBA
(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
howtoautocad.com/excel-and-autocad- -a-match-made-in-heaven-again/ 16/20
3/4/12 Excel and AutoCAD How to link Excel with AutoCAD using VBA
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 ant 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.
howtoautocad.com/excel-and-autocad- -a-match-made-in-heaven-again/ 17/20
3/4/12 Excel and AutoCAD How to link Excel with AutoCAD using VBA
Thanks.

Reply

Leave a Comment

Name *

E-mail *

Website

S bmi

{ 1 trackback }

Excel and AutoCAD – A match made in heaven – Part 3 – Create rectangles in AutoCAD from Excel

Previous post: About To Regen

Next post: Common causes for AutoCAD freezing

Blogroll

AutoCAD 2010 Courses


AutoCAD 2011 Courses
AutoCAD 2012 Courses
AutoCAD Courses

Categories

AutoCAD Best Practice (13)


AutoCAD Commands (30)
AutoCAD Entities (6)
Bug Fixes (6)
Civil 3D (2)
Cool Stuff (2)
Courses and Training (4)
Customisation (16)
Downloads (2)
HowToAutoCAD News (3)
LISP (2)
Reviews (2)
Service Packs (1)
System Variables (7)
Tips and Tricks (56)
Tools (3)
Tutorials (10)
VB.Net for AutoCAD (13)

howtoautocad.com/excel-and-autocad- -a-match-made-in-heaven-again/ 18/20


3/4/12 Excel and AutoCAD How to link Excel with AutoCAD using VBA
VBA for AutoCAD (14)

Gene a ion of
So ce Code
.NET, Java, C++, XSD,
DDL, PHP, CORBA,
Python & more. Free
Trial!
www.sparxsystems.com

10 GB F ee File
S o age
Backup Files, Photos,
Music & More High
Security, Easy Sharing.
www.cx.com

F ee CAD T aining
Learn 2D technical
drafting Read now the
online course
www.cad-training-course.com

CRLDe ign .ne


CAD Services,
Computer Repair
WebSite Design,
Custom 3D Art
www.CRLDesigns.net

F ee Re ail POS
Sof a e
RayMedi Free Retail
Stores Software
Solutions for all
business needs.
www.gofrugal.com

Get Email Updates

Enter your Email address below to receive my latest posts:


S b c ibe

Archives

January 2012 (5)


December 2011 (2)
November 2011 (1)
October 2011 (7)
September 2011 (4)
August 2011 (1)
July 2011 (4)
June 2011 (6)
May 2011 (7)
April 2011 (2)
March 2011 (1)
February 2011 (5)
January 2011 (13)
December 2010 (11)
November 2010 (14)

Copyright 2012 HowToAutoCAD.com.


howtoautocad.com/excel-and-autocad- -a-match-made-in-heaven-again/ 19/20
3/4/12 Excel and AutoCAD How to link Excel with AutoCAD using VBA
Headquarters based in the United Kingdom.

howtoautocad.com/excel-and-autocad- -a-match-made-in-heaven-again/ 20/20

You might also like