Creating a New Layer

You can create as many layers as needed using the criterion illustrated in Table 6-1. The Add method is used to create a Layer object and to add it to the Layers collection.

Set LayerObject = LayerCollection.Add(LayerName)

Table 6-1. The LayerName Property

Name

Data Type

Description

LayerName

String

The name for the new layer. If the parameter isn't a valid layer name, an exception will be raised. If you attempt to add a new layer with the same name as an existing layer, a reference to the existing Layer is returned.

The following example retrieves a layer name from the user and attempts to add it to the Layers collection:

Public Sub AddLayer()

Dim strLayerName As String Dim objLayer As AcadLayer strLayerName = InputBox("Name of Layer to add: ")

If "" = strLayerName Then Exit Sub ' exit if no name entered

On Error Resume Next ' handle exceptions inline

'check to see if layer already exists

Set objLayer = ThisDrawing.Layers(strLayerName)

If objLayer Is Nothing Then

Set objLayer = ThisDrawing.Layers.Add(strLayerName) If objLayer Is Nothing Then ' check if obj has been set MsgBox "Unable to Add '" & strLayerName & "'"

Else

MsgBox "Added Layer '" & objLayer.Name &

End If

Else

MsgBox "Layer already existed" End If End Sub

In normal programming situations, it's usually best to define entity- or object-creation routines as functions rather than subroutines. This way, you can return the object to other functions or subroutines, making it possible to further manipulate the new object outside the function that creates it.

When a layer is first created, its properties are set to certain default values. Figure 6-1 shows what you would see in the Layer Properties Manager dialog box when a new layer called Room Shell is added with the preceding code.

Figure 6-1. The Layer Properties Manager dialog box

Here you can see two layers. The first, layer 0, is created automatically by AutoCAD and may not be deleted or renamed. The second is the layer that was just created through code. The default attribute settings are shown.

We next examine how to change and retrieve the settings for some of these attributes and how to rename and delete a Layer object.

Was this article helpful?

+2 -1

Post a comment