DATA Step, Macro, Functions and more

macro with %if %then statement

Accepted Solution Solved
Reply
Valued Guide
Posts: 860
Accepted Solution

macro with %if %then statement

I have the following code that is working correctly:

%macro new_tran;

data new_tran;

set

%do i = 01 %to &num_month;

%let val=%sysfunc(putn(&i,z2.));

newtran.pid_defaults_final_&val.&year

%end;

;

run;

%mend;

%new_tran;

I would like to add something like this:

%if &num_month = 12 %then &year= &year - 1;

I tried to use %eval() but I couldn't get it to work.  &num_month = month(year()) -1.  I want to make sure that next January when the report runs for December that it takes the correct year.

I tried the following but it's really just a guess as I'm not that experienced with macros.  Any help will be appreciated:

%macro new_tran (num_month=12, year=2015);

%do i = 01 %to &num_month;

%let val=%sysfunc(putn(&i,z2.));

%let year_1 = %eval(&year -1);

%if num_month < 12 %then %do;

%put pid_defaults_final_&val.&year;

%end;

%if num_month = 12 %then %do;

%put pid_defaults_final_&val.&year_1;

%end;

%end;

%mend;

%new_tran;

Thanks

Mark


Accepted Solutions
Solution
‎06-30-2015 07:20 PM
Super User
Posts: 11,343

Re: macro with %if %then statement

Posted in reply to Steelers_In_DC

Make sure to reference your variables properly:

%if num_month < 12 %then %do;

should be

%if &num_month < 12 %then %do;

BUT

you probably mean

%if &i< 12 %then %do;

and

%if &i= 12 then do;

As you do not change the value for &nummonth.

If this were my project I would consider passing a start and end date and then parse over those using the date incrementing function INTNX and put using a selected format to build the names you're using. Then I would not have a problem with any period of reports (providing the data of the appropriate month year combinations exist.

View solution in original post


All Replies
Solution
‎06-30-2015 07:20 PM
Super User
Posts: 11,343

Re: macro with %if %then statement

Posted in reply to Steelers_In_DC

Make sure to reference your variables properly:

%if num_month < 12 %then %do;

should be

%if &num_month < 12 %then %do;

BUT

you probably mean

%if &i< 12 %then %do;

and

%if &i= 12 then do;

As you do not change the value for &nummonth.

If this were my project I would consider passing a start and end date and then parse over those using the date incrementing function INTNX and put using a selected format to build the names you're using. Then I would not have a problem with any period of reports (providing the data of the appropriate month year combinations exist.

Valued Guide
Posts: 860

Re: macro with %if %then statement

Makes perfect sense.  Just tested it, thanks for the help.

🔒 This topic is solved and locked.

Need further help from the community? Please ask a new question.

Discussion stats
  • 2 replies
  • 167 views
  • 0 likes
  • 2 in conversation