DATA Step, Macro, Functions and more

macro variable with iterating name

Posts: 33

macro variable with iterating name

So, I'm writing a macro that at a certain point must save the content of a record variable on a macro variable with incrementing name depending on the position of the table. This is a fragment

		%do i=1 %to 7;
			IF _n_ GT (4095*&i-4095) AND _n_ LT (4095*&i) THEN
					key&i.=trim(key&i.)!!' '!!trim(left(m));
					IF _n_ EQ (4095*&i-1) THEN
						CALL SYMPUT('key'||LEFT(&i), trim(key&i));
						DROP key&i;
						%PUT &&key&i;

I want to save the the macro variable called key1 to key6 to the value of the  variable key1 to key6 at intervals of 4095.

I know this program is conceptually wrong, terrible and makes me sick in the stomach, but I'm not permitted to redesign it so I have to solve this problem.

The log says "WARNING: Apparent symbolic reference KEY1 not resolved.



Super Contributor
Posts: 319

Re: macro variable with iterating name



I guess the message comes from the line

%PUT &&key&i;

Try commenting it and see if it works.

Super User
Super User
Posts: 9,599

Re: macro variable with iterating name

[ Edited ]

This code is invalid as its stands, where is the rest of it.  You are mixing Base SAS statements in with Macro statements, you are using macro variables from call symput statements - and this is about the time when things get compiled - but those macro variables have not been executed yet etc.  So think of it this way, when that is pushed through the macro compiler, the call execute has not run, so %put cannot find a macro variable call &key1.


And this statement "but I'm not permitted to redesign it", really shouldn't be the case, if something is wrong it should be fixed, not perpetuated.


This is basically a very simple dataset problem.

data _null_;
  retain i;
  if _n_=1 then i=1;
  if mod(_n_,100)=0 then do;
    call symput(cat('key',put(i,1.)),model);

Although why you want to create X amount of macro variables is beyond me, sounds like th ewhole process is a bit shaky.

Super User
Posts: 10,278

Re: macro variable with iterating name

The %put is dealt with by the macro processor immediately when encountered, which means before the data step is compiled. But the call symput executes during data step execution phase, so &keyX (X being 1 to 7) will never exist when the %put is executed.


Short: you cannot %put a macro variable before the data step that creates it with call symput() has run.

Maxims of Maximally Efficient SAS Programmers
How to convert datasets to data steps
How to post code
Posts: 33

Re: macro variable with iterating name

Posted in reply to KurtBremser

I understand the problem. I put the %PUT (oh boy) there only to check if the macro variables were written, didn't think about the order on witch are executed, my bad

Ask a Question
Discussion stats
  • 4 replies
  • 4 in conversation