You are on page 1of 9

30/5/2014 Draw A Polyline In AutoCAD Using Excel VBA ~ My Engineering World

http://www.myengineeringworld.net/2013/04/draw-polyline-in-autocad-using-excel-vba.html 1/9
Draw A Polyline In AutoCAD Using Excel VBA
Written by Christos Samaras on Friday, 5 April 2013 at 23:43

A friend of mine, who is surveying engineer, asked me recently if it is possible to draw a polyline in AutoCAD using
coordinates from an Excel file. He had a large Excel file with points coordinates (x, y) and he wanted to connect them
through a polyline in order to create a 2D profile. I manage to fulfill his request by using a lightweight polyline, which is a
2D line consisting of straight and arced segments.
I thought that the interaction between Excel and AutoCAD using VBA might be useful for all types of engineers who
using AutoCAD (especially civil and surveying engineers), so I decided to post the VBA code that I wrote here. Although
the example is quite simple I think that it illustrates the general idea about using VBA from Excel in order to draw
objects in AutoCAD.
VBA code
Option Explicit
Option Private Module
Sub DrawPolyline()
RSS Feed Twitter Google Plus
195 pessoas gostam disto. Gosto
My Engineering World
+ 44
Follow +1
Follow @MyEnginWorld 27 f ollowers
Your e-mail address... Submit
Professional Excel Development
Search this blog...
Top 10 Stories
Excel VBA Read And Write Text Files
VBA Macro To Open A PDF File
VBA Macro To Convert PDF Files Into Different Format
Draw A Polyline In AutoCAD Using Excel VBA
Welding Discontinuities X-ray Films
Descarga
Hofmann 9.1
albumdigital.com/Hofmann
Nova Verso. Totalmente Gratuito.
Cria o teu lbum Digital j hoje!
Free Download CAD,
ZWCAD+
zwsoft.com/cad
ACAD compatible, DWG 2D /3D
design. Zero learning cost, Free
download.
Tweet
3
2
4
11
Gosto
Home Blog Contents About Work With Me ERTAT Add-In Advertise Here Suggested Books Disclaimer
30/5/2014 Draw A Polyline In AutoCAD Using Excel VBA ~ My Engineering World
http://www.myengineeringworld.net/2013/04/draw-polyline-in-autocad-using-excel-vba.html 2/9
'Draws a polyline in AutoCAD using X and Y coordinates from sheet Coordinates.

'By Christos Samaras
'http://www.myengineeringworld.net

'In order to use the macro you must enable the AutoCAD library from VBA editor:
'Go to Tools -> References -> Autocad xxxx Type Library, where xxxx depends
'on your AutoCAD version (i.e. 2010, 2011, 2012, etc.) you have installed to your PC.

'Declaring the necessary variables.
Dim acadApp As AcadApplication
Dim acadDoc As AcadDocument
Dim LastRow As Long
Dim acadPol As AcadLWPolyline
Dim dblCoordinates() As Double
Dim i As Long
Dim j As Long
Dim k As Long

shCoordinates.Activate

'Find the last row.
With shCoordinates
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With

'Check if there are at least two points.
If LastRow < 3 Then
MsgBox "There not enough points to draw the polyline!", vbCritical, "Points Error
"
Exit Sub
End If

'Check if AutoCAD is open.
On Error Resume Next
Set acadApp = GetObject(, "AutoCAD.Application")
On Error GoTo 0

'If AutoCAD is not opened create a new instance and make it visible.
If acadApp Is Nothing Then
Set acadApp = New AcadApplication
acadApp.Visible = True
End If

'Check if there is an active drawing.
On Error Resume Next
Set acadDoc = acadApp.ActiveDocument
On Error GoTo 0

'No active drawing found. Create a new one.
If acadDoc Is Nothing Then
Set acadDoc = acadApp.Documents.Add
acadApp.Visible = True
End If

'Get the array size.
ReDim dblCoordinates(2 * (LastRow - 1) - 1)

'Pass the coordinates to array.
k = 0
For i = 2 To LastRow
For j = 1 To 2
dblCoordinates(k) = shCoordinates.Cells(i, j)
k = k + 1
Next j
Next i

'Draw the polyline either at model space or at paper space.
If acadDoc.ActiveSpace = acModelSpace Then
Set acadPol = acadDoc.ModelSpace.AddLightWeightPolyline(dblCoordinates)
Else
Set acadPol = acadDoc.PaperSpace.AddLightWeightPolyline(dblCoordinates)
End If
Numerical Integration In Excel Using The Trapezoidal
Rule
Open A Google Earth File (kmz) With Google Maps
Fatigue Analysis In Turbomachinery

Open A PDF File With VBA
30/5/2014 Draw A Polyline In AutoCAD Using Excel VBA ~ My Engineering World
http://www.myengineeringworld.net/2013/04/draw-polyline-in-autocad-using-excel-vba.html 3/9

'Leave the polyline open (the last point is not connected with the first point).
'Set the next line to true if you need to connect the last point with the first one.
acadPol.Closed = False
acadPol.Update

'Zooming in to the drawing area.
acadApp.ZoomExtents

'Inform the user that the polyline was created.
MsgBox "The polyline was successfully created!", vbInformation, "Finished"
End Sub
Code results
The short video below demonstrates the results of the above VBA code.
Note
If you try to use the above VBA code and get the following error "Compile error: User-defined type not defined" (see
figure below), the first thing you should do is to check if the AutoCAD reference in the VBA editor is enabled. So, go to
Tools => References => and enable Autocad xxxx Type Library, where xxxx depends on your AutoCAD version (i.e. 2010,
2011, 2012, etc.) you have installed to your computer.
If you have AutoCAD 2010 or newer, then you will need to download the VBA module from Autodesk since from 2010
version VBA is not installed with AutoCAD.
Download it from here
0:00 / 0:27
Draw A Polyline In AutoCAD Using Excel VBA
30/5/2014 Draw A Polyline In AutoCAD Using Excel VBA ~ My Engineering World
http://www.myengineeringworld.net/2013/04/draw-polyline-in-autocad-using-excel-vba.html 4/9
4
Newer Post Older Post
The above code was successfully tested in Excel and AutoCAD 2010. However, it should also work in other
Excel/AutoCAD versions.
Read also
Draw A 3D Polyline (Pipe-Like) In AutoCAD Using Excel & VBA
AutoCAD VBA Add-In: Calculate Polylines Length & Area
Drawing Circles In AutoCAD Using Excel & VBA
Add Text In AutoCAD Using Excel & VBA
Drawing Points In AutoCAD Using Excel & VBA
Did you like this post? If yes, then share it with your friends. Thank you!
11 Gosto Tweet 3 2
StumbleUpon
Categories: Office Tips
Christos Samaras
Mechanical Engineer (Ph.D. cand.), M.Sc. Cranfield University, Dipl.-Ing. Aristotle University, Thessaloniki - Greece.
Communication: tel. +30-6973513308, e-mail , Facebook , Twitter , Google+ and Linkedin. Full CV here.
Home
27 Comments My Engineering World Login
Sort by Newest Share
Join the discussion
Reply
a a 2 months ago
Hello, I have autocad 2013 and excel 2010, when I try to use your example (just draw a
polyline with numbers in file) i get this picture. I have install vba for ac2013.
Can you help? Thx.


Christos Samaras 2 months ago Admin a a
Hi,
If you read at the code comments it says:
'In order to use the macro you must enable the AutoCAD library from VBA editor:
'Go to Tools -> References -> Autocad xxxx Type Library, where xxxx depends
'on your AutoCAD version (i.e. 2010, 2011, 2012, etc.) you have installed to your
PC.
The workbook you downloaded has a reference to AutoCAD 2010 library since at
Favorite
Share
30/5/2014 Draw A Polyline In AutoCAD Using Excel VBA ~ My Engineering World
http://www.myengineeringworld.net/2013/04/draw-polyline-in-autocad-using-excel-vba.html 5/9
Reply
The workbook you downloaded has a reference to AutoCAD 2010 library since at
that time I have the 2010 version of AutoCAD installed on my (old) computer.
Use the above steps and add the correct reference in the VBA editor (AutoCAD
2013 type library in your case) and your problem will be solved.


Reply
glaudeslm 2 months ago
Christos! Needing help his friend. I'm using the worksheet Draw Polyline with multiple
coordinates that are calculated in other columns, so I created a macro to copy and
paste the coordinates in columns A, B for x, y. But the error of the images attached, and
I am unable to resolve this error. I sent the Bill to the copy routine, just like the one I am
working on attachment to your email. Can you help? Thank you!


Reply
Christos Samaras 2 months ago Admin glaudeslm
I think that the file that I sent you solves your problem... :-)

1
Reply
glaudeslm 2 months ago Christos Samaras
Ok Christos! I'm building an advanced spreadsheet for georeferencing,
and usirio come with hundreds of coordinates that are calculated and
then copied the macro to the columns A and B. How do not know the total
coordinate the user will enter the worksheet, my macro copy at least
some three thousand cells, so that error occurs.
When colulas A and B do not have enough coordinates, opens the box
informing the user. In my case, I would do the same action when
ocorrece this type of error.
Are you doing this?
Att,
Glaudes


Reply
Christos Samaras 2 months ago Admin glaudeslm
Check the coordinates before you copy them, or before draw the
polyline.
Two choices here:
If something goes wrong then stop the code and inform the user
to correct them manually or you can correct them by code, while
the user doesn't see anything.
It usually depends on the errors you are expecting to have.
In many cases I have done the latter (correct the input via code).


Need_help 3 months ago
I'm trying to do what little I know about VBA (EXCEL) - AUTOCAD ... But I'm having
trouble in a line of code:
Sub DrawPolyline()
'Draws a polyline in AutoCAD using X and Y coordinates from sheet Coordinates.
'By Christos Samaras
'http://www.myengineeringworld....
'In order to use the macro you must enable the AutoCAD library from VBA editor:
'Go to Tools -> References -> Autocad xxxx Type Library, where xxxx depends
'on your AutoCAD version (i.e. 2010, 2011, 2012, etc.) you have installed to your PC.
'Declaring the necessary variables.
Dim acadApp1 As AcadApplication
Share
Share
Share
Share
Share
30/5/2014 Draw A Polyline In AutoCAD Using Excel VBA ~ My Engineering World
http://www.myengineeringworld.net/2013/04/draw-polyline-in-autocad-using-excel-vba.html 6/9
Reply
see more
Dim acadApp1 As AcadApplication
Dim acadDoc1 As AcadDocument
Dim LastRow_Abs As Long
Dim i_Abs As Integer
Dim j_Abs As Integer


Reply
Christos Samaras 3 months ago Admin Need_help
The error is related with the number of arguments in AddLine method.
The start point and end point should be 3-element arrays, so you should first
change the next 3 lines (in variables declaration):
Dim startPoint1(0 To 2) As Double
Dim endPoint1(0 To 2) As Double
And then add these two lines:
startPoint1(2) = 0
endPoint1(2) = 0
Note that the line will appear in PaperSpace.
I hope this will help you solve your problem...


Reply
Need_help 3 months ago Christos Samaras
thanks. You are a genius. XD


Reply
Christos Samaras 3 months ago Admin Need_help
;-)


Reply
Need_help 3 months ago
Men ... I'm creating a "curve" using several straight polyline segments .. know how I can
create a line perpendicular to the start point and end point of each segment?
Each segment must allow perpendicular add the size I tell it and also lets me add text
perpendicular to each segment (the text must come from a column of the same Excel
file that you created - can be column C and in the same direction-orientation the
perpendicular segment created)
HELP ME PLEASE ... I NEED URGENT. THANKS AND I HOPE YOUR PROMPT
RESPONSE.


Reply
Christos Samaras 3 months ago Admin Need_help
The perpendicular line can be created with the above code by adjusting your
coordinates. If your first line has coordinates (0,0) and (100,0) then a
perpendicular line could have coordinates (100,0) and (100,100) for example..
For the text you will need other code, which involves the AddText method.
Within the month I will publish a post about this method.

1
Reply
Niven 4 months ago
I am trying to develop a macro to link excel to autocad drawings. In fact, 1 must produce
a simple 2d drawing through VBA excel coding. After trying your code, BA shows a
"complie error : Variable not defined" at "shCoordinates.Activate


Reply
Christos Samaras 4 months ago Admin Niven
Niven, shCoordinates is the codename of the sheet that contains the coordinates
in the sample workbook. You can change this to something like Sheet1.Activate
(if the codenmae of your sheet is Sheet1 of course), or to something like
Sheets("Sheet Name").Activate.
See also my answer below, at Myth's question.


Josh a year ago
Thanks Christos,
This was very helpful! I am currently using a similar code to draw closed
Share
Share
Share
Share
Share
Share
Share
Share
30/5/2014 Draw A Polyline In AutoCAD Using Excel VBA ~ My Engineering World
http://www.myengineeringworld.net/2013/04/draw-polyline-in-autocad-using-excel-vba.html 7/9
Reply
This was very helpful! I am currently using a similar code to draw closed
lightweightpolylines within AutoCAD (to form a closed boundary.. thus acadPol.Closed =
True), and would like to add a hatch as well, but for some reason my attempts to hatch
the boundary error out. If you have any suggestions on how to hatch the boundary, I'd
appreciate it.

1
Reply
Christos Samaras a year ago
see more
Admin Josh
Hi Josh,
The macro bellow loops through all the closed polylines of the current drawing
and adds a hatch inside the polyline area. You can adjust it to your own needs.
Sub HatchPolyline()
'Adds a hatch to all closed polylines of the current drawing.
'By Christos Samaras
'http://www.myengineeringworld....
Dim objEnt As AcadHatch
Dim entObj As Object
Dim i As Integer
Dim varOuter() As AcadEntity
With ThisDrawing.ModelSpace
For i = 0 To .Count - 1

1
Reply
Myth a year ago
For ALL who not familiar with Excel VBA tutorials: shVariables is a name of a main
working sheet of excel workspace =]
Sheets("shCoordinates").Activate - does the trick in 2010


Reply
Christos Samaras a year ago Admin Myth
Myth, generally speaking your suggestion is correct, but in the specific case is
wrong. Here the main sheet is named "Coordinates", so by using your
suggestion should be Sheets("Coordinates").Activate.
In the Excel object model a Worksheet has 2 different name properties:
Worksheet.Name (is the tab's name), here "Coordinates" and
Worksheet.CodeName (inside VBA editor), here "shCoordinates"
So, there are two possibilities to activate the particular sheet. You can use either:
Sheets("Coordinates").Activate or shCoordinates.activate. Both ways are
correct, BUT, if a user changes the "Coordinates" to "New Coordinates" the first
code will fail! This is the reason why I use the second code, which is user-
independent.


Reply
Myth a year ago Christos Samaras
Sorry, I used Excel 2010 and AutoCad 2011 =]
Without these changes code simply is not working:
shCoordinates.Activate -> Sheets("shCoordinates").Activate
with shCoordinates -> with ActiveSheet
shCoordinates.Cells(i, j) -> ActiveSheet.Cells(i, j)
---------------------------------------------------------------------------
I'm a programmer and I'm new to VBA and Excel, but this code works
and your's not on my machine =] so ... this comment is only for those
who has some trouble =]
P.S. thanks for the code! it really saved my time


Christos Samaras a year ago Admin Myth
Myth, can you please in your intermediate windows of VBA "run"
the following line:
debug.Print "VBA Name: "& Worksheets(1).CodeName &" VS
Sheet Name: "& worksheets(1).name
Share
Share
Share
Share
Share
30/5/2014 Draw A Polyline In AutoCAD Using Excel VBA ~ My Engineering World
http://www.myengineeringworld.net/2013/04/draw-polyline-in-autocad-using-excel-vba.html 8/9
Reply
And tell me what returns to you. In my case returns:
VBA Name: shCoordinates VS Sheet Name: Coordinates
I think that the problem might be caused by regional settings. Do
you have the English version of Excel 2010? Because I have seen
a similar problem with a Greek Version of Excel 2007.
See also this link:
http://msdn.microsoft.com/en-u...
Thanks in advance!
Christos


Reply
Myth a year ago Christos Samaras
in my current project first list is called "tables"
line output: VBA Name: 1 VS Sheet Name: tables
P.S. the strange output name stands for RUSSIAN equivalent for
List number 1.... yeap! i regret this but I am using RUS
localization of MS Office...


Reply
Christos Samaras a year ago Admin Myth
So, this was the problem and the code didn't work. In general I
write VBA code considering that the English version of Excel is
used. So, it seems that sometimes this is a problem...
Anyway, thanks for the info... ;-)


Reply
JakeJimenez a year ago
Hi Christos, very nice code. However, as a quantity surveyor, I would really appreciate it
more if you can post the reverse code of what you have posted. That is, in AutoCAD,
polyline (PL command) is used to measure length, area/volume and the code writes the
measurement to an open excel table, directly. Every after polyline drawn, an add-in
button will extract the measurement and paste it directly on to the open excel sheet. This
is the first scenario.Second scenario is, draw and name all the polylines using AutoCAD
(on a separate layer i think) then using an add-in button, all the measurement data will
be exported onto an open excel sheet or create one sheet if an excel sheet is not open.
(I use AutoCAD 2010 with VBA and Excel 2010 with VBA as well).Thanks


Reply
Christos Samaras a year ago Admin JakeJimenez
JakeJimenez, thank you very much for the interesting suggestions. I will
work on the two scenarios and I will create a post based on them. From a
quick thought I think that is feasible to be done...


Reply
Christos Samaras a year ago Admin Christos Samaras
JakeJimenez, your request up to a point was fulfilled. See this post:
http://www.myengineeringworld....


Reply
Christos Samaras a year ago
Hi,
There is no shVariables anywhere in the code. Were did you find that?
Did you rename anything from this code?
If you like post the code here or send me an email to check the file.
Kind Regards,
Christos


Reply
Anonymous a year ago
Hello, AutoCAD2012 and Excel 2010 give shVariables not defined error. Any ideas?
Thank you!


Share
Share
Share
Share
Share
Share
Share
Share
30/5/2014 Draw A Polyline In AutoCAD Using Excel VBA ~ My Engineering World
http://www.myengineeringworld.net/2013/04/draw-polyline-in-autocad-using-excel-vba.html 9/9
Copyright 2013 Christos Samaras Follow us on Facebook , Google+ & Twitter
Running Access Queries From Excel
Using VBA
4 comments 8 months ago
Christos Samaras Hi Ruddy,Since I don't
work with Access very often it didn't
happen to need something like
Retrieve USB Device Information (VBA
& WMI)
2 comments 5 months ago
Christos Samaras That was first think I
did. However, since the USB stick was
quite old and probably close to the
Workbook Index Add-In
2 comments 6 months ago
Christos Samaras Petros,ere are my
answers to your comments/questions.I
dont have
Delete Rows Based On ActiveCell's
Value (Excel COM Add-In)
2 comments 11 months ago
hhap I have a userform with five
textboxes to correct wrong data entries
(figures) in an excel sheet. Based on
ALSO ON MY ENGINEERING WORLD WHAT'S THIS?
Subscribe Add Disqus to your site

You might also like