To type a macro in SAS, you write the %MACRO statement followed by the macro name, then the macro body (SAS statements or macro language), and end with %MEND. For example, %macro mymacro; proc print data=sashelp.class; run; %mend mymacro; defines a macro; you then invoke it by typing %mymacro; on a new line. But that’s just the surface—here’s the full picture of how macros work, when to use them, and the pitfalls that trip up beginners.
What a SAS Macro Actually Is
A SAS macro is a piece of text that the macro processor generates before SAS compiles your program. It’s not a runtime function like in Python or R; it’s a text-substitution system. When you write %macro, you’re telling SAS to store a snippet of code. When you later call that macro by name with a percent sign, SAS replaces the call with the stored text and then runs it as if you had typed it directly.
This distinction matters: macros don’t execute at data-step runtime. They execute during the compilation phase. So a macro can’t, for example, loop over rows of a dataset as a data step would. Instead, it can generate many data steps or procedures based on parameters you pass.
Basic Syntax and a Simple Example
Here’s the minimal structure:
%macro macro_name(parameter1, parameter2);
/* SAS statements or macro language */
%mend macro_name;
To use it, type %macro_name(value1, value2); on a line by itself. For a concrete example, suppose you want to print the first 10 rows of any dataset:
%macro print10(dsn);
proc print data=&dsn (obs=10);
run;
%mend print10;
%print10(sashelp.class);
Here &dsn is a macro variable that gets replaced with sashelp.class when the macro runs. The result is identical to typing proc print data=sashelp.class (obs=10); run;.
How to Choose Between Macro and Plain Code
Not every repetition needs a macro. Use a macro when:
- You repeat the same block of code multiple times with only small changes (like different variable names or datasets).
- You need to conditionally generate code based on parameters (e.g., if a flag is 1, run a regression; if 0, run a means).
- You want to automate a series of steps that depend on a list of values (like months or product categories).
- You’re building a reusable utility that other programmers will call.
Avoid macros for one-off tasks or when a simple %let statement suffices. For example, if you only need to change a filename once, just hardcode it. Overusing macros makes code harder to debug because the actual generated code isn’t visible unless you turn on options mprint;.
Common Problems and How to Fix Them
Beginners often hit these issues:
- Missing semicolon after %macro statement: The
%macroline itself does not need a semicolon, but many people add one. It’s harmless, but a missing semicolon after the%mendcan cause errors. - Macro variable resolution: If you write
&dsnwithout a dot after it, SAS might try to resolve a longer variable name. Use&dsn.(with a trailing dot) when you need to append text directly, like&dsn._final. - Quoting issues: If you pass a string with spaces or special characters, you must quote it correctly. For example,
%mymacro(hello world)will treathelloandworldas two parameters. Use%str()or%nrstr()to mask them. - Macro not found: If you define a macro in one program and call it in another, it’s not automatically available. You must either include the definition in the same session or use
%includeto bring it in. - Unbalanced %if/%end: Every
%ifmust have a matching%end. A missing%endis a classic error that produces cryptic messages.
Comparing Macros to Other SAS Features
Macros are often confused with two other things: macro variables and SQL pass-through.
Macro variables (created with %let or call symput) store single text values. Macros are the larger container that uses those variables. You can have a macro without any macro variables, but you can’t have a macro variable that executes code on its own.
PROC SQL can do many things macros do, like looping over values, but SQL is for data manipulation, not for generating code. If you need to run a series of procedures, SQL won’t help. If you need to build a dynamic WHERE clause, SQL with into can create macro variables, but the macro itself is still needed to wrap the whole process.
Also, note that SAS has a built-in macro facility (the macro processor) that is separate from the DATA step compiler. Understanding this separation helps you debug: errors in macro code are often reported as “Apparent invocation of macro not resolved” or “Macro keyword not resolved,” which point to text substitution issues, not data errors.
Costs and Safety: Where Macros Can Go Wrong
There’s no monetary cost to using macros—they’re part of Base SAS. But there is a “cost” in terms of debugging time and code readability. A macro that generates thousands of lines of code can slow down your session slightly, but the bigger risk is logical errors.
Safety considerations:
- Always test with a small dataset first. A macro that works on 10 rows might fail on a million if you have a logic error in a loop.
- Use
options mprint;to see the generated code. This helps you verify that the macro is doing what you think. - Be careful with macro variables that contain special characters. If you pass a value like
a&b, the ampersand will be interpreted as a macro reference. Use%superq()to mask it. - Never use a macro to modify the macro itself (self-referencing). This can cause infinite loops or crashes.
- Save your macro definitions in a separate file and use
%includeto bring them in, so you don’t accidentally lose them when you clear your session.
Alternatives to Macros for Repetitive Tasks
If macros feel too complex, consider these simpler approaches:
- Use
%letfor a single variable. For example,%let dsn=sashelp.class;then use&dsnin your code. This is the simplest way to avoid retyping. - Use
PROC FORMATorPROC TEMPLATEto handle repetitive output formatting without macros. - Use
BY-group processingwithPROC SORTand aBYstatement to run a procedure on multiple groups in one call, avoiding a macro loop. - Use
CALL EXECUTEin a data step to generate code dynamically at runtime. This is a hybrid: it’s not a macro, but it can create code based on data values.
For example, if you want to run a regression for each value of a variable, you could use PROC REG with a BY statement instead of a macro that loops over values. That’s often cleaner and faster.
Frequently Asked Questions
How do I type a macro that takes no parameters?
Simply write %macro mymacro; (no parentheses) and end with %mend mymacro;. Call it with %mymacro;. The parentheses are optional when there are no parameters.
Why does my macro say “Apparent invocation of macro not resolved”?
This means SAS can’t find a macro with that name. Check the spelling, make sure the macro is defined in the same session (or included via %include), and verify you didn’t accidentally put a space between the % and the macro name. Also, ensure the macro definition is not inside a data step or proc that hasn’t ended.
Can I use a macro to create a variable name dynamically?
Yes, but you need to be careful. For example, %let i=1; data want; var&i.=5; run; creates a variable named var1. In a macro, you can loop with %do i=1 %to 3; to create multiple variables. But remember that macro variables are text, so you must resolve them at the right time.
What’s the difference between %macro and %let?
%let creates a single macro variable that stores a text value. %macro defines a block of code that can be called multiple times. You can use %let inside a macro to set local variables, but %let alone cannot execute code or loop.
How do I debug a macro that isn’t working?
Turn on options mprint; to see the generated code in the log. Also use options symbolgen; to see how macro variables are resolved. This shows you exactly what SAS is substituting. Then compare that to what you expected. Also, add %put statements to print macro variable values to the log.
Can I use a macro inside a data step?
You can call a macro that generates data step code, but you cannot invoke a macro as a function within a data step expression. For example, data want; x=%mymacro(); run; will not work unless the macro returns a numeric literal. Instead, use call execute to generate code that runs after the data step.
Related
- How to Use App Script in Google Sheets
- Random Number 1-12: How to Generate One
- Balance Sheet Equity Accounts Explained Clearly
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- Excel VBA Index Match Multiple CriteriaYes, you can use VBA to perform an INDEX/MATCH lookup with multiple criteria by building a helper column…
- Delete the Last Row in Excel VBA SafelyTo delete the last data row of an Excel table, use the table’s ListRows collection: tbl.ListRows(tbl.ListRows.Count).Delete. For a…
- Excel VBA Protect Cells: Lock and Unlock RangesTo protect specific cells in Excel with VBA, you must first unlock the cells you want editable, then…
- VBA UserForm References: How to Show and Control FormsIn Excel VBA, reference a UserForm by its form class name, such as UserForm1, or create an explicit…
- Excel VBA Function Key: Run Macros and Assign ShortcutsIn Excel VBA, press F5 in the Visual Basic Editor to run the current procedure; press F8 to…
- VBA Test for Null: IsNull, IsEmpty, and NothingThe direct answer: in VBA, use the IsNull function to test whether a Variant variable or expression contains…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.