How do I select objects in an AutoCAD script?


Any command that asks "Select objects:" (ERASE, MOVE, CHPROP, SCALE, and many more) needs a selection, and a script cannot click. Instead, the script types a selection option, gives any points it needs as coordinates, and then sends a blank line to say "done selecting".

Selection options that work in scripts

TypeSelects
ALLEvery object on thawed layers in the current space.
W + 2 cornersWindow: objects completely inside the box.
C + 2 cornersCrossing: objects inside or touching the box.
F + pointsFence: objects the line touches. End the points with a blank line.
WP / CP + pointsWindow or crossing polygon.
LLast: the most recently created visible object.
PPrevious: the objects selected by the previous command.

To see the full list in your version, start ERASE and type ? at the "Select objects:" prompt.

Example: erase everything in one corner of every drawing

ZOOM
E
ERASE
C
0,0
50,50
;the next line is intentionally blank: it ends the selection

Always ZOOM Extents first. Window, crossing and fence selections only find objects that are visible on screen. A script that works on one drawing and misses objects on the next is almost always zoomed differently. ALL, L and P do not have this problem.

Example: move everything to layer 0

CHPROP
ALL
;blank line ends the selection

LA
0
;blank line exits CHPROP

Select by layer or object type (full AutoCAD or LT 2024 and later)

AutoCAD has no command-line "select by layer" option, but a one-line LISP expression in the script builds the selection set for you. This erases all text and mtext on the NOTES layer in model space:

(setq ss (ssget "X" '((0 . "TEXT,MTEXT") (8 . "NOTES") (410 . "Model"))))
ERASE
!ss
;blank line ends the selection

The (410 . "Model") filter keeps the selection to model space; drop it and AutoCAD skips the objects that are not in the current space. The classic SSX routine does the same job interactively; a copy is on the forum: Selecting by layer in a script (SSX).

AutoCAD LT 2023 and earlier cannot run LISP. A no-LISP workaround: lock every layer except the one you want with -LAYER, then use ALL. Objects on locked layers are skipped by editing commands. See How do I script LAYER operations?

Related