sassas-macro

Trying to create a macro which checks for a macro variable existence and creates it if doesn't exist


%Macro symexistchk(valuex);
                %if %symexist(&valuex) %then %put &valuex;
                    %else %do; %let valuex = 0;
                            %end;
%Mend symexistchk;

%symexistchk(g900_r);

I want to check if macro variable g900_r exist and create one if it doesn't exist.

Thanks, Sam.


Solution

  • You almost had it... There were 2 key things you were missing. You need to include the %global statement to declare the macro as a global macro variable. This will make it available outside of the macro. You also were missing the & in your %let statement where you assign it to zero.

    Your final code should be something like this:

    %Macro symexistchk(valuex);
    
      %if %symexist(&valuex) %then %do;
        %put Macro Variable &valuex exists.;
      %end;
      %else %do; 
        %global &valuex;
        %let &valuex = 0;  * NOTE THE AMPERSAND TO THE LEFT OF THE EQUALS SIGN;
        %put Macro Variable &valuex created and initialized to zero.;
      %end;
    %Mend symexistchk;
    
    %symexistchk(g900_r);
    %put &g900_r;