SAS® Macros

A macro is simply stored text that is identified by a name. As we saw previously, a macro variable is simply text stored as a special variable. A SAS macro is an extension of macro variables. A macro stores text, but this text may be entire SAS programs, pieces of programs, pieces of a datastep or procedure. In addition you can pass arguments or parameters to the macro when you call it. Macros can be very specific or very dynamic, depending on their intended use and programmer. In general, macros are very useful for generating repetitive pieces of code and for conditionally executing code.

Defining a Macro
Each macro definition begins with a %MACRO statement and ends with a %MEND statement.

Syntax

%MACRO macroname;
   macro text
%MEND macroname;
%MACRO macroname;
This statement begins the macro definition and assigns a name to the macro.
macro text
This can contain simply text, SAS statements or datasteps or proc steps, macro variables, functions or statements, or any combination of the above.
%MEND macroname;
This statement ends the macro definition. Including the macroname after the %MEND is not required syntax, but is very helpful in documenting your macro, especially if you have more than one macro defined in a program.

Submitting a macro definition compiles the macro, but the macro is not executed until a macro call is submitted. Since the macro is compiled before it is executed, it only needs to be submitted once, or after changes. Because it is only submitted and compiled once, it is more efficient to use the macro facility and repeatedly submit a macro call, than to repeatedly submit the entire code outside a macro.


Example

%MACRO SortID;

  PROC SORT DATA=_LAST_;
    BY id;
  RUN;

%MEND SortId;

Calling a Macro

To call a defined macro, use a macro call statement. A macro call statement is simply the name of the defined macro, starting with a percent symbol (%). In most cases you SHOULD NOT use a semi-colon at the end of the macro call statement. Macro call statements can appear anywhere in a program, where appropriate. Imagine inserting the macro into the space where you are calling the macro, if it does not violate any syntatical rules, then it is most likely appropriate.

Syntax

%macroname


Example to call above defined macro

DATA data1;
  set classlist;

%SortId

PROC PRINT data=data1;
  BY id;
RUN;

This example will read a dataset, sort it by a variable id and then print it.

Conditional Execution
Macros with Parameters
Macro Options and other statements