my friend Christos Samaras got me started on this.

this first routine is shamelessly cut and pasted from his site. he doesnt do it quite like this, and it is essential to have this routine in every project, so maybe i am forgiven for borrowing. Search his site for Autocad Excel. He has the basics covered how to start creating objects in autocad from excel VBA.

this routine has to exist in every excel project, it has to be called once. it uses a global AcadDocument variable that all other routines can use.

if you get an error on compile or run – “User-defined type not defined” – then you have not told Excel you want to use the Autocad Type library.  In the excel VBA programming interface, use the Tools References dialog and select Autocad 2015 Type Library, or whatever version you have installed. I go between 2015 and 2016 at home and work, and sometimes i have to uncheck this and re-check it. i have had odd errors that went away when i raised the priority on this library as high as it would go – the Priority arrows to the right of the list box where it is selected.

in an excel module, we have this –

Option Explicit
Public acadApp As AcadApplication
Public acadDoc As AcadDocument

'note this program for educational purpose only
'there is no guarantee for it to do anything.
'terry priest 9-9-2015

Sub connect_acad()
'Check if AutoCAD application is open. If is not opened create a new instance and make it visible.
On Error Resume Next
Set acadApp = GetObject(, "AutoCAD.Application")
If acadApp Is Nothing Then
Set acadApp = New AcadApplication
acadApp.Visible = True
End If

'Check (again) if there is an AutoCAD object.
If acadApp Is Nothing Then
MsgBox "Sorry, it was impossible to start AutoCAD!", vbCritical, "AutoCAD Error"
Exit Sub
End If
On Error GoTo 0

'If there is no active drawing create a new one.
On Error Resume Next
Set acadDoc = acadApp.ActiveDocument
If acadDoc Is Nothing Then
Set acadDoc = acadApp.Documents.Add
acadApp.Visible = True
End If
On Error GoTo 0

'Check if the active space is paper space and change it to model space.
If acadDoc.ActiveSpace = 0 Then
acadDoc.ActiveSpace = 1
End If
End Sub

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.