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;

sas-innovate-2024.png

Don't miss out on SAS Innovate - Register now for the FREE Livestream!

Can't make it to Vegas? No problem! Watch our general sessions LIVE or on-demand starting April 17th. Hear from SAS execs, best-selling author Adam Grant, Hot Ones host Sean Evans, top tech journalist Kara Swisher, AI expert Cassie Kozyrkov, and the mind-blowing dance crew iLuminate! Plus, get access to over 20 breakout sessions.

 

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.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

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