A SAS macro is a stored block of code that you write once and reuse, and you create one by wrapping your code between %macro name; and %mend;, saving it, and calling it with %name. The simplest useful pattern is a macro that takes parameters, so the same code runs on different variables or data sets without editing. This guide builds one from scratch, explains how macro variables and macro functions fit together, and shows the mistakes that trip up almost everyone the first time.
What You'll Need
- A SAS installation with a Base SAS license - SAS Studio, SAS Enterprise Guide, or the display manager (Base SAS windowing environment) all work. Macros are a Base SAS feature, not an add-on.
- A data set to practice on. SAS ships with
SASHELP.CLASSandSASHELP.CARS, which are perfect for this - no import needed. - Access to a library you can write to, such as
WORK, which exists in every session and is cleared when you exit. - The habit of reading the log. Macro errors are reported there, not on screen, and the log is where
MPRINTandMLOGICoutput appears.
Step-by-Step
- Understand the two pieces before writing anything. A macro definition (
%macro ... %mend) is code that only compiles when you submit it. A macro call (%myname) executes the compiled definition. If you submit%mynamewithout having submitted the definition in that session, SAS reports that the macro does not exist. Definitions live in the session until you close it, so in practice you keep them in a program you run first. - Write the plain SAS code first, without a macro. For example, a PROC MEANS that produces a summary for one variable:
proc means data=sashelp.class n mean std min max;Get it working exactly as you want it. Macros do not fix broken code - they wrap it. Debugging plain SAS first is far easier than debugging macro-generated SAS.
var age;
run; - Wrap the working code in a macro definition. Add the shell around it and give it a name of eight characters or fewer:
%macro summ;Note there is no semicolon after
proc means data=sashelp.class n mean std min max;
var age;
run;
%mend summ;%mendrequired, and%mendmay optionally repeat the macro name. Inside the definition, do not add semicolons after%macrostatements that are not meant to execute. - Add a parameter so the macro is reusable. Parameters are declared in the
%macrostatement, separated by commas:%macro summ(dsn=, var=);The ampersand resolves a macro variable.
proc means data=&dsn n mean std min max;
var &var;
run;
%mend summ;&dsnis replaced with whatever value the caller passes before SAS sees the PROC MEANS. - Call the macro with keyword arguments. Submit
%summ(dsn=sashelp.cars, var=mpg_city)and then a second call such as%summ(dsn=sashelp.class, var=height). Two reports from one definition - that is the whole point. - Turn on the debugging options while you learn. Put
options mprint mlogic symbolgen;near the top of your program.MPRINTprints the SAS code the macro actually generated,MLOGICtraces macro execution and parameter values, andSYMBOLGENshows each macro variable resolved to its value. Read these in the log. Turn them off withoptions nomprint nomlogic nosymbolgen;once things work, because they clutter large logs. - Add a check so bad input fails clearly. A missing parameter is the most common cause of confusing errors, so validate early:
%if %length(&var) = 0 %then %do;The
%put ERROR: var= is required;
%return;
%end;%returnexits the macro cleanly. Doing this turns a cryptic syntax error deep in a PROC step into a plain message at the top. - Generate a name with macro logic when you need one. A common second pattern is a loop that creates data sets with numbered names.
%do i = 1 %to 3; ... data part&i; ... %end;produces PART1, PART2, PART3. Use%do %whileor%do %untilwhen the end point is not known in advance. - Know when you need a macro versus a macro variable. If you only need to substitute a text value once, a
%letis enough:%let yr = 2024;then reference&yr. Reach for a full macro only when you need conditional logic, loops, or repeated blocks that take parameters. - Store the definition and call it again later. Save the definition in a
.sasfile and%includeit at the top of future programs, or compile it withoptions sasautos=pointing at a folder of macro files so SAS finds definitions automatically. Either way the definition must be submitted before the call in the same session.
Common Mistakes
- Mixing up
&and%.&resolves a macro variable (&var);%invokes a macro (%summ). Swapping them gives errors like "Apparent symbolic reference VAR not resolved." - Leaving a stray semicolon after
%if ... %then. A semicolon there often becomes the entire body of the%thenbranch, so nothing executes and no error appears. Use%do ... %endblocks when the branch has more than one statement. - Forgetting that macro variables are text.
%let n = 10;stores the characters "10". Arithmetic in macro logic needs%evalor%sysevalf, and comparisons of numbers behave oddly otherwise. - Quoting values that should not be quoted. Macro quoting functions such as
%strand%quoteare needed for special characters, but overusing them prevents resolution. Insert them only where a comma, semicolon, or parenthesis is causing trouble. - Using reserved names. Avoid naming a macro the same as a SAS statement or procedure - a macro called
PRINTorMEANScan shadow the real one and produce baffling results. - Assuming the data step is needed for everything. Macro code runs before SAS executes your data step; a macro statement inside open code is resolved first and cannot read data values. To act on values from a table, use
CALL SYMPUTXinside a data step orPROC SQL INTO :first.
Tips
- Indent the code inside
%macroso it is clear where the macro ends - it also makesMPRINToutput easier to scan. - Write
%put _user_;to list all user-defined macro variables and their current values. It is the fastest way to see why a value is not resolving. - Put a short comment block with usage examples directly above each
%macrostatement. Six months later you will not remember whatdsnandvarwere meant to be. - Learn
%upcase,%substr, and%scanearly - they handle most string manipulation you will need. - Keep one macro per file when you use
sasautos; SAS looks for a file matching the macro name, so bundles of macros in one file will not be found automatically. - Test with a tiny data set before running on a large one. A macro that works on three rows and fails on three million wastes far more time to diagnose.
Troubleshooting
If SAS says "Macro SUMM not resolved" or "Apparent invocation of macro SUMM not resolved," the definition was never compiled in this session. Submit the %macro ... %mend block first, and check the matching %mend was actually included - a missing %mend leaves SAS waiting for more input, shown by the cursor alone on a line with no log message.
If the log shows "Apparent symbolic reference VAR not resolved" or a note that a macro variable has no value, the value was never assigned or was assigned in a different scope. A %let inside a macro definition is local by default and disappears when the macro ends; use %global when you intend a value to survive afterwards. %put _all_; lists every macro variable currently defined and shows which are global and which are local.
If the macro runs with no error but produces the wrong report, turn on MPRINT and look at the generated SAS. Almost always a parameter arrived empty, arrived with an unexpected value, or a comparison in %if was evaluated as text. Compare the generated code to the plain code you had working in step two.
If output appears twice or the wrong data set is used, look for a stray semicolon, a duplicated call, or a macro variable left over from an earlier run. Restarting the session clears leftover macro variables; that is often faster than hunting for the cause.
Frequently Asked Questions
What is the difference between a macro and a macro variable?
A macro variable is a named text value referenced with &; a macro is a block of code invoked with % that can take parameters and use conditional logic and loops. A macro usually contains and creates macro variables.
Do I need a separate license for SAS macros?
No. The macro facility is part of Base SAS and is available in any SAS session without extra licensing. Third-party macro libraries may have their own terms.
Can a macro return a value?
Not directly, because macros generate code rather than compute results. The usual pattern is to have the macro assign a macro variable that the calling code then references.
Can I debug a macro without rewriting it?
Yes. MPRINT shows the generated SAS, MLOGIC traces execution, and SYMBOLGEN shows resolved values. Together they usually reveal the problem in the log without changing the macro.
Why does my macro work in one program but not another?
Macro definitions last only for the session and are not stored in data sets. The program that fails needs the definition submitted, typically via %include or sasautos, before the call.
Can macros read values from a data set?
Not directly. Macro statements run before a data step executes, so read values into macro variables first with CALL SYMPUTX or PROC SQL INTO :, then use those variables.