SASŪ Macro Variables

SAS Macro variables can be defined and used anywhere in a SAS program, except in data lines (raw data). They are independent of a SAS dataset. Macro variables contain a single character value that remains constant until it is explicitly changed.

To define a macro variable, use the %LET statement.

Syntax

%LET macrovar = value;
macrovar is the name of the macro variable, under the limits of the regular SAS naming conventions. value is any string or macro expression.

The value is stored as a character and quotations are not needed. Any characters between the equal symbol (=) and the semi-colon (;) are considered the value of the macro variable. Leading and trailing spaces are removed.

Math expression are not evaluated unless additional macro functions are used.

A macro variables part of the macro expression is resolved (converted to its text value) before being assigned to the new macro variable.



To use a macro variable, precede the macro variable name with an ampersand (&).

Examples

%LET first = Ed;
%LET last = Jones;
%LET name = &first &last;



%LET idnum = 123-45-6789;

 PROC PRINT DATA=data1;
   WHERE id = &idnum;
 RUN;



SAS has a set of macro variables that are created whenever SAS starts. These macro variables are available to be used in your programs. They include:



Combining Macro Variables with Text

Macro variables can be appended to the end of text or variable names by simply adding the macro variable name, including the ampersand, to the end of the text.

varname&macrovar

Macro variables can also be placed at the beginning of text or variable names by joining the macro variable and text wth a decimal point, to tell SAS where the text begins.

&macrovar.text

If the macrovar is a libref and you want to use it when referring to a permanent dataset name, you must use two decimal points instead of one to join the two together.

&libref..datafile

Similarly macro variables can be joined together.

Examples:

%LET yr = 1980;
%LET mth = 12;

DATA Y&yr.M&mth;
  SET in.datafile;
  WHERE MONTH(datevar) = &mth AND YEAR(datevar) = &yr;
RUN;


DATA Y1980M12;
  SET in.datafile;
  WHERE MONTH(datevar) = 12 AND YEAR(datevar) = 1980;
RUN;


Macro Functions
Macro Quoting
Macro Call Subroutines