SAS_learner
SAS_learner

Reputation: 521

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.

Upvotes: 1

Views: 638

Answers (3)

moreQthanA
moreQthanA

Reputation: 55

To add an update since this was answered in 2015, from SAS9.4M5 this can be done in open code. https://blogs.sas.com/content/sasdummy/2018/07/05/if-then-else-sas-programs/

%if not(%symexist(g900_r)) %then %do; %let g900_r=0; %end;

Upvotes: 0

SRSwift
SRSwift

Reputation: 1710

You will want to assign the newly created macro to the global scope with %global, resolve your macro variable argument in the %let statement (so you are not just creating a variable called valuex) and evaluate the resolved macro variable in your %put statement with &&&.

%macro symexistchk(valuex);
    %if %symexist(&valuex.) %then %put Already exists: &valuex = &&&valuex;
    %else %do;
        /* Make macro variable available outside macro */
        %global &valuex.;
        %let &valuex. = 0;
        %put Assigning: &valuex = &&&valuex;
    %end;
%mend symexistchk;
%symexistchk(mVar);
%symexistchk(mVar);

Upvotes: 1

Robert Penridge
Robert Penridge

Reputation: 8513

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;

Upvotes: 4

Related Questions