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:
- AutoLISP
-
(vla-Item layerCollection "ABC")
- VBA (AutoCAD Only)
-
ThisDrawing.Layers.Item("ABC") ThisDrawing.Layers("ABC")
Note: Do 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.
Iterate through the Layers collection
The following example iterates through a collection and displays the names of all layers in the collection:
- AutoLISP
-
(vl-load-com) (defun c:Ch2_IterateLayer() (setq acadObj (vlax-get-acad-object) doc (vla-get-ActiveDocument acadObj) layerCollection (vla-get-Layers doc) msg "") (vlax-for item layerCollection (setq msg (strcat msg (vla-get-Name item) "\n")) ) (alert msg) )
- VBA (AutoCAD Only)
-
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:
- AutoLISP
-
(vl-load-com) (defun c:Ch2_FindLayer() (setq acadObj (vlax-get-acad-object) doc (vla-get-ActiveDocument acadObj) layerCollection (vla-get-Layers doc)) (setq ABCLayer (vl-catch-all-apply 'vla-Item (list layerCollection "MyLayer"))) (if (vl-catch-all-error-p ABCLayer) (alert "The layer 'MyLayer' does not exist.") ) )
- VBA (AutoCAD Only)
-
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