In SAS, a macro is a piece of code that generates or modifies SAS statements before they are compiled. Macros let you automate repetitive tasks, pass parameters, and make your programs dynamic and reusable. This guide walks you through creating your first macro, from the basic %MACRO/%MEND structure to using parameters and macro variables.
What You’ll Need
- A SAS environment (SAS Studio, SAS Enterprise Guide, or Base SAS) — any version that supports the macro facility (all modern versions do).
- Basic familiarity with SAS data steps and procedures (e.g., PROC PRINT, DATA step).
- A dataset to test with, or you can create one in the examples.
Step-by-Step
- Understand the macro structure. A macro starts with
%MACRO macroname;, contains SAS code or macro statements, and ends with%MEND macroname;. The name can be up to 32 characters, letters, digits, or underscores, starting with a letter or underscore. - Define a simple macro without parameters. For example, to print the first 10 rows of a dataset:
%macro print_first10; proc print data=sashelp.class (obs=10); run; %mend print_first10;This macro, when called, will run the PROC PRINT step.
- Compile the macro. When you submit the %MACRO block, SAS compiles it and stores it in the macro catalog. You won’t see output until you call it.
- Call the macro. Use a percent sign followed by the name and a semicolon:
%print_first10;. This executes the macro, running the code inside. - Add parameters. To make the macro flexible, declare parameters inside parentheses after the macro name. For example, to print any dataset with a specified number of observations:
%macro print_top(dsn=, n=10); proc print data=&dsn (obs=&n); run; %mend print_top;Here,
&dsnand&nare macro variables that get replaced with the values you pass. - Call the macro with arguments. Use keyword notation:
%print_top(dsn=sashelp.class, n=5);. This prints the first 5 observations of sashelp.class. You can also use positional notation (order matters) if you define parameters without defaults, but keyword is clearer. - Use macro variables inside the macro. Macro variables are prefixed with an ampersand (&). They can be assigned with
%LETor via parameters. For example:%macro summarize(dsn); %let varlist = name age; proc means data=&dsn; var &varlist; run; %mend summarize;The
&varlistis resolved toname agebefore the PROC runs. - Create a macro that generates a data step. You can wrap a DATA step in a macro. For example:
%macro make_subset(dsn, keepvars); data subset; set &dsn; keep &keepvars; run; %mend make_subset;Call it:
%make_subset(sashelp.class, name age);to create a dataset named SUBSET with only NAME and AGE. - Use conditional logic in macros. Macros can contain %IF/%THEN statements to make decisions at compile time. For example:
%macro check(dsn); %if %sysfunc(exist(&dsn)) %then %do; proc contents data=&dsn; run; %end; %else %put WARNING: Dataset &dsn does not exist.; %mend check;This checks if a dataset exists before running PROC CONTENTS.
- Store macros permanently (optional). By default, macros are stored in the WORK library (temporary). To reuse them across sessions, store them in a permanent catalog using the
STOREDoption or by saving the macro code in an autocall library. For simplicity, you can put the macro definition in a .sas file and %INCLUDE it when needed.
Common Mistakes
- Forgetting %MEND. Each %MACRO must have a matching %MEND. If you omit it, SAS may error or treat subsequent code as part of the macro.
- Using a semicolon after the macro call incorrectly. For a macro call that generates statements (like a PROC), you do not need an extra semicolon after the call; the macro’s internal code already has semicolons. But for a macro that only assigns macro variables (like %LET), you do need a semicolon after the call.
- Misspelling macro variable names. SAS is case-insensitive, but a typo like &dsn vs &dsn2 will cause a warning or error.
- Not quoting macro parameters that contain spaces. If you pass a value with spaces, like a list of variables, it works, but if you pass a string that needs quotes (like a title), you must include the quotes in the argument or use %STR.
- Using %MACRO inside a DATA step. Macros are compiled before the DATA step runs; you cannot define a macro inside a DATA step (unless you use CALL EXECUTE, which is advanced).
Tips
- Use descriptive macro names and add comments inside the macro to explain what it does.
- Test with a small dataset first, then expand.
- Use
%PUTstatements to debug:%put &dsn;will print the value of the macro variable to the log. - Make parameters default to common values to reduce typing.
- Use
%SYSFUNCto call data step functions within macros, e.g.,%sysfunc(today()). - Keep macros in a separate file and use %INCLUDE to bring them into your program, so you can edit them easily.
Troubleshooting
- Macro not found when called. Ensure you have submitted the %MACRO block before calling it. If you restarted SAS, you need to re-submit the definition.
- Error: “Macro variable X is not defined.” Check spelling and ensure the variable is assigned before use. If it’s a parameter, verify you passed it in the call.
- Unexpected output or no output. Check the log for macro resolution messages. Use
%PUT _ALL_;to list all macro variables and their values. - Macro generates invalid SAS code. The macro facility simply text-substitutes; if the resulting code has a syntax error, SAS will show the error in the log. Look at the expanded code by using
OPTIONS MPRINT;before calling the macro. - Quoting issues. If you need to pass a string with quotes, use %STR or %BQUOTE. For example,
%let title = %str(My "Quoted" Title);.
Frequently Asked Questions
- Can I use macros to loop over datasets? Yes, use %DO loops inside a macro. For example,
%do i = 1 %to 5;to repeat code with a counter. - What is the difference between %MACRO and a macro variable? A macro variable stores a single text value (like &dsn). A macro is a block of code that can generate many statements and use macro variables.
- How do I pass a list of variable names as one parameter? Just pass them as a space-separated string, e.g.,
%myMacro(vars=name age height). Inside the macro, use &vars directly in a VAR statement. - Can I call a macro from within a DATA step? Not directly. Use CALL EXECUTE or %SYSFUNC to invoke macro code at runtime, but that’s advanced. Usually you call macros outside DATA steps.
- Why do I get a warning about macro variable resolution? This happens when a macro variable is referenced but not defined. Check the spelling and ensure you’ve assigned it.
- How do I make a macro permanent so I don’t retype it? Save the macro definition in a .sas file and use %INCLUDE ‘path/file.sas’; at the start of your program. Or set up an autocall library with the SASAUTOS option.
Related
- Data Entry Jobs: Skills Required
- Johnson & Johnson Balance Sheet: Key Figures Explained
- In a Balanced Budget? What It Means and How to Build One
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- How to Allow Macros in Excel (Step-by-Step)Allowing macros in Excel lets you run VBA (Visual Basic for Applications) code that automates repetitive tasks, such…
- VBA Array Index: Bounds, Options, and ExamplesIn VBA, an array index is the number inside an array’s parentheses that identifies an element, such as…
- Access VBA MsgBox Constants: Buttons, Icons and ResultsAccess VBA uses the built-in MsgBox function to show a message and, optionally, buttons, an icon, and a…
- SteelSeries GG Macro Editor: Setup, Uses and FixesThe SteelSeries GG Macro Editor is a tool within SteelSeries GG’s Engine section for creating input sequences and…
- VBA Sort Custom Order: Code Examples and Common Fixes in ExcelTo sort Excel rows in a chosen sequence with VBA, add a custom sort field and give it…
- Pivot Table Refresh From VBA: Code and Common FixesTo refresh a PivotTable with VBA in Excel for Microsoft 365 on Windows, call its RefreshTable method, such…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.