SAS Macros

SAS supports a macro feature. For more options for extending and programming in SAS (or related software), see this crosswalk of programming features.


Text Substitution

Built-in Macros

There are several built-in macros including %sysdate (system date as `DATE7`), or %systime (system time as `TIME5`).

Custom Macros

A macro can be defined as:

%let LABEL = VALUE;

These macros are referenced using &LABEL.

%let mon       = 1;
%let curr_yr   = %sysfunc(year("&sysdate"d));
%let mon_title = %sysfunc(mdy(&mon,1,&curr_yr), monname9.);

Note: %sysfunc cannot take nested functions, but can take nested %sysfunc calls.

Program-Set Macros

A macro can also be set by symputx calls. This enables programmatic creation of macros, for example to store aggregated values from a data step.

data _NULL_;
  set LIBREF.TABLE end=lastobs;
  retain sum_my_var 0;
  sum_my_var = sum_my_var + my_var;
  if lastobs then call symputx('sum_of_my_var', put(sum_my_var, dollar10.2));
run;
proc means data=LIBREF.TABLE;
  title "Allocation of &sum_of_my_var"
run;

Note: symputx and symput are very similar. The former is silent (i.e., does not log) and trims leading spaces when converting a value into character data (which all macros must be reduced into.


Looping

It is possible to iterate over ranges using %do LABEL=START %to END. The loop value is accessed by &LABEL.

%macro mymacro;
  %do year=2000 %to 2020;
    proc means data=LIBREF.data_from_&year;
      title "Data from &year";
    run;
  %end;
%mend mymacro;

%mymacro;


Conditional Processing

%macro mymacro;
  %if %month=12 %then %do;
    proc means data=LIBREF.TABLE;
      title "Year-end Summary";
    run;
  %end;
%mend;

%mymacro;


CategoryRicottone