带条件循环的 SAS 宏 (%if %then %else %do %end)

时间:2021-03-14 16:58:27

标签: if-statement sas sas-macro

我是 SAS 的初学者,我正在尝试使用宏通过条件循环导入 excel 文件。 导入过程基于 initial_year ;最后一年; initial_month 和 final_month 值。 但似乎 If 条件不起作用。你能帮忙吗?谢谢。

这是我的 SAS 程序:

%let path=\\xxxx.yy.pt\aaa$\INFO\; 
%let initial_year=2019; %let initial_month=2;  
%let final_year=2021; %let final_month=1;

%Macro import_loop; 

 %if &final_month >= &initial_month %then %do;

    %DO x = &initial_year %TO &final_year;

        %DO i = &initial_month %TO &final_month;

            %if &i <=9 %then %let anomes=&x.0&i;
            %else %let anomes=&x&i ;

            proc import datafile="&path&x\Farmacias_EA_&anomes..xlsx" 
            out=Farmacias_EA_&anomes REPLACE dbms=xlsx;
            run;

            data Farmacias_EA_&anomes;
            set Farmacias_EA_&anomes;
            Data_anomes=&anomes;
            run;
 
        %end;
    %end;

%else %do
 

     %DO x = &initial_year %TO &final_year-1;

        %DO i = &initial_month %TO 12;

            %if &i <=9 %then %let anomes=&x.0&i;
            %else %let anomes=&x&i ;

            proc import datafile="&path&x\Farmacias_EA_&anomes..xlsx" 
            out=Farmacias_EA_&anomes REPLACE dbms=xlsx;
            run;

            data Farmacias_EA_&anomes;
            set Farmacias_EA_&anomes;
            Data_anomes=&anomes;
            run;
 
        %end;
    %end;

        %DO x = &final_year %TO &final_year;

        %DO i = 1 %TO &final_month;

            %if &i <=9 %then %let anomes=&x.0&i;
            %else %let anomes=&x&i ;

            proc import datafile="&path&x\Farmacias_EA_&anomes..xlsx" 
            out=Farmacias_EA_&anomes REPLACE dbms=xlsx;
            run;

            data Farmacias_EA_&anomes;
            set Farmacias_EA_&anomes;
            Data_anomes=&anomes;
            run;
 
        %end;
    %end;

%end;

%mend import_loop;
%import_loop

1 个答案:

答案 0 :(得分:0)

只需将您的日期视为日期,循环就会容易得多。

%macro import(from,to);
%local start end offset yymm year ;
%let start=%sysfunc(inputn(&from.01,yymmdd8.));
%let end=%sysfunc(inputn(&to.01,yymmdd8.));
%do offset=0 %to %sysfunc(intck(month,&start,&end));
  %let yymm=%sysfunc(intnx(month,&start,&offset),yymmn6.);
  %let year=%substr(&yymm,1,4);

proc import datafile="&path.&year.\Farmacias_EA_&yymm..xlsx" 
  out=Farmacias_EA_&yymm. REPLACE dbms=xlsx
;
run;

data Farmacias_EA_&yymm.;
  set Farmacias_EA_&yymm.;
  Data_anomes=&yymm.;
run;

%end;
%mend import ;


%let path=\\xxxx.yy.pt\aaa$\INFO\; 
%import(201902,201201);

您真的希望变量 DATA_ANOMES 具有类似 201,902 的数字吗?为什么不将其存储为“201902”之类的字符串或“01FEB2019”d 之类的实际日期值?

相关问题