Upload
divyadristi
View
1.124
Download
19
Tags:
Embed Size (px)
DESCRIPTION
Link Excel and Autocad for beginners
Citation preview
3/4/12 Excel and AutoCAD How to link Excel with AutoCAD using VBA
1/20howtoautocad.com/excel-and-autocad--a-match-made-in-heaven-again/
HowToAutoCAD.com
Home
ForumSubscribe
Shop
AboutContact Me
Links
Privacy PolicySubscribe
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, Illput this to you now I cringe at the thought of having to do things manually. Often (and yes, I mean often), Ill 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 isntas hard as it looks.
Today Im going to explain how you can write code in Microsoft Excel VBA that controls AutoCAD. Firstly, lets get VBA open in
Microsoft Excel. With Excel open, press Alt+F11, which should open the VBA IDE (integrated development environment). If this doesnt
work, you can open this by going Tools>Macro>Visual Basic Editor. If youre 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 were 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 youre feeling adventurous you can rename the
module to whatever you like. Double click the module to edit it.
Now lets see if we can get AutoCAD to do something.
If youve 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 extratypes that werent available before.
MaWh PUacWice - AgeV 5-15 www.IXL.com/MathA math website kids LOVE Win awards,certificates, have fun!
ClaVV 1 Wo ClaVV 12 www.MeritNation.comFree NCERT Solutions, Test Papers, Lessons,Animations, Videos, Puzzle
E[cel VieZeU ComponenW www.anydraw.comHost excel, xlsx, xls in a web page or form. supportautomation, upload
DoZnload PaVVZoUd ManageU www.RoboForm.com/PasswordManagementNever Forget Your Passwords Again. Over 50Million Downloads To Date!
FUee PUogUamming CoXUVeV code.he.netGet started in minutes! Become a SoftwareEngineer
FUee 3D CAD foU AUchiWecW myArchicad.com/freeDownloadArchiCAD 15 3D modeling tool for architects &interior designers!
PoZeUBaVic YV ViVXalBaVic www.powerbasic.comFaster. No Run-Times. No Bloat! CGI, Macros, ASM,Reg Expressions
LeaUn E[cel BaVicV Online www.WallStreetPrep.comStep-by-Step Self Study Program $39 Intuitive, DrillBased Crash Course
3/4/12 Excel and AutoCAD How to link Excel with AutoCAD using VBA
2/20howtoautocad.com/excel-and-autocad--a-match-made-in-heaven-again/
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.
SXE MDLQ() DLP ACAD AV AFDGASSOLFDWLRQ 'CUHDWH ACAD YDULDEOH RI W\SH AFDGASSOLFDWLRQ SHW ACAD = NHZ AFDGASSOLFDWLRQ 'SHW WKH ACAD YDULDEOH WR HTXDO D QHZ LQVWDQFH RI AXWRCAD ACAD.VLVLEOH = TUXH 'OQFH ORDGHG, VHW AXWRCAD WR EH YLVLEOH ACAD.AFWLYHDRFXPHQW.UWLOLW\.PURPSW "HHOOR IURP E[FHO!" 'PULQW D PHVVDJH WR WKH AXWRCAD FRPPDQG OLQHEQG SXE
Here weve 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 were 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:
SXE MDLQ() DLP ACAD AV AFDGASSOLFDWLRQ 'CUHDWH ACAD YDULDEOH RI W\SH AFDGASSOLFDWLRQ SHW ACAD = GHWOEMHFW(, "AXWRCAD.ASSOLFDWLRQ") 'GHW D UXQQLQJ LQVWDQFH RI WKH FODVV AXWRCAD.ASSOLFDWLRQ ACAD.AFWLYHDRFXPHQW.UWLOLW\.PURPSW "HHOOR IURP E[FHO!" 'PULQW D PHVVDJH WR WKH AXWRCAD FRPPDQG OLQHEQG SXE
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 heres one way this could be dealt with:
SXE MDLQ() DLP ACAD AV AFDGASSOLFDWLRQ 'CUHDWH ACAD YDULDEOH RI W\SH AFDGASSOLFDWLRQ OQ EUURU RHVXPH NH[W 'TKLV WHOOV VBA WR LJQRUH HUURUV SHW ACAD = GHWOEMHFW(, "AXWRCAD.ASSOLFDWLRQ") 'GHW D UXQQLQJ LQVWDQFH RI WKH FODVV AXWRCAD.ASSOLFDWLRQ OQ EUURU GRTR 0 'TKLV WHOOV VBA WR JR EDFN WR NOT LJQRULQJ HUURUV II ACAD IV NRWKLQJ TKHQ 'CKHFN WR VHH LI WKH DERYH ZRUNHG SHW ACAD = NHZ AFDGASSOLFDWLRQ 'SHW WKH ACAD YDULDEOH WR HTXDO D QHZ LQVWDQFH RI AXWRCAD ACAD.VLVLEOH = TUXH 'OQFH ORDGHG, VHW AXWRCAD WR EH YLVLEOH EQG II ACAD.AFWLYHDRFXPHQW.UWLOLW\.PURPSW "HHOOR IURP E[FHO!" 'PULQW D PHVVDJH WR WKH AXWRCAD FRPPDQG OLQHEQG SXE
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 were done ignoring errors. At first glance you might think that its 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 itwas 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 were getting there.
Lets actually do something useful now. Go to Excel Sheet1, and fill columns A and B with some coordinates, X being in column A, and Y
being in column B. Here is some data you can copy/paste if you like, though you may need to copy and paste the columns seperately:
3
7
5
2
3
45
6
7
8
8
5
3
1.6
11
1
1.6
3/4/12 Excel and AutoCAD How to link Excel with AutoCAD using VBA
3/20howtoautocad.com/excel-and-autocad--a-match-made-in-heaven-again/
LiNe 0
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 were 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 youll end up with a nice smiley face drawn in points!
SXE MDLQ() DLP ACAD AV AFDGASSOLFDWLRQ 'CUHDWH ACAD YDULDEOH RI W\SH AFDGASSOLFDWLRQ OQ EUURU RHVXPH NH[W 'TKLV WHOOV VBA WR LJQRUH HUURUV SHW ACAD = GHWOEMHFW(, "AXWRCAD.ASSOLFDWLRQ") 'GHW D UXQQLQJ LQVWDQFH RI WKH FODVV AXWRCAD.ASSOLFDWLRQ OQ EUURU GRTR 0 'TKLV WHOOV VBA WR JR EDFN WR NOT LJQRULQJ HUURUV II ACAD IV NRWKLQJ TKHQ 'CKHFN WR VHH LI WKH DERYH ZRUNHG SHW ACAD = NHZ AFDGASSOLFDWLRQ 'SHW WKH ACAD YDULDEOH WR HTXDO D QHZ LQVWDQFH RI AXWRCAD ACAD.VLVLEOH = TUXH 'OQFH ORDGHG, VHW AXWRCAD WR EH YLVLEOH EQG II ACAD.AFWLYHDRFXPHQW.UWLOLW\.PURPSW "HHOOR IURP E[FHO!" 'PULQW D PHVVDJH WR WKH AXWRCAD FRPPDQG OLQH DLP CRRUGV(2) AV DRXEOH 'TKLV LV DQ DUUD\ RI GRXEOH SUHFLVLRQ IORDWLQJ SRLQW QXPEHUV ' TKH DUUD\ JRHV IURP 0 - 2, ZKLFK ZLOO FRQWDLQ RXU FRRUGLQDWHV X, Y DQG Z DLP Q AV IQWHJHU 'CUHDWH WKH YDULDEOH Q DV WKH W\SH IQWHJHU FRU Q = 1 TR 10 'LRRS WKLV FRGH, LQFUHPHQWLQJ WKH YDOXH RI Q IURP 1 WR 10 CRRUGV(0) = SKHHW1.CHOOV(Q, 1) 'PXW WKH CROXPQ 1 YDOXH LQWR WKH CRRUGV DUUD\ CRRUGV(1) = SKHHW1.CHOOV(Q, 2) 'PXW WKH CROXPQ 2 YDOXH LQWR WKH CRRUGV DUUD\ ACAD.AFWLYHDRFXPHQW.MRGHOSSDFH.AGGPRLQW CRRUGV 'AGG D SRLQW LQ AXWRCAD DW WKLV ORFDWLRQ NH[WEQG SXE
So there we have it an introduction to using VBA in Excel to control AutoCAD. Obviously what we have done here only scratches thesurface of the capabilities, but Ill leave you to get creative with the that for now at least.
As with all my posts Id finally like to encourage you to subscribe to my blog. Im always going to be adding new content on here, and Ill
always try to explain everything the best I can. Also, Ill 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
Be Sociable, Share!
{ 39 comments read them below or add one }
Aprinto December 9, 2010 at 5:38 pm
Thanks Will,
EnWeU YoXU Mail AddUeVV
.
3/4/12 Excel and AutoCAD How to link Excel with AutoCAD using VBA
4/20howtoautocad.com/excel-and-autocad--a-match-made-in-heaven-again/
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 RangeSet 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 + 1ReDim 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
3/4/12 Excel and AutoCAD How to link Excel with AutoCAD using VBA
5/20howtoautocad.com/excel-and-autocad--a-match-made-in-heaven-again/
If hatch position is same with Koordinat then change color relevant to its value.
But how? I still dont 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. Ive 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 Ive 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) ThenTargetPoint(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
3/4/12 Excel and AutoCAD How to link Excel with AutoCAD using VBA
6/20howtoautocad.com/excel-and-autocad--a-match-made-in-heaven-again/
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 Varianth.GetBoundingBox minPnt, maxPnt
pnt(0) = (minPnt(0) + maxPnt(0)) / 2pnt(1) = (minPnt(1) + maxPnt(1)) / 2
GetHatchGripPosition = pntEnd 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
3/4/12 Excel and AutoCAD How to link Excel with AutoCAD using VBA
7/20howtoautocad.com/excel-and-autocad--a-match-made-in-heaven-again/
Aprinto December 12, 2010 at 5:51 pm
Sorry, WillMy problem solved.
Based on your GetHatchGripPosition function, I try to adopt to write function finding to a txt file.
Sub FindHatch()
Dim Acad As AcadApplicationSet Acad = GetObject(, AutoCAD.Application)Dim ent As AcadEntity
Dim h As AcadHatchDim pnt(2) As Double
Dim minPnt As VariantDim maxPnt As Variant
Open d:\Hatch2.txt For Append Access Write As #10Write #10, Hatch CoordinatesFor Each ent In Acad.ActiveDocument.ModelSpace
If TypeOf ent Is AcadHatch ThenSet h = ent
h.GetBoundingBox minPnt, maxPntpnt(0) = (minPnt(0) + maxPnt(0)) / 2
pnt(1) = (minPnt(1) + maxPnt(1)) / 2Write #10, pnt(0) & ; & pnt(1)
End IfNext
Close #10MsgBox 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 dont hesitate to ask.
Will
Reply
ion March 2, 2011 at 8:30 am
hello willi have a few questions:
1. how i add lines from a specific range2. 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
3/4/12 Excel and AutoCAD How to link Excel with AutoCAD using VBA
8/20howtoautocad.com/excel-and-autocad--a-match-made-in-heaven-again/
Reply
Will March 3, 2011 at 8:43 am
Hello ion,
1. Im 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 arange you could use:
Dim r As Range
Dim c As RangeSet r = Range(A1:d2)
For Each c In rc loops through the cells in the range
MsgBox c.ValueNext
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 Im 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 AcadApplicationSet ACAD = New AcadApplication Set the ACAD variable to equal a new instance of AutoCAD
ACAD.Visible = True Once loaded, set AutoCAD to be visibleDim adoc As AcadDocument
Set adoc = ACAD.ActiveDocumentDim aspace As AcadBlock
Dim oLine As AcadLineSet aspace = adoc.ActiveLayout.Block
Dim startPt(0 To 2) As DoubleDim 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#
3/4/12 Excel and AutoCAD How to link Excel with AutoCAD using VBA
9/20howtoautocad.com/excel-and-autocad--a-match-made-in-heaven-again/
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 dont know i want to beak the conection beetwin vba and autocadSet AcadApplication = Nothing
End Sub
Point 2:Insert in excel dwg objectSub Insert_Desen_Ca_Fisier_Click()
Dim objNewDWG As ObjectDim DWGToOpen As String
On Error Resume NextDWGToOpen = Application.GetOpenFilename(All Files,*.dwg, Title:=Insert Fisier)
If DWGToOpen False ThenActiveSheet.OLEObjects.Add Filename:=DWGToOpen, Link:=True
Setting The Opened Picture Into A Cell RangeSet objNewDWG = InsertDWGInRange(DWGToOpen, Range(i20:l26))
End IfEnd SubFunction InsertDWGInRange(DWGFileName As String, TargetCells As Range) As Object
inserts a picture and resizes it to fit the TargetCells rangeDim p As Object, t As Double, l As Double, w As Double, h As Double
If TypeName(ActiveSheet) Worksheet Then Exit FunctionIf Dir(DWGFileName) = Then Exit Function
import DWGSet p = ActiveSheet.OLEObjects
determine positionsWith TargetCells
t = .Topl = .Left
w = .Offset(0, .Columns.Count).Left .Lefth = .Offset(.Rows.Count, 0).Top .Top
End With position pictureWith p
.Top = t
.Left = l
.Width = w
.Height = h
End WithSet InsertDWGInRange = p
Set p = NothingEnd 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 dont think you need:
ACAD.ApplicationExit filesave:=True
3/4/12 Excel and AutoCAD How to link Excel with AutoCAD using VBA
10/20howtoautocad.com/excel-and-autocad--a-match-made-in-heaven-again/
There is no real link to AutoCAD as such, all youve done is created a reference to the AutoCAD object in the variableACAD. Set ACAD = Nothing will remove the reference.
For points 2 & 3, can you tell me how you would achieve this manually? Im 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 produceanother 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, im a beginner and i know how to import points from excel to Autocad but i would like further toknow 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 toachieve 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 didnt get too complicated too fast. I
have now successfully been drawing 3D models in AutoCAD through Excels VBA. Question I am trying to insert text into differentplanes (XY,XZ, and YZ). My workaround has been to have the user manually switch plane views and then run separate macros foreach 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 DoubleDim Width As Double
Dim Text As String
InsertionPoint(0) = Sheets(Structural Model Input).Range(AB5)
3/4/12 Excel and AutoCAD How to link Excel with AutoCAD using VBA
11/20howtoautocad.com/excel-and-autocad--a-match-made-in-heaven-again/
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, Im not sure off the top of my head I will look it up asap. However, another approachcould be to rotate the text after youve created it (programmatically of course!)
Reply
RochaPinto April 4, 2011 at 10:36 am
Hello everyone,
Im having a problem writing information on an excel file. I already know how to read/write the information i want from/to the cells iwant. I just cant 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 doesnt write the information in it. It also creates another file called Book1, which i have to save manually, where it writesthe information.
Option Explicit
Dim comp As DoubleDim largura As Double
Dim area As DoubleDim referencia As String
Private Sub CommandButton1_Click()
textbox 1 and 2 recieve values for algebric operations
comp = TextBox1.Valuelargura = TextBox2.Value
area = comp * larguratextbox3 recieves a string with the name of the file where i want the information to be stored
referencia = TextBox3.Value
Dim oExcel As Excel.ApplicationDim wrkb As Excel.Workbooks
Dim wrks1 As Excel.WorksheetSet 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
3/4/12 Excel and AutoCAD How to link Excel with AutoCAD using VBA
12/20howtoautocad.com/excel-and-autocad--a-match-made-in-heaven-again/
Set wrkb = oExcel.Workbooks.AddSet wrks1 = oExcel.ActiveSheet
Set wrks1 = oExcel.ActiveWorkbook.Sheets(wrks1)
Code below adds column names
wrks1.Range(A1) = COMPRIMENTOwrks1.Range(B1) = LARGURAwrks1.Range(C1) = AREA
Fill the columns with block data from modelspace
wrks1.Range(A & 2) = compwrks1.Range(B & 2) = largurawrks1.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, im using AutoCad 2009.
Thank you
Reply
Will April 4, 2011 at 12:13 pm
Hi there,
At a glance, Im not sure youre creating a link to Excel correctly using GetObject and CreateObject. I think you needsomething like:
Check if Excel is open and if not open it.Set oExcel = GetObject(, Excel.Application)If Err.Number > 0 ThenSet 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, butwhen 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 beencorrupted and that the file extension matches the format of the file.
3/4/12 Excel and AutoCAD How to link Excel with AutoCAD using VBA
13/20howtoautocad.com/excel-and-autocad--a-match-made-in-heaven-again/
It still asks me to save Book1 mannually (with the information it was suposed to save in the yuyu.xlsx)
Any idea? Dont 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 pointsobtained 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 youll need to apply your own logic to ensure that you account for yourown formatting etc. To be able to help with a specific example Ill need you to send me an example for me to work with feelfree 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 toembrace change. We currently use pen and paper to make notes and the surveyors data input to excel back in the office onto ourserver database. manual calculations are them made and new data entered to an excel sheet( the sheets auto calculate a number ofitems 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 ontoandroid pc/phones and the surveyors can input and upload info to the database from site. I would like to take this height and widthinfo and either draw a number of rectangles that all have a defined height and width, are spaced appropriately in the x plane and arepositioned in the y plane based on excel data ( rectangle lower start point, y reference = column value), or (in a perfect world!) usethem 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 notsure wheter to do this in excel alone or in conjunction with autocad. I have no programming experience but can follow instructionsand 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 issomething 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.
3/4/12 Excel and AutoCAD How to link Excel with AutoCAD using VBA
14/20howtoautocad.com/excel-and-autocad--a-match-made-in-heaven-again/
However often the stumbling blocks come in when we start using phrases like spaced appropriately this needs to beexplicitly defined really, for example, spaced with 1m gaps.
Assuming you have all the information required, it can be automated. Ill quickly write an example of drawing some rectanglesfor 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 its 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 makethe 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 inAutoCad.I wanted to reference indvidual Autocad blocks to excel cells expecting Autocad to pick values automatically. Once Iimport 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 thesame 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 Id need to see an example of anactual file youre working with, and what you want to end up with. Feel free to forward this on and Ill 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 drawingssimilar to the attachment.
Thanks & Regards
Loganath
3/4/12 Excel and AutoCAD How to link Excel with AutoCAD using VBA
15/20howtoautocad.com/excel-and-autocad--a-match-made-in-heaven-again/
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 shapesI 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 doesnt 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 arrayHow 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 youre putting it in the AutoCAD one, Sheet1 doesnt 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.
Im afraid working out the length is going to involve some maths, but dont worry its 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 aportion of the circumference, namely:
3/4/12 Excel and AutoCAD How to link Excel with AutoCAD using VBA
16/20howtoautocad.com/excel-and-autocad--a-match-made-in-heaven-again/
(endAngle startAngle) / 360
Thats 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 theircolor, line type and all.
Reply
Will November 14, 2011 at 8:28 am
Ill start by answering the second part of your question. To change the properties of entities youve added, youwill need to do something like this:
Dim myPoint
myPoint = ACAD.ActiveDocument.ModelSpace.AddPoint CoordsmyPoint.Color = 10
The AddPoint method does something called returning a value from the method. This return value is actually areference to the entity we just created, which is precisely what you need.
As for the first, youll 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 Ive read it I think it could point me in the right direction of curing one of myproblems.I am an AutoCAD user (not brilliant but basic) and I am a VBA fettler (again not the worlds best) but never connected the two sothanks for showing me the light there.
Further Im 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. Ihavent 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
3/4/12 Excel and AutoCAD How to link Excel with AutoCAD using VBA
17/20howtoautocad.com/excel-and-autocad--a-match-made-in-heaven-again/
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 dont think this will be easy. But, the way Id start is by finding a way to identify what a shape is inAutoCAD. If its a polyline or something, and youre only selecting 1 polyline per shape, then that makes it easier. Onceyouve 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 Im not sure what that would be, but youd need to convertpolyline.coordinates to whatever the shape equivalent is in Excel. There may even be some scaling involved to get stuff to showup right etc.. sounds like a lot of hassle really if Im honest.
Id try to avoid conversion if possible unless you actually Zant the end result to be in Excel. If not, it will be far easier to dowhat you need doing natively in AutoCAD. So when you get to the point of having identified your shapes, you can thenmanipulate 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 Ive sort of fettled it now. I can export AutoCAD in DXF and I now decode DXF in excel andredraw 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 cant use the filloption. I have a plant information system and excel on all machines and not only would it be tricky to get the plant info in toAutoCAD we only have one PC with AutoCAD on so Im 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.
3/4/12 Excel and AutoCAD How to link Excel with AutoCAD using VBA
18/20howtoautocad.com/excel-and-autocad--a-match-made-in-heaven-again/
Thanks.
Reply
Leave a Comment
Name *
E-mail *
Website
SXbmiW
{ 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 CoursesAutoCAD 2011 Courses
AutoCAD 2012 CoursesAutoCAD 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)
3/4/12 Excel and AutoCAD How to link Excel with AutoCAD using VBA
19/20howtoautocad.com/excel-and-autocad--a-match-made-in-heaven-again/
VBA for AutoCAD (14)
Get Email Updates
Enter your Email address below to receive my latest posts:
SXbVcUibe
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.
GeneUaWion ofSoXUce Code.NET, Java, C++, XSD,DDL, PHP, CORBA,Python & more. FreeTrial!www.sparxsystems.com
10 GB FUee FileSWoUageBackup Files, Photos,Music & More HighSecurity, Easy Sharing.www.cx.com
FUee CAD TUainingLearn 2D technicaldrafting Read now theonline coursewww.cad-training-course.com
CRLDeVignV.neWCAD Services,Computer RepairWebSite Design,Custom 3D Artwww.CRLDesigns.net
FUee ReWail POSSofWZaUeRayMedi Free RetailStores SoftwareSolutions for allbusiness needs.www.gofrugal.com
3/4/12 Excel and AutoCAD How to link Excel with AutoCAD using VBA
20/20howtoautocad.com/excel-and-autocad--a-match-made-in-heaven-again/
Headquarters based in the United Kingdom.