Chapter 4


Being able to record a series of keystrokes for later recall is power enough, but WordPerfect's macro feature also includes a method of programming your macros so that they behave like stand-alone applications.

With just a little bit of ingenuity, you can create macros that create, from scratch, a complete invoice for services or products, an electronic while-you-were-out telephone note pad, a note pad, mini calculator, a self-testing and scoring quiz game, a text adventure game, and much, much more. In short, there is almost no limit to what you an do with WordPerfect's macro programming language.

This chapter explains how how to access the programming feature and the meaning of the various programming commands or instructions. This chapter does not delve too deeply in actually employing the various programming commands in real macros -- the rest of the book is devoted to that. If you are serious about macro programming, be sure to also read Part Three of this book. The chapters in this section provide additional insights on applying the macro programming language, as well as how to avoid its frustrating pitfalls.



Although you don't need any previous training or experience at computer programming to master WordPerfect's programming language, it does help. At the very least, you should learn how to think like a programmer.

It is not the intent of this book to teach programming principles; that would require far too much space. However, you can gain a good grasp of programming fundamentals by concentrating on 10 main areas of macro design:

Let's take a closer look at each.

Going With the Flow

Simple, one-function macros can be created without a blueprint or flow chart but you should give extra thought and consideration to macros that are more complex in nature. You may find it helpful to draw a programming flow chart that includes the basic steps of the macro. In each box is a complete step; arrows connect the boxes to indicate the progress of steps throughout the macro. Flow charts are particularly handy when creating chained and nested macros, or macros that consists of many self-contained routines, because the drawing helps you visualize the function and flow of each macro.

While you are planning the macro, note the steps required to create it. On a scrap document, go through the motions of executing the macro -- but don't record it just yet. On a piece of paper, note the commands and menu options you choose to complete the task. Don't forget the [Enter]key, as well as all other keys you must press to make the macro work properly. Be sure to note each time you press it. When you think you have the procedure mapped out, define the macro and record it.

If you make a mistake, you can either cancel the recording by pressing [Ctrl]-[F10] again or edit out the errors later. Small mistakes usually make no difference, but you'll want to get into the habit of cleaning up your macros once you have created them.

After defining the macro, try it out to make sure it works the way you originally planned. If you spot a mistake, double-check the steps you took and redefine the macro.

The Benefit of Routines

One of the first things a programmer does when he or she starts on a project is to map out the individual segments, or routines, that make up the software. Even the longest, most complex program -- and this includes macros -- consist of little more than bite-size routines. The macro progresses from one routine to the next in an orderly and logical fashion.

What's a routine? A routine is any self-contained segment of code that performs a basic action. In the context of macros, a routine can be a single command or character of text, or it can take up the majority of a mammoth 20K macro. Suppose your macro resets the active printer, formats the document to legal size, and prints it. The macro can be divided into three distinct routines:

While there's no need to physically separate these routines within a macro, or even create separate macros and chain to each one in turn (although this can be done, as explained in Chapter 2), it helps to think of the macro as being composed of these more basic parts. If the macro doesn't work properly, you can more easily analyze the problem if you can narrow it down to a specific segment of the code. For example, if the macro is resetting the active printer and printing the document, but not properly formatting the document to legal size, you can readily trace the problem to the number 2 routine.

Many macros simply start at the beginning and advance one step at a time to the end, taking each instruction in turn and acting upon it. This is the approach of our example macro just cited.

But some WordPerfect macros jump around. They may start with routine 1, but then jump to routine 3, back to 1, then move on to 2. Jumping around within the macro pays off when you need to re-use a routine two or more times. Instead of repeating the steps of the routine each time, you can simply direct the macro to repeat the same routine. All it takes is a single command, which you'll learn about later in this chapter.

Here's another benefit of working with discrete routines. Depending on the application of the macro, it may behave one way when used with a particular type of document, and behave in a totally different way with another document. This concept may take some time to get used to, but it lends a great deal of power and flexibility to your macros. Instead of your macros conforming to a strict procedure, they are free to interact and adapt with your documents. In other words, your macros are "intelligent," automatically adapting to the situation and document at hand.

WordPerfect macros don't use line numbers, as found on some other programming languages, such as BASIC. You identify routines by name, or label. When you instruct WordPerfect to jump from one routine to another, you tell it which label to go to. Of course, if your macro is designed to go from beginning to end without stopping, you don't need labels, but it's still a good idea to think of the construction of the macro as discrete routines.


Subroutines are similar to routines, but are specifically designed to be used by the macro as a sub-component. Most often, subroutines are activated only when certain criteria exists -- an error occurs or a search fails, for instance. These are routines that the macro branches off to temporarily, in order to accomplish some task or to wait until a certain condition is met. When the subroutine ends, the macro jumps back to where it left off.

Like a routine, a subroutine consists of a label (so the macro can find it), but it also has a return identifier. The return marks the end of the subroutine, and instructs the macro to go back to where it first left off.


A variable is a special holding tank for information, sort of a placeholder. WordPerfect has three types of variables, numbered, named, and internal.

Numbered variables, a hold-over from version 5.0 of WordPerfect, are identified by a single-digit number, from 0 to 9. You can access these numbered variables at any spot within WordPerfect by pressing a number with the [Alt] key. For instance, suppose you've previously assigned the text

Hello there

to variable 4. Press [Alt]-4 and WordPerfect types "Hello there" at the cursor.

You'll have plenty of cause to use variables in more sophisticated programmed macros, but you can also use the feature to create up to 10 more temporary macros (in addition to the one that you can create with the [Enter] key). The limitations of variables is that they can contain numbers and text only, making them best suited for adding boilerplate text. Unless you use more sophisticated programming, you can't code them with commands, cursor movements, or other keyboard functions.

WordPerfect macros also support named variables. These are variables you assign within the macro editor, and are used to "remember" a piece of vital information so that it can be used elsewhere in the macro, or even in another macro.

Internal variables are variables generated by WordPerfect and reflect certain operating characteristics or states. For example, one internal variable keeps track of the current page number; another contains the absolute position of the cursor on the page.


The term expressions, as used in WordPerfect macros, is a programmer's word that means pretty much what it means to the rest of the world. You'll be seeing the word many times throughout this book, so it's a good idea to learn how it relates to macro programming.

An expression is a procedure a WordPerfect macro must follow to complete a task you've given it. Sometimes the expression is a simple variable -- "take the contents of this variable and apply it to that command." Often times, the expression is a little more complex, like take the number already in a variable, and add another one to it.

When you ask a WordPerfect macro to perform some type of calculation or thinking process, you're asking it to evaluate the expression. For example, if the expression reads "1+1," then the macro must first evaluate it (add one and one to make two) before proceeding.

Some more advanced macro expressions may appear exotic, but you'll have plenty of chance to use them. The most common is the evaluating if a statement is TRUE or FALSE (the words TRUE or FALSE are capitalized, to show you we're dealing with logical functions). Here's a good example of a TRUE/FALSE expression that must be evaluated by the macro:

IF variable 1 = 10 THEN QUIT

In reading the expression (which isn't in acceptable macro notation, by the way, but it's close), it reads "IF the contents of variable 1 is equal to 10, then stop." Before proceeding with the remainder of the macro, WordPerfect must pause, take a peek inside variable 1, and apply it to the logical equation. If the result is TRUE, then the macro ends. If it's FALSE (variable 1 has a number other than 10), then something else happens.


A common term in programming circles is the string. A string is simply a sequence of alphabet or number keys. In the context of macros, strings are used in variables. Once stored in a variable, the string can be acted upon by the macro.

For example, if the string is a number, you can multiply it with another number or the numeric contents of another variable. If the string is text, you can compare it with another string to see if the two are the same. The concept of comparing string comes in handy when designing interactive macros. The advanced macros in Part Two of this book rely heavily on comparing strings.

Conditional Statements

You've already learned that macros can be constructed so that they perform certain routines in one instance, and other routines in another. The macro is responding to specific conditions, set either by the user, by the document, by information in the document, or by some other variable.

A conditional statement is a fork in the road with a choice of two directions to take, depending on the response to a simple true/false question. WordPerfect macros provide many ways to create conditional statements, but they all have one thing in common: to activate a certain routine (or path of routines) depending on external data.

Here's an example of a conditional statement. "If it's cold outside, I'll wear my jacket. Otherwise, I'll leave the jacket at home." The statement can be broken down into three segments:

Obviously, this isn't the kind of conditional statement you'll write with WordPerfect macros. But you may design a conditional statement that starts one macro depending on one type of user input, or another macro depending on other types of user input.

All conditional statements have a condition that must be met, and a specified action if the condition is TRUE or FALSE. Not all conditional statements specify an action for both a TRUE or FALSE, but most do.


Akin to the conditional statement is the branch, where the macro has two or more paths to take depending on external criteria. A good example of a branch is a menu selection. Here, you have four choices:

Each of these choices is a branch. Each branch specifies one or more unique routines in the macro. The Edit a Document branch, for example, will not use the same routines as Print a Document, Format a Document, or Quit WordPerfect.


A loop is a routine that is repeating two or more times. A typical loop is a "keyboard scan" where the macro constantly checks the keys you press. If you press the key the loop routine is looking for, the macro breaks out of the loop and continues on with some other routines. If the key isn't the one that the loop is looking for, the routine is restarted again.

Loops are really specialized versions of conditional statements. Instead of stopping to provide a choice of two directions, the macro is designed to continue the loop until a certain condition is met. WordPerfect macros contain many sophisticated ways to construct loops. You'll find loops helpful in tackling the most demanding macro assignments.

Entering Data

The basic WordPerfect macro is merely a recording of a series of keystrokes. But you can also program macros to stop and wait for user input. Once the user has entered the data, the macro uses the information -- be it text, a number, or a single keypress -- to complete its task.

You might pause a macro to allow the user to enter her name, the current date, or some other variable information. Your macro may then use that information to create a mailing label, or to date a series of database entries. Input data can be entered directly into the document, or can be temporarily stored in a variable. The macro can then sample the contents of the variable, and use it in a conditional statement, a branch, or a loop -- or even save it for use later on.

Outputting Data

WordPerfect macros output data in two basic ways:


The commands in WordPerfect's macro programming language is available while in the macro editing window. To access the programming statements while editing a macro, press [Ctrl]-[Page Up]. A pop-up menu appears over the editing box. Use the up and down arrow keys to scroll through the contents of the programming menu. You can quickly shuttle to a particular statement by typing the first couple of characters in its name.

Each statement, such as {DISPLAY ON} and {CHAIN}, is enclosed in brackets. Some statements are followed by one or more arguments. These arguments tell WordPerfect what to do with the statement. For example, the {CHAIN} statement is followed by a macro file name argument. To complete the statement in an actual macro, you'd enter:


WordPerfect uses tilde character as a delimiter. The program knows that the argument is done when it reaches the tilde, and that it should expect text or another programming code to follow.

To enter a programming command (otherwise known as a statement; we'll use the two words interchangeably throughout the book) in the macro editing box, select it and press [Enter]. Note that the text for the argument is not included, only the command itself, and that the command is shown in bold.

You may exit the pop-up menu without making a selection by pressing the [Esc] key. If you press [Ctrl]-[Page Up] or [Esc] again, WordPerfect re-selects the macro command that you last used. This allows you to quickly enter a series of the same statements in the macro editing box.



It's helpful to categorize WordPerfect's macro commands into discrete types. For consistency, we'll retain the categorization that WordPerfect uses in its documentation (and we've added one of our own).

There are nine categories of macro commands:

Note that some commands serve double duty. For example, the {DISPLAY OFF} command is found in both the macro execution control and programming aides categories.

User Interface Commands

The user interface commands allow input from the user and/or display a message on the screen. The user interface commands are:

Sounds a short warning tone.
Allows for single character user input.
Allows for multiple character user input.
Samples the key you just pressed.
Pauses macro execution and allows for keyboard entry.
Displays a message on the screen.
Displays a semi-permanent message on the screen.
Allows for multiple character user input.

Flow Control Commands

Flow control commands redirect macro execution depending on external criteria (such as user input). The flow control commands are:

Prematurely terminates a conditional statement, loop, or macro.
Calls a subroutine.
Establishes one or more branches.
Establishes one or more branches, with each branch executed as a subroutine.
Executes another macro.
Establishes a FALSE condition for an IF statement.
Ends a FOR and FOR EACH loop.
Ends an IF statement.
Ends a WHILE loop.
Establishes a self-contained "counter" loop.
Applies one or more commands or routines to a single variable.
Jumps to a labeled routine.
Establishes an IF conditional statement and what happens when the statement is TRUE.
Checks if a variable is empty (doesn't exist).
Names a routine.
Temporarily executes another macro, then returns to the original macro.
Increments the counter in a FOR, FOR EACH, and WHILE loop.
Provides an alternative response in case the macro is canceled.
Provides an alternative response in case an error occurs during macro execution.
Provides an alternative response in case a search fails during macro execution.
Stops the macro.
Stops all macro execution at the end of a nested macro.
Returns from a nested macro or a subroutine.
Generates a "cancel condition."
Generates an "error condition."
Generates a "not found condition."
Starts a shell macro.
Runs a self-repeating loop until a condition is met.

Macro and Subroutine Termination Commands

The macro and subroutine termination commands end macro execution, or break out of subroutines and continues with the rest of the macro. The macro and subroutine termination commands are:

Prematurely terminates a conditional statement or macro.
Stops the macro.
Stops all macro execution at the end of a nested macro.
Returns from a nested macro or a subroutine.
Generates a "cancel condition."
Generates an "error condition."
Generates a "not found condition"

External Condition Handling Commands

The external condition handling commands specify how a condition that occurs outside the macro is handled. In the case of the RETURN commands, they generate or create the condition. The external condition handling commands are:

Disables the Cancel key.
Enables the Cancel key.
Provides an alternative response in case the macro is canceled.
Provides an alternative response in case an error occurs during macro execution.
Provides an alternative response in case a search fails during macro execution.
Generates a "cancel condition."
Generates an "error condition."
Generates a "not found condition."

Macro Execution Commands

The macro execution commands run a macro.

Starts a new macro.
Temporarily executes another macro, then returns to the original macro.
Starts a Shell macro.

Macro Execution Control Commands

Macro execution commands affect the operation of macros by either controlling the display, macro execution speed, or delay until the next command is executed. The macro execution control commands are:

Turns the display off.
Turns the display on.
Turns menu display off.
Turns menu display on.
Slows down macro execution.
Waits a predetermined time before continuing.

Variable Commands

The variable commands assign values to variables or determines some characteristic or state of a variable. The variable commands are:

Assigns a value to variable.
Displays a message on the screen and assigns the next keypress to a variable.
Checks if a variable is empty.
Counts the number of characters in a variable.
Assigns the next keypress to a variable.
Captures a sub-string of a variable.
Contains any of several internal WordPerfect variables.
Displays a message on the screen and assigns one or more keypresses to a variable.
Displays the contents of variable.

Programming Aid Commands

Programming aid commands help make programming and "debugging" macros easier. The programming aid commands are:

Provides non-executing comment within the macro.
Sounds a short tone (audible feedback).
Slows down macro execution.
Disables {STEP OFF}.
Executes one character or command at a time.

Special Purpose Commands

Some WordPerfect Macro commands defy easy categorization. These extend the usefulness of the macro language and are most often used with other commands, like {ASSIGN} or {IF}.

Translate a key (alphabetic, numeric, symbol, or WordPerfect function) to its numbered equivalent.
Translates a number to its key equivalent.
Echos the last key pressed.
Indicates one or more current operating states of WordPerfect.

Additional Macro Codes

Some useful macro codes are not found in the macro command list. These are:



If you're familiar with BASIC you'll find many of WordPerfect's macro commands are similar in function and syntax. A comparison of the functions may help you to understand how WordPerfect macro commands work.

Macro Command   BASIC Keyword or Code
{;}     	REM
{BELL}      	BEEP  
{CANCEL OFF}   	KEY OFF ([F1] key only)
{CANCEL ON}     KEY ON ([F1] key only)
{CHAR}      	INPUT (single character), INKEY$
{ELSE}      	ELSE
{FOR}   	FOR  
{GO}    	GOTO
{IF}    	IF (THEN implied)
{IF EXISTS}     IF var=""
{KTON}      	STR$    
{LABEL}     	LABEL:, LineNumber
{LEN}   	LEN
{LOOK}      	INKEY$
{MID}   	MID$
{NEST}      	RUN
{NEXT}      	NEXT
{NTOK}      	CHR$
{ON CANCEL}     ON KEY (3B) (ON Cancel key event trap)
{PAUSE}     	INPUT (no message)
{QUIT}      	STOP
{STATE}     	PEEK (specific internal variables only)
{SYSTEM}    	ENVIRON$, PEEK (specific variables only) 
{TEXT}      	INPUT (multiple character)
{WAIT}      	WAIT


The example macros presented in Part Two of this book rely heavily on macro programming commands. You will learn, first hand, how to use the statements in actual macros. As a reference, the following is a summary of all macro statements and what they do.


Used to document a macro; the text before the tilde delimiter is ignored during execution.


{;}This section checks to see if the Enter key is pressed, then
continues on.~ 


Assigns a value to a variable.



Assigns the number 1000 to variable number 1. 

Variables can contain text or whole numbers. When entering fractional numbers, or those with non-numeric characters, WordPerfect treats it as text.


Produces a short tone through the computer's speaker. Used without an argument.


Moves the macro to the end of an IF...ELSE structure, or breaks out of a FOR, FOR EACH, or WHILE loop. If an IF...ELSE structure doesn't exist, it ends the macro. Used without an argument.


{CHAR}1~Enter a number~
{IF}{VAR 1}=1~

This example shows a FOR loop that repeats a total of ten times. With each loop, the macro asks to "Enter a number," and stores the number into variable 1. If variable 1 is equal to 1, then the FOR loop is broken before the count gets to 10. If the numeral 1 is never entered, the loop will end by itself at the 10th excursion.


Calls a subroutine inside the current macro. After the subroutine is finished, the macro returns to the point immediately after the {CALL} statement and continues on. Each {CALL}ed subroutine must end with a {RETURN} statement.



Calls the subroutine that begins with the label "loop."


Inhibits the use of the Cancel key. Used without an argument.


Allows the use of the Cancel key. Used without an argument.


Checks the expression (usually a variable) and compares it against each case number in the argument string. When (and if) the macro finds a match, WordPerfect branches off to the corresponding label. You can use any number of case/label arguments that you wish. Remember to end the {CASE} statement with two tildes -- one tilde is the delimiter for the last label, and the other tilde is the delimiter for the {CASE} instruction.


{CASE}{VAR 1}~

Compares the value variable 1 against cases the numbers 1 and 2. If the value in variable in variable 1 is 1, then the macro jumps to the "end" label. If the value is 2, then the macro jumps to the "start" label.


Same as {CASE}, above, but calls the subroutine identified with the corresponding label. After the subroutine is finished, the macro returns to the {CASE CALL} statement and continues on. Each {CASE CALL}ed subroutine must end with a {RETURN} statement.


Executes the named macro, leaving the current one.



Immediately switches off to a macro named "dolist."


Prompts you with the message and stores the next keystroke you type in the variable indicated. Causes a pause in the macro; the message stays until you press a key.


{CHAR}0~Type Y or N.~

Assigns the next keystroke to variable 0.


Turns the display off during macro execution. Used without an argument.


Turns the display on during macro execution. Used without an argument.


Used with the {IF} and {END IF} statements. Indicates what should happen if the {IF} statement is FALSE. Should the {IF} instruction be TRUE, {ELSE} terminates the IF...ELSE structure (put another way, instructions following {ELSE} are NOT executed when the {IF} instruction is TRUE). See the description of {IF} for an example of how the {ELSE} statement is used. The {ELSE} command can optionally be used with the {CASE} and {CASE CALL} commands. It has the same function with these commands as it does with the {IF} statement.


Ends a FOR or FOR EACH loop. See the {FOR} command (above) for a description of how to use {END FOR}. Used without an argument.


Ends a WHILE loop. See the {WHILE} command (below) for a description of how to use {END WHILE}. Used without an argument.


Ends the IF...ELSE structure. See the description of {IF} for an example of how the {END IF} statement is used.


Repeats a loop the specified number of times. The loop itself normally consists of one or more commands as a repeating routine. This routine is enclosed between the {FOR} command and a terminating {END FOR} command.

The {FOR} command uses four arguments: variable, start, stop, and step. Variable is a unique variable name that will, when the FOR loop is run, contain a number beginning with start and ending with stop. The start argument is often 0 or 1, but it can be any number. The step variable indicates how you want the FOR loop to count, by 1s, 2s, 5s, 10s, etc.

The {NEXT} command is not strictly required when using a FOR loop, but you may wish to include it in any case. The {NEXT} command signals that the repeating loop is finished and that the macro should increment the FOR counter and restart the loop. You can use the {NEXT} command to end the routine before it completes all the steps -- for instance, if a certain {IF} condition is TRUE.



The FOR counter counts from 10 to 100, stepping 10 digits at a time (10, 20, 30, 40, etc.). With each loop, the contents of variable ("10," "20," "30," etc.) is printed in the document.

{FOR EACH}variable~expression1~expression#~~

{FOR EACH} is a unique looping command. It uses a variable as a temporary placeholder and allows you to assign a series of expressions to the variable with each cycle of the loop. When running, the {FOR EACH} command evaluates the expressions and inserts the result into the variable. The "expressions" can be simple numbers, text, calculations, and just about anything else that can be stored in a variable.

Additional codes you add between the {FOR EACH} command and {END FOR} command are repeated with each cycle of the loop. Note: The {FOR EACH} command expects a tilde delimiter after each argument, including all the expressions you use, plus an additional tilde to end the {FOR EACH} command itself. Don't forget this last tilde, or the macro will not function properly. You may wish to format the {FOR EACH} command within the macro as shown in the example. That way, you can readily identify each of the expressions and remember to enter the last tilde.


{FOR EACH}variable~

The {FOR EACH} loop is repeated a total of four times, one for each expression. On the first loop, the expression "2+2" is evaluated, and the result (4) is placed into thevariable "variable." The contents of the variable is then printed in the document, and the loop repeats. With each pass, another expression in the list is evaluated, until all expressions are complete.


Go to the named label inside the current macro. You can go to labels that are in front of or behind the {GO} statement.



Goes to the label identified as "testrun."


If the expression is TRUE, perform the very next command or jump to the point after the {END IF} instruction. If the value is FALSE, go to the command immediately after the {ELSE} instruction, if any.


{IF}{VAR 0}=10~

Example 2:

{IF}{VAR 0}=10~

Both examples do the same thing. If the value in variable number 0 is equal to 10 (true), go to the label named "start." If the value in variable 0 is not equal to 10 (false), quit the macro.

Note that the equal sign is not the only operator you can use with the {IF} statement, although it is the most common. You can also test for not equal to, greater than, less than, and others. See Chapter 5, "Making More of Macros," for more information on WordPerfect's operators.

{IF EXISTS}variable~

If the variable has something in it (text or numbers), then the IF instruction is true. If the variable is empty (undefined), then the IF statement is false. Follow the same logic described above for the {IF} statement.



If variable number 0 has something in it (TRUE), skip to the next instruction after {END IF} (in this example, there is nothing immediately after the {IF EXISTS} statement, so the macro jumps to the end of the IF...ELSE structure). If the variable is empty, quit the macro.


The {INPUT} command displays a message on the screen that remains until the user presses the [Enter] key. The message is then removed. Note that the {INPUT} and {STATUS PROMPT} commands operate inclusively. Messages displayed with either command will erase a message displayed by the other.


{INPUT}This is a sample message~

Displays "This is a sample message" along the bottom of the screen.


{KTON} stands for key-to-number. It translates the value of a key to its ASCII equivalent, as used by WordPerfect. Normally, you'd use the {KTON} command to convert some alphabetic key to its ASCII equivalent, but you can also convert WordPerfect function keys and special characters to their equivalents. The {KTON} key is complemented by the {NTOK} (number-to-key) command.



Prints the number 65 in the document (65 is the ASCII equivalent of the letter A). Chapter 18, "Macro Strategies," includes a key-to-ASCII conversion chart you can refer to when using the {KTON} command.


This command identifies the macro codes that follows with a unique name. It's used with the {GO}, {CALL}, {CASE}, and {CASE CALL} statements. Text or macro commands after the label are executed.


This is the text for the "start" routine.

Identifies the label as "start," and prints the text that follows.

Label names can only be used once in a macro. The names can use any characters and can be any length. To avoid typing errors, however, try to limit label names to one or two short words.


The {LEN} command counts the number of characters in a variable. You can use {LEN} to limit text entry, to determine if a variable contains more characters that it should, or to develop sophisticated macros that "parse" the contents of variables.


{PROMPT}Variable 1 contains {VAR 0} characters.~ 

Assigns the length of variable 1 to variable 0, then displays the message "Variable 1 contains nnnn characters."

For instance, if variable 1 contains the text "this is a test," the result stored in variable 0 is 14 (the number of characters in the string "this is a test"). The message would then read "Variable 1 contains 14 characters."


Scan the keyboard and assign the next keystroke to the variable. If a key isn't pressed, continue on with the macro (the macro doesn't stop). Most often used with a repeating loop to continually check for key presses.



Assigns the next key pressed to variable number 1.


The {MID} command is used to sample, or "return," a portion of the contents of a variable (called a sub-string). The command can be used to return the entire contents of the variable, but in most cases, you'll use it to return only one or two characters. The variable argument is the variable that contains the string you want to sample. The offset is the number of characters you want to start counting from. Character 0 is the beginning of the string. The count argument is the number of characters from the string you want to return.



Returns the first two characters in the variable "string."

The {MID} command returns nothing if you try to extract a sub-string that goes beyond the bounds of the variable. For example, if the string in the variable is only five characters long, you try to extract characters starting from the eight character position, the {MID} command returns nothing.


Nest the named macro. After the named macro finishes, WordPerfect returns to the original one and continues execution where it left off.



Temporarily branches off to a macro named "dolist."


Increments the counter in a FOR, FOR EACH, or WHILE loop, and restart the loop. Used without an argument.


{NTOK} stands for number-to-key. It translates an ASCII number to its key equivalent, as used by WordPerfect. Normally, you'd use the {NTOK} command to generate keys from numeric input -- print the alphabet from A to Z using a incrementing loop counter, for instance. The {NTOK} key is complemented by the {KTON} (key-to-number) command.



Prints the letter A in the document (65 is the ASCII equivalent of the letter A).

Chapter 18, "Macro Strategies," includes a key-to-ASCII conversion chart you can refer to when using the {NTOK} command.

{ON CANCEL}command~

If the [Cancel] key is pressed, or a macro encounters a cancel from within itself or in a nested macro, this statement indicates what should happen next. The default instruction, when no {ON CANCEL} statement is provided, is RETURN CANCEL.



When Cancel is encountered, the {RESTART} instruction terminates all macro execution at the end of current subroutine or nested macro.

Only a limited number of programming instructions are allowed with {ON CANCEL}:

IF no instruction is included with the {ON CANCEL} statement, it is ignored and the macro continues. The {GO} and {CALL} statements require arguments of their own, which need a tilde as a delimiter. When used with these statements, you must provide two tildes at the end of the {ON CANCEL} instruction, such as {ON CANCEL}{GO}label~~.

Note: The {ON CANCEL} command is ignored if you've preceded the code with {CANCEL OFF} command. {CANCEL OFF} cancels the action of the [Cancel] key, as well as internally generated cancel conditions. If you want to use {ON CANCEL} be sure to enable cancel (use the {CANCEL ON} command).

{ON ERROR}command~

Tells WordPerfect what to do if an error is detected during macro execution. The error can occur in the macro, in WordPerfect, or in DOS. The default command, when no {ON ERROR} statement is included, is RETURN ERROR. The syntax and use is the same as with {ON CANCEL}.

{ON NOT FOUND}command~

Tells WordPerfect what to do if a search ends with a *not found* message. The default command, when no {ON NOT FOUND} statement is included, is RETURN NOT FOUND. The syntax and use is the same as {ON CANCEL}.


Echos the key you last typed. The value of key is the un-reassigned version. That is, if you have reassigned the [Esc] key to something else, WordPerfect still echos back the original definition for the [Esc] key. The {ORIGINAL KEY} statement is used without an argument.


Pauses macro execution. Press [Enter] to restart. Used without an argument.


Displays the message in the status line. The {PROMPT} statement must be nested in a loop or pause or the message will only flash on the screen and disappear as the macro continues execution. You can also keep the prompt message on the screen during the execution of a long macro by turning the display off. However, you must be sure to move the prompt message up a line, as detailed in the following chapter, or the *waiting* message that appears during macro execution will erase the prompt massage.


{PROMPT}When you are ready, press Enter and the macro will begin.~ 



Terminates all macro execution. Used without an argument.


Stops all macro execution (including nested macros) at the end of the current subroutine or nested macro. Used without an argument.


Used with the {CALL} and {CASE CALL} instructions. Marks the end of a subroutine. When {RETURN} is encountered, the macro jumps back to the point immediately after the {CALL} or {CASE CALL} instruction. When {RETURN} is placed by itself without a subroutine, it terminates the macro (used most often in this application to return from a nested macro). The {RETURN} statement is used without an argument.


Return from a subroutine or nested macro and indicate a cancel condition to the main routine or macro. Used without an argument.


Return from the subroutine or nested macro and indicate an error condition to the main routine or macro. Used without an argument.


Return from the subroutine or nested macro and indicate an error condition to the main routine or macro. Used without an argument.

{SHELL MACRO}shell_macro~

This command lets you execute a Shell macro from a WordPerfect macro. You must have the Library program (which contains the Shell program) to use this command. Conversely, you can start WordPerfect 5.1 macros from within Shell (requires Shell version 2.1 or later). Use the {SHELL MACRO} to quickly transfer between WordPerfect Corp. programs, or to automate DOS or Library tasks.



Starts the Shell macro named "shell."

{SPEED}1/100th secs~

Slow down macro execution by the indicated amount, or wait the amount of time indicated between each key input.



Slows down macro execution by an extra 50/100ths (equal to 5/10 or 1/2) of a second.


Returns a number that represents the current operating state of WordPerfect. The number is in binary form and adds together if more than one state applies.

State Number Condition
1 Document 1 current
2 Document 2 current
4 Main editing screen
8 Editing structure other than main screen
16 Macro definition active
32 Macro execution active (always on)
64 Merge active
128 Block active
256 Typeover active
512 Reveal Codes display active
1024 Yes/no prompt active
2048 Cursor currently inside table


Assuming assuming document 1, block active, and typeover active


Prints the number 417 (1+32+128+256).

You can check for specific conditions using the AND logical operator, expressed as &. For example, {STATE}&256 checks to see if typeover is active.

The {STATE} instruction is not used with an argument, but is often coupled with other programming statements. You can combine the {STATE} instruction with {ASSIGN}, {IF}, {CASE}, and {CASE CALL} statements. The instruction {ASSIGN}1~{STATE}~ assigns the {STATE} number to variable number 1.


The {STATUS PROMPT} command prints a semi-permanent message on the screen. The message stays until you quit WordPerfect, or write another message using the {STATUS PROMPT} or {INPUT} commands (in addition, messages with the {CHAR}, {PAUSE}, and {TEXT} commands temporarily over-write the {STATUS PROMPT} display.


Turns stepping off. Used without an argument.


Slows down macro execution to one step at a time. You manually advance the macro by pressing a key. You can cancel the macro at any time by pressing [F1]. During stepping, the contents of the macro appears in the status line. Text is shown normally but programming statements are given command numbers. These numbers are detailed in Chapter 20. {STEP ON} is used without an argument.


The {SYSTEM} command is an internal variable that reports any of several attributes and conditions of WordPerfect and the document currently open. For example, you can determine the current page page number of the document with:



Chapter 5, "Making More of Macros," presents a complete list of {SYSTEM} variables and what they do.


Prompts you with the message and stores your keystrokes in the variable. The instruction ends when you press [Enter]. Each variable can hold a maximum of about 120 characters.


{TEXT}7~Enter name and address.~

Displays "Enter name and address" and stores the answer in variable number 7.


The {VARIABLE} command retrieves the contents of the named variable. You can use the {VARIABLE} command to print the contents of a variable in the document, assign one variable to another, and so forth. In the following examples, assume the text "WordPerfect 5.1 Macros and Templates" has been assigned to the variable "text."



Prints "WordPerfect 5.1 Macros and Templates" in the document.



Assigns the contents of variable "text" to a new variable, "new_var." Now, "new_var" also contains the text, "WordPerfect 5.1 Macros and Templates."

{WAIT}1/10th secs~

Wait the specified period of time before continuing.



Wait 1.5 seconds (15/10ths) then continue.


The {WHILE} command sets up a unique WHILE loop that causes the macro to repeat a given set of instructions until a certain condition is met. {WHILE} is a simpler way of producing a keyboard loop where is a routine is to be repeated until a certain key is pressed.


{WHILE} "{VAR 1}"~!="{Enter}"~
	{VAR 1}

This example repeatedly tests the keys you press and looks for the [Enter] key. If you don't press the [Enter] key (variable 1 does not equal {Enter}), the routine is repeated. When the [Enter]key is struck, the WHILE loop is terminated and the macro continues.



The commands list in the pop-up macro editor window includes several other items that aren't really true "commands." These items, for moving the cursor to the next or previous paragraph, or to move the cursor within columns and tables, are duplicated with [Ctrl] and [Alt] keyboard equivalents. But these equivalents only work with enhanced keyboards (such as the 101-key keyboards found on the IBM PS/2 and similar models). If your keyboard can't generate these codes you can still access them in the macro editor.

Common keyboard codes found in macros are {Enter}, {Tab}, {ALTx}, and {VAR x}. These are not found in the pop-up commands list, but are entered directly from the keyboard. Here's what they do and how to enter them:


The {Enter} code within the macro indicates you want a hard return in the macro, or else want to simulate pressing the [Enter] key while in a menu, list, etc. Normally, pressing the [Enter]key inserts a blank line only. To include the {Enter} code in a macro, press [Ctrl]-V first, then press [Enter].


The {Tab} key code within the macro indicates you want to tab some text to the next tab stop. Normally, pressing the [Tab] key inserts a empty spaces in a line, and is most often used to "format" the macro code for readability. To include the {Tab} code in a macro, press [Ctrl]-V first, then press [Tab].


The {ALT x} code ("x" is a letter of the alphabet) commands the macro to either nest to or chain to an [Alt]-key macro. The {ALTx} code is the same as:


when the {ALTx} code is not at the end of the macro.


when the {ALTx} code is at the end of the macro.

To enter the {ALTx} code, first press [Ctrl]-V, then press the [Alt] key and a letter key. For example, to enter {ALTZ}, press [Ctrl]-V, [Alt]-Z.

{VAR x}

The {VAR x} code ("x" is a number from 0 to 9} indicates a numbered variable. You'll use the {VAR x} code to print the contents of a variable in a document, to assign one variable to another, and for many other tasks.

To enter the {VAR x} code, first press [Ctrl]-V, then press the [Alt] key and a number key (use the numbers along the top of the keyboard, not the ones in the numeric keypad). For example, to enter {VAR 1}, press [Ctrl]-V, [Alt]-1.



You've learned the basics of WordPerfect macro programming, and about the various commands used to produce sophisticated macros. You also learned:


 Top Contents

WordPerfect 5.1 Macros and Templates
Electronic Edition
Copyright 1990, 1997, Gordon McComb.  All Rights Reserved.
First published by Bantam Electronic Publishing, 1990.