SAS Macro Language: Automating Repetitive Code
The SAS Macro Language is a code generation tool that resolves before SAS code is compiled and executed. Mastering macros transforms you from someone who writes SAS programs to someone who writes programs that write SAS programs — dramatically increasing productivity and code quality.
Macro Variables
A macro variable stores text that is substituted into your SAS code wherever referenced. Define with %LET: %LET dataset = mydata.employees;. Reference with an ampersand: PROC PRINT DATA=&dataset; RUN;. This resolves to PROC PRINT DATA=mydata.employees; RUN; before execution. Macro variables created with %LET are global by default; those created inside a macro definition are local to that macro.
The %SYSFUNC macro function executes SAS functions within macro code: %LET today = %SYSFUNC(TODAY(), DATE9.); stores today's date as text in the macro variable. SYMGET and SYMPUT move values between macro variables and DATA step variables.
OPTIONS MPRINT MLOGIC SYMBOLGEN; before running macro code. SYMBOLGEN shows macro variable resolution, MPRINT shows the generated SAS code, and MLOGIC shows macro logic execution. Turn them off afterward with OPTIONS NOMPRINT NOMLOGIC NOSYMBOLGEN; to reduce log clutter in production.
Macro Programs
A macro program is defined with %MACRO and %MEND and can accept parameters: %MACRO summary(data=, var=); PROC MEANS DATA=&data; VAR &var; RUN; %MEND summary;. Called with: %summary(data=mydata.employees, var=salary);. Parameters can have defaults, making them optional when called.
Macro Conditional Logic and Loops
%IF-%THEN-%ELSE provides conditional macro execution. %DO-%END creates macro loops. A common pattern processes a list of variables: %DO i = 1 %TO &nvars; %LET var = %SCAN(&varlist, &i); ...process &var... %END;. Combined with PROC SQL INTO to build macro variable lists from data, this pattern enables dynamic code generation that adapts to changing data structures.
Calling Macros from Autocall Libraries
SAS includes an autocall macro facility that automatically locates and compiles macros stored in designated folders when called. Define with SASAUTOS= in the OPTIONS statement. This enables building libraries of reusable macros that can be shared across programs and analysts without copy-pasting code — essential for team-based analytical environments.
Read our final article on ODS for report generation, or return to our tutorials for hands-on macro exercises.