Using Move, Copy with AcadSelectionSet

Selection Sets in Autocad VBA do not contain methods to Move, Copy, Rotate, Scale, Mirror etc. The programmer has to make a For-Each loop to iterate through the Selection Set and apply the method to each individual entity one at a time. There are quite a few steps between making the selection set, populating it, then looping through its members and actually doing something to them. Breaking down these steps into small re-usable sub-procedures is the way to go.

Other than how to use them, Selection Sets have pretty good documentation not too hard to understand. The first sub-procedure makes a new clean Selection Set in the drawing. If it already exists it deletes it. Its called with a parameter name.

Sub addss(strname As String)
'adds a clean selection set
    Dim sset As AcadSelectionSet
    On Error Resume Next
    
    Set sset = acadDoc.SelectionSets.Item(strname)
    sset.Delete
    Set sset = acadDoc.SelectionSets.Add(strname)
    
    If sset Is Nothing Then
    MsgBox "unable to add " & strname & " selection set"
    End If
End Sub

In a recent program I made two kinds of selection, ALL and Window, so I made two function procedures to handle this task and return an AcadSelectionSet object. These functions call addss above. The way these work are documented and easily found with VBA ACADSelectionSets. Think of this as the second layer of abstraction, a function to make and return a set according to your selection method.

Function sset_all() As AcadSelectionSet
'returns a selection set ALL
    addss ("All_Entities")
    Set sset_all = acadDoc.SelectionSets.Item("All_Entities")
     sset_all.Select acSelectionSetAll
End Function

 Function sset_win(x1 As Double, y1 As Double, x2 As Double, y2 As Double) As AcadSelectionSet
 'returns a selection set with window selection
    Dim pt1(0 To 2) As Double
    Dim pt2(0 To 2) As Double
    
    Call initpt(pt1, x1, y1, 0)
    Call initpt(pt2, x2, y2, 0)
    
    'items not visible do not select
    acadApp.Update
    acadApp.ZoomAll

    addss ("Win_Entities")
    Set sset_win = acadDoc.SelectionSets.Item("Win_Entities")
    sset_win.Select acSelectionSetWindow, pt1, pt2
End Function

Sub initpt(ByRef ptn() As Double, val1 As Double, val2 As Double, val3 As Double)
ptn(0) = val1: ptn(1) = val2: ptn(2) = val3
End Sub

initpt is a little helper I made. You don’t need the ByRef keyword, I put it in there to remind that arrays always pass by reference. It would not work otherwise.

Now we have, when properly called, a selection set of our choosing. We want to make sub-procedures for MOVE, COPY, ROTATE, MIRROR and SCALE which accept a selection set as an argument and whatever other basic parameters required, such as a displacement for MOVE. This is the third level of abstraction. We are calling these methods with a selection set previously selected by whatever method.

Erase is the simplest case. it doesnt require a loop.

Sub erase_ss(sset As AcadSelectionSet)
    sset.Erase 'erases the autocad entities in the drawing
    sset.Delete 'deletes the selection set
    Set sset = Nothing
        'call by reference will set to nothing in calling program
End Sub

now finally here is the code to MOVE a selection set using a loop to go thru the set for each item. It takes the set itself as argument and the displacement in x and y. You can select items with either of the subs above by window or all or your program with Crossing or Filters. Deleting the selection set at the end of the routine is optional and may not always be desired, say if you wanted to move and rotate.

Sub move_ss(sset As AcadSelectionSet, x1 As Double, y1 As Double)
'x1 y1 is the displacement
    Dim objent As AcadEntity
    Dim pt0(0 To 2) As Double
    Dim pt1(0 To 2) As Double
    
    Call initpt(pt0, 0, 0, 0)
    Call initpt(pt1, x1, y1, 0)
    
    If 0 <> sset.Count Then
    For Each objent In sset
    objent.Move pt0, pt1
    Next
    End If

    sset.Delete 'deletes the selection set
    Set sset = Nothing
        'call by reference will set to nothing in calling program
End Sub

At this point these sub-procedures still do not change per program requirements. They are basic tools.
Here are mirror and scale (I have not needed COPY yet).

Sub mirror_ss(sset As AcadSelectionSet, pt1() As Double, pt2() As Double)
  'deletes old copy, pt1 pt2 are axis
    Dim objent As AcadEntity
    Dim objent_mirrored As AcadEntity

   If 0 <> sset.Count Then
    For Each objent In sset
    Set objent_mirrored = objent.Mirror(pt1, pt2)
    objent.Delete
    Next
  End If
         sset.Delete
    Set sset = Nothing
 End Sub
 
 Sub scale_ss(sset As AcadSelectionSet, x1 As Double, y1 As Double, sc As Integer)
'x1 y1 is the scale from point, sc is the scale factor
    Dim objent As AcadEntity
    Dim pt0(0 To 2) As Double
    Call initpt(pt0, x1, y1, 0)

    If 0 <> sset.Count Then
    For Each objent In sset
    objent.ScaleEntity pt0, sc
    Next
    End If
    
    acadApp.Update
    acadApp.ZoomAll

    sset.Delete 'deletes the selection set
    Set sset = Nothing
        'call by reference will set to nothing in calling program
End Sub

Now to some extent, we have hidden the loops, we don’t have to duplicate them, and we can call them with simple programs. Here are some upper level calling programs. You will need to write your own according to the method and selection you want to use.

Sub erase_all()
    Dim sset As AcadSelectionSet
    Set sset = sset_all
    Call erase_ss(sset)
End Sub

Sub move_all(x1 As Double, y1 As Double)
    Dim sset As AcadSelectionSet
    Set sset = sset_all
    Call move_ss(sset, x1, y1)
End Sub

Sub scale_w(x1 As Double, y1 As Double, x2 As Double, y2 As Double, sc As Integer)
 'scales from pt 0,0
    Dim sset As AcadSelectionSet
    Set sset = sset_win(x1, y1, x2, y2)
    Call scale_ss(sset, 0, 0, sc)
 End Sub

Sub mirror_all(pt1() As Double, pt2() As Double)
    Dim sset As AcadSelectionSet
    Set sset = sset_all
    Call mirror_ss(sset, pt1, pt2)
 End Sub

those get called rather simply by your top level, where you can see what you are doing without having to dive in to the details.

Call erase_all
Call move_all (0,20)
Call scale_w(-1, -1, 12, 9.5, sc)
Call mirror_all(vt1, vt4)

when you draw with xy data starting at the origin, this is how you move and position the piece onto your drawing assembly or border.

Advertisements

Excel VBA – > Autocad Basics

Microsoft “deprecated” VBA and then Autodesk made the VBA module not a part of their massive install, convincing just about everybody it was no longer a viable platform to write any code. I am not going to write code for other people if i have to go sit at their computer and download and install a 100 mb file and do it on every release of autocad. But two things happened. Microsoft recanted. There must be a million people worldwide who code VBA excel. And it was never necessary to download the VBA module for autocad to run VBA code anyway. The download is just the code editor. The VBA objects are there. The code editor in excel works fine and in fact better because excel can hold data such as parameters, bills of material and cut-lists. For a few years now I have been making it a point not to download the autocad VBA module just to make sure other people could run my programs without adding anything.

To begin writing your Autocad VBA code in excel – start excel. Most of the time you have to add the developer tab to the ribbon. That is done with the File tab, Options, Customize Ribbon. Add the Developer tab. Start the Visual Basic editor. When you save an excel file with visual basic code, save it with XLSM file extension. In the visual basic editor, important first step, you must add a reference for excel to see autocad programming objects. This is under Tools, References. Look for Autocad Type Library. Move it up in the list as high as it will go.

2018-01-28_2.jpg

now you need a standard module to connect to autocad. insert a module, add two public variables at the top.

Public acadApp As AcadApplication
Public acadDoc As AcadDocument

start your sub procedure by typing
sub connect_acad()
and hit return

generally you will want to start autocad yourself the way you always do. if autocad is running the vba code to obtain a reference to it is

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

notice we use our global variable. type this in to your sub procedure. I find this works fine but most online help shows it with a version dependent string like this.

Set acadApp = GetObject(, "AutoCAD.Application.22")
22 is the version that autocad is using to designate version 2018

to demystify this, what is GetObject, why is there a comma, where does this come from, open up the Object Browser. you can double click the word GetObject, right click, and pick Definition. if you dont find it that way, search the VBA library, top box, for GetObject –

The Object Browser shows its parent, VBA.Interaction and it shows the parameter list PathName comma Class. Right click on GetObject in the Object Browser and click Help to open MS online help.

2018-01-28_5.jpg

2018-01-28_3.jpg

If Autocad is not running, GetObject will return an error. The code to start autocad in VBA is CreateObject or New AcadApplication. They both work for me, just as the version independent and dependent string both seem to work equally well.

We need to handle the error, then deal with either autocad running or not. Autodesk has the logic and a file to do it here.

https://knowledge.autodesk.com/search-result/caas/CloudHelp/cloudhelp/2018/ENU/AutoCAD-ActiveX/files/GUID-73EC319D-9D7D-43FF-91B7-78CF36284028-htm.html

this file is also in the Autodesk AutoCAD 2018: ActiveX Developer’s Guide, or whatever year you have, which is file acad_aag.chm somewhere in your autocad installation. find that and also acadauto.chm and copy them where you want them.

First we have to add the essential statement
acadApp.Visible = True
otherwise we will not see any autocad.

Autodesk has the commands and logic but not the best form. We have to make some improvements. The code to start autocad needs to be in its own sub procedure with the code to reference the active drawing. We want to call connect_acad once and we want to obtain a global variable for the active drawing.

When autocad opens, it probably opens to a blank drawing, or maybe its already open to a drawing, but we have to get that drawing into a VBA object. Generally I want it to be a blank drawing because I am going to use it. The connect_acad sub procedure will not run until we want it to, so it just gets the activedocument which is a property of AcadApplication. Those are our two global variables, the application and the active drawing, and active drawing is the main one we use.

Put connect_acad in your module as a stand-alone. Anytime you want to write a program in excel vba to draw or interact with autocad, the first thing in the program is

call connect_acad

at that point you have a global variable AcadDoc that you use for all of autocad’s vba objects.

here is the full acad_connect

Option Explicit
 
 Public acadApp As AcadApplication
 Public acadDoc As AcadDocument
 
 
 Sub Connect_Acad()
    
    On Error Resume Next
        
    Set acadApp = Interaction.GetObject(, "AutoCAD.Application")
    'Set acadApp = Interaction.GetObject(, "AutoCAD.Application.22")
    'both statements above behave without any discernible difference
    
    If Err Then
        Debug.Print "ERROR " & Err.Number
        Debug.Print Err.Description
        Debug.Print "starting autocad"
                
        Err.Clear
                      
         Set acadApp = New AcadApplication
         'Set acadApp = Interaction.CreateObject("AutoCAD.Application.22")
         'both statements above behave without any discernible difference
        
        'essential statement
        acadApp.Visible = True
        
        If Err Then
             MsgBox Err.Description
             Exit Sub
        End If
    End If
    
    Debug.Print "Now running " + acadApp.Name + " version " + acadApp.Version
         
    Set acadDoc = acadApp.ActiveDocument
        If acadDoc Is Nothing Then
            Set acadDoc = acadApp.Documents.Add
        End If
  
    If acadDoc.ActiveSpace = 0 Then
       acadDoc.ActiveSpace = 1
    End If
   
End Sub

in bricscad, try these (i dont have bricscad loaded currently but these worked a couple releases back)

Set acadApp = GetObject(, "BricscadApp.AcadApplication")

Set acadApp = New AcadApplication

using autodesk’s example to draw a single line would be modified like this. I made no other changes except adding connect_acad

Sub testline()

Call Connect_Acad

Dim lineObj As AcadLine
Dim startPoint(0 To 2) As Double
Dim endPoint(0 To 2) As Double
startPoint(0) = 1
startPoint(1) = 1
startPoint(2) = 0
endPoint(0) = 5
endPoint(1) = 5
endPoint(2) = 0

Set lineObj = acadDoc.ModelSpace.AddLine(startPoint, endPoint)
ZoomAll

End Sub

Using this method, any code on autodesk help website that uses Thisdrawing.object can be run from excel by adding connect_acad at the top and replacing the word Thisdrawing with AcadDoc.