Calling a macro program 30 times

Reply
N/A
Posts: 0

Calling a macro program 30 times

I created a macro program. I'd call it by
%task(day_num);

If I want to call it 30 times with different day_num, how would I set it in a loop (Is it the efficient way)? My day_num goes from 1 to 30 in sequence.

Thanks.

-Nilan
SAS Super FREQ
Posts: 8,647

Re: Calling a macro program 30 times

Hi:
Again, a macro program with a macro %DO loop is going to help you out. There are 2 different ways to write your macro program.
[pre]
** Approach 1: use 2 macro programs;
** the macro program for your main task;
%macro task(day=1);
proc print data=sashelp.shoes(obs=&day);
title "TASK macro: value of DAY is &day";
run;
%mend task;

** then make a macro program that will just;
** invoke the %TASK macro inside a %do loop;
%macro dotask(start=, stop=);
%do i = &start %to &stop;
%task(day=&i);
%end;
%mend dotask;

%dotask(start=1,stop=4);
[/pre]

Which is not really 1 macro program, but is 2 -- the first one that does something(in this case, a PROC PRINT). And the second macro program that uses a %DO loop to invoke the first macro program. There is an alternate way to code this, which is to just use one macro program:
[pre]
** Approach 2: do everything within 1 macro program;
** and put the program code you want to generate;
** inside the %DO loop;
%macro alttask(start=, stop=);
%do i = &start %to &stop;
proc print data=sashelp.shoes(obs=&i);
title "ALTTASK macro: value of I is &i";
run;
%end;
%mend alttask;

%alttask(start=3,stop=6);

[/pre]

I prefer the use of keyword parameters for macro programs instead of positional parameters. The thing I like about keyword parameters is that you can specify default values to use if the parameter is not specified and I just find macros with keyword parameters easier to maintain and easier to invoke. But that's my preference (based on mumblety-mumble years of coding in SAS) -- you could, of course, code your macros with positional parameters. However, my examples always come with keyword parameters.

For more help with writing or invoking macro programs, consult the SAS Macro facility documentation or contact Tech Support for help with a specific coding problem.

cynthia
N/A
Posts: 0

Re: Calling a macro program 30 times

Hi Cynthia,

Thanks for your detailed response. I prefer the first method although it uses 2 macros. It is more readable and I don't want to modify my original macro Smiley Happy

I found the following idea in some pdf files from sugi, that's same as your first idea.

%macro create(howmany);
%do i=1 %to &howmany;
%task(&i);
%end;
%mend create;

%create(3)

Thanks.

-Nilan
Post a Question
Discussion Stats
  • 2 replies
  • 283 views
  • 0 likes
  • 2 in conversation