How to Use Character Values on a Macro %DO Loop?

The macro facility does not permit character values on an iterative%DO loop. There are two macros shown below that circumvent this constraint.

This post contains two macro techniques for iterating through character values on a macro %DO loop.

Character Values on a Macro Do Loop using %SCAN function

%macro iterm(lst);
 %let cnt=%sysfunc(countw(&lst));
  %do i = 1 %to &cnt;
   %put %scan(&lst,&i);
  %end;
%mend iterm;

%iterm(S A S);

Result:

Use Character Values on a Macro %DO Loop

The %SYSFUNC function is needed to use the SAS function CONTWW within the macro facility.

The macro variable named &cnt contains the number of characters or words returned by the COUNTW function.

The %SCAN function pulls off each character or word in the macro variable named &LST and uses the %PUT statement to write contents to the log.

Character Values on a Macro Do Loop using BYTE and RANK Function

An alternative approach to the above example is using the RANK and BYTE functions.

The BYTE returns one character in the ASCII collating sequence.

The RANK function returns the position of a character in the ASCII collating sequence.

%macro letters(beg,end);
%do i = %sysfunc(rank(&beg)) %to %sysfunc(rank(&end));
  %put %sysfunc(byte(&i));
%end;
%mend letters;

%letters(L,Q);

Result:

Use Character Values on a Macro %DO Loop

Every week we'll send you SAS tips and in-depth tutorials

JOIN OUR COMMUNITY OF SAS Programmers!

Subhro

Subhro provides valuable and informative content on SAS, offering a comprehensive understanding of SAS concepts. We have been creating SAS tutorials since 2019, and 9to5sas has become one of the leading free SAS resources available on the internet.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.