VBA
Discuss AutoCAD ActiveX and VBA (Visual Basic for Applications) questions here.
cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

I got an error

1 REPLY 1
SOLVED
Reply
Message 1 of 2
Anonymous
1167 Views, 1 Reply

I got an error

I am trying to write code in Microsoft Excel VBA that controls Auto CAD. As a beginner in that subject, i started to just draw a line from visual basic in excel under Developer option

Unfortunately, i got an error message at the highlighted red color line

ACAD.ActiveDocument.ModelSpace.AddLine startPoint, endPoint

This is the code i am using

Sub access_Autocad()

Dim startPoint(0 To 2) As Double

Dim endPoint(0 To 2) As Double

Dim ACAD As AcadApplication  

Dim n As Integer  

For n = 1 To 10  

startPoint(0) = 1#

startPoint(1) = 1#

startPoint(2) = 0#

endPoint(0) = 5#

endPoint(1) = 5#

endPoint(2) = 0#

ACAD.ActiveDocument.ModelSpace.AddLine startPoint, endPoint

ZoomAll

Next

End Sub

 

1 REPLY 1
Message 2 of 2
norman.yuan
in reply to: Anonymous

The reason of the error is because your code does not initialize the variable ACAD to make it point to a running AutoCAD instance (your code runs inside Excel). That is, ACAD is Nothing. So, the code needs to try to find an existing running AutoCAD instance in the computer, and if not found, try to start AutoCAD. Only after a running AutoCAD instance is obtained, you can go ahead to do something with AutoCAD, in your case, draw lines.

 

The code would roughly look like:

 

Sub Access_AutoCAD()

 

  Dim ACAD As AutoCAD.Application

  Set ACAD=GetAutoCADInstance()

  If ACAD is Nothing Then Exit Sub

 

  ''Start to draw lines here

 

End Sub

 

Private Function GetAutoCADInstance() As AcadApplication

 

  On Error Resume Next

  Dim cad As AcadApplication

 

  Set cad=GetObject(, "AutoCAD.Application")

  If cad Is Nothing Then

    Set cad=CreateObject("AutoCAD.Application")

  End If

 

  Set GetAutoCADInstance=cad 

 

End Function

Norman Yuan

Drive CAD With Code

EESignature

Can't find what you're looking for? Ask the community or share your knowledge.

Post to forums  

AutoCAD Inside the Factory


Autodesk Design & Make Report