Iterate through a Collection Object

AutoCAD ActiveX

 
Iterate through a Collection Object
 
 
 

To select a specific member of a Collection object, use the Item method. The Item method requires an identifier as either an index number specifying the location of the item within the collection or a string representing the name of the item.

The Item method is the default method for a collection. If you do not specify a method name when referring to a collection, Item is assumed. The following statements are equivalent:

ThisDrawing.Layers.Item("ABC")
ThisDrawing.Layers("ABC")
NoteDo not use the entity edit methods (Copy, Array, Mirror, and so forth) on any object while simultaneously iterating through a collection using the For Each mechanism. Either finish your iteration before you attempt to edit an object in the collection or create a temporary array and set it equal to the collection. Then you can iterate through the copied array and perform your edits.

Iteratethrough the Layers collection

The following example iterates through a collection and displays the names of all layers in the collection:

Sub Ch2_IterateLayer()
    ' Iterate through the collection
    On Error Resume Next
      
    Dim I As Integer
    Dim msg As String
    msg = ""
    For I = 0 To ThisDrawing.Layers.count - 1
        msg = msg + ThisDrawing.Layers.Item(I).Name + vbCrLf
    Next
    MsgBox msg
End Sub

Find the layer named MyLayer

The following example refers to layer named MyLayer, and issues a message if the layer does not exist:

Sub Ch2_FindLayer()
    ' Use the Item method to find a layer named MyLayer
    On Error Resume Next
      
    Dim ABCLayer As AcadLayer
    Set ABCLayer = ThisDrawing.Layers("MyLayer")
    If Err <> 0 Then
        MsgBox "The layer 'MyLayer' does not exist."
    End If
End Sub