BookmarkSubscribeRSS Feed
nickspencer
Obsidian | Level 7
Hi,
I had this code which was running fine.


%macro check_list;
%global list;
%if &list= %then %do;
%let list=“myname”;

(Other code)

%end;
%mend check_list;


Now I had to loop this process so I updated it to below.

%macro loop;
%do i = 1 to 4;

%macro check_list;
%global list&i;
%if &&list&i= %then %do;
%let list&i=“myname”;

(Other code)
%end;
%mend loop;

%loop;

%end;
%mend check_list;


But now I am getting this error.

Error: attempt to %global a name (list2) which exists in a local environment.

How can I get rid of this and run the program successfully.

Any suggestions is appreciated. Thanks in advance.


2 REPLIES 2
Astounding
PROC Star

First suggestion:  untangle the macro definitions so that a human has a prayer of understanding the code.  There is hardly ever a reason to define one macro inside the definition of another macro.  Don't do it.  You can still have a macro call another macro, even if the macro being called is defined later.

 

Second suggestion:  check that "other code" section to make sure it doesn't assign a value to &LIST2 when &i=1.

Tom
Super User Tom
Super User

The reason you cannot make a variable GLOBAL if it already exists in a local symbol table is because there is no way for you to assign it a value or reference its value. It will be hidden by the existing macro variable with the same name in a closer scope.

 

The only real purpose in defining a macro variable %GLOBAL inside a macro is if you want to make sure the values you assign to it will live after the macro exits.   But if the macro variable already exists when your macro starts running then it will exist after your macro ends.

 

So just make the macro that it causing the error smart enough NOT to cause the error.  Have it test whether the macro variable variable already exists before trying to define it as global. 

%macro check_list;
%if not %symexist(list) %then %global list;
%if &list= %then %do;
%let list=“myname”;

(Other code)

%end;
%mend check_list;

hackathon24-white-horiz.png

2025 SAS Hackathon: There is still time!

Good news: We've extended SAS Hackathon registration until Sept. 12, so you still have time to be part of our biggest event yet – our five-year anniversary!

Register Now

How to Concatenate Values

Learn how use the CAT functions in SAS to join values from multiple variables into a single value.

Find more tutorials on the SAS Users YouTube channel.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 2 replies
  • 983 views
  • 0 likes
  • 3 in conversation