SAS® Macro Programming    

Most Popular Links

 e-Guide (Mini-book)

Mind Map

 Getting Started

 Training Videos

 SAS® Savvy ClassAutomating Tasks using SAS Macro and Metadata Programming

As SAS® programmers advance in their career, there is at least an 80% chance that you will encounter SAS macros to help automate and standardize processes. SAS Macro programming are also known as 'Code Generators'.  From SAS® macro essentials to advanced SAS® macro quoting functions, I am confident you will find these SAS® papers useful as they have been for me.  See also Proc SQL, SAS Dictionary Tables and System Options.  See SAS Savvy training sessions on SAS Macro Programming e-guide below.


SAS Macro Programming


 

 

______________________________________________

In general, SAS® Macro Programs have three sections

A. Define Input Parameters with Defaults (Use global macro variables and system  functions)                          

B. Data Process within Macro or Macro Do Loop (Use metadata and collect or report findings)

C. Defensive Programming of Input Parameters and Data Processing (Display user message or abort if invalid dataset, variable name, data value or zero records)
                
Useful SAS Macro Debugging Options SYMBOLGEN (Confirm macro variable assignments) MPRINTNEST (Confirm resolved code executed) MLOGICNEST (Confirm correct program logic execution) 

SAS® Guide SAS Macro Examples

SAS® Blog The SAS Training Post - Macro Q Functions, Author Tip, Environment, Parameters

sasCommunity.org Best Practices

______________________________________________

 Beginner SAS Programmer

 

 

Beginner 1 Nine Steps to Get Started using SAS Macros, Jane Stroupe

Beginner 2 SAS Macros Are Just Text Substitution!!, Dianne Piaskoski 

Beginner 3 Macro Basics for New SAS® Users, Cynthia L. Zender

Beginner 4 An Introduction to SAS® Macro, Ian Whitlock

Beginner 5 Macros Made Simple, Tom Mannigel

Hands-on-Workshops (HOW) SAS® Macro Programming for Beginners, Susan Slaughter, Lora Delwiche

(HOW) SAS® Macro Variables and Simple Macro Programs, Steven First, Katie Ronk

Animated Guides by Russ Lavery: SAS Macro ProgrammingHow %Str and %NRStr Work

 Advanced SAS Programmer



Advanced 1 CALL EXECUTE: How and Why, Ian Whitlock

Clinical Application Paper Considerations for Building an Integrated Safety Database Using SAS, Denise J. Smith, Daniel Schulz, Gayle Kloss, Wei Cheng

Clinical Application Paper Clinical Data Management: Building a Dynamic Application, Arthur Carpenter, Richard Smith

 Macro SAS Programmer

 

 

Intermediate and Advanced SAS Macros Course Notes

UCLA Self-Course

More About SAS Macros Examples

______________________________________________

Macro Parameter Checklist - See SAS Debugging for automatic macro variables

 
Object 
 
Exists?

Values/Records? 

Total
 
 
# Unique
 
Unique List (DoLoop/Arrays)

 
First/Last

 Macro Parameter

 X 

       

 Libname/Pathname

 X

 N/A 

       

 File (Convert to dataset)

- Excel (VDTs, Control files)

- RTF/Log (Timestamp)

 

X

 

 X

  

   X 

   

   X

             

X

     

        X 

 Dataset

 X

X

 X

 X

 X

 X

 Variable

- Character (Text Management - spaces, case-sensitive, special characters)

- Numeric/Dates (Calculations)

 

X

 

X

 

X

 

 X

 

 X

 

X

 
Inside-Out SAS Syntax (Code Examples)


 Inside-Out SAS Syntax (Options, Metadata) 

%IF %THEN; %ELSE %IF %THEN; ;

%DO %TO; <CODE> %END;

End Result -

TITLES; FOOTNOTES;

 

DATA; <> ; RUN;

 

PROC REPORT ...

 COLUMN ...; DEFINE ...;

 COMPUTE BLOCK;

RUN;

Decision points to construct SAS Syntax

Loop through list of ...

One / More Values / Variables / Options

Valid SAS Syntax

Within/By SAS Procedure

Direct (&name) / Indirect (&&name&i, &&&name&i) Macro Variable Reference

Proc SQL / Proc Contents Metadata (type, length, label, unique values, or nobs)

Non-Duplicate / Duplicate records

Data-driven macro variables (create using SYMPUT and access using SYMGET)

Non-Macro / Macro SAS functions

Character Management functions

Parameter Checks in Design

 

 
Indirect Macro Reference

Macro Resolution  SAS Paper, 2

Macro variable equals  another macro variable.

%let dog = hound;
%let pet = dog; 

'&' resolves to name of macro variable.  '&&&' resolves to internal macro variable value. 

%put My &pet is a &&&pet;
         My dog  is a hound;

Root name and suffix number as one macro variable.

%let dsn   = animals;
%let n      = 2;          
%let dsn2 = cats;           

'&' resolves to name of root and suffix macro variable name.  '&&' resolves to internal macro variable value.

%put  ‘**  &dsn&n = ‘  &dsn&n  ‘   **  &&dsn&n = ‘  &&dsn&n;
           **  &dsn&n =  animals2      **  &&dsn&n =  cats;

Root name and suffix number as one macro variable.

%let i = 1;
%let var=Engine;

%let Engine1=Make Model EngineSize;

'&' resolves to name of root and suffix macro variable name. '&&' resolves to internal macro variable value.

var &&&var&i. ;
var Make Model EngineSize;

Root name and two suffix numbers as one macro variable.

%let i = 1;
%let j = 3;
%let rss_1_3 = gender;

'&' resolves to name of root and suffix macro variable name. '&&' resolves to internal macro variable value.

var &&rss_&i._&j;
var gender;

The Validator: A Macro to Validate Parameters, Paper 2 [Defensive Programming]

OBJECT_EXIST: A Macro to Check if a specified Object Exists, Jim Johnson

Macro Cleanup Checklist

Temporary Objects 

Delete at end of macro 

 Libnames

 Filenames

X

 Datasets

 Global Macro Variables

X

Carpenter's SAS Macro Programs

Categories: Character Variables, Dataset/File Management, Date/Time Variables, Library Tools, Macro Variables, Numeric Variables, and Programming Technique

Tips for Macro Testing (Combinations Calculator)

1. Account for all assumptions and requirements.

2. Develop test cases based on macro logic.  May require reviewing source macro program.

3. Apply specific test cases including:
 - Good / Bad data sets
 - Required / Optional parameters
 - Valid / Invalid variable type and value
 - Possible combination of macro parameters
 - Duplicate records and empty subsets

4. Boundary testing - if a numeric parm with valid values of 1-5, you have to check a negative value, 0, 1, 5, 6.  Checking outside the boundary, at the boundary, and inside boundary, missing values, char values etc.  if char parm, you have to check for blank/missing values, long text strings, a non alphabetic value (i.e. a number), lowercase, mixed case, uppercase, multiple words in a string, etc.etc,

You want to be sure that program can handle virtually anything since users can certainly do so. (and they don’t always read the documentation!). Sometimes you can create a list of valid values to shorten the testing, but that is not always the case depending on how the parms are set up.  Consider handling special characters, ex. %, & and other special chars.

5. Take advantages of system options:
MFILE saves the resolved macro variables to a separate file.  MPRINT displays nested macro calls with indents.

6. Add _debug parameter for debugging purpose

Macro Debugging 1 The Macro Degubbing Primer, Frank DiIorio

Macro Debugging 2 Demystifying the SAS Macro Facility, Marje Fecht, Harry Droogendyk

Macro Testing Discussions Welcome to Dullsville!! The System Testing of SAS Macros, James McGiffen

Macro Testing Methods SAS macro validation criteria, Jim Groeneveld

UnToken Paper with MFILE option A Macro to Unravel Macros, Sarah WoodruffHave it Both Ways: Macros that Produce Publication-Quality Tables and Stand-alone Code, Linda Collins, Lisa Brooks, Michael Rea, Alan Hopkins

1. A Simple Approach to the Automated Unit Testing of Clinical SAS® Macros, Matthew Nizol [Automate]

2. Automated Test Framework for SAS Macros, Sven Prasse [Automate]

3. Automated Testing of Your SAS® Code, and Collation of Results (Using Hash Tables) Andrew Ratcliffe [Automate]

4. Testing Your SAS Code Against Known Data, Sharon Schiro [Test data]

5. Validation of SAS Macro Systems, Philip Pochon, Thomas Burger

6. The Power of Testing! – An automated SAS® Enterprise Guide® System for Testing, Karine Désilets

7. Regression Testing: the SAS Programmer’s Friend, Phil Busby

8. Testing the night away, Stephan Minnaert

9. Macro Design Automation Tool (MDAT) – A methodology for storing macro design information, generating documentation and code templates, and automating parameter validation, Richard Schneck, Mindy Rodgers [Metadata, Automate]


______________________________________________ 

Macro Downloads:

1. General Utility Macros Macros to get to “Know Thy Data”, Diane Foose, Mike Gunshenan, Rick Morales

2. Compare Two Datasets Macro

3. Dataset Codebook Macro

4. Scan Log LOGCHK Macro

5. .LST Files with Proc Compare Result, Manvitha Yennam, Srinivas Vanam, Phaneendhar Vanam

 

Processing Macro Variables as Arrays

DO_OVER Utility Macro Tight Looping With Macro Arrays, Ted Clay

List Making Paper Names, Names, Names - Make Me a List, Ian Whitlock, Proc SQL

data _null_;                                                  /* create macro variables */
 length j $2.;
 set sashelp.class;
 i + 1;
 j = left(put(i, best12.));
 put j=;
 call symput('n', j);                                       /* final n = total number of records */
 call symput('name'||j, trim(left(name)));     /* name1=John name2=Mary */
run;      

%do i=1 %to &n;                     /* loop through total number of variables */
 %put name&i = &&name&i;     /* display name1 = John name2 = Mary etc. */
%end;                                                     

 

%let mlnam = acc.dth.dis;
* macro variable containing list of tokens;

%let nval = 1;
* Create counter macro variable;

%let clab = ;
* Create token macro variable;

data supupdate;

%do %while(%length(%scan(&mlnam, &nval, %str('.')))> 0);
* Do Loop through each token in the list until last token is read;

 %let clab = %scan(&mlnam, &nval, %str('.'));
 * Assign token value based on order in list;

 liv&clab=1;

 %put clab = &clab;
 * Display token value;

 &clab.rt = 100*liv&clab;
 * Reference token value in statement;

 %let nval = %eval(&nval + 1);
 * Increment counter by 1;

%end;
run;

/*
livacc=1; accrt = 100*livacc;
livdth=1; dthrt = 100*livdth;
livdis=1; disrt = 100*livdis;
*/

/* %Do %While Loop processes the MLNAM macro variable for each value.  The SAS statement within the loop is repeated 3 items – once for each item in the MLNAM macro. */

______________________________________________

SAS® Macro Slides: SAS Techies, SAS Institute, Arthur

Compile/Execute Paper IF and %IF You Don't Understand, Ian Whitlock 

1. IF-THEN logic is like one SAS Program using variable values to make decisions.  Thus, conditions should not be based on macro variable values.  IF-THEN logic can be embedded within %IF-%THEN logic.  All code is compiled and executed.

2. The %IF-%THEN macro logic is similar to two separate SAS Programs using macro variable values to make decisions.  Thus, in general, conditions should not be based on dataset variable values.  Only the code passing the condition will be compiled.

Table Title: title1 %nrbquote(^S={font=("arial", 11 pt) }Table 14-2. Demographics and Baseline Characteristics); 

Global Footnote: footnote1 (SOURCE: &pgmdir.\&pgm..sas %upcase(&sysuserid) SASv&sysver (%sysfunc(date(),date9.)%sysfunc(time(),time5.)));

Search for SAS Macro Papers by Ian Whitlock and Art Carpenter

PARMBUFF and SYSPBUFF SAS Example

Automatic macro variables, Data Step CALL Routines, Data Step Functions, Macro Functions, SCL

SAS Macro Language Reference On-Line Documentation

Search for SAS Institute Macro Examples

Different Levels of Metadata for standardization and automation

 1. Basic method to standardize - apply dataset and variable attributes

 2. Basic method to automate - process list of datasets or files

 3. Advanced method to standardize - create standardized codelists

 4. Advanced method to handle standard and custom programming - transform datasets based on source to target mapping attributes, black-box technology

______________________________________________

1. Get A Grip on Macros in just 50 Minutes!, Arthur Li [Beginner, Examples]

2. SAS® Macro: Symbols of Frustration? %Let us help! A Guide to Debugging Macros
Kevin Delaney, Art Carpenter

3. Using Macros to Automate SAS® Processing, Kari Richardson, Eric Rossland [%GOTO]

4. Storing and Using a List of Values in a Macro Variable, Arthur L. Carpenter

5. Five Ways to Create Macro Variables: A Short Introduction to the Macro Language, Arthur L. Carpenter

6. A Tutorial on the SAS Macro Language, John Cohen

7. SAS Macros: Beyond the Basics, Jay A. Jaffe

8. Using Macro Functions, Art Carpenter [%INDEX, %SCAN]

9. Macro Functions: How to Make Them - How to Use Them, Art Carpenter

10. Consistent Variables + Consistent Checks = Cleaner Data, Greg Silva

11. Advanced Macro Topics, Steven First

12. The Path, The Whole Path, And Nothing But the Path, So Help Me Windows,
Art Carpenter

13. A SASautos Companion: Reusing Macros, Ronald Fehd

14. A Serious Look Macro Quoting, Ian Whitlock

15. Macro Quoting Functions, Other Special Character Masking Tools, and How To
Use Them, Art Carpenter
 [System Macro Variables]

16. How to Develop User-Friendly Macros, Sy Truong

17. Programming Squared (Writing Programs that Write Programs),
Jim Johnson

18. Considerations for Building an Integrated Safety Database Using SAS
Denise Smith, Daniel Schulz, Gayle Kloss, Wei Cheng
 [Clinical]

19. Advanced Macro Topics: Utilities and Examples, Art Carpenter

20. Developing a SAS System Autocall Macro Library as an Effective Toolkit, Steven A. Wilson

21. Creating Display Manager Abbreviations and Keyboard Macros for the Enhanced Editor, Art Carpenter

22. Macro Quoting to the Resue: Passing Special Characters, Mary Rosenbloom

23. Sam and Max's Adventure in SAS Macro Land, Sam and Seunghee Chung

24. Making your Way through the Metadata Maze, Frank Poppe, Laurent de Walick

25. Maximize the power of %SCAN using WORDSCAN utility, Priya Saradha

26. CALL EXECUTE: How and Why, Ian Whitlock

27. Developing and Managing a SAS® Macro Library, Margaret James, Carolyn Maass, Ginger Redner

28. Macro Quoting to the Rescue: Passing Special Characters, Mary F. O. Rosenbloom, Art Carpenter

29. Building Macros and Tracking Their Use, Richard Koopmann

30. Why and How to use SAS Macro Language: Easy Ways to get more value and power from your SAS software tools, LeRoy Bessler

31. Taking Control of Macro Variables, Dante diTommaso

32. Array: Construction and Usage of Arrays of Macro Variables, Ronald Fehd

33. Journeymen’s Tools: Data Review Macro FreqAll: Using Proc SQL List
Processing with Dictionary.Columns to Eliminate Macro Do Loops, Ronald Fehd

34. The Role of Consecutive Ampersands in Macro Variable Resolution and the
Mathematical Patterns that Follow, Michael J. Molter

35. &&&, ;;, and Other Hieroglyphics Advanced Macro Topics, Chris Yindra [Process Flow]

36. The Easy Way to Flexible Code: SAS® Macro Variables, Mel Widawski

37. A General Purpose Macro to Obtain a List of Files: Plus Macro Programming Techniques, Mel Widawski

38. The Six Ampersand Solution, John Gerlach

39. Macro Makes PROC MEANS Flexible, Kimberly Yarbrough

40. How Symbolic Variables Can Reduce Code in a Graphics Environment, Monique Bryher

41. Using SAS to Calculate Kappa and Confidence Intervals for Binary Data with Multiple
Raters, and for the Consensus of Multiple Diagnoses, Art Noda, Helena Chmura Kraemer, Vyjeyanthi S. Periyakoil

42. The Next Step with Macros – Double Ampersand Macros &&helpme&i.., Jennifer Rosson

43. A Macro Tool for Quickly Producing a Handy Documented Listing of SAS® Data Sets for Use as a Reference While Writing Programs to Analyze the Same, Hugh Geary

44. Robust Programming Techniques in the SAS® System, Alice M. Cheng

45. Protecting Macros and Macro Variables: It Is All About Control, Eric Sun, Arthur Carpenter [Secure, Protect]

46. A Modular Approach to Portable Programming, Michael Litzsinger, Michael Riddle

47. Rules for Tools – The SAS Utility Primer, Frank DiIorio

48. SAS Keyboard Macros, Pete Lund

49. Using SAS Macros to Help Document SAS Macro Program Files, Patrick Thornton

50. Guidelines on Writing SASÆ Macros for Public Use, Frank Ivis [Program Header, Error Checking]

51. BASICS OF MACRO PROCESSING - ‘Q’ WAY, Usha Kumar

52. SAS® Macro Programming Tips, Tricks and Techniques, Kirk Paul Lafler

53. Before You Get Started: A Macro Language Preview in Three Parts, Art Carpenter

54. AN INTRODUCTION TO SAS MACRO LANGUAGE, Gary Katsanis

55. IS THIS MACRO PARAMETER BLANK? Chang Chung, John King [Defensive Programming]

56. Quotes within Quotes: When Single (‘) and Double (“) Quotes are not Enough, Arthur Carpenter

57. Are You a Control Freak? Control Your Programs – Don’t Let Them Control You!, Mary F. O. Rosenbloom, Art Carpenter

58. SAS® Macro Autocall and %Include, Jie Huang, Tracy Lin [SOURCE2]

59. SAS® Code and Macros: How They Interact, Bruce Gilsen

60. Building Programs with the SAS Macro Facility

61. How Many Observations Are In My Data Set? Jack Hamilton

62. %SYSFUNC - The Brave New Macro World, Chris Yindra [INPUTC, INPUTN, FINFO]

63. Three Easy Ways around Nonexistent or Empty Datasets, Spencer Childress, Brandon Welch [Defensive Programming]

64. Analyse That : Getting Information Quickly About Your SAS Data, Steve Prust [SCL functions]

65. Data Transparency Through Metadata Management, Judith Goud, Julie Smiley

66. %DO Loop – a Simple Dynamic Programming Technique, Yunchao (Susan) Tian

67. SAS® Macro Dynamics - From Simple Basics to Powerful Invocations, Rick Andrews [Basic, Advanced]

68. Large-Scale System Development in Base SAS, Craig Ray

69. Performing Multiple Statements for Each Record in a SAS® Data Set, Edward Moore

70. No %’s or &’s: Macros Inside the SAS® DATA Step, William C. Murphy [Call Execute]

71. Accessing SAS® metadata and using it to help us develop data-driven SAS programs, Iain Humphreys [Applications]

72. Using CALL SYMPUT to Simplify, W. Jodi Auyuen

73. Not Just Another Macro, Y. Christina Song

74. Using SAS® Macro Functions to Manipulate Data, Ben Cochran

75. Considerations in Organizing the Structure of SAS® Macro Libraries, Roger Muller

76. No More Bad Dates!: A Guide to SAS® Dates in Macro Language, Kate Burnett-Isaacs

77. Writing Reusable Macros, Philip Holland

78. IN-HOUSE SAS ® USER’S GUIDES: SITE-SPECIFIC INFORMATION AND CONVERSION GUIDES, Bruce Gilsen

79. Take an In-Depth Look at the %EVAL Function, Beilei Xu, Lei Zhang

80. SAS MACRO: Beyond the Basics, Stephen Philp

81. To %bquote or not to %bquote? That is the question, Andrew Howell [e-poster]

82. Avoid Change Control by Using Control Tables, Frank Ferriola [Proc SQL, Proc FORMAT]

83. Intermediate and Advanced SAS® Macros, Steven First, Katie Ronk

84. SAS Macros Bits and Pieces, Lawrence Heaton-Wright [%GOTO]

85. Return Code From Macro; Passing Parameter By Reference, Hsiwei Yu, Gary Huang

86. Macro Design Ideas: Theory, Template, Practice, Ronald Fehd

87. Dynamic Code Creation Using Call Symput and the SAS Macro Language, Mark Gustafson [MTRACE]

88. Macro: Bells and Whistles for Version 6, Lynn Patrick [MTRACE]

89. A Sample Macro for Creating a List on the Fly, Debbie Miller

90. Choosing the Best Way to Store and Manipulate Lists in SAS, Dmitry Rozhetskin

91. Get into the Groove with %SYSFUNC: Generalizing SAS® Macros with Conditionally Executed Code, Kathy Fraeman

92. The Ins and Outs of %IF, Michelle Buchecker

93. Building Intelligent Macros: Using Metadata Functions with the SAS® Macro Language, Arthur Carpenter

94. SAS Macro Language Quick Study, Clarence Jackson

95. %DO Loop – a Simple Dynamic Programming Technique, Yunchao Tian

96. Automating Code Generation to Reduce Errors and Effort, Steve Cavill [Call Execute]

97. Macros I Use Every Day (And You Can, Too!), Joe DeShon

98. %SASFUNC SAS Blog

99. Simple %str(ER)ROR Checking in Macros, Magnus Mengelbier

100. Autocall Macros – A Quick Overview, Vinod Panangattiri Parambil

101. Which SASAUTOS Macros Are Available to My SAS® Session?, Harry Droogendyk

102. Run Time Comparison Macro, Robert Patten

103. Techniques for writing robust SAS macros, Martin Gregory, Merck Serono

104. Why Aren’t Exception Handling Routines Routine? Toward Reliably Robust Code through Increased Quality Standards in Base SAS, Troy Hughes

105. A Macro that can Search and Replace String in your SAS Programs,Ting Sa [Macro, Scan Keywords]

106. End of Computing Chores with Automation: SAS® Techniques That Generate SAS® Codes, Yun Zhuo

107. The Use of Metadata in Creating, Transforming and Transporting, Clinical Data, Gregory Steffens

108. Secrets of Macro Quoting Functions – How and Why, Susan OConnor

109. Store and Recall Macros with SAS ® Macro Libraries, John Myers

110. Exporting & Importing Datasets & Catalogs: Utility Macros Adel Fahmy

111. Using a SAS Catalog to Develop and Manage a SAS® Project, David Chapman

112. Documenting SAS® Macro Programs using CATALOGS, Patrick Thornton 

113. Ways to Store Macro Source Codes and How to Retrieve Them, Mirjana Stojanovic, Donna Hollis

114. Protecting Macros and Macro Variables: It Is All About Control, Eric Sun, Art Carpenter

115. SAS Macro Application Using Microsoft Excel As Both Control File and Process Documentation, Mike Tangedal

116. Developing Large SAS Macro Applications, John Ingersoll

117. Usability and Usability Testing at SAS, Paul Hankey

118. Large Scale Standard Macros A Methodical Approach to Development and Implementation, John Adams, Jeremy Gratt

119. Read Titles and Footnotes from a Table Shell into a SAS Dataset, Daniel Huang, Lois Lynn [Program Index]

120. Automatic Generation of Titles, Footnotes, and Superscripts for Tables with Macros and PROC REPORT, Paul Cascagnette [Program Index]

121. An Animated Guide: A program to Read information from Program Headers and Produce Reports for Programming Managers, Russ Lavery [QA Macro]

122. How Readable and Comprehensible Is a SAS® Program? A Programmatic Approach to Getting an Insight into a Program, Rajesh Lal, Raghavender Ranga

123. A Case Study in Using Unit Testing as a Method of Primary Validation, Ross Farrugia

124. Modular Programming - Some Lessons Learned and Benefits Gained, Ross Farrugia

______________________________________________

Connect to key SAS® books and references for more information

Carpenter’s Complete Guide to SAS Macro Language and SAS Macro Program downloads by Art Carpenter,  Macro Examples

Table-Driven Strategies for Rapid SAS(r) Applications Development by Tanya Kolosova and Samuel Berestizhevsky Macro Examples

Powered by Wild Apricot Membership Software