DATA Step, Macro, Functions and more

How to name a macro with a macro variable

Reply
Contributor
Posts: 74

How to name a macro with a macro variable

Hi,

How can I make the 2nd part below work?  It will be part of a macro DO loop and I want to create the macros dynamically.  Is there a macro quoting function that will resolve the i first?

%macro macroname1;

%put hello 1;

%mend;

%macroname1;

%let i = 1;

%macro macroname&i;

%put hello 2;

%mend;

%macroname&i.;

Many thanks.

Super User
Posts: 11,343

Re: How to name a macro with a macro variable

Before going down the make a macro within a macro route, what are you attempting to do? You might be better off with a single macro that allows parameters to pass that will do the task conditional on values passed.

For example in the trivial example you are using:

%macro Hello(word=);

%put Hello &word;

%mend;

Then another macro could call and pass a value;

%macro loop (loops=);

%do I = 1 %to &loops;

     %hello(word=&loops);

%end;

%mend;

%loop (loops=3);

Contributor
Posts: 74

Re: How to name a macro with a macro variable

Thank you for responding but no, I don't believe it can be done that way.  For certain records, I have to do a number of checks to assign another value.  The checks (sets of rules) are in an external file and vary greatly, both in the number of checks within each setand how they are performed.  So I wanted to create a macro for each set of rules directly from that external file, to be executed for the appropriate records.  The code (created by the macros) will use values from the original data.  The part about naming the macros was the only roadblock I hit so I simplified the example to just show that part.  

Super User
Super User
Posts: 7,076

Re: How to name a macro with a macro variable

You should think of a better way to handle your actual problem.  But as a purely theoretical problem you need to use a different method to generate the code.  The macro processor is not designed to allow the name of a macro to be generated by the macro processor itself.

For example you could use a data step to write the macro statement.

%let i = 1;


filename code temp ;

data _null_;

  file code ;

  put '%macro macroname' "&i;" ;

run;


%inc code / source2 ;

%put hello 2;

%mend;


Or use the %UNQUOTE() macro function.

%let i = 1;

%unquote(%qsysfunc(dequote('%macro')) macroname&i);

%put hello 2;

%mend;

%macroname&i.;

Contributor
Posts: 74

Re: How to name a macro with a macro variable

Thank you.  Yes, I have decided to approach it differently but it is interesting to see how you would get around the problem with the quoting functions.

Ask a Question
Discussion stats
  • 4 replies
  • 226 views
  • 4 likes
  • 3 in conversation