Chapter 7. AutoCAD Scripts

Most users have forgotten AutoCAD Scripts over the past few years, and that's too bad, because scripts are simple—and powerful. I use them every day to manage network computers, set up drawings, and test individual workstations to see how well they run AutoCAD. Scripts are my own personal insurance policy—they prevent those unwelcome surprises that sometimes occur when I'm presenting material on somebody else's computer.

But when it comes to updating drawings, this poor-man's programming tool packs an even bigger punch. I've written scripts that update literally thousands of drawings while I'm busy doing something else. In the last section of this chapter, I'll show you a few examples. Once you've seen them, I guarantee you'll be thinking up a few of your own.

Note

If you changed the default path for AutoCAD when it was installed, you must use your own path in the code used in this chapter. C:Program FilesAutoCAD 2007acad.exe is used as the path to the acad.exe file throughout.

  • Characteristics of Scripts

  • Writing and Running Scripts

  • Updating Thousands of Drawings

Characteristics of Scripts

Scripts are essentially extremely fast typists. When you have to do one thing the same way every time, scripts can't be beat. They even have one advantage over real programming languages: You can use them in AutoCAD LT.

Let's start with a few characteristics of scripts:

  • Scripts are ASCII text files. Use a text editor for best results.

  • They consist of things you would normally type at the command prompt, such as:

    • Commands, but not command aliases

    • Command options as you would type them (E or Extents works for the ZOOM command)

    • AutoCAD system variables

    • Lisp code (unless you're using AutoCAD LT)

    • External commands defined in the ACAD.PGP file, but not aliases

    • Commands and functions defined with AutoLISP, ARX, or VBA

  • They can be run automatically at AutoCAD startup by using the /b switch.

  • They must be saved with an .scr extension.

  • They form the basis of a process used to update large numbers of drawings.

  • They can load AutoLISP programs.

  • They can run AutoLISP programs.

  • They can call another script using the SCRIPT command.

  • They can open tool palettes but can't make selections from them.

  • You can make a script open a file-management dialog box by placing a tilde after the command name, as in SAVE ~.

Scripts also have a few limitations:

  • The only possible user input is to pause and restart the script.

  • Variables can't be defined directly in a script the way they can in a Lisp program—but if you need to define variables, you can run Lisp code in a script to do it.

  • If something goes wrong, a script stops until the user takes some action.

Table 7.1 shows the few special functions used with scripts.

Writing and Running Scripts

If you can type, then you can write script files. The script file is AutoCAD's version of a batch file. It's an ASCII text file with the extension .scr. You can create one in any word processor or text editor, but a text editor is far preferable because word processors add codes that will interfere with the script if you don't save the file in the proper text format.

Table 7.1. Special Functions Used with Scripts

FUNCTION

PURPOSE

Backspace key

Pauses a script in progress

RESUME

Resumes a paused script when typed at the keyboard

;

Designates that a remark line follows

DELAY

Delays the next step in the script for a specified time period

RSCRIPT

Repeats the entire script when placed at the end of the script file.

Space in a line

The same as pressing

Special Functions Used with Scripts
Special Functions Used with Scripts

Also the same as pressing

Special Functions Used with Scripts

Note

Windows uses the .scr extension for screen savers. Before AutoCAD 2006, unless you've changed the association, you can't double-click a script file to open it. If you try, Windows assigns it as your screen saver. After a set period of inactivity, you'll get a confusing error message about not being able to run the screen saver. Change the association of the file extension in Windows Explorer (or any Windows file-management dialog box) by using the menu sequence Tools → Folder Options → File Types → New → SCR → Advanced → AutoCAD Script.

A script automatically executes a series of commands that are contained in a text file, as long as it has an .scr extension. You can use it for any number of tasks, such as the following:

  • Create a drawing.

  • Test a computer.

  • Set up layers, text styles, dimension styles, and other things in a drawing.

  • Change variable settings that are saved in the drawing.

  • Change settings that are saved in the system registry.

  • Extract block attributes.

  • Make slides, and run a slide show.

  • Edit an unlimited number of drawing files while you do something else.

Creating and using a script file requires the following steps:

  1. In a text, file, type a list of AutoCAD commands just as you would at the command prompt.. You can place one command on each line or separate commands with spaces. Be careful not to put extra spaces between commands or at the ends of lines. A space in a script has the same effect as pressing the Enter key, as does a new line.

  2. Save the file with a filename and the extension .scr. This is critical. Without the .scr extension, AutoCAD won't recognize the text file as a script when you try to run it.

  3. Have AutoCAD run the script. Use the SCRIPT (SCR) command, or choose Tools → Run Script.

Note

By default, the SCRIPT command uses a file-management dialog box. If you want to enter options at the command line, first turn off the File dialog box by setting FILEDIA to 0. That way, you can see how the command works. If you run the SCRIPT command from a script file, it won't open the dialog box.

A Simple Script File

To get a sense of how a script works, create a text file named layer.scr and type the following lines. Be careful not to create extra lines or spaces anywhere in the file. However, enter

A Simple Script File
LAYER
New
fl1,fl1-dim,fl1-txt
Color
2
fl1
Color
3
fl1-dim
Color
4
fl1-txt

If you highlight the entire file in Notepad you can see whether you have any extra spaces or lines. Notice the location of the cursor in the image.

You can also type the script file on one line, with a single space between the commands. The same setup script looks like this:

A Simple Script File
Layer new fl1,fl1-dim,fl1-txt color 2 fl1 color 3 fl1-dim color 4 fl1-txt

Save the file (don't forget the .scr extension). Run the script in AutoCAD. If everything goes right, three new layer names are created, with their colors set to 2, 3, and 4.

Note

If you're wondering why the Layer Properties Manager doesn't appear when you run this script file, remember that some commands work differently in a script than they do when typed at the keyboard. A script can't be paused, but a dialog box would cause it to stop. The LAYER command in a script doesn't open the dialog box; it behaves like the version of the LAYER command you get if you type -LAYER.

Drawing Setup

The simple script in the previous section can be expanded to automatically set up limits, units, variables, a text style, and so on. If you use good template files, much of this setup is already be in place, but I can think of a few reasons why a script may be a better choice than a template file:

  • An existing drawing's setup may need to be changed after the drawing has been created. By then it's too late to start the drawing with a template file, and you can't insert a DWT file to bring in layers and styles.

  • You may be working with drawings from other offices that don't follow your standards. A script can help you fix that.

  • Many of AutoCAD's system variables are saved in the system registry, not in the drawing file, so a template can't control them.

  • You may have to use a shared computer on which another user has changed some AutoCAD settings. Restoring the defaults or your preferred settings is much easier with a script than manually.

Let's take the script layer.scr and rewrite it with a few additional functions:

;Create new layers
LAYER New obj,hid,cen,txt,dim Color 1 hid Color 3 cen
Color 4 txt Color 5 dim L hidden hid L center cen S obj

;Create new text style
STYLE romans romans 0 1 0 N N N
;Reset variable values
APERTURE 5 ATTDIA 1 AUNITS 0 AUPREC 1 BLIPMODE 0
CECOLOR bylayer CELTSCALE 1 CELTYPE bylayer
CMDDIA 1 CMDECHO 1 CURSORSIZE 5 DRAGMODE A ELEVATION 0
EXPERT 0 FACETRES 1 FILEDIA 1 FILLETRAD 0 GRIPCOLOR 5
GRIPHOT 1 GRIPS 1 GRIPSIZE 3 HIGHLIGHT 1 LTSCALE 1
MBUTTONPAN 1 MIRRTEXT 0 OSMODE 4133 PELLIPSE 0 PICKADD 1
PICKAUTO 1 PICKBOX 3 PICKFIRST 1 PICKSTYLE 1 PLINEGEN 1
PSLTSCALE 1 SAVETIME 15 SDI 0 SORTENTS 23 THICKNESS 0
UCSICON off UCS w UCSVP 1

The following graphic shows the result of highlighting this file. In this case the cursor is directly below the beginning of the last line. There is no need for a blank line to exit the previous command.

Drawing Setup

This script sets up layers, an acceptable text style, and set key variables. The purpose of a setup script is to restore standard settings if something goes wrong with AutoCAD and you can't figure out why.

Note

Make sure there are no extra spaces or lines anywhere in this file. (There's a reason why I'm mentioning this over and over.) Each of them is interpreted as the

Drawing Setup

Computer Bench Testing

If you've ever wondered how well AutoCAD will run on a particular workstation, the script function gives you a handy way to find out. You may want to duplicate a colleague's problem with AutoCAD crashing (unless, of course, AutoCAD has never crashed for you). Or, you may want to compare a variety of computers to decide which one to buy.

I wrote the following script because, as the person responsible for all the computers in my department, I'm all too familiar with the Law of Unintended Consequences. Whenever it's time for the college to upgrade or add computers to a lab, I load AutoCAD on each station and then run a version of the following script. You'd be surprised at the amount of variation between systems with similar specs.

Before running this script you must start a new Imperial drawing from scratch.

TIME R

BOX 0,0 10,10,10 SPHERE 5,5,5 5 SUBTRACT NON 0,0  L

VPOINT 1,−1,1 SLICE L   5,0 5,5 5,5,5 −1,0
3DARRAY L  R 4 4 4 10 10 10
ZOOM ALL HIDE
VPORTS 4
CVPORT 5 UCS X 90 PLAN C
CVPORT 4 UCS W PLAN C
CVPORT 2 UCS X 90 UCS Y 90 PLAN C
TILEMODE 0 ERASE ALL  MVIEW R  F
MSPACE CVPORT 3 SOLPROF ALL  Y Y Y
CVPORT 4 SOLPROF ALL  Y Y Y
CVPORT 5 SOLPROF ALL  Y Y Y
CVPORT 6 SOLPROF ALL  Y Y Y
TIME

Note

This script will run properly only if you start a new drawing before executing it.

To make sure you have no spaces at the end of each line, highlight the entire file by dragging the mouse with the left button held down, and make sure it looks like the following image. Note that the cursor is by itself on the last line, which is below TIME. If you have trouble running this script, try turning off running object snaps or setting APERTURE to 3.

What does this script do? Let's take one line at a time; see Table 7.1

SLUGGISH COMPUTERS

Table 7.2. benchtest.scr

SCRIPT LINE

PURPOSE

TIME R

Resets the time.

 

A

benchtest.scr

BOX 0,0 10,10,10 SPHERE 5,5,5 5 SUBTRACT NON 0,0 L

Creates a solid box and a sphere, and subtracts the sphere from the box. The use of NON cancels any running object snaps. Giving a location of 0,0 selects the box. An extra space is a

benchtest.scr
 

A

benchtest.scr

VPOINT 1,−1,1 SLICE L 5,0 5,5 5,5,5 −1,0

Creates an isometric view, and slices the resulting solid using a plane defined by the coordinates given. Note the 3 spaces after L.

3DARRAY L R 4 4 4 10 10 10

Creates a rectangular 3D array of the sliced object. The larger the values used for the number of entities, the more entities are created in the array. To decrease the amount of time it takes to run this test, lower the value from 10. To increase the amount of time, increase the value.

ZOOM ALL HIDE

Displays the entire array, and displays it as hidden.

VPORTS 4

Sets up four tiled viewports.

CVPORT 5 UCS X 90 PLAN C

Makes viewport 5 active, and creates a front view.

CVPORT 4 UCS W PLAN C

Makes viewport 4 active, and creates a top view.

CVPORT 2 UCS X 90 UCS Y 90

Makes viewport 2 active, and creates a right view.

PLAN C

 

TILEMODE 0 ERASE ALL MVIEW R F

Switches to a layout, and creates four views.

MSPACE CVPORT 3 SOLPROF ALL Y Y Y

Creates a solid profile in viewport 3.

CVPORT 4 SOLPROF ALL Y Y Y

Creates a solid profile in viewport 4.

CVPORT 5 SOLPROF ALL Y Y Y

Creates a solid profile in viewport 5.

CVPORT 6 SOLPROF ALL Y Y Y

Creates a solid profile in viewport 6.

TIME

Activates the TIME command, and displays the total elapsed time.

 
benchtest.scr

I use these particular functions because they have caused me past problems in AutoCAD. You can easily adjust the program to increase or decrease the time it takes to run by changing the number of objects in the 3D array. When I ran this program on my current workstation, I got the following result at the end.

benchtest.scr

Using Scripts at Drawing Startup

You can automate AutoCAD at startup with switches by using the RUN option or using a startup icon. One of those switches, /b, allows you to name a script that runs each time AutoCAD starts.

Note

You can also start AutoCAD by having it open a named drawing. By combining the two functions, you can have AutoCAD start with a specific drawing and then run a script.

Figure 7.1 shows the Properties window of an AutoCAD desktop icon. In the Target field, I've added the /b switch and the name and path of a script file. The entire line reads like this:

"C:Program FilesAutoCAD 2007acad.exe" /b R:setup.scr

When you select the icon, AutoCAD starts up and executes the named script, which is on a network drive. I use this script to easily change the setup for plotters and specific variables; I can also send a message to users by adding an Alert box. AutoCAD system variables, such as REMEMBERFOLDERS, can be set directly; you need AutoLISP code to set environmental variables. Here's a sample startup script:

Running a script on startup

Figure 7.1. Running a script on startup

;;No blank lines!
rememberfolders 0
ACADLSPASDOC 1
Savefilepath S:
(if (= 120 (getvar "savetime"))(setvar "savetime" 5))
(setenv "HideSystemPrinters" "1")
(setvar "pickadd" 1)
(setenv "PrinterConfigDir" "r:\plotters")
(setenv "PrinterStyleSheetDir" "")
(setenv "PrinterDescDir" "r:\plotters\pmp files")
(startapp "net start spooler")
(alert "Message text begins after the quote, for display
Running a script on startup
in an AutoCAD Message box. A new line would start after the backslash n and appear here. A third line would appear here. The closing quote and parenthesis
Running a script on startup
is on the next line. ") (defun C:AED()(startapp "C:\Program Files\Adobe\
Running a script on startup
Acrobat 6.0\Reader\AcroRd32.exe"
Running a script on startup
"r:\TECHNICAL GRAPHICS STANDARDS_rev8.pdf")) (princ)

Resetting All AutoCAD Variables

Let's say AutoCAD starts misbehaving: You know something's gone awry but can't target the problem. Sometimes the only solution is to reset all variables to their defaults.

If Express Tools are installed on your system, look for a file named defaults.scr in the Express folder under the AutoCAD folder in Program Files. That file is a script you can use to restore all default settings for AutoCAD variables. Unfortunately, it hasn't been updated for the past several releases. The website for this book contains contains an updated version of this file with the default values. It uses Lisp language to reset each variable, primarily because that approach allows more accuracy in values that must be calculated using pi. It also lets you set environmental variables like MAXHATCH that can only be set with AutoLISP.

System Variables dialog box

Figure 7.2. System Variables dialog box

You can use another Express Tool, SYSVDLG (the System Variables editor), to save your current settings and then retrieve them, as shown in Figure 7.2. These won't be the default values if you've changed anything.

Updating Thousands of Drawings

Although I've yet to run into another engineer who needs to explode all the blocks and polylines in a drawing, I've nevertheless created various sets of programs over the years to solve the problem of updating large numbers of drawings. One company wanted to reduce the size of its archived drawings to preserve drive space. Another wanted to extract specific attribute data from all of its drawings and place the data in a text file. Yet another wanted to update the title block in all of its drawings to reflect a company name change. And still another wanted to create a separate drawing file from each block definition in all of the company's symbol-library drawings.

I'll share three of these solutions with you. Each one requires the following three elements:

  • A script file

  • A batch file

  • A Lisp program

Note

Write your programs in such a way that new drawing files are created. Don't delete the existing files until you're confident that the program did what you wanted it to. You may even want to mark them as read-only before you try this system.

Batch File

In these solutions, I use a batch file to edit multiple drawings primarily because doing so allows me to use the DOS function FOR. The FOR function lets you specify a directory and filenames using wildcards and have the operating system do something with those files. In this case, I use the batch file to start AutoCAD and open each DWG file in a specified directory. The key line of each batch file is in the following form:

FOR %%f in (C:dwg*.dwg) do start /wait acad.exe "%%f" /b
Batch File
C:Sybexwbout.scr

To process drawings in subdirectories, you can add a /r switch to the FOR command in the batch file. Note that the path comes before the replaceable parameter, and the set (in parentheses) includes only the files, designated by a wildcard and file extensions. You can also reference a text file to specify a list of filenames, but this is the system I use. Consult the DOS help system for the FOR command if you want more details:

FOR /r C:SybexDWG %%f in (*.dwg) do start /wait
Batch File
C:"Program Files""AutoCAD 2007"acad.exe "%%f" /b
Batch File
C:Sybexwbout.scr

Script File

In addition to the batch file, I also use a script for these solutions because I can run a script on startup by pointing to it in the batch file. The following line shows the syntax to use at a DOS command prompt in the target window of a desktop icon, or in the Run window reached from the Windows Start button:

C:"Program Files""AutoCAD 2007"acad.exe C:dwghouse.dwg /b
Script File
C:Scriptsstartup.scr

This line starts AutoCAD (acad.exe), opens a specified drawing (house.dwg), and executes a named script (C:Scriptsstartup.scr) automatically.

AutoLISP File

Like both script files and batch files, an AutoLISP file is a text file, but it's designated by an .lsp extension. Lisp is a programming language, and its tie to AutoCAD makes it possible to do nearly anything to a drawing. Every experienced AutoCAD user should be familiar with it. In this system for updating drawings, AutoLISP generally does the real work.

Learning AutoLISP is beyond the scope of this chapter, but read Chapters 8 and 9, "AutoLISP by Example: Getting Started," and "AutoLISP by Example: Getting Better." For now, I'll provide you with the necessary AutoLISP code for these examples. Go ahead and copy it.

Because AutoLISP functions can be typed at the command line in AutoCAD, AutoLISP code can be placed directly within a script file as long as it is enclosed in parentheses. I use that feature in these solutions only to load an AutoLISP file. Most of the AutoLISP code resides in its own separate file.

For the purpose of these examples, specific folder names and filenames are used. To complete these exercises, create the following folders:

  • C:Sybex

  • C:SybexDWG

Once the folders exist, place some sample drawings in the C:SybexDWG folder.

  • Include one drawing named new-border.dwg, which will be used in the border update example.

  • Include a few drawings whose file names start with the characters D5.

  • Copy some of the symbol drawings from the C:Program FilesAutoCAD 2007SampleDesignCenter folder, and rename them by adding SYM at the beginning of each file name.

Putting Them All Together

All these files—batch, script, and Lisp—must work together to accomplish the task of updating a lot of drawings. That makes troubleshooting this system at least three times more difficult than if it used a single file. So, let me make a point about frustration. When you do any kind of programming, the chances are good that when you test it, it won't work. Why? For one thing, it's easy to overlook a little thing, like a

Putting Them All Together

Troubleshooting

What if you create these three files and fire up the batch file, and things don't work the first time? Start by looking for the most common typos. Next, look for clues that can help you pinpoint which of the three files may be the culprit, so you can focus your attention in the right place. With that in mind, here's a little troubleshooting advice:

Typos Carefully review each file for typing errors, which may be obvious or subtle:

  • 1 and l look a lot alike. What, you think I just typed the same character? Nope, I typed the number one and a lowercase L.

  • 0 and O can get you, too (in the old days, that zero would have had a dot in the middle).

  • 2 and Z can fool you on a bad day.

Batch file Look here if AutoCAD never opens, or if it opens but can't "find the specified drawing file":

  • Check to see whether the first line of the batch file worked. If the new folder was created, you know the batch file was named correctly.

  • Count quotation marks in the second line. If you don't have an even number, figure out why.

  • Quote filenames and folder names that contain spaces. That includes putting quotes around the variable name %%f, but only when it follows the program name acad.exe.

  • Sometimes case matters. The variables %%f and %%F aren't the same. Make sure you haven't changed the case in the second reference.

  • Make sure you haven't left out a space. Check in front of the /b switch.

Script file Look here if AutoCAD opens a drawing file but goes no further. Press the F2 key to see the entire text history, and look for a line showing that the program stopped working:

  • Check the line that loads the AutoLISP file to make sure you used a double backslash to separate folder and filenames.

  • Make sure there are no extra spaces within a line or at the ends of lines.

  • Make sure any command option is separated from its command name by one space.

  • Make sure there are no extra lines at the beginning or end of the file.

AutoLISP file This file will be harder to troubleshoot if you have no experience yet with AutoLISP:

  • Be even more careful about spelling errors on words like defun, because they won't be as familiar to you as English words.

  • Make sure there's no space after the C: in the first line of each AutoLISP program. The C: defines the new function as an AutoCAD command name and should appear as C:WBOUT(), for example.

  • Anything between quotes must appear exactly as shown in each example. Don't add any spaces that shouldn't be there.

Note

Use a text editor for programming, not a word processor. Smart quotes and other specialty characters can cause programs to fail even if you've saved the file in text format.

Example 1: Reducing File Size

The first example of a solution for automated updating involves reducing the size of all drawing files within one or more directories to their minimum. I use the WBLOCK command, but you can use the PURGE command instead. This solution was written for an office that wanted to clean up archived drawings, eliminating unused layer names, block definitions, dimension styles, and so on to reduce the amount of space they took up.

The batch file starts AutoCAD, loads the first drawing in the named directory, executes the script file, and waits until AutoCAD finishes with that drawing so it can go on and load the next file in the directory. The script file loads the AutoLISP file, runs the command it defines, and then quits AutoCAD. The AutoLISP file gets the name of the drawing and uses the WBLOCK command to save it with the same name, but in a different directory. Once the script file quits AutoCAD, the whole process returns to the batch file and continues until all the files are processed.

STEP 1: WBOUT.BAT

Use a text editor to create the following batch file, and save it as wbout.bat in the folder C:Sybex. Type the entire FOR statement on one line. When you type it in a text editor, it will appear as a single line, even though it appears on multiple lines here. This batch file has only two lines of text:

MD C:SybexDWGwb
FOR %%f in (C:SybexDWG*.dwg) DO START /WAIT
STEP 1: WBOUT.BAT
C:"Program Files""AutoCAD 2007"acad.exe "%%f" /b
STEP 1: WBOUT.BAT
C:Sybexwbout.scr

When you execute this batch file, AutoCAD starts, and opens each drawing. Because of the /b switch, the script file named wbout.scr runs every time AutoCAD starts. When all files with a .dwg extension have been processed (made equal to variable %%f), the program stops.

Table 7.2 shows the purpose of each line.

Table 7.3. wbout.bat

LINE IN BATCH FILE

PURPOSE

MD C:SybexDWGwb

This line makes a new folder named wb within the C:SybexDWG folder. The drawing files created in this example are placed in this folder.

FOR %%f in
(C:SybexDWG*.dwg) DO
START /WAIT C:"Program
Files""AutoCAD
2007"acad.exe "%%f" /b
C:Sybexwbout.scr

FOR each filename represented by the replaceable parameter %%f, within the folder named C:SybexDWG, DO the following: START a Windows application, and WAIT for it to finish before continuing on to the next file in the directory.

 

The Windows application is the ACAD.EXE program. When it's started, load the drawing whose name is represented by the replaceable parameter %%f, and run the script named wbout.scr, which is located in the C:Sybex folder.

Note

I used the default path for AutoCAD in all of these examples. If you installed AutoCAD in a location other than the default, edit this file so it uses your path. You can omit the path and use only the filename ACAD.EXE unless there is more than one ACAD.EXE file on your computer. This can happen if you have multiple releases of AutoCAD or if you have one or more vertical applications. It's generally better to be explicit in giving a path.

STEP 2: WBOUT.SCR

Use a text editor to create the following script file, and save it as wbout.scr in C:Sybex with wbout.bat. You should have five lines of text, with no extra spaces or extra lines anywhere. You must press

STEP 2: WBOUT.SCR
(load "C:\Sybex\wbout.lsp")
ZOOM All
WBOUT
QUIT
Y

When AutoCAD runs this script, an AutoLISP file is loaded that defines WBOUT, a new AutoCAD command. The script runs the WBOUT command and then quits AutoCAD.

Table 7.3 shows the purpose of each line.

Table 7.4. wbout.scr

LINE IN SCRIPT FILE

PURPOSE

(load "C:\Sybex\wbout.lsp")

This line of AutoLISP code loads the wbout.lsp file. Note the \.

ZOOM All

This is here to make a change in the drawing. Otherwise, AutoCAD won't allow a file to be saved by the WBLOCK command, which is used in the AutoLISP program.

WBOUT

This is the name of the new command defined in wbout.lsp. Placing it here executes that command.

QUIT

The AutoCAD QUIT command closes AutoCAD without saving the drawing file that was opened.

Y

This confirms that AutoCAD should quit without saving. See the following note for an explanation.

Note

The QUIT command, when used in a script, results in a different prompt than it does when used in AutoCAD directly. The prompt for the script version is Really want to discard all changes to drawing? <N>, which requires the response Y to quit without saving.

STEP 3: WBOUT.LSP

Use a text editor to create the following AutoLISP file, and save it as wbout.lsp in the folder C:Sybex:

(defun C:WBOUT(/ dn pa pawbdn)
   (setq dn (getvar "dwgname"))
   (setq pa (getvar "dwgprefix"))
   (setq pawbdn (strcat pa "wb\" dn))
   (command "WBLOCK" pawbdn "*")
)

This program gets the current drawing name, issues the WBLOCK command, selects all entities in the drawing (that's what the * does), and saves the drawing in the new WB folder with the same filename as the original drawing file.

Table 7.4 shows the purpose of each line.

Table 7.5. [.] wbout.lsp

LINE IN SCRIPT FILE

PURPOSE

(defun C:WBOUT(/ dn pa pawbdn)

This line defines the new function named WBOUT. The C: makes it an AutoCAD command. Leave a space after the forward slash.

(setq dn (getvar "dwgname"))

This line gets the name of the current drawing and saves it as a variable. Type both quotes.

(setq pa (getvar "dwgprefix"))

This line gets the path of the current drawing and saves it as a variable.

(setq pawbdn (strcat pa "wb\" dn))

This line creates a new path by adding the folder WB to the existing path where the current drawing is stored.

(command "WBLOCK" pawbdn "*")

This is the line that saves the drawing in the new WB folder using the same drawing name.

)

This line closes the opening parenthesis in the file. Every opening parenthesis must have a closing one.

Note

By using a Lisp program to change the drawing and then save it to a new location, you can get the current location and the current filename, modify them by appending a new folder name, and store them as variables. This can't be done using a script file alone.

STEP 4: RUN THE PROGRAM

Once there are drawing files in the C:Sybex folder, you can start this process by running the batch file. The batch file gets the whole thing moving, because it selects each drawing file and starts AutoCAD with the proper script. You can run this program from the Run window, a command prompt, Explorer, My Computer, or a desktop shortcut.

For now, use Explorer to find the C:Sybex folder. Double-click the wbout.bat icon; or select it, right-click, and select Open. See Figure 7.3. If everything goes well, you can sit back and watch AutoCAD opening and closing as it modifies each file. When the batch file is completed, the DOS window closes. Look in the C:SybexDWGWB folder, and see whether your new files are there.

Running a batch file

Figure 7.3. Running a batch file

Note

Don't double-click a batch file if you only want to edit it. To change text, select Edit from the right-click menu. Double-clicking automatically launches the batch file. (You can also launch the batch file by selecting Open from the right-click menu.)

You may have to try this several times. If so, delete the WB folder before running the batch file a second time. Otherwise, you'll get a prompt asking you if you want to replace the existing drawings as AutoCAD tries to save files with the same name to the WB folder.

Using this collection of programs—a batch file, a script, and an AutoLISP routine—can greatly reduce the space used for archiving DWG files. However, as with any automated process, there are a number of things to consider, including whether you really want to eliminate all unused layers, block references, text styles, and dimension styles from the drawings.

This kind of programming should be tested carefully on a limited number of test files before you use it. Once you've run this program and are convinced that it did what you wanted, you can delete the old files and place the new files where you want them.

Example 2: Redefining Existing Block Definitions

I devised this second solution for a company that had been purchased and renamed. The company didn't want to send out or plot any existing drawings with the old name in the title block. Over a number of years, the company had inserted the same title block drawing into all of its AutoCAD drawings, and now it wanted to redefine the resulting block reference in all of them. I had one preliminary question: Did the company ever explode its title blocks? It hadn't, which is why this system worked. Except for the logo and company information, the new title block and the old title block were identical, so all it needed to do was replace the definition for the Border block in each drawing.

Note

If you want to try this example, you'll have to create a drawing with entities representing a title block in Model Space and save the drawing with the name new-border.dwg. Place it in the C:SybexDWG folder along with several drawings that have a block reference named border. The new-border.dwg file is used to update the border Block definitions in each drawing.

STEP 1: TBUPDATE.BAT

Use a text editor to create the following batch file, and save it as C:Sybex bupdate.bat. Type the entire FOR statement on one line. When you type it in a text editor, it will appear as a single line, even though it appears on multiple lines here. This file has only two lines of text:

MD C:SybexDWGNewBorder
FOR %%f in (C:SybexDWGd5*.dwg) DO START /WAIT
STEP 1: TBUPDATE.BAT
C:"Program Files""AutoCAD 2007"acad.exe "%%f" /b
STEP 1: TBUPDATE.BAT
C:Sybex bupdate.scr

Table 7.5 shows the purpose of each line.

Table 7.6. tbupdate.bat

LINE IN SCRIPT FILE

PURPOSE

MD C:SybexDWGNewBorder

This line makes a new folder named NewBorder in the C:SybexDWG folder. The drawing files created in this example are placed in this folder.

FOR %%f in
(C:SybexDWGd5*.dwg) DO
START /WAIT C:"Program
Files""AutoCAD
2007"acad.exe "%%f" /b
C:Sybex	bupdate.scr

FOR each file name represented by the replaceable parameter %%f, within the folder named C:SybexDWG, DO the following: START a Windows application, and WAIT for it to finish before continuing on to the next file whose name begins with D5 in the directory.

 

The Windows application is the ACAD.EXE program. When it's started, load the drawing whose name is represented by the replaceable parameter %%f, and run the script named tbupdate.scr, which is located in the C:Sybex folder.

Note

This example is more selective about the files being processed than the first example. Only drawings whose names begin with the characters D5 are opened.

STEP 2: TBUPDATE.SCR

Use a text editor to create the following script file, and save it as tbupdate.scr in a folder named C:Sybex. You should have eight lines (one is blank), with no extra spaces anywhere. You must press

STEP 2: TBUPDATE.SCR
INSERT border=C:SybexDWG
ew-border.dwg
0,0 1 1 0
ERASE L

(load "C:\Sybex\tbupdate.lsp")
TBUPDATE
QUIT
Y

When AutoCAD runs this script, an AutoLISP file is loaded that defines TBUPDATE, a new AutoCAD command. The script runs the TBUPDATE command and then quits AutoCAD.

Table 7.6 shows the purpose of each line.

STEP 3: TBUPDATE.LSP

Use a text editor to create the following AutoLISP file, and save it as tbupdate.lsp in the folder C:Sybex:

(defun C:TBUPDATE(/  dn pa panbdn)
   (setq dn (getvar "dwgname"))
   (setq pa (getvar "dwgprefix"))
   (setq panbdn (strcat pa "NewBorder\" dn))
   (command "SAVE" panbdn)
)

It gets the current drawing name and saves the drawing in the new NewBorder folder with the same filename as the original drawing file. The WBLOCK command isn't used here because it isn't necessary. This system isn't designed to reduce the file sizes.

Table 7.7 shows the purpose of each line.

STEP 4: RUN THE PROGRAM

Double-click the tbupdate.bat icon; or select it, right-click, and choose Open. This one goes by quickly. Look in the C:SybexDWGNewBorder folder and see whether your new files are there. Open one to see if the block did in fact update.

Table 7.7. tbupdate.scr

LINE IN SCRIPT FILE

PURPOSE

INSERT
border=C:SybexDWG
new-border.dwg

Using the INSERT command in this manner redefines the existing block reference border using the entities in Model Space in the drawing new-border.dwg.

0,0 1 1 0

The block reference created from the NEW-BORDER drawing is inserted at 0,0. X and Y scale factors and a rotation angle are required when inserting a block reference. Here, you use scale factors of 1 and a rotation angle of 0.

ERASE L

This line erases the last object created, which is the block reference just inserted. Why erase it? Because the only reason to insert it is to update the existing block reference. Once that is accomplished, this additional reference isn't needed.

 

This blank line is used as a

tbupdate.scr

(load "C:\Sybex\tbupdate.lsp")

This line loads the AutoLISP program that is used to save the drawing file.

TBUPDATE

This is the name of the new command defined in tbupdate.lsp that saves the resulting updated drawing file. Placing it here executes that command.

QUIT

The AutoCAD QUIT command closes AutoCAD without saving the drawing file that was opened.

Y

This confirms that AutoCAD should quit without saving.

 
tbupdate.scr

Table 7.8. tbupdate.lsp

LINE IN SCRIPT FILE

PURPOSE

(defun C:TBUPDATE(/ dn pa panbdn)

This line defines the new command TBUPDATE.

(setq dn (getvar "dwgname"))

This line gets the name of the current drawing file and saves it to a variable named dn.

(setq pa (getvar "dwgprefix"))

This line gets the path of the current drawing file and saves it to the variable pa.

(setq panbdn (strcat pa "NewBorder\" dn))

This line creates a new path by adding NewBorder\ to the existing path where the drawings are saved.

(command "SAVE" panbdn)

This line saves the drawing in the NewBorder folder using the same drawing name.

)

This line closes the opening parenthesis in the file.

Example 3: Creating Drawings from Block Definitions

I wrote this one for an architectural firm that decided to change its system for managing its library of symbols. The company had been using single drawings with related groups of block definitions to store symbol libraries. It decided it would prefer to have a separate drawing file for each of the block definitions used and assigned the task of creating them to a recently hired designer. After doing a few, he called me to see if there was some way to reduce the tedium of manually creating the drawing files.

The purpose of this final example is to automatically open a group of drawings that contain block definitions and create a new drawing file from each of them. It uses the same process as in examples 1 and 2, but with a somewhat more involved AutoLISP program.

STEP 1: BLOCKOUT.BAT

Use a text editor to create the following batch file, and save it as C:Sybexlockout.bat. Type the entire FOR statement on one line. When you type it in a text editor, it will appear as a single line, even though it appears on multiple lines here. Like the earlier examples, this file has only two lines of text. For an explanation for what this file does, see Table 7.8:

MD C:SybexDWGNewBlocks
FOR %%f in (C:SybexDWGsym*.dwg) DO START /WAIT
STEP 1: BLOCKOUT.BAT
C:"Program Files""AutoCAD 2007"acad.exe "%%f" /b
STEP 1: BLOCKOUT.BAT
C:Sybexlockout.scr

STEP 2: BLOCKOUT.SCR

Use a text editor to create the following script file, and save it as blockout.scr in the folder named C:Sybex. You should have four lines with no blank lines anywhere in the file. You must press

STEP 2: BLOCKOUT.SCR
(load "C:\Sybex\blockout.lsp")
BLOCKOUT
QUIT
Y

Table 7.9. tbupdate.bat

LINE IN SCRIPT FILE

PURPOSE

MD C:SybexDWGNewBlocks

This line makes a new folder named NewBlocks in the C:SybexDWG folder. The drawing files created in this example are placed in this folder.

FOR %%f in
(C:SybexDWGsym*.dwg) DO
START /WAIT C:"Program
Files""AutoCAD 2007"acad.exe
"%%f" /b C:Sybexlockout.scr

FOR each filename represented by the replaceable parameter %%f, in the folder named C:SybexDWG, DO the following: START a Windows application, and WAIT for it to finish before continuing on to the next file whose name begins with Sym in the directory.

 

The Windows application is the ACAD.EXE program. When it's started, load the drawing whose name is represented by the replaceable parameter %%f, and run the script named blockout.scr, which is located in the C:Sybex folder.

It isn't necessary to do a ZOOM ALL in this example. Once the Block definitions have been extracted using the blockout.lsp program, the drawing can be closed.

Table 7.9 shows the purpose of each line.

Table 7.10. blockout.scr

LINE IN SCRIPT FILE

PURPOSE

(load "C:\Sybex\blockout.lsp")

This line of AutoLISP code loads the blockout.lsp file. Note the \.

BLOCKOUT

This is the name of the new command defined in blockout.lsp. Placing it here executes that command.

QUIT

The AutoCAD QUIT command closes AutoCAD without saving the drawing file that was opened.

Y

This confirms that AutoCAD should quit without saving.

 
blockout.scr

STEP 3: BLOCKOUT.LSP

Use a text editor to create the following AutoLISP file, and save it as blockout.lsp in the folder C:Sybex. Table 7.10 shows the purpose of each line:

(defun C:BLOCKOUT (/  dn pa s1 blkdata blname fullname)
   (setq dn (getvar "dwgname"))
    (setq pa (getvar "dwgprefix"))
    (setq s1 (strcat pa "NewBlocks\"  dn))
    (setq blkdata (tblnext "BLOCK" T))
       (while blkdata
          (setq blname (cdr (assoc 2 blkdata)))
          (setq fullname (strcat s1 blname))
          (command "WBLOCK" fullname blname)
          (setq blkdata (tblnext "BLOCK"))
        )
)

STEP 4: RUN THE PROGRAM

Put some DWG files that contain block definitions into the C:SybexDWG folder. Then, double-click the blockout.bat icon; or select it, right-click, and choose Open. This one is fun because it shows you each drawing file in a preview window as the program creates it from a block definition. Look in the C:SybexDWGNewBlocks folder, and see whether your new files are there. Open one to see if it contains the entities used to define the original block.

Table 7.11. blockout.lsp

LINE IN SCRIPT FILE

PURPOSE

(defun C:BLOCKOUT (/ dn pa s1 blkdata blname fullname)

This line defines the new command BLOCKOUT.

(setq dn (getvar "dwgname"))

This line gets the name of the current drawing and saves it to the variable dn.

(setq pa (getvar "dwgprefix"))

This line gets the path of the current drawing and saves it to the variable pa.

(setq s1 (strcat pa "NewBlocks\" dn))

This line adds a new folder name to the path, appends the drawing name to the end of the path, and saves the result to the variable s1.

(setq blkdata (tblnext "BLOCK" T))

This line sets the variable blkdata to the first entity name in the list of clock definitions.

(while blkdata

This line uses the while function to begin the loop through the following steps while blkdata has a value.

(setq blname (cdr (assoc 2 blkdata)))

This line sets blname equal to the name of the next block definition in the list.

(setq fullname (strcat s1 blname))

This line creates a variable fullname from the path and block name set in the variables s1 and blname. The result is a drawing file whose name is a combination of the name of the current drawing file and the name of the block definition.

(command "WBLOCK" fullname blname)

This is the line that does the work. It uses the WBLOCK command to create a drawing file from the block definition and save it to the new location with the new filename.

(setq blkdata (tblnext "BLOCK"))

This sets blkdata equal to the next block definition in the list, which causes the While function to repeat the previous three lines. Once all the block definitions have been used, blkdata is nil, and the WHILE function causes the program to execute the next line.

)

This ends the WHILE function.

)

This ends the program.

Other Possibilities

In your own company or practice, you'll find many other possibilities for using this updating system. I certainly have. I've used it for lots of different companies, all of whom have specific, even unique, needs. Here's a short list of applications:

  • Extract the title block attributes from all drawings.

  • Convert layer names to a new standard using the RENAME command.

  • Change page setups for all drawings.

  • Create WMF files from a group of drawings.

  • Batch-plot all the drawings in a folder and subfolders.

Even if you don't have a specific use for this system right now, try it anyway. It's a great way to develop troubleshooting skills with each of these types of files. The more you understand this system, the more likely you are to find a use for it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.163.159