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:
(vla-Item layerCollection "ABC")
ThisDrawing.Layers.Item("ABC")
ThisDrawing.Layers("ABC")
The following example iterates through a collection and displays the names of all layers in the collection:
(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)
)
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
The following example refers to layer named MyLayer, and issues a message if the layer does not exist:
(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.")
)
)
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