Macro functions in SAS are pre-written pieces of code that perform text manipulation, evaluation, and data-driven tasks within the SAS macro language, allowing you to automate repetitive tasks and make your programs dynamic. They are not the same as SAS data step functions; they operate on macro variables and text strings at compile time, before the DATA or PROC steps run. This guide explains what they are, how they work, and how to use them effectively.
What the SAS Macro Language Actually Does
The macro language is a separate text-processing facility that runs before your main SAS code executes. It uses macro variables (like &var) and macro programs (defined with %macro and %mend) to generate SAS code. Macro functions are the built-in tools that let you manipulate those text values—extracting substrings, converting case, evaluating arithmetic, or conditionally building code. They are invoked with a percent sign (%) and can return a value that is then inserted into your program. For example, %upcase(&name) converts the value of the macro variable &name to uppercase before your DATA step sees it.
Key Macro Functions You Will Use Daily
Here are the most common macro functions, grouped by what they do. All of these are built into Base SAS and work in SAS 9.4 and SAS Viya.
- Text manipulation:
%upcase,%lowcase,%substr,%length,%index,%scan,%qscan,%trim,%left - Evaluation:
%eval(integer arithmetic),%sysevalf(floating point),%cmpres(compress blanks) - Quoting functions:
%str,%nrstr,%quote,%nrbquote—these hide special characters like semicolons or ampersands from being interpreted too early - Conditional logic:
%sysfunc(call a DATA step function),%ifand%then(used inside macro definitions) - System interaction:
%sysget(read environment variables),%sysfuncwithexist()oropen()to check datasets
Example: to extract the first word from a macro variable, use %scan(&string,1,' '). This returns the text before the first space.
How Macro Functions Differ from DATA Step Functions
The biggest confusion for new SAS users is mixing up macro functions with DATA step functions. DATA step functions (like substr(), upcase(), input()) operate on variables within a dataset row, at execution time. Macro functions operate on text strings that exist before the DATA step runs. For example, %substr(&var,1,3) returns the first three characters of the macro variable &var, not a dataset variable. To use a DATA step function on a macro variable, you wrap it in %sysfunc(). For instance, %sysfunc(putn(&num,8.2)) formats a numeric macro variable as a character string.
Using %sysfunc to Bridge the Gap
%sysfunc is arguably the most powerful macro function because it lets you call almost any DATA step function or SAS function from within the macro language. This is essential for tasks like: getting today’s date (%sysfunc(today())), checking if a dataset exists (%sysfunc(exist(work.mydata))), or using intnx() to calculate date intervals. The syntax is %sysfunc(function-name(argument-list)). One caveat: the function must return a single value, and you cannot use it to call functions that require a data step context like lag() or merge(). Also, %sysfunc returns a text string; if you need numeric evaluation, combine it with %sysevalf or %eval.
Common Pitfalls and How to Avoid Them
Macro functions fail silently more often than you would expect. Here are the frequent mistakes:
- Not quoting special characters: If your macro variable contains a semicolon, ampersand, or percent sign, use
%str()or%nrstr()when defining it, otherwise SAS may misinterpret it. - Using %eval on decimals:
%evalonly does integer arithmetic. For 3.5*2, use%sysevalf(3.5*2). - Forgetting that macro functions return text: If you compare
%eval(&a = 1)inside a%if, remember the result is a text string ‘1’ or ‘0’, not a numeric. - Overlooking macro quoting: When you pass a macro variable as an argument to a macro function, it is automatically resolved. If you want to pass the literal text
&name(not its value), use%nrstr(&name). - Not testing with
%put: Always use%put &result;to see what a macro function returns before using it in a larger program.
Example of a silent failure: %let x = %substr(&string, 1, 0); returns an empty string, not an error. That empty string can break downstream code.
Writing Your Own Macro Functions with %macro
You can create custom macro functions that return a value, just like built-in ones. The trick is to use %sysfunc or a %let statement inside the macro to set a result variable, then reference that variable after the macro call. For example:
%macro get_month(ds);
%local dsid rc;
%let dsid = %sysfunc(open(&ds));
%if &dsid > 0 %then %do;
%let rc = %sysfunc(fetch(&dsid));
%let month = %sysfunc(getvarc(&dsid, %sysfunc(varnum(&dsid, month))));
%let rc = %sysfunc(close(&dsid));
%end;
%else %let month = ;
&month
%mend get_month;
%put %get_month(work.sales);
This macro opens a dataset, reads the first row’s month variable, and returns its value. Note that the macro ends with &month—that is how you return a value. Always declare local variables with %local to avoid clobbering global macro variables.
When to Use Macro Functions vs. DATA Step Logic
Macro functions are best for tasks that happen once, before data processing: defining file paths, setting titles, choosing which variables to include in a PROC, or looping over a list of datasets. They are not efficient for row-by-row operations on large datasets—that is what DATA steps and SQL are for. A common mistake is using a macro loop to process each row of a dataset; that is almost always slower and more error-prone than a single DATA step with by groups or a PROC SQL join. Use macro functions for code generation, not data transformation.
Frequently Asked Questions
What is the difference between %eval and %sysevalf?
%eval performs integer arithmetic and returns an integer. %sysevalf performs floating-point arithmetic and can return decimals. Use %eval for counts and loop counters; use %sysevalf for any calculation that might produce a fraction, like 10/4.
Can I use macro functions inside a DATA step?
No, not directly. Macro functions are resolved before the DATA step compiles. If you need to manipulate a macro variable based on a dataset value, use CALL SYMPUT inside the DATA step to create a macro variable, then use macro functions after the step ends. Alternatively, use %sysfunc only for functions that do not depend on the current row.
Why is my macro function returning a leading or trailing space?
Macro variables often inherit spaces from the source text. Use %cmpres(%superq(var)) to compress multiple blanks, or %trim(%left(&var)) to remove leading and trailing spaces. Also check if you used %let with a value that includes spaces.
How do I pass a macro variable containing an ampersand to a macro function?
Wrap the variable reference in %nrstr() to prevent resolution. For example, %let text = %nrstr(&name); stores the literal string &name. Then %length(&text) returns 5, not the length of the value of &name.
Can I use %sysfunc with any SAS function?
Most functions that return a single scalar value work, but functions that require a data step environment (like lag, dif, merge, or input with an informat that reads multiple lines) will not. Also, functions that return a list or an array are not supported. Stick to character and numeric functions, date/time functions, and utility functions like exist or open.
Debugging Macro Functions Effectively
When a macro function does not behave as expected, turn on macro debugging options. Use options mprint mlogic symbolgen; at the top of your program. mprint shows the generated SAS code, mlogic traces macro execution, and symbolgen shows macro variable resolutions. Also use %put _all_; to dump all macro variables to the log. A common trick is to write a small test macro that just does %put %myfunction(...); to see the returned value in isolation. Remember that macro functions are resolved left-to-right, so if you have nested functions, the innermost is evaluated first.
Related
- Google Sheets Split Get First: How-To & Examples
- Go to Specific Cell Excel: Quick Jump Methods
- Google Sheets BIN2OCT Function Explained
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- Defender Risky Action Excel Macro: Meaning and Safe StepsYes—Microsoft Defender can flag an Excel macro as risky or block an action it tries to take. That…
- Excel VBA Functions That Return ArraysYes. In Excel VBA, declare the function as Variant, place an array in that Variant, and assign it…
- VBA MsgBox Font Size: What You Can and Cannot ChangeYou cannot set the font size of VBA’s built-in MsgBox in Excel: the function has no font-size argument…
- SteelSeries Macro: How to Add and Assign One in GGTo add a macro in SteelSeries GG, open GG > Engine, select your connected device, choose the key…
- Excel VBA If Not IsDate: Check Dates in Excel CellsIn Excel VBA, use If Not IsDate(value) Then to run code when a value is not recognized as…
- Excel VBA Bubble Sort for Arrays: Code and ExplanationTo bubble-sort a one-dimensional VBA array, compare neighboring items and swap them when they are out of order;…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.