Search code examples
sassas-macro

SAS: Creating a macro variable containing all months between two dates


I have a macro variable in date yyyymm format, where yyyy is year like 2020 and mm is month like 02, as shown below:

%let m=202002;

How can I construct a macro variable m_new having as many months in the past as we specify? For eg; if num is 5, we get a macro variable having that many months from the past including the one itself. Something like

%put &m_new.
    202002 202001 201912 201911 201910

Solution

  • You could do it with a macro (or just a %DO loop if you are already inside a macro).

    The issue is you need to convert YYYYMM values into an actual date. Then you can use INTNX() to generate the new dates and format them with YYMMN6. format to generate new YYYMM strings.

    %macro months(start,number);
    %local i date ;
    %let date=%sysfunc(inputn(&start.01,yymmdd8));
    %do i=0 %to %eval(&number-1); %sysfunc(intnx(month,&date,-&i),yymmn6)%end;
    %mend ;
    
    %put %months(start=202002,number=5);