Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 37 ยท Macros

Macro Programs and Parameters

Write reusable SAS macro programs with %MACRO and %MEND, positional and keyword parameters, defaults, local variables, macro functions and the MPRINT debugging options, with a Python stand-in.

A macro variable replaces a value. A macro program replaces a whole block of code and lets you pass it parameters. When you notice that you copy the same PROC step ten times and change only the data set name, you are looking at a macro waiting to be written. A macro is compiled once and then called by name, and the macro processor writes the final SAS code.

SAS is not available on this site. The sas blocks are read-only; I never show real SAS output. The TryIts are Python stand-ins that model parameter handling and text generation.

Defining and calling a macro

SAS
%macro summarize(ds, var);
  proc means data=&ds n mean max;
    var &var;
    title "Summary of &var in &ds";
  run;
%mend summarize;

%summarize(work.sales, amount)
%summarize(work.costs, price)
  • %macro name(parameters); starts the definition, %mend name; ends it (the name after %mend is optional but makes long programs readable).
  • Parameters become local macro variables you use as &ds and &var.
  • You call the macro with %name(values). There is no semicolon needed after the call; adding one is harmless in most places, but it can add a stray ; to the generated code, so omit it.

The two calls above expand to two complete PROC MEANS steps. Nothing runs until the call, and the definition itself produces no output.

Positional and keyword parameters

Positional parameters are matched by order, as in %summarize(work.sales, amount). Keyword parameters are written name=default and matched by name, in any order:

SAS
%macro report(ds=, var=amount, stat=mean, title=Report);
  proc means data=&ds &stat;
    var &var;
    title "&title";
  run;
%mend;

%report(ds=work.sales)
%report(ds=work.sales, stat=sum, title=Total sales)

Why keyword parameters win for real work:

  • They document themselves at the call site.
  • They carry defaults, so callers specify only what differs.
  • Order does not matter.

You can mix both styles, but positional parameters must come first in the definition. Values are text, so a value containing a comma needs protection with %str(a, b) or %bquote() (see the quoting note below). An empty value is allowed, which is how you make a parameter optional:

SAS
%macro list(ds, where=);
  proc print data=&ds;
    %if %length(&where) > 0 %then %do;
      where &where;
    %end;
  run;
%mend;

Stand-in: how a call becomes text

Python Stand-in: expand a macro with defaults

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The stand-in produces the generated program text. Seeing that text is the key skill: a macro is only a code generator, and when something is wrong you debug the code it generated.

Local variables

Parameters are local. Any other variable you create inside a macro with %let becomes global if it already exists globally, otherwise local to that macro. To avoid collisions with the rest of the program, declare them:

SAS
%macro total(ds, var);
  %local n result;
  proc sql noprint;
    select count(*), sum(&var) into :n trimmed, :result trimmed
    from &ds;
  quit;
  %put NOTE: &n rows, total &result;
%mend;

Always declare helper variables with %local, especially loop counters like i, so that nested macros cannot overwrite each other.

Macro functions

The macro language has its own functions that work on text and return text:

Function Result
%length(&s) Length in characters
%upcase(&s), %lowcase(&s) Case changes
%substr(&s, 2, 3) Part of the text
%scan(&s, 2, %str( )) Nth word
%index(&s, abc) Position of text
%eval(&a + &b) Integer arithmetic
%sysevalf(&a / &b) Floating-point arithmetic
%sysfunc(today(), date9.) Call a DATA step function
%trim, %left, %cmpres Whitespace handling

Macro arithmetic is limited, so remember: %eval truncates decimals and refuses non-integers. For fractions use %sysevalf. %sysfunc opens the door to nearly every DATA step function, with an optional format as the last argument:

SAS
%let today = %sysfunc(today(), yymmdd10.);
%put Run date: &today;
%let n = %sysfunc(countw(&list));

Stand-in: %eval vs %sysevalf

Python Stand-in: integer vs floating arithmetic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Debugging macros

Three options make macro code visible in the log:

SAS
options mprint mlogic symbolgen;
  • mprint shows the SAS statements the macro generated.
  • mlogic traces %if, %do and parameter handling.
  • symbolgen shows each macro variable as it resolves.

Turn them on while developing and off (nomprint nomlogic nosymbolgen) in production, because they produce a lot of log text. Another standard habit is to add %put statements that print parameter values at the start of every macro.

Storing macros

A macro defined in a program exists only for that session. To reuse it, put the code in a file and load it with %include "C:\sas\macros\summarize.sas";, or add an autocall library (options mautosource sasautos=("C:\sas\macros" sasautos);): when SAS meets %summarize, it searches the folder for summarize.sas and loads it automatically. The file name must match the macro name.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What do %macro and %mend do?

    %macro begins the definition (with its parameters) and %mend ends it.
  2. 2. Why are keyword parameters often better than positional ones?

    name=value is self-describing, may carry defaults, and does not depend on position.
  3. 3. Which function should you use for decimal arithmetic in the macro language?

    %eval handles integers only; %sysevalf performs floating-point calculations.
  4. 4. What does the MPRINT option write to the log?

    mprint shows the generated statements; symbolgen shows resolutions and mlogic shows the logic flow.

Summary

  • %macro name(params); ... %mend; defines a reusable code generator; call it with %name(...).
  • Keyword parameters with defaults make calls readable; positional parameters must come first.
  • Declare working variables with %local.
  • Macro functions (%length, %scan, %eval, %sysevalf, %sysfunc) process text; they never read data set values.
  • Debug with mprint, mlogic, symbolgen and %put; share macros through %include or an autocall library.

Next: Conditional Logic and Loops in Macros