A macro in SAS is a text-substitution tool that generates and executes SAS code before your program runs. It is part of the SAS Macro Language, a separate programming facility built into Base SAS. Macros let you write reusable code, automate repetitive tasks, and make your programs dynamic by changing values, variable names, or entire code blocks based on parameters. The macro language is not a statistical procedure; it works behind the scenes to write the actual SAS statements that the SAS compiler then processes.
Background: Why SAS Has Macros
The SAS macro facility was introduced in the early days of SAS (around SAS 82, the 1982 release) to address a common pain point: analysts were writing nearly identical code for every report or dataset, changing only a date or a variable name. The developers added a preprocessing layer that scans your code for macro triggers, substitutes text, and passes the expanded code to the SAS compiler. This design mirrors macro features in older languages like C or assembler, but SAS’s version is tightly integrated with the DATA step and procedures.
Today, macros are a core part of SAS programming. They are used in everything from simple date-stamping of output to building entire report-generating systems. Understanding macros is often considered a rite of passage for SAS programmers because they separate beginner-level code from professional, maintainable code.
How Macros Work: Compilation and Execution
When you submit a SAS program, SAS first scans it for macro triggers. These triggers are either a percent sign followed by a macro name (like %LET or %MACRO) or an ampersand followed by a macro variable name (like &var). The macro facility resolves these triggers by replacing them with the text you defined. This happens before the DATA step or proc runs, so the resulting code is what actually executes.
There are two main components:
- Macro variables – named containers for text. You create them with
%LETor with theSYMPUTroutine in a DATA step. Example:%LET cutoff_date = 31DEC2023;then use&cutoff_datein your code. - Macro programs – blocks of reusable code defined with
%MACROand%MEND. They can accept parameters and contain conditional logic with%IF/%THEN.
For example, a simple macro to run a frequency table on any variable:
%macro freq(var);
proc freq data=sashelp.class;
tables &var;
run;
%mend freq;
%freq(Sex);
%freq(Age);
When you call %freq(Sex), SAS expands it to proc freq data=sashelp.class; tables Sex; run;. The macro processor handles the expansion, then the compiler runs the resulting code.
How to Write and Use Macros
Creating a macro is straightforward. Start with %MACRO, give it a name, optionally list parameters, then write the SAS code you want to generate. End with %MEND and the macro name. Here are the key steps:
- Define the macro with
%MACRO name(parameters);. - Write the SAS statements, using
¶mto insert parameter values. - Close with
%MEND name;. - Call it with
%name(values);.
Parameters can have default values: %macro freq(var, data=sashelp.class); – then you can call %freq(Sex) or %freq(Sex, data=yourdata).
Macro variables can also be created dynamically. For instance, to store the number of observations in a dataset:
data _null_;
set sashelp.class nobs=n;
call symput('numobs', put(n, 8.));
stop;
run;
%put &numobs;
This stores the count in &numobs for later use. The %PUT statement writes to the log, which is a handy way to debug.
Common Problems and Misconceptions
Beginners often confuse macro variables with regular SAS variables. A macro variable is not part of any dataset; it exists only during the session and holds text, not a data type. Another common issue is quoting. Macro code is text, so quotes can behave differently. For example, %let var = 'Hello'; stores the quotes as part of the value. To strip them, you need the %STR or %BQUOTE functions.
Macro timing also trips people up. Because macro resolution happens before compilation, you cannot use a macro variable to conditionally execute a DATA step based on a value that is only known at run time. For that, you need CALL SYMPUT combined with %IF in an open code, or you need to use SYMPUT with %SYSFUNC to evaluate at macro time.
One frequent misconception is that macros are like functions in other languages. They are not. They do not return values; they generate text. If you want a function-like behavior, you can use %SYSFUNC to call DATA step functions from macro code, but the macro itself always produces code.
Macros vs. Other SAS Features
It helps to see where macros fit relative to other SAS tools:
- DATA step – processes data row by row; macros operate on text before any data is read.
- PROC SQL – can generate dynamic code using
SELECT INTOto create macro variables, but the SQL itself is not a macro processor. - ODS – controls output formatting; macros often wrap ODS statements to produce multiple reports.
- User-defined formats – map values to labels; macros can create a set of formats but formats themselves are not macros.
In practice, you combine them: a macro might contain a PROC SQL step that creates macro variables, then a DATA step that uses them, then a PROC REPORT. The macro simply orchestrates the code.
Best Practices for Writing Macros
Good macro design makes your code easier to debug and maintain. Here are practical guidelines:
- Use meaningful names and avoid generic ones like
%m. - Keep macros small and focused; a macro that does too many things is hard to test.
- Add comments inside the macro to explain what it does.
- Use
%PUTstatements to log key values for debugging. - Be careful with global and local macro variables. Variables created inside a macro are local by default unless you use
%GLOBAL. - Test with a small dataset before running on big data.
Also, avoid using macros for everything. If a simple %LET or a loop in a DATA step works, use that. Overusing macros can make code cryptic and slow to run because the macro processor adds overhead.
Frequently Asked Questions
What is the difference between a macro variable and a regular variable? A regular variable is a column in a SAS dataset, holding values for each observation. A macro variable is a single piece of text stored in memory, not tied to any dataset. You use a regular variable in DATA step calculations; you use a macro variable to substitute text into your code before it runs.
Can I use a macro to loop through a list of values? Yes. You can use %DO loops inside a macro. For example, %do i = 1 %to 5; will generate code five times. You can also loop through a list by using %SCAN to extract each item. This is a common way to run the same analysis on multiple variables or datasets.
Why do I see %let and & in SAS code? %LET is the statement that creates or updates a macro variable. The ampersand (&) is the trigger that tells SAS to resolve the macro variable’s value. You see them together because you first define the variable, then you reference it with the ampersand.
Are macros case-sensitive? No, SAS is not case-sensitive for macro names, variable names, or keywords. %LET and %let are the same. However, the values you store in macro variables are case-sensitive, so 'ABC' is different from 'abc' if you use them in comparisons.
Can I write a macro that creates a dataset? Absolutely. A macro can contain any SAS statements, including DATA steps and PROC steps. For example, you could write a macro that takes a dataset name and a variable, then creates a summary dataset. The macro just generates the code that creates the dataset when it runs.
Is there a way to see what a macro expands to? Yes. Use the %PUT statement with _ALL_ or list the macro variable names. For example, %put _user_; shows all user-defined macro variables and their values. You can also use the SYMBOLGEN system option (options symbolgen;) to see each resolution in the log, which helps debug.
Conclusion
Macros are a powerful and essential part of SAS programming. They let you write flexible, reusable code that adapts to different inputs. The key is to remember that a macro is just a text generator – it writes SAS code for you. Once you grasp that, you can start using macros to automate reports, streamline analyses, and reduce errors from copy-paste. Start with simple %LET statements, then move to %MACRO blocks. With practice, you’ll find macros indispensable for any serious SAS work.
Related
- Battery Ah Calculation: How to Estimate Runtime
- Sample Balance Sheet Template: Free Format & Example
- How to Get i on Casio Calculator (Imaginary Unit)
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- VBA Add Leading Zeros to a String Without Losing TextIn VBA, add leading zeros to a string by placing the required number of zeros before its existing…
- VBA InputBox Example: Get and Validate User InputA VBA InputBox example can ask for a value, store the reply, and use it in a macro.…
- Excel VBA Current Date: Date, Now, Formatting, and ExamplesIn Excel VBA, use Date to get the computer’s current date, without a time; use Now to get…
- Excel VBA Macro Logo: What It Is & How to Use ItAn Excel VBA macro logo is not a built-in feature—Excel does not provide a dedicated “macro logo” tool.…
- Excel VBA: How to Assign a Keyboard Shortcut to a MacroTo assign a keyboard shortcut in Excel for Microsoft 365 on Windows, press Alt+F8, select the macro, choose…
- Excel VBA Open File Dialog: A Practical GuideTo show an Open dialog in Excel VBA, use Application.FileDialog(msoFileDialogFilePicker), set its title and filters, and call .Show.…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.