AfraLISP - Learn AutoLISP for AutoCAD productivity

VBA Primer - Part 4

by Kenny Ramage

To populate our list box we need to first find a list of all the layers in our drawing. Double-click on the form (the form, not a control). The code window will open. From the Event Procedure drop-down list box in the right hand corner of the code window choose Initiliaze.

Initialize

Now add the following code to this event procedure :

Private Sub UserForm_Initialize()
Dim AllLayers As Object
Dim Layer As Object
'declare local variables
 
Set AllLayers = ThisDrawing.Layers
'get the layers from the layers collection
 
For Each Layer In AllLayers
'for every layer listed
 
    ListBox1.AddItem Layer.Name
    'add the layer name to the list box
    
    Next
    'carry on looping
    
End Sub 

A list of all the layers in any drawing are kept in the Layers collection. This coding is telling Visual Basic that when the form is initialized, get all of the layer names from the layers collection, and add them to the list box.

Run the program again. Your dialogue should now look like this :

Change Layer Dialogue

Now let's look at the coding for the OK button event procedure.

Double click the OK button and enter the following code under the click event procedure of the button :

Private Sub CommandButton1_Click()
 
Dim Entity As Object
'declare variable as local
 
Me.Hide
'hide the dialogue box
 
Set ss = ThisDrawing.SelectionSets.Add("NEWSS")
'create a selection set reference
 
ss.SelectOnScreen
'select the objects to change
 
For Each Entity In ss
'for every entity in the selection set
 
    Entity.Layer = ListBox1.Text
    'change the layer to the layer name
    'selected in the list box
    
Next
'process the next entity
 
End
'end the programme
 
End Sub

Now run the programme again. Select a layer from the list box and then select some objects on your drawing. They should change to your selected layer.

Well I hope this has given you a bit more of an idea what VBA is all about. The application is far from perfect. There is no error checking and the items in the list box have not been sorted. Maybe that is something that you could work on now that you have had a taste of VBA. Have a look at the other sample applications in this section. They cover large areas of VBA and all come complete with source coding. All the best and good luck with VBA…

If you would like to download this VBA Primer, stand on your head, say "Yes Please" in French, place your mouse here and Click. Enjoy…