Welcome to my very first post.
This is the first post of a series of posts that I plan to complilate to show you how to control or send Commands to AutoCAD from Microsoft Visual Basic for Applications.
Software needed: Microsoft Excel and AutoCAD
STEP 1. Adding the developer tab to the toolbar excel.
Open excel then click FILE and select options.
This will open the window below. Select Customize Ribbon and then in customize the Ribbon tick the Developer option and click OK.
STEP 2. Opening Microsoft Visual basic for applications.
Click on the DEVELOPER tab and then click on Visual Basic, this will open the VBA Window. This space is where we will write the script or code to automate our tasks.
STEP 3. Adding AutoCAD library.
In order to send commands from VBA to AutoCAD we need to add the AutoCAD libray to the VBA references.
On the VBA window, click in References...
Scroll down until you find the AutoCAD Type Library, tick it and click OK.
STEP 4. Inserting a new module.
Modules help keep our script more organized. You can create as many modules as you need, for example, I have a spreadsheet that I use to generate structural drawings in AutoCad and also to print computations documentation. For that reason I created to modules to separate the tasks, I believe it helps me when I have to modify the code.
To insert the module click on the Insert tab and clink on Module. It add a space to work on similar to a note pad, This is where we will actually type our code.
STEP 4. The code.
In this example we will write two scripts, one to launch AutoCad and the second to open an existing file.
The script will look like this, you can simply copy and paste my code. If this is your first time writing a programming language I advise to do some readding about the language in order to understand it and get familiar with it.
Sub OpenAUTOCAD()
Dim ACAD As AcadApplication
On Error Resume Next
Set ACAD = GetObject(, "ACAD.Application")
If (Err <> 0) Then
Err.Clear
Set ACAD = CreateObject("autocad.Application")
If (Err <> 0) Then
MsgBox "Could Not Load AutoCAD!", vbExclamation
End
End If
End If
ACAD.Visible = True 'If you want to see AutoCAD on screen
If AcadFile.ActiveSpace = acModelSpace Then
End If
End Sub
Now to open an existing dwg file we must add a few lines to the code.
Sub OpenAUTOCAD()
Dim ACAD As AcadApplication
On Error Resume Next
Set ACAD = GetObject(, "ACAD.Application")
If (Err <> 0) Then
Err.Clear
Set ACAD = CreateObject("autocad.Application")
If (Err <> 0) Then
MsgBox "Could Not Load AutoCAD!", vbExclamation
End
End If
End If
ACAD.Visible = True 'If you want to see AutoCAD on screen
dwgName = "C:\Users\User\Desktop\SAMPLE1"
bReadOnly = True
Set AcadFile = ACAD.Documents.Open(dwgName, bReadOnly)
If AcadFile.ActiveSpace = acModelSpace Then
End If
End Sub
In my next post I will show you how to actually place objects in Autocad from VBA
I hope that this post was helpful, thanks for reading.
Rosangela
Comments