More Advanced Macro Techniques

Generating Repetitive Pieces of Text Using %DO Loops

Conditionally Generating SAS Code presents a %DO-%END group of statements to conditionally execute several SAS statements. To generate repetitive pieces of text, use an iterative %DO loop. For example, the following macro, NAMES, uses an iterative %DO loop to create a series of names to be used in a DATA statement:
%macro names(name= ,number= );
   %do n=1 %to &number;
      &name&n
   %end;
%mend names;
The macro NAMES creates a series of names by concatenating the value of the parameter NAME and the value of the macro variable N. You supply the stopping value for N as the value of the parameter NUMBER, as in the following DATA statement:
data %names(name=dsn,number=5);
Submitting this statement produces the following complete DATA statement:
data dsn1 dsn2 dsn3 dsn4 dsn5;
Note: You can also execute a %DO loop conditionally with %DO %WHILE and %DO %UNTIL statements. For more information, see %DO %WHILE Statement and %DO %UNTIL Statement.

Generating a Suffix for a Macro Variable Reference

Suppose that, when you generate a numbered series of names, you always want to put the letter X between the prefix and the number. The macro NAMESX inserts an X after the prefix you supply:
%macro namesx(name=,number=);
   %do n=1 %to &number;
      &name.x&n
   %end;
%mend namesx;
The period is a delimiter at the end of the reference &NAME. The macro processor uses the delimiter to distinguish the reference &NAME followed by the letter X from the reference &NAMEX. Here is an example of calling the macro NAMESX in a DATA statement:
data %namesx(name=dsn,number=3);
Submitting this statement produces the following statement:
data dsnx1 dsnx2 dsnx3;
See Macro Variables for more information about using a period as a delimiter in a macro variable reference.