Question

is there a short way to make ALL macro variables created inside a macro global in scope?

ie:

%macro x;  
 %global _all_;  * ??? ;  
 %let x=1;  
 %let y=1;  
 %let z=1;  
%mend;
Was it helpful?

Solution

The only way I can think of to do this without having to declare each macro as global ahead of time and then do a %let statement is to use a macro in place of the %let statement.

In the code below, I create a macro called %mylet which has as its sole purpose the task of creating a global variable with the name and value I pass as arguments. I then use this macro in place of %let everywhere I want global variables defined.

eg.

%global myvar;
%let myvar=2;

would become...

%mylet(myvar,2);

/* Define a macro to declare variables as global */
%macro mylet(var,value);
  %global &var;
  %let &var.= &value ;
%mend;

/* Test macro */
%macro test;
 %mylet(myvar,2);
 %mylet(myvar2,12);
 %mylet(myvar3,'string');

/* see that they are global inside the macro */
title "Macro scope inside test macro";
proc sql;
    select *
       from dictionary.macros
       where name in('MYVAR','MYVAR2','MYVAR3');
quit;

%mend;
%test;

/* Check to see if they are still global outside the macro */
title "Macro scope outside test macro";
proc sql;
    select *
       from dictionary.macros
       where name in('MYVAR','MYVAR2','MYVAR3');
quit;

OTHER TIPS

If you create the macro variable within open code the macro variable will automatically be added to the global macro symbol table:

%let x=1;  
%let y=1;  
%let z=1; 

This would be before you create the larger macro:

%macro x;
  <code here>
%mend x;

Another alternative would be to create the variables using a data step:

data _null_;
    set LIB.DSET;
    x = 1;
    call symput('x',x);
run;

If you create macro variables within a data-step, and that data-step is inside a macro, the macro variables created will be, by default, local in scope to that macro.

Use

call symputx('macvar',macval,'g'); 

to create global macro variables.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top